From a9b393e0ee36cd628ba4da776dee122d13789612 Mon Sep 17 00:00:00 2001 From: Owl Bot Date: Wed, 22 Mar 2023 20:34:42 +0000 Subject: [PATCH] =?UTF-8?q?=F0=9F=A6=89=20Updates=20from=20OwlBot=20post-p?= =?UTF-8?q?rocessor?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit See https://github.com/googleapis/repo-automation-bots/blob/main/packages/owl-bot/README.md --- .../services/agents/transports/rest.py | 9 - .../answer_records/transports/rest.py | 2 - .../services/contexts/transports/rest.py | 6 - .../conversation_datasets/transports/rest.py | 5 - .../conversation_models/transports/rest.py | 9 - .../conversation_profiles/async_client.py | 1 + .../services/conversation_profiles/client.py | 1 + .../conversation_profiles/transports/rest.py | 7 - .../services/conversations/transports/rest.py | 6 - .../services/documents/transports/rest.py | 8 - .../services/entity_types/transports/rest.py | 10 - .../services/environments/transports/rest.py | 6 - .../services/fulfillments/transports/rest.py | 2 - .../services/intents/transports/rest.py | 6 - .../knowledge_bases/transports/rest.py | 5 - .../services/participants/async_client.py | 67 +- .../services/participants/client.py | 67 +- .../services/participants/transports/rest.py | 8 - .../session_entity_types/transports/rest.py | 5 - .../services/sessions/async_client.py | 63 +- .../dialogflow_v2/services/sessions/client.py | 63 +- .../services/versions/transports/rest.py | 5 - .../services/agents/transports/rest.py | 9 - .../answer_records/transports/rest.py | 3 - .../services/contexts/transports/rest.py | 6 - .../conversation_profiles/async_client.py | 1 + .../services/conversation_profiles/client.py | 1 + .../conversation_profiles/transports/rest.py | 7 - .../services/conversations/transports/rest.py | 7 - .../services/documents/transports/rest.py | 7 - .../services/entity_types/transports/rest.py | 10 - .../services/environments/transports/rest.py | 6 - .../services/fulfillments/transports/rest.py | 2 - .../services/intents/transports/rest.py | 7 - .../knowledge_bases/transports/rest.py | 5 - .../services/participants/async_client.py | 76 +- .../services/participants/client.py | 76 +- .../services/participants/transports/rest.py | 10 - .../session_entity_types/transports/rest.py | 5 - .../services/sessions/async_client.py | 63 +- .../services/sessions/client.py | 63 +- .../services/versions/transports/rest.py | 5 - owl-bot-staging/v2/.coveragerc | 13 - owl-bot-staging/v2/.flake8 | 33 - owl-bot-staging/v2/MANIFEST.in | 2 - owl-bot-staging/v2/README.rst | 49 - owl-bot-staging/v2/docs/conf.py | 376 - .../v2/docs/dialogflow_v2/agents.rst | 10 - .../v2/docs/dialogflow_v2/answer_records.rst | 10 - .../v2/docs/dialogflow_v2/contexts.rst | 10 - .../dialogflow_v2/conversation_datasets.rst | 10 - .../dialogflow_v2/conversation_models.rst | 10 - .../dialogflow_v2/conversation_profiles.rst | 10 - .../v2/docs/dialogflow_v2/conversations.rst | 10 - .../v2/docs/dialogflow_v2/documents.rst | 10 - .../v2/docs/dialogflow_v2/entity_types.rst | 10 - .../v2/docs/dialogflow_v2/environments.rst | 10 - .../v2/docs/dialogflow_v2/fulfillments.rst | 6 - .../v2/docs/dialogflow_v2/intents.rst | 10 - .../v2/docs/dialogflow_v2/knowledge_bases.rst | 10 - .../v2/docs/dialogflow_v2/participants.rst | 10 - .../v2/docs/dialogflow_v2/services.rst | 22 - .../dialogflow_v2/session_entity_types.rst | 10 - .../v2/docs/dialogflow_v2/sessions.rst | 6 - .../v2/docs/dialogflow_v2/types.rst | 6 - .../v2/docs/dialogflow_v2/versions.rst | 10 - owl-bot-staging/v2/docs/index.rst | 7 - .../v2/google/cloud/dialogflow/__init__.py | 547 - .../google/cloud/dialogflow/gapic_version.py | 16 - .../v2/google/cloud/dialogflow/py.typed | 2 - .../v2/google/cloud/dialogflow_v2/__init__.py | 548 - .../cloud/dialogflow_v2/gapic_metadata.json | 1877 -- .../cloud/dialogflow_v2/gapic_version.py | 16 - .../v2/google/cloud/dialogflow_v2/py.typed | 2 - .../cloud/dialogflow_v2/services/__init__.py | 15 - .../dialogflow_v2/services/agents/__init__.py | 22 - .../services/agents/async_client.py | 1505 -- .../dialogflow_v2/services/agents/client.py | 1707 -- .../dialogflow_v2/services/agents/pagers.py | 139 - .../services/agents/transports/__init__.py | 38 - .../services/agents/transports/base.py | 316 - .../services/agents/transports/grpc.py | 676 - .../agents/transports/grpc_asyncio.py | 675 - .../services/agents/transports/rest.py | 1766 -- .../services/answer_records/__init__.py | 22 - .../services/answer_records/async_client.py | 714 - .../services/answer_records/client.py | 913 - .../services/answer_records/pagers.py | 139 - .../answer_records/transports/__init__.py | 38 - .../answer_records/transports/base.py | 209 - .../answer_records/transports/grpc.py | 385 - .../answer_records/transports/grpc_asyncio.py | 384 - .../answer_records/transports/rest.py | 887 - .../services/contexts/__init__.py | 22 - .../services/contexts/async_client.py | 1152 -- .../dialogflow_v2/services/contexts/client.py | 1351 -- .../dialogflow_v2/services/contexts/pagers.py | 139 - .../services/contexts/transports/__init__.py | 38 - .../services/contexts/transports/base.py | 266 - .../services/contexts/transports/grpc.py | 491 - .../contexts/transports/grpc_asyncio.py | 490 - .../services/contexts/transports/rest.py | 1387 -- .../conversation_datasets/__init__.py | 22 - .../conversation_datasets/async_client.py | 1072 - .../services/conversation_datasets/client.py | 1272 -- .../services/conversation_datasets/pagers.py | 139 - .../transports/__init__.py | 38 - .../conversation_datasets/transports/base.py | 258 - .../conversation_datasets/transports/grpc.py | 515 - .../transports/grpc_asyncio.py | 514 - .../conversation_datasets/transports/rest.py | 1274 -- .../services/conversation_models/__init__.py | 22 - .../conversation_models/async_client.py | 1526 -- .../services/conversation_models/client.py | 1754 -- .../services/conversation_models/pagers.py | 260 - .../transports/__init__.py | 38 - .../conversation_models/transports/base.py | 314 - .../conversation_models/transports/grpc.py | 634 - .../transports/grpc_asyncio.py | 633 - .../conversation_models/transports/rest.py | 1756 -- .../conversation_profiles/__init__.py | 22 - .../conversation_profiles/async_client.py | 1337 -- .../services/conversation_profiles/client.py | 1581 -- .../services/conversation_profiles/pagers.py | 139 - .../transports/__init__.py | 38 - .../conversation_profiles/transports/base.py | 287 - .../conversation_profiles/transports/grpc.py | 578 - .../transports/grpc_asyncio.py | 577 - .../conversation_profiles/transports/rest.py | 1513 -- .../services/conversations/__init__.py | 22 - .../services/conversations/async_client.py | 1158 -- .../services/conversations/client.py | 1384 -- .../services/conversations/pagers.py | 261 - .../conversations/transports/__init__.py | 38 - .../services/conversations/transports/base.py | 265 - .../services/conversations/transports/grpc.py | 517 - .../conversations/transports/grpc_asyncio.py | 516 - .../services/conversations/transports/rest.py | 1362 -- .../services/documents/__init__.py | 22 - .../services/documents/async_client.py | 1491 -- .../services/documents/client.py | 1692 -- .../services/documents/pagers.py | 139 - .../services/documents/transports/__init__.py | 38 - .../services/documents/transports/base.py | 300 - .../services/documents/transports/grpc.py | 626 - .../documents/transports/grpc_asyncio.py | 625 - .../services/documents/transports/rest.py | 1686 -- .../services/entity_types/__init__.py | 22 - .../services/entity_types/async_client.py | 1839 -- .../services/entity_types/client.py | 2039 -- .../services/entity_types/pagers.py | 139 - .../entity_types/transports/__init__.py | 38 - .../services/entity_types/transports/base.py | 329 - .../services/entity_types/transports/grpc.py | 697 - .../entity_types/transports/grpc_asyncio.py | 696 - .../services/entity_types/transports/rest.py | 1921 -- .../services/environments/__init__.py | 22 - .../services/environments/async_client.py | 1056 - .../services/environments/client.py | 1278 -- .../services/environments/pagers.py | 260 - .../environments/transports/__init__.py | 38 - .../services/environments/transports/base.py | 265 - .../services/environments/transports/grpc.py | 502 - .../environments/transports/grpc_asyncio.py | 501 - .../services/environments/transports/rest.py | 1361 -- .../services/fulfillments/__init__.py | 22 - .../services/fulfillments/async_client.py | 692 - .../services/fulfillments/client.py | 891 - .../fulfillments/transports/__init__.py | 38 - .../services/fulfillments/transports/base.py | 209 - .../services/fulfillments/transports/grpc.py | 384 - .../fulfillments/transports/grpc_asyncio.py | 383 - .../services/fulfillments/transports/rest.py | 878 - .../services/intents/__init__.py | 22 - .../services/intents/async_client.py | 1400 -- .../dialogflow_v2/services/intents/client.py | 1608 -- .../dialogflow_v2/services/intents/pagers.py | 139 - .../services/intents/transports/__init__.py | 38 - .../services/intents/transports/base.py | 287 - .../services/intents/transports/grpc.py | 575 - .../intents/transports/grpc_asyncio.py | 574 - .../services/intents/transports/rest.py | 1537 -- .../services/knowledge_bases/__init__.py | 22 - .../services/knowledge_bases/async_client.py | 1027 - .../services/knowledge_bases/client.py | 1226 -- .../services/knowledge_bases/pagers.py | 139 - .../knowledge_bases/transports/__init__.py | 38 - .../knowledge_bases/transports/base.py | 252 - .../knowledge_bases/transports/grpc.py | 464 - .../transports/grpc_asyncio.py | 463 - .../knowledge_bases/transports/rest.py | 1246 -- .../services/participants/__init__.py | 22 - .../services/participants/async_client.py | 1509 -- .../services/participants/client.py | 1743 -- .../services/participants/pagers.py | 139 - .../participants/transports/__init__.py | 38 - .../services/participants/transports/base.py | 313 - .../services/participants/transports/grpc.py | 590 - .../participants/transports/grpc_asyncio.py | 589 - .../services/participants/transports/rest.py | 1631 -- .../services/session_entity_types/__init__.py | 22 - .../session_entity_types/async_client.py | 1061 - .../services/session_entity_types/client.py | 1260 -- .../services/session_entity_types/pagers.py | 139 - .../transports/__init__.py | 38 - .../session_entity_types/transports/base.py | 252 - .../session_entity_types/transports/grpc.py | 482 - .../transports/grpc_asyncio.py | 481 - .../session_entity_types/transports/rest.py | 1265 -- .../services/sessions/__init__.py | 22 - .../services/sessions/async_client.py | 770 - .../dialogflow_v2/services/sessions/client.py | 986 - .../services/sessions/transports/__init__.py | 38 - .../services/sessions/transports/base.py | 215 - .../services/sessions/transports/grpc.py | 415 - .../sessions/transports/grpc_asyncio.py | 414 - .../services/sessions/transports/rest.py | 774 - .../services/versions/__init__.py | 22 - .../services/versions/async_client.py | 1057 - .../dialogflow_v2/services/versions/client.py | 1256 -- .../dialogflow_v2/services/versions/pagers.py | 139 - .../services/versions/transports/__init__.py | 38 - .../services/versions/transports/base.py | 252 - .../services/versions/transports/grpc.py | 469 - .../versions/transports/grpc_asyncio.py | 468 - .../services/versions/transports/rest.py | 1244 -- .../cloud/dialogflow_v2/types/__init__.py | 520 - .../google/cloud/dialogflow_v2/types/agent.py | 550 - .../dialogflow_v2/types/answer_record.py | 452 - .../cloud/dialogflow_v2/types/audio_config.py | 674 - .../cloud/dialogflow_v2/types/context.py | 302 - .../cloud/dialogflow_v2/types/conversation.py | 526 - .../types/conversation_dataset.py | 372 - .../dialogflow_v2/types/conversation_event.py | 122 - .../dialogflow_v2/types/conversation_model.py | 906 - .../types/conversation_profile.py | 1107 - .../cloud/dialogflow_v2/types/document.py | 695 - .../cloud/dialogflow_v2/types/entity_type.py | 601 - .../cloud/dialogflow_v2/types/environment.py | 484 - .../cloud/dialogflow_v2/types/fulfillment.py | 219 - .../google/cloud/dialogflow_v2/types/gcs.py | 68 - .../types/human_agent_assistant_event.py | 65 - .../cloud/dialogflow_v2/types/intent.py | 1823 -- .../dialogflow_v2/types/knowledge_base.py | 262 - .../cloud/dialogflow_v2/types/participant.py | 1519 -- .../cloud/dialogflow_v2/types/session.py | 1042 - .../types/session_entity_type.py | 277 - .../dialogflow_v2/types/validation_result.py | 114 - .../cloud/dialogflow_v2/types/version.py | 281 - .../cloud/dialogflow_v2/types/webhook.py | 235 - owl-bot-staging/v2/mypy.ini | 3 - owl-bot-staging/v2/noxfile.py | 184 - ..._v2_generated_agents_delete_agent_async.py | 50 - ...w_v2_generated_agents_delete_agent_sync.py | 50 - ..._v2_generated_agents_export_agent_async.py | 57 - ...w_v2_generated_agents_export_agent_sync.py | 57 - ...low_v2_generated_agents_get_agent_async.py | 52 - ...flow_v2_generated_agents_get_agent_sync.py | 52 - ...ated_agents_get_validation_result_async.py | 52 - ...rated_agents_get_validation_result_sync.py | 52 - ..._v2_generated_agents_import_agent_async.py | 57 - ...w_v2_generated_agents_import_agent_sync.py | 57 - ...v2_generated_agents_restore_agent_async.py | 57 - ..._v2_generated_agents_restore_agent_sync.py | 57 - ...v2_generated_agents_search_agents_async.py | 53 - ..._v2_generated_agents_search_agents_sync.py | 53 - ...low_v2_generated_agents_set_agent_async.py | 58 - ...flow_v2_generated_agents_set_agent_sync.py | 58 - ...w_v2_generated_agents_train_agent_async.py | 56 - ...ow_v2_generated_agents_train_agent_sync.py | 56 - ...nswer_records_list_answer_records_async.py | 53 - ...answer_records_list_answer_records_sync.py | 53 - ...swer_records_update_answer_record_async.py | 51 - ...nswer_records_update_answer_record_sync.py | 51 - ...generated_contexts_create_context_async.py | 56 - ..._generated_contexts_create_context_sync.py | 56 - ...ated_contexts_delete_all_contexts_async.py | 50 - ...rated_contexts_delete_all_contexts_sync.py | 50 - ...generated_contexts_delete_context_async.py | 50 - ..._generated_contexts_delete_context_sync.py | 50 - ...v2_generated_contexts_get_context_async.py | 52 - ..._v2_generated_contexts_get_context_sync.py | 52 - ..._generated_contexts_list_contexts_async.py | 53 - ...2_generated_contexts_list_contexts_sync.py | 53 - ...generated_contexts_update_context_async.py | 55 - ..._generated_contexts_update_context_sync.py | 55 - ...asets_create_conversation_dataset_async.py | 60 - ...tasets_create_conversation_dataset_sync.py | 60 - ...asets_delete_conversation_dataset_async.py | 56 - ...tasets_delete_conversation_dataset_sync.py | 56 - ...datasets_get_conversation_dataset_async.py | 52 - ..._datasets_get_conversation_dataset_sync.py | 52 - ...datasets_import_conversation_data_async.py | 60 - ..._datasets_import_conversation_data_sync.py | 60 - ...tasets_list_conversation_datasets_async.py | 53 - ...atasets_list_conversation_datasets_sync.py | 53 - ..._models_create_conversation_model_async.py | 60 - ...ate_conversation_model_evaluation_async.py | 56 - ...eate_conversation_model_evaluation_sync.py | 56 - ...n_models_create_conversation_model_sync.py | 60 - ..._models_delete_conversation_model_async.py | 56 - ...n_models_delete_conversation_model_sync.py | 56 - ..._models_deploy_conversation_model_async.py | 56 - ...n_models_deploy_conversation_model_sync.py | 56 - ...ion_models_get_conversation_model_async.py | 52 - ...get_conversation_model_evaluation_async.py | 52 - ..._get_conversation_model_evaluation_sync.py | 52 - ...tion_models_get_conversation_model_sync.py | 52 - ...st_conversation_model_evaluations_async.py | 53 - ...ist_conversation_model_evaluations_sync.py | 53 - ...n_models_list_conversation_models_async.py | 53 - ...on_models_list_conversation_models_sync.py | 53 - ...odels_undeploy_conversation_model_async.py | 56 - ...models_undeploy_conversation_model_sync.py | 56 - ...s_clear_suggestion_feature_config_async.py | 58 - ...es_clear_suggestion_feature_config_sync.py | 58 - ...files_create_conversation_profile_async.py | 56 - ...ofiles_create_conversation_profile_sync.py | 56 - ...files_delete_conversation_profile_async.py | 50 - ...ofiles_delete_conversation_profile_sync.py | 50 - ...profiles_get_conversation_profile_async.py | 52 - ..._profiles_get_conversation_profile_sync.py | 52 - ...ofiles_list_conversation_profiles_async.py | 53 - ...rofiles_list_conversation_profiles_sync.py | 53 - ...les_set_suggestion_feature_config_async.py | 57 - ...iles_set_suggestion_feature_config_sync.py | 57 - ...files_update_conversation_profile_async.py | 55 - ...ofiles_update_conversation_profile_sync.py | 55 - ...nversations_complete_conversation_async.py | 52 - ...onversations_complete_conversation_sync.py | 52 - ...conversations_create_conversation_async.py | 56 - ..._conversations_create_conversation_sync.py | 56 - ...ed_conversations_get_conversation_async.py | 52 - ...ted_conversations_get_conversation_sync.py | 52 - ..._conversations_list_conversations_async.py | 53 - ...d_conversations_list_conversations_sync.py | 53 - ...rated_conversations_list_messages_async.py | 53 - ...erated_conversations_list_messages_sync.py | 53 - ...ions_suggest_conversation_summary_async.py | 52 - ...tions_suggest_conversation_summary_sync.py | 52 - ...nerated_documents_create_document_async.py | 63 - ...enerated_documents_create_document_sync.py | 63 - ...nerated_documents_delete_document_async.py | 56 - ...enerated_documents_delete_document_sync.py | 56 - ...nerated_documents_export_document_async.py | 56 - ...enerated_documents_export_document_sync.py | 56 - ..._generated_documents_get_document_async.py | 52 - ...2_generated_documents_get_document_sync.py | 52 - ...erated_documents_import_documents_async.py | 65 - ...nerated_documents_import_documents_sync.py | 65 - ...enerated_documents_list_documents_async.py | 53 - ...generated_documents_list_documents_sync.py | 53 - ...nerated_documents_reload_document_async.py | 57 - ...enerated_documents_reload_document_sync.py | 57 - ...nerated_documents_update_document_async.py | 62 - ...enerated_documents_update_document_sync.py | 62 - ...ntity_types_batch_create_entities_async.py | 61 - ...entity_types_batch_create_entities_sync.py | 61 - ...ntity_types_batch_delete_entities_async.py | 57 - ...entity_types_batch_delete_entities_sync.py | 57 - ...y_types_batch_delete_entity_types_async.py | 57 - ...ty_types_batch_delete_entity_types_sync.py | 57 - ...ntity_types_batch_update_entities_async.py | 61 - ...entity_types_batch_update_entities_sync.py | 61 - ...y_types_batch_update_entity_types_async.py | 57 - ...ty_types_batch_update_entity_types_sync.py | 57 - ...d_entity_types_create_entity_type_async.py | 57 - ...ed_entity_types_create_entity_type_sync.py | 57 - ...d_entity_types_delete_entity_type_async.py | 50 - ...ed_entity_types_delete_entity_type_sync.py | 50 - ...ated_entity_types_get_entity_type_async.py | 52 - ...rated_entity_types_get_entity_type_sync.py | 52 - ...ed_entity_types_list_entity_types_async.py | 53 - ...ted_entity_types_list_entity_types_sync.py | 53 - ...d_entity_types_update_entity_type_async.py | 56 - ...ed_entity_types_update_entity_type_sync.py | 56 - ...d_environments_create_environment_async.py | 53 - ...ed_environments_create_environment_sync.py | 53 - ...d_environments_delete_environment_async.py | 50 - ...ed_environments_delete_environment_sync.py | 50 - ...ated_environments_get_environment_async.py | 52 - ...ironments_get_environment_history_async.py | 53 - ...vironments_get_environment_history_sync.py | 53 - ...rated_environments_get_environment_sync.py | 52 - ...ed_environments_list_environments_async.py | 53 - ...ted_environments_list_environments_sync.py | 53 - ...d_environments_update_environment_async.py | 51 - ...ed_environments_update_environment_sync.py | 51 - ...ated_fulfillments_get_fulfillment_async.py | 52 - ...rated_fulfillments_get_fulfillment_sync.py | 52 - ...d_fulfillments_update_fulfillment_async.py | 56 - ...ed_fulfillments_update_fulfillment_sync.py | 56 - ...ated_intents_batch_delete_intents_async.py | 60 - ...rated_intents_batch_delete_intents_sync.py | 60 - ...ated_intents_batch_update_intents_async.py | 57 - ...rated_intents_batch_update_intents_sync.py | 57 - ...2_generated_intents_create_intent_async.py | 56 - ...v2_generated_intents_create_intent_sync.py | 56 - ...2_generated_intents_delete_intent_async.py | 50 - ...v2_generated_intents_delete_intent_sync.py | 50 - ...w_v2_generated_intents_get_intent_async.py | 52 - ...ow_v2_generated_intents_get_intent_sync.py | 52 - ...v2_generated_intents_list_intents_async.py | 53 - ..._v2_generated_intents_list_intents_sync.py | 53 - ...2_generated_intents_update_intent_async.py | 55 - ...v2_generated_intents_update_intent_sync.py | 55 - ...ledge_bases_create_knowledge_base_async.py | 56 - ...wledge_bases_create_knowledge_base_sync.py | 56 - ...ledge_bases_delete_knowledge_base_async.py | 50 - ...wledge_bases_delete_knowledge_base_sync.py | 50 - ...nowledge_bases_get_knowledge_base_async.py | 52 - ...knowledge_bases_get_knowledge_base_sync.py | 52 - ...wledge_bases_list_knowledge_bases_async.py | 53 - ...owledge_bases_list_knowledge_bases_sync.py | 53 - ...ledge_bases_update_knowledge_base_async.py | 55 - ...wledge_bases_update_knowledge_base_sync.py | 55 - ...ated_participants_analyze_content_async.py | 57 - ...rated_participants_analyze_content_sync.py | 57 - ...d_participants_create_participant_async.py | 52 - ...ed_participants_create_participant_sync.py | 52 - ...ated_participants_get_participant_async.py | 52 - ...rated_participants_get_participant_sync.py | 52 - ...ed_participants_list_participants_async.py | 53 - ...ted_participants_list_participants_sync.py | 53 - ...cipants_streaming_analyze_content_async.py | 64 - ...icipants_streaming_analyze_content_sync.py | 64 - ...ted_participants_suggest_articles_async.py | 52 - ...ated_participants_suggest_articles_sync.py | 52 - ..._participants_suggest_faq_answers_async.py | 52 - ...d_participants_suggest_faq_answers_sync.py | 52 - ...articipants_suggest_smart_replies_async.py | 52 - ...participants_suggest_smart_replies_sync.py | 52 - ...d_participants_update_participant_async.py | 51 - ...ed_participants_update_participant_sync.py | 51 - ..._types_create_session_entity_type_async.py | 59 - ...y_types_create_session_entity_type_sync.py | 59 - ..._types_delete_session_entity_type_async.py | 50 - ...y_types_delete_session_entity_type_sync.py | 50 - ...ity_types_get_session_entity_type_async.py | 52 - ...tity_types_get_session_entity_type_sync.py | 52 - ...y_types_list_session_entity_types_async.py | 53 - ...ty_types_list_session_entity_types_sync.py | 53 - ..._types_update_session_entity_type_async.py | 58 - ...y_types_update_session_entity_type_sync.py | 58 - ..._generated_sessions_detect_intent_async.py | 52 - ...2_generated_sessions_detect_intent_sync.py | 52 - ..._sessions_streaming_detect_intent_async.py | 63 - ...d_sessions_streaming_detect_intent_sync.py | 63 - ...generated_versions_create_version_async.py | 52 - ..._generated_versions_create_version_sync.py | 52 - ...generated_versions_delete_version_async.py | 50 - ..._generated_versions_delete_version_sync.py | 50 - ...v2_generated_versions_get_version_async.py | 52 - ..._v2_generated_versions_get_version_sync.py | 52 - ..._generated_versions_list_versions_async.py | 53 - ...2_generated_versions_list_versions_sync.py | 53 - ...generated_versions_update_version_async.py | 51 - ..._generated_versions_update_version_sync.py | 51 - ...t_metadata_google.cloud.dialogflow.v2.json | 16802 ---------------- .../scripts/fixup_dialogflow_v2_keywords.py | 278 - owl-bot-staging/v2/setup.py | 90 - .../v2/testing/constraints-3.10.txt | 6 - .../v2/testing/constraints-3.11.txt | 6 - .../v2/testing/constraints-3.12.txt | 6 - .../v2/testing/constraints-3.7.txt | 9 - .../v2/testing/constraints-3.8.txt | 6 - .../v2/testing/constraints-3.9.txt | 6 - owl-bot-staging/v2/tests/__init__.py | 16 - owl-bot-staging/v2/tests/unit/__init__.py | 16 - .../v2/tests/unit/gapic/__init__.py | 16 - .../unit/gapic/dialogflow_v2/__init__.py | 16 - .../unit/gapic/dialogflow_v2/test_agents.py | 6314 ------ .../dialogflow_v2/test_answer_records.py | 3304 --- .../unit/gapic/dialogflow_v2/test_contexts.py | 5176 ----- .../test_conversation_datasets.py | 4634 ----- .../dialogflow_v2/test_conversation_models.py | 6691 ------ .../test_conversation_profiles.py | 5910 ------ .../gapic/dialogflow_v2/test_conversations.py | 5548 ----- .../gapic/dialogflow_v2/test_documents.py | 5920 ------ .../gapic/dialogflow_v2/test_entity_types.py | 7145 ------- .../gapic/dialogflow_v2/test_environments.py | 4837 ----- .../gapic/dialogflow_v2/test_fulfillments.py | 3080 --- .../unit/gapic/dialogflow_v2/test_intents.py | 6040 ------ .../dialogflow_v2/test_knowledge_bases.py | 4742 ----- .../gapic/dialogflow_v2/test_participants.py | 6426 ------ .../test_session_entity_types.py | 4725 ----- .../unit/gapic/dialogflow_v2/test_sessions.py | 2759 --- .../unit/gapic/dialogflow_v2/test_versions.py | 4759 ----- owl-bot-staging/v2beta1/.coveragerc | 13 - owl-bot-staging/v2beta1/.flake8 | 33 - owl-bot-staging/v2beta1/MANIFEST.in | 2 - owl-bot-staging/v2beta1/README.rst | 49 - owl-bot-staging/v2beta1/docs/conf.py | 376 - .../docs/dialogflow_v2beta1/agents.rst | 10 - .../dialogflow_v2beta1/answer_records.rst | 10 - .../docs/dialogflow_v2beta1/contexts.rst | 10 - .../conversation_profiles.rst | 10 - .../docs/dialogflow_v2beta1/conversations.rst | 10 - .../docs/dialogflow_v2beta1/documents.rst | 10 - .../docs/dialogflow_v2beta1/entity_types.rst | 10 - .../docs/dialogflow_v2beta1/environments.rst | 10 - .../docs/dialogflow_v2beta1/fulfillments.rst | 6 - .../docs/dialogflow_v2beta1/intents.rst | 10 - .../dialogflow_v2beta1/knowledge_bases.rst | 10 - .../docs/dialogflow_v2beta1/participants.rst | 10 - .../docs/dialogflow_v2beta1/services.rst | 20 - .../session_entity_types.rst | 10 - .../docs/dialogflow_v2beta1/sessions.rst | 6 - .../v2beta1/docs/dialogflow_v2beta1/types.rst | 6 - .../docs/dialogflow_v2beta1/versions.rst | 10 - owl-bot-staging/v2beta1/docs/index.rst | 7 - .../google/cloud/dialogflow/__init__.py | 495 - .../google/cloud/dialogflow/gapic_version.py | 16 - .../v2beta1/google/cloud/dialogflow/py.typed | 2 - .../cloud/dialogflow_v2beta1/__init__.py | 496 - .../dialogflow_v2beta1/gapic_metadata.json | 1674 -- .../cloud/dialogflow_v2beta1/gapic_version.py | 16 - .../google/cloud/dialogflow_v2beta1/py.typed | 2 - .../dialogflow_v2beta1/services/__init__.py | 15 - .../services/agents/__init__.py | 22 - .../services/agents/async_client.py | 1509 -- .../services/agents/client.py | 1711 -- .../services/agents/pagers.py | 139 - .../services/agents/transports/__init__.py | 38 - .../services/agents/transports/base.py | 316 - .../services/agents/transports/grpc.py | 678 - .../agents/transports/grpc_asyncio.py | 677 - .../services/agents/transports/rest.py | 1767 -- .../services/answer_records/__init__.py | 22 - .../services/answer_records/async_client.py | 830 - .../services/answer_records/client.py | 1030 - .../services/answer_records/pagers.py | 139 - .../answer_records/transports/__init__.py | 38 - .../answer_records/transports/base.py | 223 - .../answer_records/transports/grpc.py | 412 - .../answer_records/transports/grpc_asyncio.py | 411 - .../answer_records/transports/rest.py | 1017 - .../services/contexts/__init__.py | 22 - .../services/contexts/async_client.py | 1172 -- .../services/contexts/client.py | 1371 -- .../services/contexts/pagers.py | 139 - .../services/contexts/transports/__init__.py | 38 - .../services/contexts/transports/base.py | 266 - .../services/contexts/transports/grpc.py | 492 - .../contexts/transports/grpc_asyncio.py | 491 - .../services/contexts/transports/rest.py | 1388 -- .../conversation_profiles/__init__.py | 22 - .../conversation_profiles/async_client.py | 1337 -- .../services/conversation_profiles/client.py | 1581 -- .../services/conversation_profiles/pagers.py | 139 - .../transports/__init__.py | 38 - .../conversation_profiles/transports/base.py | 287 - .../conversation_profiles/transports/grpc.py | 578 - .../transports/grpc_asyncio.py | 577 - .../conversation_profiles/transports/rest.py | 1513 -- .../services/conversations/__init__.py | 22 - .../services/conversations/async_client.py | 1267 -- .../services/conversations/client.py | 1493 -- .../services/conversations/pagers.py | 261 - .../conversations/transports/__init__.py | 38 - .../services/conversations/transports/base.py | 279 - .../services/conversations/transports/grpc.py | 545 - .../conversations/transports/grpc_asyncio.py | 544 - .../services/conversations/transports/rest.py | 1489 -- .../services/documents/__init__.py | 22 - .../services/documents/async_client.py | 1399 -- .../services/documents/client.py | 1599 -- .../services/documents/pagers.py | 139 - .../services/documents/transports/__init__.py | 38 - .../services/documents/transports/base.py | 286 - .../services/documents/transports/grpc.py | 611 - .../documents/transports/grpc_asyncio.py | 610 - .../services/documents/transports/rest.py | 1560 -- .../services/entity_types/__init__.py | 22 - .../services/entity_types/async_client.py | 1869 -- .../services/entity_types/client.py | 2069 -- .../services/entity_types/pagers.py | 139 - .../entity_types/transports/__init__.py | 38 - .../services/entity_types/transports/base.py | 329 - .../services/entity_types/transports/grpc.py | 697 - .../entity_types/transports/grpc_asyncio.py | 696 - .../services/entity_types/transports/rest.py | 1921 -- .../services/environments/__init__.py | 22 - .../services/environments/async_client.py | 1055 - .../services/environments/client.py | 1277 -- .../services/environments/pagers.py | 260 - .../environments/transports/__init__.py | 38 - .../services/environments/transports/base.py | 265 - .../services/environments/transports/grpc.py | 501 - .../environments/transports/grpc_asyncio.py | 500 - .../services/environments/transports/rest.py | 1361 -- .../services/fulfillments/__init__.py | 22 - .../services/fulfillments/async_client.py | 695 - .../services/fulfillments/client.py | 894 - .../fulfillments/transports/__init__.py | 38 - .../services/fulfillments/transports/base.py | 209 - .../services/fulfillments/transports/grpc.py | 384 - .../fulfillments/transports/grpc_asyncio.py | 383 - .../services/fulfillments/transports/rest.py | 878 - .../services/intents/__init__.py | 22 - .../services/intents/async_client.py | 1418 -- .../services/intents/client.py | 1626 -- .../services/intents/pagers.py | 139 - .../services/intents/transports/__init__.py | 38 - .../services/intents/transports/base.py | 287 - .../services/intents/transports/grpc.py | 576 - .../intents/transports/grpc_asyncio.py | 575 - .../services/intents/transports/rest.py | 1539 -- .../services/knowledge_bases/__init__.py | 22 - .../services/knowledge_bases/async_client.py | 1041 - .../services/knowledge_bases/client.py | 1240 -- .../services/knowledge_bases/pagers.py | 139 - .../knowledge_bases/transports/__init__.py | 38 - .../knowledge_bases/transports/base.py | 252 - .../knowledge_bases/transports/grpc.py | 478 - .../transports/grpc_asyncio.py | 477 - .../knowledge_bases/transports/rest.py | 1246 -- .../services/participants/__init__.py | 22 - .../services/participants/async_client.py | 1739 -- .../services/participants/client.py | 1984 -- .../services/participants/pagers.py | 260 - .../participants/transports/__init__.py | 38 - .../services/participants/transports/base.py | 341 - .../services/participants/transports/grpc.py | 681 - .../participants/transports/grpc_asyncio.py | 680 - .../services/participants/transports/rest.py | 1850 -- .../services/session_entity_types/__init__.py | 22 - .../session_entity_types/async_client.py | 1067 - .../services/session_entity_types/client.py | 1266 -- .../services/session_entity_types/pagers.py | 139 - .../transports/__init__.py | 38 - .../session_entity_types/transports/base.py | 252 - .../session_entity_types/transports/grpc.py | 482 - .../transports/grpc_asyncio.py | 481 - .../session_entity_types/transports/rest.py | 1265 -- .../services/sessions/__init__.py | 22 - .../services/sessions/async_client.py | 780 - .../services/sessions/client.py | 1005 - .../services/sessions/transports/__init__.py | 38 - .../services/sessions/transports/base.py | 215 - .../services/sessions/transports/grpc.py | 415 - .../sessions/transports/grpc_asyncio.py | 414 - .../services/sessions/transports/rest.py | 774 - .../services/versions/__init__.py | 22 - .../services/versions/async_client.py | 1059 - .../services/versions/client.py | 1258 -- .../services/versions/pagers.py | 139 - .../services/versions/transports/__init__.py | 38 - .../services/versions/transports/base.py | 252 - .../services/versions/transports/grpc.py | 470 - .../versions/transports/grpc_asyncio.py | 469 - .../services/versions/transports/rest.py | 1245 -- .../dialogflow_v2beta1/types/__init__.py | 472 - .../cloud/dialogflow_v2beta1/types/agent.py | 584 - .../dialogflow_v2beta1/types/answer_record.py | 468 - .../dialogflow_v2beta1/types/audio_config.py | 736 - .../cloud/dialogflow_v2beta1/types/context.py | 331 - .../dialogflow_v2beta1/types/conversation.py | 598 - .../types/conversation_event.py | 122 - .../types/conversation_profile.py | 1072 - .../dialogflow_v2beta1/types/document.py | 666 - .../dialogflow_v2beta1/types/entity_type.py | 626 - .../dialogflow_v2beta1/types/environment.py | 474 - .../dialogflow_v2beta1/types/fulfillment.py | 218 - .../cloud/dialogflow_v2beta1/types/gcs.py | 88 - .../types/human_agent_assistant_event.py | 73 - .../cloud/dialogflow_v2beta1/types/intent.py | 2429 --- .../types/knowledge_base.py | 261 - .../dialogflow_v2beta1/types/participant.py | 2241 --- .../cloud/dialogflow_v2beta1/types/session.py | 1251 -- .../types/session_entity_type.py | 300 - .../types/validation_result.py | 114 - .../cloud/dialogflow_v2beta1/types/version.py | 281 - .../cloud/dialogflow_v2beta1/types/webhook.py | 265 - owl-bot-staging/v2beta1/mypy.ini | 3 - owl-bot-staging/v2beta1/noxfile.py | 184 - ...ta1_generated_agents_delete_agent_async.py | 50 - ...eta1_generated_agents_delete_agent_sync.py | 50 - ...ta1_generated_agents_export_agent_async.py | 56 - ...eta1_generated_agents_export_agent_sync.py | 56 - ...2beta1_generated_agents_get_agent_async.py | 52 - ...v2beta1_generated_agents_get_agent_sync.py | 52 - ...ated_agents_get_validation_result_async.py | 52 - ...rated_agents_get_validation_result_sync.py | 52 - ...ta1_generated_agents_import_agent_async.py | 57 - ...eta1_generated_agents_import_agent_sync.py | 57 - ...a1_generated_agents_restore_agent_async.py | 57 - ...ta1_generated_agents_restore_agent_sync.py | 57 - ...a1_generated_agents_search_agents_async.py | 53 - ...ta1_generated_agents_search_agents_sync.py | 53 - ...2beta1_generated_agents_set_agent_async.py | 55 - ...v2beta1_generated_agents_set_agent_sync.py | 55 - ...eta1_generated_agents_train_agent_async.py | 56 - ...beta1_generated_agents_train_agent_sync.py | 56 - ..._answer_records_get_answer_record_async.py | 51 - ...d_answer_records_get_answer_record_sync.py | 51 - ...nswer_records_list_answer_records_async.py | 52 - ...answer_records_list_answer_records_sync.py | 52 - ...swer_records_update_answer_record_async.py | 51 - ...nswer_records_update_answer_record_sync.py | 51 - ...generated_contexts_create_context_async.py | 52 - ..._generated_contexts_create_context_sync.py | 52 - ...ated_contexts_delete_all_contexts_async.py | 50 - ...rated_contexts_delete_all_contexts_sync.py | 50 - ...generated_contexts_delete_context_async.py | 50 - ..._generated_contexts_delete_context_sync.py | 50 - ...a1_generated_contexts_get_context_async.py | 52 - ...ta1_generated_contexts_get_context_sync.py | 52 - ..._generated_contexts_list_contexts_async.py | 53 - ...1_generated_contexts_list_contexts_sync.py | 53 - ...generated_contexts_update_context_async.py | 51 - ..._generated_contexts_update_context_sync.py | 51 - ...s_clear_suggestion_feature_config_async.py | 58 - ...es_clear_suggestion_feature_config_sync.py | 58 - ...files_create_conversation_profile_async.py | 56 - ...ofiles_create_conversation_profile_sync.py | 56 - ...files_delete_conversation_profile_async.py | 50 - ...ofiles_delete_conversation_profile_sync.py | 50 - ...profiles_get_conversation_profile_async.py | 52 - ..._profiles_get_conversation_profile_sync.py | 52 - ...ofiles_list_conversation_profiles_async.py | 53 - ...rofiles_list_conversation_profiles_sync.py | 53 - ...les_set_suggestion_feature_config_async.py | 57 - ...iles_set_suggestion_feature_config_sync.py | 57 - ...files_update_conversation_profile_async.py | 55 - ...ofiles_update_conversation_profile_sync.py | 55 - ...nversations_batch_create_messages_async.py | 57 - ...onversations_batch_create_messages_sync.py | 57 - ...nversations_complete_conversation_async.py | 52 - ...onversations_complete_conversation_sync.py | 52 - ...conversations_create_conversation_async.py | 56 - ..._conversations_create_conversation_sync.py | 56 - ...ed_conversations_get_conversation_async.py | 52 - ...ted_conversations_get_conversation_sync.py | 52 - ..._conversations_list_conversations_async.py | 53 - ...d_conversations_list_conversations_sync.py | 53 - ...rated_conversations_list_messages_async.py | 53 - ...erated_conversations_list_messages_sync.py | 53 - ...ions_suggest_conversation_summary_async.py | 52 - ...tions_suggest_conversation_summary_sync.py | 52 - ...nerated_documents_create_document_async.py | 63 - ...enerated_documents_create_document_sync.py | 63 - ...nerated_documents_delete_document_async.py | 56 - ...enerated_documents_delete_document_sync.py | 56 - ..._generated_documents_get_document_async.py | 52 - ...1_generated_documents_get_document_sync.py | 52 - ...erated_documents_import_documents_async.py | 65 - ...nerated_documents_import_documents_sync.py | 65 - ...enerated_documents_list_documents_async.py | 53 - ...generated_documents_list_documents_sync.py | 53 - ...nerated_documents_reload_document_async.py | 56 - ...enerated_documents_reload_document_sync.py | 56 - ...nerated_documents_update_document_async.py | 62 - ...enerated_documents_update_document_sync.py | 62 - ...ntity_types_batch_create_entities_async.py | 60 - ...entity_types_batch_create_entities_sync.py | 60 - ...ntity_types_batch_delete_entities_async.py | 57 - ...entity_types_batch_delete_entities_sync.py | 57 - ...y_types_batch_delete_entity_types_async.py | 57 - ...ty_types_batch_delete_entity_types_sync.py | 57 - ...ntity_types_batch_update_entities_async.py | 60 - ...entity_types_batch_update_entities_sync.py | 60 - ...y_types_batch_update_entity_types_async.py | 57 - ...ty_types_batch_update_entity_types_sync.py | 57 - ...d_entity_types_create_entity_type_async.py | 57 - ...ed_entity_types_create_entity_type_sync.py | 57 - ...d_entity_types_delete_entity_type_async.py | 50 - ...ed_entity_types_delete_entity_type_sync.py | 50 - ...ated_entity_types_get_entity_type_async.py | 52 - ...rated_entity_types_get_entity_type_sync.py | 52 - ...ed_entity_types_list_entity_types_async.py | 53 - ...ted_entity_types_list_entity_types_sync.py | 53 - ...d_entity_types_update_entity_type_async.py | 56 - ...ed_entity_types_update_entity_type_sync.py | 56 - ...d_environments_create_environment_async.py | 53 - ...ed_environments_create_environment_sync.py | 53 - ...d_environments_delete_environment_async.py | 50 - ...ed_environments_delete_environment_sync.py | 50 - ...ated_environments_get_environment_async.py | 52 - ...ironments_get_environment_history_async.py | 53 - ...vironments_get_environment_history_sync.py | 53 - ...rated_environments_get_environment_sync.py | 52 - ...ed_environments_list_environments_async.py | 53 - ...ted_environments_list_environments_sync.py | 53 - ...d_environments_update_environment_async.py | 51 - ...ed_environments_update_environment_sync.py | 51 - ...ated_fulfillments_get_fulfillment_async.py | 52 - ...rated_fulfillments_get_fulfillment_sync.py | 52 - ...d_fulfillments_update_fulfillment_async.py | 56 - ...ed_fulfillments_update_fulfillment_sync.py | 56 - ...ated_intents_batch_delete_intents_async.py | 60 - ...rated_intents_batch_delete_intents_sync.py | 60 - ...ated_intents_batch_update_intents_async.py | 57 - ...rated_intents_batch_update_intents_sync.py | 57 - ...1_generated_intents_create_intent_async.py | 56 - ...a1_generated_intents_create_intent_sync.py | 56 - ...1_generated_intents_delete_intent_async.py | 50 - ...a1_generated_intents_delete_intent_sync.py | 50 - ...eta1_generated_intents_get_intent_async.py | 52 - ...beta1_generated_intents_get_intent_sync.py | 52 - ...a1_generated_intents_list_intents_async.py | 53 - ...ta1_generated_intents_list_intents_sync.py | 53 - ...1_generated_intents_update_intent_async.py | 55 - ...a1_generated_intents_update_intent_sync.py | 55 - ...ledge_bases_create_knowledge_base_async.py | 56 - ...wledge_bases_create_knowledge_base_sync.py | 56 - ...ledge_bases_delete_knowledge_base_async.py | 50 - ...wledge_bases_delete_knowledge_base_sync.py | 50 - ...nowledge_bases_get_knowledge_base_async.py | 52 - ...knowledge_bases_get_knowledge_base_sync.py | 52 - ...wledge_bases_list_knowledge_bases_async.py | 53 - ...owledge_bases_list_knowledge_bases_sync.py | 53 - ...ledge_bases_update_knowledge_base_async.py | 55 - ...wledge_bases_update_knowledge_base_sync.py | 55 - ...ated_participants_analyze_content_async.py | 52 - ...rated_participants_analyze_content_sync.py | 52 - ...d_participants_compile_suggestion_async.py | 51 - ...ed_participants_compile_suggestion_sync.py | 51 - ...d_participants_create_participant_async.py | 52 - ...ed_participants_create_participant_sync.py | 52 - ...ated_participants_get_participant_async.py | 52 - ...rated_participants_get_participant_sync.py | 52 - ...ed_participants_list_participants_async.py | 53 - ...ted_participants_list_participants_sync.py | 53 - ...ted_participants_list_suggestions_async.py | 52 - ...ated_participants_list_suggestions_sync.py | 52 - ...cipants_streaming_analyze_content_async.py | 64 - ...icipants_streaming_analyze_content_sync.py | 64 - ...ted_participants_suggest_articles_async.py | 52 - ...ated_participants_suggest_articles_sync.py | 52 - ..._participants_suggest_faq_answers_async.py | 52 - ...d_participants_suggest_faq_answers_sync.py | 52 - ...articipants_suggest_smart_replies_async.py | 52 - ...participants_suggest_smart_replies_sync.py | 52 - ...d_participants_update_participant_async.py | 51 - ...ed_participants_update_participant_sync.py | 51 - ..._types_create_session_entity_type_async.py | 52 - ...y_types_create_session_entity_type_sync.py | 52 - ..._types_delete_session_entity_type_async.py | 50 - ...y_types_delete_session_entity_type_sync.py | 50 - ...ity_types_get_session_entity_type_async.py | 52 - ...tity_types_get_session_entity_type_sync.py | 52 - ...y_types_list_session_entity_types_async.py | 53 - ...ty_types_list_session_entity_types_sync.py | 53 - ..._types_update_session_entity_type_async.py | 51 - ...y_types_update_session_entity_type_sync.py | 51 - ..._generated_sessions_detect_intent_async.py | 52 - ...1_generated_sessions_detect_intent_sync.py | 52 - ..._sessions_streaming_detect_intent_async.py | 63 - ...d_sessions_streaming_detect_intent_sync.py | 63 - ...generated_versions_create_version_async.py | 52 - ..._generated_versions_create_version_sync.py | 52 - ...generated_versions_delete_version_async.py | 50 - ..._generated_versions_delete_version_sync.py | 50 - ...a1_generated_versions_get_version_async.py | 52 - ...ta1_generated_versions_get_version_sync.py | 52 - ..._generated_versions_list_versions_async.py | 53 - ...1_generated_versions_list_versions_sync.py | 53 - ...generated_versions_update_version_async.py | 51 - ..._generated_versions_update_version_sync.py | 51 - ...adata_google.cloud.dialogflow.v2beta1.json | 15031 -------------- .../fixup_dialogflow_v2beta1_keywords.py | 267 - owl-bot-staging/v2beta1/setup.py | 90 - .../v2beta1/testing/constraints-3.10.txt | 6 - .../v2beta1/testing/constraints-3.11.txt | 6 - .../v2beta1/testing/constraints-3.12.txt | 6 - .../v2beta1/testing/constraints-3.7.txt | 9 - .../v2beta1/testing/constraints-3.8.txt | 6 - .../v2beta1/testing/constraints-3.9.txt | 6 - owl-bot-staging/v2beta1/tests/__init__.py | 16 - .../v2beta1/tests/unit/__init__.py | 16 - .../v2beta1/tests/unit/gapic/__init__.py | 16 - .../unit/gapic/dialogflow_v2beta1/__init__.py | 16 - .../gapic/dialogflow_v2beta1/test_agents.py | 6310 ------ .../dialogflow_v2beta1/test_answer_records.py | 3483 ---- .../gapic/dialogflow_v2beta1/test_contexts.py | 5176 ----- .../test_conversation_profiles.py | 5910 ------ .../dialogflow_v2beta1/test_conversations.py | 6014 ------ .../dialogflow_v2beta1/test_documents.py | 5595 ----- .../dialogflow_v2beta1/test_entity_types.py | 7157 ------- .../dialogflow_v2beta1/test_environments.py | 4837 ----- .../dialogflow_v2beta1/test_fulfillments.py | 3080 --- .../gapic/dialogflow_v2beta1/test_intents.py | 6058 ------ .../test_knowledge_bases.py | 4742 ----- .../dialogflow_v2beta1/test_participants.py | 7200 ------- .../test_session_entity_types.py | 4725 ----- .../gapic/dialogflow_v2beta1/test_sessions.py | 2782 --- .../gapic/dialogflow_v2beta1/test_versions.py | 4759 ----- 888 files changed, 280 insertions(+), 431904 deletions(-) delete mode 100644 owl-bot-staging/v2/.coveragerc delete mode 100644 owl-bot-staging/v2/.flake8 delete mode 100644 owl-bot-staging/v2/MANIFEST.in delete mode 100644 owl-bot-staging/v2/README.rst delete mode 100644 owl-bot-staging/v2/docs/conf.py delete mode 100644 owl-bot-staging/v2/docs/dialogflow_v2/agents.rst delete mode 100644 owl-bot-staging/v2/docs/dialogflow_v2/answer_records.rst delete mode 100644 owl-bot-staging/v2/docs/dialogflow_v2/contexts.rst delete mode 100644 owl-bot-staging/v2/docs/dialogflow_v2/conversation_datasets.rst delete mode 100644 owl-bot-staging/v2/docs/dialogflow_v2/conversation_models.rst delete mode 100644 owl-bot-staging/v2/docs/dialogflow_v2/conversation_profiles.rst delete mode 100644 owl-bot-staging/v2/docs/dialogflow_v2/conversations.rst delete mode 100644 owl-bot-staging/v2/docs/dialogflow_v2/documents.rst delete mode 100644 owl-bot-staging/v2/docs/dialogflow_v2/entity_types.rst delete mode 100644 owl-bot-staging/v2/docs/dialogflow_v2/environments.rst delete mode 100644 owl-bot-staging/v2/docs/dialogflow_v2/fulfillments.rst delete mode 100644 owl-bot-staging/v2/docs/dialogflow_v2/intents.rst delete mode 100644 owl-bot-staging/v2/docs/dialogflow_v2/knowledge_bases.rst delete mode 100644 owl-bot-staging/v2/docs/dialogflow_v2/participants.rst delete mode 100644 owl-bot-staging/v2/docs/dialogflow_v2/services.rst delete mode 100644 owl-bot-staging/v2/docs/dialogflow_v2/session_entity_types.rst delete mode 100644 owl-bot-staging/v2/docs/dialogflow_v2/sessions.rst delete mode 100644 owl-bot-staging/v2/docs/dialogflow_v2/types.rst delete mode 100644 owl-bot-staging/v2/docs/dialogflow_v2/versions.rst delete mode 100644 owl-bot-staging/v2/docs/index.rst delete mode 100644 owl-bot-staging/v2/google/cloud/dialogflow/__init__.py delete mode 100644 owl-bot-staging/v2/google/cloud/dialogflow/gapic_version.py delete mode 100644 owl-bot-staging/v2/google/cloud/dialogflow/py.typed delete mode 100644 owl-bot-staging/v2/google/cloud/dialogflow_v2/__init__.py delete mode 100644 owl-bot-staging/v2/google/cloud/dialogflow_v2/gapic_metadata.json delete mode 100644 owl-bot-staging/v2/google/cloud/dialogflow_v2/gapic_version.py delete mode 100644 owl-bot-staging/v2/google/cloud/dialogflow_v2/py.typed delete mode 100644 owl-bot-staging/v2/google/cloud/dialogflow_v2/services/__init__.py delete mode 100644 owl-bot-staging/v2/google/cloud/dialogflow_v2/services/agents/__init__.py delete mode 100644 owl-bot-staging/v2/google/cloud/dialogflow_v2/services/agents/async_client.py delete mode 100644 owl-bot-staging/v2/google/cloud/dialogflow_v2/services/agents/client.py delete mode 100644 owl-bot-staging/v2/google/cloud/dialogflow_v2/services/agents/pagers.py delete mode 100644 owl-bot-staging/v2/google/cloud/dialogflow_v2/services/agents/transports/__init__.py delete mode 100644 owl-bot-staging/v2/google/cloud/dialogflow_v2/services/agents/transports/base.py delete mode 100644 owl-bot-staging/v2/google/cloud/dialogflow_v2/services/agents/transports/grpc.py delete mode 100644 owl-bot-staging/v2/google/cloud/dialogflow_v2/services/agents/transports/grpc_asyncio.py delete mode 100644 owl-bot-staging/v2/google/cloud/dialogflow_v2/services/agents/transports/rest.py delete mode 100644 owl-bot-staging/v2/google/cloud/dialogflow_v2/services/answer_records/__init__.py delete mode 100644 owl-bot-staging/v2/google/cloud/dialogflow_v2/services/answer_records/async_client.py delete mode 100644 owl-bot-staging/v2/google/cloud/dialogflow_v2/services/answer_records/client.py delete mode 100644 owl-bot-staging/v2/google/cloud/dialogflow_v2/services/answer_records/pagers.py delete mode 100644 owl-bot-staging/v2/google/cloud/dialogflow_v2/services/answer_records/transports/__init__.py delete mode 100644 owl-bot-staging/v2/google/cloud/dialogflow_v2/services/answer_records/transports/base.py delete mode 100644 owl-bot-staging/v2/google/cloud/dialogflow_v2/services/answer_records/transports/grpc.py delete mode 100644 owl-bot-staging/v2/google/cloud/dialogflow_v2/services/answer_records/transports/grpc_asyncio.py delete mode 100644 owl-bot-staging/v2/google/cloud/dialogflow_v2/services/answer_records/transports/rest.py delete mode 100644 owl-bot-staging/v2/google/cloud/dialogflow_v2/services/contexts/__init__.py delete mode 100644 owl-bot-staging/v2/google/cloud/dialogflow_v2/services/contexts/async_client.py delete mode 100644 owl-bot-staging/v2/google/cloud/dialogflow_v2/services/contexts/client.py delete mode 100644 owl-bot-staging/v2/google/cloud/dialogflow_v2/services/contexts/pagers.py delete mode 100644 owl-bot-staging/v2/google/cloud/dialogflow_v2/services/contexts/transports/__init__.py delete mode 100644 owl-bot-staging/v2/google/cloud/dialogflow_v2/services/contexts/transports/base.py delete mode 100644 owl-bot-staging/v2/google/cloud/dialogflow_v2/services/contexts/transports/grpc.py delete mode 100644 owl-bot-staging/v2/google/cloud/dialogflow_v2/services/contexts/transports/grpc_asyncio.py delete mode 100644 owl-bot-staging/v2/google/cloud/dialogflow_v2/services/contexts/transports/rest.py delete mode 100644 owl-bot-staging/v2/google/cloud/dialogflow_v2/services/conversation_datasets/__init__.py delete mode 100644 owl-bot-staging/v2/google/cloud/dialogflow_v2/services/conversation_datasets/async_client.py delete mode 100644 owl-bot-staging/v2/google/cloud/dialogflow_v2/services/conversation_datasets/client.py delete mode 100644 owl-bot-staging/v2/google/cloud/dialogflow_v2/services/conversation_datasets/pagers.py delete mode 100644 owl-bot-staging/v2/google/cloud/dialogflow_v2/services/conversation_datasets/transports/__init__.py delete mode 100644 owl-bot-staging/v2/google/cloud/dialogflow_v2/services/conversation_datasets/transports/base.py delete mode 100644 owl-bot-staging/v2/google/cloud/dialogflow_v2/services/conversation_datasets/transports/grpc.py delete mode 100644 owl-bot-staging/v2/google/cloud/dialogflow_v2/services/conversation_datasets/transports/grpc_asyncio.py delete mode 100644 owl-bot-staging/v2/google/cloud/dialogflow_v2/services/conversation_datasets/transports/rest.py delete mode 100644 owl-bot-staging/v2/google/cloud/dialogflow_v2/services/conversation_models/__init__.py delete mode 100644 owl-bot-staging/v2/google/cloud/dialogflow_v2/services/conversation_models/async_client.py delete mode 100644 owl-bot-staging/v2/google/cloud/dialogflow_v2/services/conversation_models/client.py delete mode 100644 owl-bot-staging/v2/google/cloud/dialogflow_v2/services/conversation_models/pagers.py delete mode 100644 owl-bot-staging/v2/google/cloud/dialogflow_v2/services/conversation_models/transports/__init__.py delete mode 100644 owl-bot-staging/v2/google/cloud/dialogflow_v2/services/conversation_models/transports/base.py delete mode 100644 owl-bot-staging/v2/google/cloud/dialogflow_v2/services/conversation_models/transports/grpc.py delete mode 100644 owl-bot-staging/v2/google/cloud/dialogflow_v2/services/conversation_models/transports/grpc_asyncio.py delete mode 100644 owl-bot-staging/v2/google/cloud/dialogflow_v2/services/conversation_models/transports/rest.py delete mode 100644 owl-bot-staging/v2/google/cloud/dialogflow_v2/services/conversation_profiles/__init__.py delete mode 100644 owl-bot-staging/v2/google/cloud/dialogflow_v2/services/conversation_profiles/async_client.py delete mode 100644 owl-bot-staging/v2/google/cloud/dialogflow_v2/services/conversation_profiles/client.py delete mode 100644 owl-bot-staging/v2/google/cloud/dialogflow_v2/services/conversation_profiles/pagers.py delete mode 100644 owl-bot-staging/v2/google/cloud/dialogflow_v2/services/conversation_profiles/transports/__init__.py delete mode 100644 owl-bot-staging/v2/google/cloud/dialogflow_v2/services/conversation_profiles/transports/base.py delete mode 100644 owl-bot-staging/v2/google/cloud/dialogflow_v2/services/conversation_profiles/transports/grpc.py delete mode 100644 owl-bot-staging/v2/google/cloud/dialogflow_v2/services/conversation_profiles/transports/grpc_asyncio.py delete mode 100644 owl-bot-staging/v2/google/cloud/dialogflow_v2/services/conversation_profiles/transports/rest.py delete mode 100644 owl-bot-staging/v2/google/cloud/dialogflow_v2/services/conversations/__init__.py delete mode 100644 owl-bot-staging/v2/google/cloud/dialogflow_v2/services/conversations/async_client.py delete mode 100644 owl-bot-staging/v2/google/cloud/dialogflow_v2/services/conversations/client.py delete mode 100644 owl-bot-staging/v2/google/cloud/dialogflow_v2/services/conversations/pagers.py delete mode 100644 owl-bot-staging/v2/google/cloud/dialogflow_v2/services/conversations/transports/__init__.py delete mode 100644 owl-bot-staging/v2/google/cloud/dialogflow_v2/services/conversations/transports/base.py delete mode 100644 owl-bot-staging/v2/google/cloud/dialogflow_v2/services/conversations/transports/grpc.py delete mode 100644 owl-bot-staging/v2/google/cloud/dialogflow_v2/services/conversations/transports/grpc_asyncio.py delete mode 100644 owl-bot-staging/v2/google/cloud/dialogflow_v2/services/conversations/transports/rest.py delete mode 100644 owl-bot-staging/v2/google/cloud/dialogflow_v2/services/documents/__init__.py delete mode 100644 owl-bot-staging/v2/google/cloud/dialogflow_v2/services/documents/async_client.py delete mode 100644 owl-bot-staging/v2/google/cloud/dialogflow_v2/services/documents/client.py delete mode 100644 owl-bot-staging/v2/google/cloud/dialogflow_v2/services/documents/pagers.py delete mode 100644 owl-bot-staging/v2/google/cloud/dialogflow_v2/services/documents/transports/__init__.py delete mode 100644 owl-bot-staging/v2/google/cloud/dialogflow_v2/services/documents/transports/base.py delete mode 100644 owl-bot-staging/v2/google/cloud/dialogflow_v2/services/documents/transports/grpc.py delete mode 100644 owl-bot-staging/v2/google/cloud/dialogflow_v2/services/documents/transports/grpc_asyncio.py delete mode 100644 owl-bot-staging/v2/google/cloud/dialogflow_v2/services/documents/transports/rest.py delete mode 100644 owl-bot-staging/v2/google/cloud/dialogflow_v2/services/entity_types/__init__.py delete mode 100644 owl-bot-staging/v2/google/cloud/dialogflow_v2/services/entity_types/async_client.py delete mode 100644 owl-bot-staging/v2/google/cloud/dialogflow_v2/services/entity_types/client.py delete mode 100644 owl-bot-staging/v2/google/cloud/dialogflow_v2/services/entity_types/pagers.py delete mode 100644 owl-bot-staging/v2/google/cloud/dialogflow_v2/services/entity_types/transports/__init__.py delete mode 100644 owl-bot-staging/v2/google/cloud/dialogflow_v2/services/entity_types/transports/base.py delete mode 100644 owl-bot-staging/v2/google/cloud/dialogflow_v2/services/entity_types/transports/grpc.py delete mode 100644 owl-bot-staging/v2/google/cloud/dialogflow_v2/services/entity_types/transports/grpc_asyncio.py delete mode 100644 owl-bot-staging/v2/google/cloud/dialogflow_v2/services/entity_types/transports/rest.py delete mode 100644 owl-bot-staging/v2/google/cloud/dialogflow_v2/services/environments/__init__.py delete mode 100644 owl-bot-staging/v2/google/cloud/dialogflow_v2/services/environments/async_client.py delete mode 100644 owl-bot-staging/v2/google/cloud/dialogflow_v2/services/environments/client.py delete mode 100644 owl-bot-staging/v2/google/cloud/dialogflow_v2/services/environments/pagers.py delete mode 100644 owl-bot-staging/v2/google/cloud/dialogflow_v2/services/environments/transports/__init__.py delete mode 100644 owl-bot-staging/v2/google/cloud/dialogflow_v2/services/environments/transports/base.py delete mode 100644 owl-bot-staging/v2/google/cloud/dialogflow_v2/services/environments/transports/grpc.py delete mode 100644 owl-bot-staging/v2/google/cloud/dialogflow_v2/services/environments/transports/grpc_asyncio.py delete mode 100644 owl-bot-staging/v2/google/cloud/dialogflow_v2/services/environments/transports/rest.py delete mode 100644 owl-bot-staging/v2/google/cloud/dialogflow_v2/services/fulfillments/__init__.py delete mode 100644 owl-bot-staging/v2/google/cloud/dialogflow_v2/services/fulfillments/async_client.py delete mode 100644 owl-bot-staging/v2/google/cloud/dialogflow_v2/services/fulfillments/client.py delete mode 100644 owl-bot-staging/v2/google/cloud/dialogflow_v2/services/fulfillments/transports/__init__.py delete mode 100644 owl-bot-staging/v2/google/cloud/dialogflow_v2/services/fulfillments/transports/base.py delete mode 100644 owl-bot-staging/v2/google/cloud/dialogflow_v2/services/fulfillments/transports/grpc.py delete mode 100644 owl-bot-staging/v2/google/cloud/dialogflow_v2/services/fulfillments/transports/grpc_asyncio.py delete mode 100644 owl-bot-staging/v2/google/cloud/dialogflow_v2/services/fulfillments/transports/rest.py delete mode 100644 owl-bot-staging/v2/google/cloud/dialogflow_v2/services/intents/__init__.py delete mode 100644 owl-bot-staging/v2/google/cloud/dialogflow_v2/services/intents/async_client.py delete mode 100644 owl-bot-staging/v2/google/cloud/dialogflow_v2/services/intents/client.py delete mode 100644 owl-bot-staging/v2/google/cloud/dialogflow_v2/services/intents/pagers.py delete mode 100644 owl-bot-staging/v2/google/cloud/dialogflow_v2/services/intents/transports/__init__.py delete mode 100644 owl-bot-staging/v2/google/cloud/dialogflow_v2/services/intents/transports/base.py delete mode 100644 owl-bot-staging/v2/google/cloud/dialogflow_v2/services/intents/transports/grpc.py delete mode 100644 owl-bot-staging/v2/google/cloud/dialogflow_v2/services/intents/transports/grpc_asyncio.py delete mode 100644 owl-bot-staging/v2/google/cloud/dialogflow_v2/services/intents/transports/rest.py delete mode 100644 owl-bot-staging/v2/google/cloud/dialogflow_v2/services/knowledge_bases/__init__.py delete mode 100644 owl-bot-staging/v2/google/cloud/dialogflow_v2/services/knowledge_bases/async_client.py delete mode 100644 owl-bot-staging/v2/google/cloud/dialogflow_v2/services/knowledge_bases/client.py delete mode 100644 owl-bot-staging/v2/google/cloud/dialogflow_v2/services/knowledge_bases/pagers.py delete mode 100644 owl-bot-staging/v2/google/cloud/dialogflow_v2/services/knowledge_bases/transports/__init__.py delete mode 100644 owl-bot-staging/v2/google/cloud/dialogflow_v2/services/knowledge_bases/transports/base.py delete mode 100644 owl-bot-staging/v2/google/cloud/dialogflow_v2/services/knowledge_bases/transports/grpc.py delete mode 100644 owl-bot-staging/v2/google/cloud/dialogflow_v2/services/knowledge_bases/transports/grpc_asyncio.py delete mode 100644 owl-bot-staging/v2/google/cloud/dialogflow_v2/services/knowledge_bases/transports/rest.py delete mode 100644 owl-bot-staging/v2/google/cloud/dialogflow_v2/services/participants/__init__.py delete mode 100644 owl-bot-staging/v2/google/cloud/dialogflow_v2/services/participants/async_client.py delete mode 100644 owl-bot-staging/v2/google/cloud/dialogflow_v2/services/participants/client.py delete mode 100644 owl-bot-staging/v2/google/cloud/dialogflow_v2/services/participants/pagers.py delete mode 100644 owl-bot-staging/v2/google/cloud/dialogflow_v2/services/participants/transports/__init__.py delete mode 100644 owl-bot-staging/v2/google/cloud/dialogflow_v2/services/participants/transports/base.py delete mode 100644 owl-bot-staging/v2/google/cloud/dialogflow_v2/services/participants/transports/grpc.py delete mode 100644 owl-bot-staging/v2/google/cloud/dialogflow_v2/services/participants/transports/grpc_asyncio.py delete mode 100644 owl-bot-staging/v2/google/cloud/dialogflow_v2/services/participants/transports/rest.py delete mode 100644 owl-bot-staging/v2/google/cloud/dialogflow_v2/services/session_entity_types/__init__.py delete mode 100644 owl-bot-staging/v2/google/cloud/dialogflow_v2/services/session_entity_types/async_client.py delete mode 100644 owl-bot-staging/v2/google/cloud/dialogflow_v2/services/session_entity_types/client.py delete mode 100644 owl-bot-staging/v2/google/cloud/dialogflow_v2/services/session_entity_types/pagers.py delete mode 100644 owl-bot-staging/v2/google/cloud/dialogflow_v2/services/session_entity_types/transports/__init__.py delete mode 100644 owl-bot-staging/v2/google/cloud/dialogflow_v2/services/session_entity_types/transports/base.py delete mode 100644 owl-bot-staging/v2/google/cloud/dialogflow_v2/services/session_entity_types/transports/grpc.py delete mode 100644 owl-bot-staging/v2/google/cloud/dialogflow_v2/services/session_entity_types/transports/grpc_asyncio.py delete mode 100644 owl-bot-staging/v2/google/cloud/dialogflow_v2/services/session_entity_types/transports/rest.py delete mode 100644 owl-bot-staging/v2/google/cloud/dialogflow_v2/services/sessions/__init__.py delete mode 100644 owl-bot-staging/v2/google/cloud/dialogflow_v2/services/sessions/async_client.py delete mode 100644 owl-bot-staging/v2/google/cloud/dialogflow_v2/services/sessions/client.py delete mode 100644 owl-bot-staging/v2/google/cloud/dialogflow_v2/services/sessions/transports/__init__.py delete mode 100644 owl-bot-staging/v2/google/cloud/dialogflow_v2/services/sessions/transports/base.py delete mode 100644 owl-bot-staging/v2/google/cloud/dialogflow_v2/services/sessions/transports/grpc.py delete mode 100644 owl-bot-staging/v2/google/cloud/dialogflow_v2/services/sessions/transports/grpc_asyncio.py delete mode 100644 owl-bot-staging/v2/google/cloud/dialogflow_v2/services/sessions/transports/rest.py delete mode 100644 owl-bot-staging/v2/google/cloud/dialogflow_v2/services/versions/__init__.py delete mode 100644 owl-bot-staging/v2/google/cloud/dialogflow_v2/services/versions/async_client.py delete mode 100644 owl-bot-staging/v2/google/cloud/dialogflow_v2/services/versions/client.py delete mode 100644 owl-bot-staging/v2/google/cloud/dialogflow_v2/services/versions/pagers.py delete mode 100644 owl-bot-staging/v2/google/cloud/dialogflow_v2/services/versions/transports/__init__.py delete mode 100644 owl-bot-staging/v2/google/cloud/dialogflow_v2/services/versions/transports/base.py delete mode 100644 owl-bot-staging/v2/google/cloud/dialogflow_v2/services/versions/transports/grpc.py delete mode 100644 owl-bot-staging/v2/google/cloud/dialogflow_v2/services/versions/transports/grpc_asyncio.py delete mode 100644 owl-bot-staging/v2/google/cloud/dialogflow_v2/services/versions/transports/rest.py delete mode 100644 owl-bot-staging/v2/google/cloud/dialogflow_v2/types/__init__.py delete mode 100644 owl-bot-staging/v2/google/cloud/dialogflow_v2/types/agent.py delete mode 100644 owl-bot-staging/v2/google/cloud/dialogflow_v2/types/answer_record.py delete mode 100644 owl-bot-staging/v2/google/cloud/dialogflow_v2/types/audio_config.py delete mode 100644 owl-bot-staging/v2/google/cloud/dialogflow_v2/types/context.py delete mode 100644 owl-bot-staging/v2/google/cloud/dialogflow_v2/types/conversation.py delete mode 100644 owl-bot-staging/v2/google/cloud/dialogflow_v2/types/conversation_dataset.py delete mode 100644 owl-bot-staging/v2/google/cloud/dialogflow_v2/types/conversation_event.py delete mode 100644 owl-bot-staging/v2/google/cloud/dialogflow_v2/types/conversation_model.py delete mode 100644 owl-bot-staging/v2/google/cloud/dialogflow_v2/types/conversation_profile.py delete mode 100644 owl-bot-staging/v2/google/cloud/dialogflow_v2/types/document.py delete mode 100644 owl-bot-staging/v2/google/cloud/dialogflow_v2/types/entity_type.py delete mode 100644 owl-bot-staging/v2/google/cloud/dialogflow_v2/types/environment.py delete mode 100644 owl-bot-staging/v2/google/cloud/dialogflow_v2/types/fulfillment.py delete mode 100644 owl-bot-staging/v2/google/cloud/dialogflow_v2/types/gcs.py delete mode 100644 owl-bot-staging/v2/google/cloud/dialogflow_v2/types/human_agent_assistant_event.py delete mode 100644 owl-bot-staging/v2/google/cloud/dialogflow_v2/types/intent.py delete mode 100644 owl-bot-staging/v2/google/cloud/dialogflow_v2/types/knowledge_base.py delete mode 100644 owl-bot-staging/v2/google/cloud/dialogflow_v2/types/participant.py delete mode 100644 owl-bot-staging/v2/google/cloud/dialogflow_v2/types/session.py delete mode 100644 owl-bot-staging/v2/google/cloud/dialogflow_v2/types/session_entity_type.py delete mode 100644 owl-bot-staging/v2/google/cloud/dialogflow_v2/types/validation_result.py delete mode 100644 owl-bot-staging/v2/google/cloud/dialogflow_v2/types/version.py delete mode 100644 owl-bot-staging/v2/google/cloud/dialogflow_v2/types/webhook.py delete mode 100644 owl-bot-staging/v2/mypy.ini delete mode 100644 owl-bot-staging/v2/noxfile.py delete mode 100644 owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_agents_delete_agent_async.py delete mode 100644 owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_agents_delete_agent_sync.py delete mode 100644 owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_agents_export_agent_async.py delete mode 100644 owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_agents_export_agent_sync.py delete mode 100644 owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_agents_get_agent_async.py delete mode 100644 owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_agents_get_agent_sync.py delete mode 100644 owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_agents_get_validation_result_async.py delete mode 100644 owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_agents_get_validation_result_sync.py delete mode 100644 owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_agents_import_agent_async.py delete mode 100644 owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_agents_import_agent_sync.py delete mode 100644 owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_agents_restore_agent_async.py delete mode 100644 owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_agents_restore_agent_sync.py delete mode 100644 owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_agents_search_agents_async.py delete mode 100644 owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_agents_search_agents_sync.py delete mode 100644 owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_agents_set_agent_async.py delete mode 100644 owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_agents_set_agent_sync.py delete mode 100644 owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_agents_train_agent_async.py delete mode 100644 owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_agents_train_agent_sync.py delete mode 100644 owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_answer_records_list_answer_records_async.py delete mode 100644 owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_answer_records_list_answer_records_sync.py delete mode 100644 owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_answer_records_update_answer_record_async.py delete mode 100644 owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_answer_records_update_answer_record_sync.py delete mode 100644 owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_contexts_create_context_async.py delete mode 100644 owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_contexts_create_context_sync.py delete mode 100644 owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_contexts_delete_all_contexts_async.py delete mode 100644 owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_contexts_delete_all_contexts_sync.py delete mode 100644 owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_contexts_delete_context_async.py delete mode 100644 owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_contexts_delete_context_sync.py delete mode 100644 owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_contexts_get_context_async.py delete mode 100644 owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_contexts_get_context_sync.py delete mode 100644 owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_contexts_list_contexts_async.py delete mode 100644 owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_contexts_list_contexts_sync.py delete mode 100644 owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_contexts_update_context_async.py delete mode 100644 owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_contexts_update_context_sync.py delete mode 100644 owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_conversation_datasets_create_conversation_dataset_async.py delete mode 100644 owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_conversation_datasets_create_conversation_dataset_sync.py delete mode 100644 owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_conversation_datasets_delete_conversation_dataset_async.py delete mode 100644 owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_conversation_datasets_delete_conversation_dataset_sync.py delete mode 100644 owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_conversation_datasets_get_conversation_dataset_async.py delete mode 100644 owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_conversation_datasets_get_conversation_dataset_sync.py delete mode 100644 owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_conversation_datasets_import_conversation_data_async.py delete mode 100644 owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_conversation_datasets_import_conversation_data_sync.py delete mode 100644 owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_conversation_datasets_list_conversation_datasets_async.py delete mode 100644 owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_conversation_datasets_list_conversation_datasets_sync.py delete mode 100644 owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_conversation_models_create_conversation_model_async.py delete mode 100644 owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_conversation_models_create_conversation_model_evaluation_async.py delete mode 100644 owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_conversation_models_create_conversation_model_evaluation_sync.py delete mode 100644 owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_conversation_models_create_conversation_model_sync.py delete mode 100644 owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_conversation_models_delete_conversation_model_async.py delete mode 100644 owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_conversation_models_delete_conversation_model_sync.py delete mode 100644 owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_conversation_models_deploy_conversation_model_async.py delete mode 100644 owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_conversation_models_deploy_conversation_model_sync.py delete mode 100644 owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_conversation_models_get_conversation_model_async.py delete mode 100644 owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_conversation_models_get_conversation_model_evaluation_async.py delete mode 100644 owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_conversation_models_get_conversation_model_evaluation_sync.py delete mode 100644 owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_conversation_models_get_conversation_model_sync.py delete mode 100644 owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_conversation_models_list_conversation_model_evaluations_async.py delete mode 100644 owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_conversation_models_list_conversation_model_evaluations_sync.py delete mode 100644 owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_conversation_models_list_conversation_models_async.py delete mode 100644 owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_conversation_models_list_conversation_models_sync.py delete mode 100644 owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_conversation_models_undeploy_conversation_model_async.py delete mode 100644 owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_conversation_models_undeploy_conversation_model_sync.py delete mode 100644 owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_conversation_profiles_clear_suggestion_feature_config_async.py delete mode 100644 owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_conversation_profiles_clear_suggestion_feature_config_sync.py delete mode 100644 owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_conversation_profiles_create_conversation_profile_async.py delete mode 100644 owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_conversation_profiles_create_conversation_profile_sync.py delete mode 100644 owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_conversation_profiles_delete_conversation_profile_async.py delete mode 100644 owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_conversation_profiles_delete_conversation_profile_sync.py delete mode 100644 owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_conversation_profiles_get_conversation_profile_async.py delete mode 100644 owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_conversation_profiles_get_conversation_profile_sync.py delete mode 100644 owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_conversation_profiles_list_conversation_profiles_async.py delete mode 100644 owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_conversation_profiles_list_conversation_profiles_sync.py delete mode 100644 owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_conversation_profiles_set_suggestion_feature_config_async.py delete mode 100644 owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_conversation_profiles_set_suggestion_feature_config_sync.py delete mode 100644 owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_conversation_profiles_update_conversation_profile_async.py delete mode 100644 owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_conversation_profiles_update_conversation_profile_sync.py delete mode 100644 owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_conversations_complete_conversation_async.py delete mode 100644 owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_conversations_complete_conversation_sync.py delete mode 100644 owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_conversations_create_conversation_async.py delete mode 100644 owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_conversations_create_conversation_sync.py delete mode 100644 owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_conversations_get_conversation_async.py delete mode 100644 owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_conversations_get_conversation_sync.py delete mode 100644 owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_conversations_list_conversations_async.py delete mode 100644 owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_conversations_list_conversations_sync.py delete mode 100644 owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_conversations_list_messages_async.py delete mode 100644 owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_conversations_list_messages_sync.py delete mode 100644 owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_conversations_suggest_conversation_summary_async.py delete mode 100644 owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_conversations_suggest_conversation_summary_sync.py delete mode 100644 owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_documents_create_document_async.py delete mode 100644 owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_documents_create_document_sync.py delete mode 100644 owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_documents_delete_document_async.py delete mode 100644 owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_documents_delete_document_sync.py delete mode 100644 owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_documents_export_document_async.py delete mode 100644 owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_documents_export_document_sync.py delete mode 100644 owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_documents_get_document_async.py delete mode 100644 owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_documents_get_document_sync.py delete mode 100644 owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_documents_import_documents_async.py delete mode 100644 owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_documents_import_documents_sync.py delete mode 100644 owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_documents_list_documents_async.py delete mode 100644 owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_documents_list_documents_sync.py delete mode 100644 owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_documents_reload_document_async.py delete mode 100644 owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_documents_reload_document_sync.py delete mode 100644 owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_documents_update_document_async.py delete mode 100644 owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_documents_update_document_sync.py delete mode 100644 owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_entity_types_batch_create_entities_async.py delete mode 100644 owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_entity_types_batch_create_entities_sync.py delete mode 100644 owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_entity_types_batch_delete_entities_async.py delete mode 100644 owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_entity_types_batch_delete_entities_sync.py delete mode 100644 owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_entity_types_batch_delete_entity_types_async.py delete mode 100644 owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_entity_types_batch_delete_entity_types_sync.py delete mode 100644 owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_entity_types_batch_update_entities_async.py delete mode 100644 owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_entity_types_batch_update_entities_sync.py delete mode 100644 owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_entity_types_batch_update_entity_types_async.py delete mode 100644 owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_entity_types_batch_update_entity_types_sync.py delete mode 100644 owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_entity_types_create_entity_type_async.py delete mode 100644 owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_entity_types_create_entity_type_sync.py delete mode 100644 owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_entity_types_delete_entity_type_async.py delete mode 100644 owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_entity_types_delete_entity_type_sync.py delete mode 100644 owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_entity_types_get_entity_type_async.py delete mode 100644 owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_entity_types_get_entity_type_sync.py delete mode 100644 owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_entity_types_list_entity_types_async.py delete mode 100644 owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_entity_types_list_entity_types_sync.py delete mode 100644 owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_entity_types_update_entity_type_async.py delete mode 100644 owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_entity_types_update_entity_type_sync.py delete mode 100644 owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_environments_create_environment_async.py delete mode 100644 owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_environments_create_environment_sync.py delete mode 100644 owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_environments_delete_environment_async.py delete mode 100644 owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_environments_delete_environment_sync.py delete mode 100644 owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_environments_get_environment_async.py delete mode 100644 owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_environments_get_environment_history_async.py delete mode 100644 owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_environments_get_environment_history_sync.py delete mode 100644 owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_environments_get_environment_sync.py delete mode 100644 owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_environments_list_environments_async.py delete mode 100644 owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_environments_list_environments_sync.py delete mode 100644 owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_environments_update_environment_async.py delete mode 100644 owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_environments_update_environment_sync.py delete mode 100644 owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_fulfillments_get_fulfillment_async.py delete mode 100644 owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_fulfillments_get_fulfillment_sync.py delete mode 100644 owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_fulfillments_update_fulfillment_async.py delete mode 100644 owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_fulfillments_update_fulfillment_sync.py delete mode 100644 owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_intents_batch_delete_intents_async.py delete mode 100644 owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_intents_batch_delete_intents_sync.py delete mode 100644 owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_intents_batch_update_intents_async.py delete mode 100644 owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_intents_batch_update_intents_sync.py delete mode 100644 owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_intents_create_intent_async.py delete mode 100644 owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_intents_create_intent_sync.py delete mode 100644 owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_intents_delete_intent_async.py delete mode 100644 owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_intents_delete_intent_sync.py delete mode 100644 owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_intents_get_intent_async.py delete mode 100644 owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_intents_get_intent_sync.py delete mode 100644 owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_intents_list_intents_async.py delete mode 100644 owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_intents_list_intents_sync.py delete mode 100644 owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_intents_update_intent_async.py delete mode 100644 owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_intents_update_intent_sync.py delete mode 100644 owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_knowledge_bases_create_knowledge_base_async.py delete mode 100644 owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_knowledge_bases_create_knowledge_base_sync.py delete mode 100644 owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_knowledge_bases_delete_knowledge_base_async.py delete mode 100644 owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_knowledge_bases_delete_knowledge_base_sync.py delete mode 100644 owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_knowledge_bases_get_knowledge_base_async.py delete mode 100644 owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_knowledge_bases_get_knowledge_base_sync.py delete mode 100644 owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_knowledge_bases_list_knowledge_bases_async.py delete mode 100644 owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_knowledge_bases_list_knowledge_bases_sync.py delete mode 100644 owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_knowledge_bases_update_knowledge_base_async.py delete mode 100644 owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_knowledge_bases_update_knowledge_base_sync.py delete mode 100644 owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_participants_analyze_content_async.py delete mode 100644 owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_participants_analyze_content_sync.py delete mode 100644 owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_participants_create_participant_async.py delete mode 100644 owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_participants_create_participant_sync.py delete mode 100644 owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_participants_get_participant_async.py delete mode 100644 owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_participants_get_participant_sync.py delete mode 100644 owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_participants_list_participants_async.py delete mode 100644 owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_participants_list_participants_sync.py delete mode 100644 owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_participants_streaming_analyze_content_async.py delete mode 100644 owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_participants_streaming_analyze_content_sync.py delete mode 100644 owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_participants_suggest_articles_async.py delete mode 100644 owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_participants_suggest_articles_sync.py delete mode 100644 owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_participants_suggest_faq_answers_async.py delete mode 100644 owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_participants_suggest_faq_answers_sync.py delete mode 100644 owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_participants_suggest_smart_replies_async.py delete mode 100644 owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_participants_suggest_smart_replies_sync.py delete mode 100644 owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_participants_update_participant_async.py delete mode 100644 owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_participants_update_participant_sync.py delete mode 100644 owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_session_entity_types_create_session_entity_type_async.py delete mode 100644 owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_session_entity_types_create_session_entity_type_sync.py delete mode 100644 owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_session_entity_types_delete_session_entity_type_async.py delete mode 100644 owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_session_entity_types_delete_session_entity_type_sync.py delete mode 100644 owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_session_entity_types_get_session_entity_type_async.py delete mode 100644 owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_session_entity_types_get_session_entity_type_sync.py delete mode 100644 owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_session_entity_types_list_session_entity_types_async.py delete mode 100644 owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_session_entity_types_list_session_entity_types_sync.py delete mode 100644 owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_session_entity_types_update_session_entity_type_async.py delete mode 100644 owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_session_entity_types_update_session_entity_type_sync.py delete mode 100644 owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_sessions_detect_intent_async.py delete mode 100644 owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_sessions_detect_intent_sync.py delete mode 100644 owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_sessions_streaming_detect_intent_async.py delete mode 100644 owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_sessions_streaming_detect_intent_sync.py delete mode 100644 owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_versions_create_version_async.py delete mode 100644 owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_versions_create_version_sync.py delete mode 100644 owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_versions_delete_version_async.py delete mode 100644 owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_versions_delete_version_sync.py delete mode 100644 owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_versions_get_version_async.py delete mode 100644 owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_versions_get_version_sync.py delete mode 100644 owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_versions_list_versions_async.py delete mode 100644 owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_versions_list_versions_sync.py delete mode 100644 owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_versions_update_version_async.py delete mode 100644 owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_versions_update_version_sync.py delete mode 100644 owl-bot-staging/v2/samples/generated_samples/snippet_metadata_google.cloud.dialogflow.v2.json delete mode 100644 owl-bot-staging/v2/scripts/fixup_dialogflow_v2_keywords.py delete mode 100644 owl-bot-staging/v2/setup.py delete mode 100644 owl-bot-staging/v2/testing/constraints-3.10.txt delete mode 100644 owl-bot-staging/v2/testing/constraints-3.11.txt delete mode 100644 owl-bot-staging/v2/testing/constraints-3.12.txt delete mode 100644 owl-bot-staging/v2/testing/constraints-3.7.txt delete mode 100644 owl-bot-staging/v2/testing/constraints-3.8.txt delete mode 100644 owl-bot-staging/v2/testing/constraints-3.9.txt delete mode 100644 owl-bot-staging/v2/tests/__init__.py delete mode 100644 owl-bot-staging/v2/tests/unit/__init__.py delete mode 100644 owl-bot-staging/v2/tests/unit/gapic/__init__.py delete mode 100644 owl-bot-staging/v2/tests/unit/gapic/dialogflow_v2/__init__.py delete mode 100644 owl-bot-staging/v2/tests/unit/gapic/dialogflow_v2/test_agents.py delete mode 100644 owl-bot-staging/v2/tests/unit/gapic/dialogflow_v2/test_answer_records.py delete mode 100644 owl-bot-staging/v2/tests/unit/gapic/dialogflow_v2/test_contexts.py delete mode 100644 owl-bot-staging/v2/tests/unit/gapic/dialogflow_v2/test_conversation_datasets.py delete mode 100644 owl-bot-staging/v2/tests/unit/gapic/dialogflow_v2/test_conversation_models.py delete mode 100644 owl-bot-staging/v2/tests/unit/gapic/dialogflow_v2/test_conversation_profiles.py delete mode 100644 owl-bot-staging/v2/tests/unit/gapic/dialogflow_v2/test_conversations.py delete mode 100644 owl-bot-staging/v2/tests/unit/gapic/dialogflow_v2/test_documents.py delete mode 100644 owl-bot-staging/v2/tests/unit/gapic/dialogflow_v2/test_entity_types.py delete mode 100644 owl-bot-staging/v2/tests/unit/gapic/dialogflow_v2/test_environments.py delete mode 100644 owl-bot-staging/v2/tests/unit/gapic/dialogflow_v2/test_fulfillments.py delete mode 100644 owl-bot-staging/v2/tests/unit/gapic/dialogflow_v2/test_intents.py delete mode 100644 owl-bot-staging/v2/tests/unit/gapic/dialogflow_v2/test_knowledge_bases.py delete mode 100644 owl-bot-staging/v2/tests/unit/gapic/dialogflow_v2/test_participants.py delete mode 100644 owl-bot-staging/v2/tests/unit/gapic/dialogflow_v2/test_session_entity_types.py delete mode 100644 owl-bot-staging/v2/tests/unit/gapic/dialogflow_v2/test_sessions.py delete mode 100644 owl-bot-staging/v2/tests/unit/gapic/dialogflow_v2/test_versions.py delete mode 100644 owl-bot-staging/v2beta1/.coveragerc delete mode 100644 owl-bot-staging/v2beta1/.flake8 delete mode 100644 owl-bot-staging/v2beta1/MANIFEST.in delete mode 100644 owl-bot-staging/v2beta1/README.rst delete mode 100644 owl-bot-staging/v2beta1/docs/conf.py delete mode 100644 owl-bot-staging/v2beta1/docs/dialogflow_v2beta1/agents.rst delete mode 100644 owl-bot-staging/v2beta1/docs/dialogflow_v2beta1/answer_records.rst delete mode 100644 owl-bot-staging/v2beta1/docs/dialogflow_v2beta1/contexts.rst delete mode 100644 owl-bot-staging/v2beta1/docs/dialogflow_v2beta1/conversation_profiles.rst delete mode 100644 owl-bot-staging/v2beta1/docs/dialogflow_v2beta1/conversations.rst delete mode 100644 owl-bot-staging/v2beta1/docs/dialogflow_v2beta1/documents.rst delete mode 100644 owl-bot-staging/v2beta1/docs/dialogflow_v2beta1/entity_types.rst delete mode 100644 owl-bot-staging/v2beta1/docs/dialogflow_v2beta1/environments.rst delete mode 100644 owl-bot-staging/v2beta1/docs/dialogflow_v2beta1/fulfillments.rst delete mode 100644 owl-bot-staging/v2beta1/docs/dialogflow_v2beta1/intents.rst delete mode 100644 owl-bot-staging/v2beta1/docs/dialogflow_v2beta1/knowledge_bases.rst delete mode 100644 owl-bot-staging/v2beta1/docs/dialogflow_v2beta1/participants.rst delete mode 100644 owl-bot-staging/v2beta1/docs/dialogflow_v2beta1/services.rst delete mode 100644 owl-bot-staging/v2beta1/docs/dialogflow_v2beta1/session_entity_types.rst delete mode 100644 owl-bot-staging/v2beta1/docs/dialogflow_v2beta1/sessions.rst delete mode 100644 owl-bot-staging/v2beta1/docs/dialogflow_v2beta1/types.rst delete mode 100644 owl-bot-staging/v2beta1/docs/dialogflow_v2beta1/versions.rst delete mode 100644 owl-bot-staging/v2beta1/docs/index.rst delete mode 100644 owl-bot-staging/v2beta1/google/cloud/dialogflow/__init__.py delete mode 100644 owl-bot-staging/v2beta1/google/cloud/dialogflow/gapic_version.py delete mode 100644 owl-bot-staging/v2beta1/google/cloud/dialogflow/py.typed delete mode 100644 owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/__init__.py delete mode 100644 owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/gapic_metadata.json delete mode 100644 owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/gapic_version.py delete mode 100644 owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/py.typed delete mode 100644 owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/__init__.py delete mode 100644 owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/agents/__init__.py delete mode 100644 owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/agents/async_client.py delete mode 100644 owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/agents/client.py delete mode 100644 owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/agents/pagers.py delete mode 100644 owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/agents/transports/__init__.py delete mode 100644 owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/agents/transports/base.py delete mode 100644 owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/agents/transports/grpc.py delete mode 100644 owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/agents/transports/grpc_asyncio.py delete mode 100644 owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/agents/transports/rest.py delete mode 100644 owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/answer_records/__init__.py delete mode 100644 owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/answer_records/async_client.py delete mode 100644 owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/answer_records/client.py delete mode 100644 owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/answer_records/pagers.py delete mode 100644 owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/answer_records/transports/__init__.py delete mode 100644 owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/answer_records/transports/base.py delete mode 100644 owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/answer_records/transports/grpc.py delete mode 100644 owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/answer_records/transports/grpc_asyncio.py delete mode 100644 owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/answer_records/transports/rest.py delete mode 100644 owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/contexts/__init__.py delete mode 100644 owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/contexts/async_client.py delete mode 100644 owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/contexts/client.py delete mode 100644 owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/contexts/pagers.py delete mode 100644 owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/contexts/transports/__init__.py delete mode 100644 owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/contexts/transports/base.py delete mode 100644 owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/contexts/transports/grpc.py delete mode 100644 owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/contexts/transports/grpc_asyncio.py delete mode 100644 owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/contexts/transports/rest.py delete mode 100644 owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/conversation_profiles/__init__.py delete mode 100644 owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/conversation_profiles/async_client.py delete mode 100644 owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/conversation_profiles/client.py delete mode 100644 owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/conversation_profiles/pagers.py delete mode 100644 owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/conversation_profiles/transports/__init__.py delete mode 100644 owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/conversation_profiles/transports/base.py delete mode 100644 owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/conversation_profiles/transports/grpc.py delete mode 100644 owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/conversation_profiles/transports/grpc_asyncio.py delete mode 100644 owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/conversation_profiles/transports/rest.py delete mode 100644 owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/conversations/__init__.py delete mode 100644 owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/conversations/async_client.py delete mode 100644 owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/conversations/client.py delete mode 100644 owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/conversations/pagers.py delete mode 100644 owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/conversations/transports/__init__.py delete mode 100644 owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/conversations/transports/base.py delete mode 100644 owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/conversations/transports/grpc.py delete mode 100644 owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/conversations/transports/grpc_asyncio.py delete mode 100644 owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/conversations/transports/rest.py delete mode 100644 owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/documents/__init__.py delete mode 100644 owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/documents/async_client.py delete mode 100644 owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/documents/client.py delete mode 100644 owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/documents/pagers.py delete mode 100644 owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/documents/transports/__init__.py delete mode 100644 owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/documents/transports/base.py delete mode 100644 owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/documents/transports/grpc.py delete mode 100644 owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/documents/transports/grpc_asyncio.py delete mode 100644 owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/documents/transports/rest.py delete mode 100644 owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/entity_types/__init__.py delete mode 100644 owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/entity_types/async_client.py delete mode 100644 owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/entity_types/client.py delete mode 100644 owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/entity_types/pagers.py delete mode 100644 owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/entity_types/transports/__init__.py delete mode 100644 owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/entity_types/transports/base.py delete mode 100644 owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/entity_types/transports/grpc.py delete mode 100644 owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/entity_types/transports/grpc_asyncio.py delete mode 100644 owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/entity_types/transports/rest.py delete mode 100644 owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/environments/__init__.py delete mode 100644 owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/environments/async_client.py delete mode 100644 owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/environments/client.py delete mode 100644 owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/environments/pagers.py delete mode 100644 owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/environments/transports/__init__.py delete mode 100644 owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/environments/transports/base.py delete mode 100644 owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/environments/transports/grpc.py delete mode 100644 owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/environments/transports/grpc_asyncio.py delete mode 100644 owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/environments/transports/rest.py delete mode 100644 owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/fulfillments/__init__.py delete mode 100644 owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/fulfillments/async_client.py delete mode 100644 owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/fulfillments/client.py delete mode 100644 owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/fulfillments/transports/__init__.py delete mode 100644 owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/fulfillments/transports/base.py delete mode 100644 owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/fulfillments/transports/grpc.py delete mode 100644 owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/fulfillments/transports/grpc_asyncio.py delete mode 100644 owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/fulfillments/transports/rest.py delete mode 100644 owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/intents/__init__.py delete mode 100644 owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/intents/async_client.py delete mode 100644 owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/intents/client.py delete mode 100644 owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/intents/pagers.py delete mode 100644 owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/intents/transports/__init__.py delete mode 100644 owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/intents/transports/base.py delete mode 100644 owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/intents/transports/grpc.py delete mode 100644 owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/intents/transports/grpc_asyncio.py delete mode 100644 owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/intents/transports/rest.py delete mode 100644 owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/knowledge_bases/__init__.py delete mode 100644 owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/knowledge_bases/async_client.py delete mode 100644 owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/knowledge_bases/client.py delete mode 100644 owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/knowledge_bases/pagers.py delete mode 100644 owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/knowledge_bases/transports/__init__.py delete mode 100644 owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/knowledge_bases/transports/base.py delete mode 100644 owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/knowledge_bases/transports/grpc.py delete mode 100644 owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/knowledge_bases/transports/grpc_asyncio.py delete mode 100644 owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/knowledge_bases/transports/rest.py delete mode 100644 owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/participants/__init__.py delete mode 100644 owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/participants/async_client.py delete mode 100644 owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/participants/client.py delete mode 100644 owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/participants/pagers.py delete mode 100644 owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/participants/transports/__init__.py delete mode 100644 owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/participants/transports/base.py delete mode 100644 owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/participants/transports/grpc.py delete mode 100644 owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/participants/transports/grpc_asyncio.py delete mode 100644 owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/participants/transports/rest.py delete mode 100644 owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/session_entity_types/__init__.py delete mode 100644 owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/session_entity_types/async_client.py delete mode 100644 owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/session_entity_types/client.py delete mode 100644 owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/session_entity_types/pagers.py delete mode 100644 owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/session_entity_types/transports/__init__.py delete mode 100644 owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/session_entity_types/transports/base.py delete mode 100644 owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/session_entity_types/transports/grpc.py delete mode 100644 owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/session_entity_types/transports/grpc_asyncio.py delete mode 100644 owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/session_entity_types/transports/rest.py delete mode 100644 owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/sessions/__init__.py delete mode 100644 owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/sessions/async_client.py delete mode 100644 owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/sessions/client.py delete mode 100644 owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/sessions/transports/__init__.py delete mode 100644 owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/sessions/transports/base.py delete mode 100644 owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/sessions/transports/grpc.py delete mode 100644 owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/sessions/transports/grpc_asyncio.py delete mode 100644 owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/sessions/transports/rest.py delete mode 100644 owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/versions/__init__.py delete mode 100644 owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/versions/async_client.py delete mode 100644 owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/versions/client.py delete mode 100644 owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/versions/pagers.py delete mode 100644 owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/versions/transports/__init__.py delete mode 100644 owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/versions/transports/base.py delete mode 100644 owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/versions/transports/grpc.py delete mode 100644 owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/versions/transports/grpc_asyncio.py delete mode 100644 owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/versions/transports/rest.py delete mode 100644 owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/types/__init__.py delete mode 100644 owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/types/agent.py delete mode 100644 owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/types/answer_record.py delete mode 100644 owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/types/audio_config.py delete mode 100644 owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/types/context.py delete mode 100644 owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/types/conversation.py delete mode 100644 owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/types/conversation_event.py delete mode 100644 owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/types/conversation_profile.py delete mode 100644 owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/types/document.py delete mode 100644 owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/types/entity_type.py delete mode 100644 owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/types/environment.py delete mode 100644 owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/types/fulfillment.py delete mode 100644 owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/types/gcs.py delete mode 100644 owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/types/human_agent_assistant_event.py delete mode 100644 owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/types/intent.py delete mode 100644 owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/types/knowledge_base.py delete mode 100644 owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/types/participant.py delete mode 100644 owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/types/session.py delete mode 100644 owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/types/session_entity_type.py delete mode 100644 owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/types/validation_result.py delete mode 100644 owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/types/version.py delete mode 100644 owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/types/webhook.py delete mode 100644 owl-bot-staging/v2beta1/mypy.ini delete mode 100644 owl-bot-staging/v2beta1/noxfile.py delete mode 100644 owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_agents_delete_agent_async.py delete mode 100644 owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_agents_delete_agent_sync.py delete mode 100644 owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_agents_export_agent_async.py delete mode 100644 owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_agents_export_agent_sync.py delete mode 100644 owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_agents_get_agent_async.py delete mode 100644 owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_agents_get_agent_sync.py delete mode 100644 owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_agents_get_validation_result_async.py delete mode 100644 owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_agents_get_validation_result_sync.py delete mode 100644 owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_agents_import_agent_async.py delete mode 100644 owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_agents_import_agent_sync.py delete mode 100644 owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_agents_restore_agent_async.py delete mode 100644 owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_agents_restore_agent_sync.py delete mode 100644 owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_agents_search_agents_async.py delete mode 100644 owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_agents_search_agents_sync.py delete mode 100644 owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_agents_set_agent_async.py delete mode 100644 owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_agents_set_agent_sync.py delete mode 100644 owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_agents_train_agent_async.py delete mode 100644 owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_agents_train_agent_sync.py delete mode 100644 owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_answer_records_get_answer_record_async.py delete mode 100644 owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_answer_records_get_answer_record_sync.py delete mode 100644 owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_answer_records_list_answer_records_async.py delete mode 100644 owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_answer_records_list_answer_records_sync.py delete mode 100644 owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_answer_records_update_answer_record_async.py delete mode 100644 owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_answer_records_update_answer_record_sync.py delete mode 100644 owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_contexts_create_context_async.py delete mode 100644 owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_contexts_create_context_sync.py delete mode 100644 owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_contexts_delete_all_contexts_async.py delete mode 100644 owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_contexts_delete_all_contexts_sync.py delete mode 100644 owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_contexts_delete_context_async.py delete mode 100644 owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_contexts_delete_context_sync.py delete mode 100644 owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_contexts_get_context_async.py delete mode 100644 owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_contexts_get_context_sync.py delete mode 100644 owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_contexts_list_contexts_async.py delete mode 100644 owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_contexts_list_contexts_sync.py delete mode 100644 owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_contexts_update_context_async.py delete mode 100644 owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_contexts_update_context_sync.py delete mode 100644 owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_conversation_profiles_clear_suggestion_feature_config_async.py delete mode 100644 owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_conversation_profiles_clear_suggestion_feature_config_sync.py delete mode 100644 owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_conversation_profiles_create_conversation_profile_async.py delete mode 100644 owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_conversation_profiles_create_conversation_profile_sync.py delete mode 100644 owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_conversation_profiles_delete_conversation_profile_async.py delete mode 100644 owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_conversation_profiles_delete_conversation_profile_sync.py delete mode 100644 owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_conversation_profiles_get_conversation_profile_async.py delete mode 100644 owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_conversation_profiles_get_conversation_profile_sync.py delete mode 100644 owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_conversation_profiles_list_conversation_profiles_async.py delete mode 100644 owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_conversation_profiles_list_conversation_profiles_sync.py delete mode 100644 owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_conversation_profiles_set_suggestion_feature_config_async.py delete mode 100644 owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_conversation_profiles_set_suggestion_feature_config_sync.py delete mode 100644 owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_conversation_profiles_update_conversation_profile_async.py delete mode 100644 owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_conversation_profiles_update_conversation_profile_sync.py delete mode 100644 owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_conversations_batch_create_messages_async.py delete mode 100644 owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_conversations_batch_create_messages_sync.py delete mode 100644 owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_conversations_complete_conversation_async.py delete mode 100644 owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_conversations_complete_conversation_sync.py delete mode 100644 owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_conversations_create_conversation_async.py delete mode 100644 owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_conversations_create_conversation_sync.py delete mode 100644 owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_conversations_get_conversation_async.py delete mode 100644 owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_conversations_get_conversation_sync.py delete mode 100644 owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_conversations_list_conversations_async.py delete mode 100644 owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_conversations_list_conversations_sync.py delete mode 100644 owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_conversations_list_messages_async.py delete mode 100644 owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_conversations_list_messages_sync.py delete mode 100644 owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_conversations_suggest_conversation_summary_async.py delete mode 100644 owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_conversations_suggest_conversation_summary_sync.py delete mode 100644 owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_documents_create_document_async.py delete mode 100644 owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_documents_create_document_sync.py delete mode 100644 owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_documents_delete_document_async.py delete mode 100644 owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_documents_delete_document_sync.py delete mode 100644 owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_documents_get_document_async.py delete mode 100644 owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_documents_get_document_sync.py delete mode 100644 owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_documents_import_documents_async.py delete mode 100644 owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_documents_import_documents_sync.py delete mode 100644 owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_documents_list_documents_async.py delete mode 100644 owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_documents_list_documents_sync.py delete mode 100644 owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_documents_reload_document_async.py delete mode 100644 owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_documents_reload_document_sync.py delete mode 100644 owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_documents_update_document_async.py delete mode 100644 owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_documents_update_document_sync.py delete mode 100644 owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_entity_types_batch_create_entities_async.py delete mode 100644 owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_entity_types_batch_create_entities_sync.py delete mode 100644 owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_entity_types_batch_delete_entities_async.py delete mode 100644 owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_entity_types_batch_delete_entities_sync.py delete mode 100644 owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_entity_types_batch_delete_entity_types_async.py delete mode 100644 owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_entity_types_batch_delete_entity_types_sync.py delete mode 100644 owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_entity_types_batch_update_entities_async.py delete mode 100644 owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_entity_types_batch_update_entities_sync.py delete mode 100644 owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_entity_types_batch_update_entity_types_async.py delete mode 100644 owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_entity_types_batch_update_entity_types_sync.py delete mode 100644 owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_entity_types_create_entity_type_async.py delete mode 100644 owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_entity_types_create_entity_type_sync.py delete mode 100644 owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_entity_types_delete_entity_type_async.py delete mode 100644 owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_entity_types_delete_entity_type_sync.py delete mode 100644 owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_entity_types_get_entity_type_async.py delete mode 100644 owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_entity_types_get_entity_type_sync.py delete mode 100644 owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_entity_types_list_entity_types_async.py delete mode 100644 owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_entity_types_list_entity_types_sync.py delete mode 100644 owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_entity_types_update_entity_type_async.py delete mode 100644 owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_entity_types_update_entity_type_sync.py delete mode 100644 owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_environments_create_environment_async.py delete mode 100644 owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_environments_create_environment_sync.py delete mode 100644 owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_environments_delete_environment_async.py delete mode 100644 owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_environments_delete_environment_sync.py delete mode 100644 owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_environments_get_environment_async.py delete mode 100644 owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_environments_get_environment_history_async.py delete mode 100644 owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_environments_get_environment_history_sync.py delete mode 100644 owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_environments_get_environment_sync.py delete mode 100644 owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_environments_list_environments_async.py delete mode 100644 owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_environments_list_environments_sync.py delete mode 100644 owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_environments_update_environment_async.py delete mode 100644 owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_environments_update_environment_sync.py delete mode 100644 owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_fulfillments_get_fulfillment_async.py delete mode 100644 owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_fulfillments_get_fulfillment_sync.py delete mode 100644 owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_fulfillments_update_fulfillment_async.py delete mode 100644 owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_fulfillments_update_fulfillment_sync.py delete mode 100644 owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_intents_batch_delete_intents_async.py delete mode 100644 owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_intents_batch_delete_intents_sync.py delete mode 100644 owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_intents_batch_update_intents_async.py delete mode 100644 owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_intents_batch_update_intents_sync.py delete mode 100644 owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_intents_create_intent_async.py delete mode 100644 owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_intents_create_intent_sync.py delete mode 100644 owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_intents_delete_intent_async.py delete mode 100644 owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_intents_delete_intent_sync.py delete mode 100644 owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_intents_get_intent_async.py delete mode 100644 owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_intents_get_intent_sync.py delete mode 100644 owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_intents_list_intents_async.py delete mode 100644 owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_intents_list_intents_sync.py delete mode 100644 owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_intents_update_intent_async.py delete mode 100644 owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_intents_update_intent_sync.py delete mode 100644 owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_knowledge_bases_create_knowledge_base_async.py delete mode 100644 owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_knowledge_bases_create_knowledge_base_sync.py delete mode 100644 owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_knowledge_bases_delete_knowledge_base_async.py delete mode 100644 owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_knowledge_bases_delete_knowledge_base_sync.py delete mode 100644 owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_knowledge_bases_get_knowledge_base_async.py delete mode 100644 owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_knowledge_bases_get_knowledge_base_sync.py delete mode 100644 owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_knowledge_bases_list_knowledge_bases_async.py delete mode 100644 owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_knowledge_bases_list_knowledge_bases_sync.py delete mode 100644 owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_knowledge_bases_update_knowledge_base_async.py delete mode 100644 owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_knowledge_bases_update_knowledge_base_sync.py delete mode 100644 owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_participants_analyze_content_async.py delete mode 100644 owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_participants_analyze_content_sync.py delete mode 100644 owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_participants_compile_suggestion_async.py delete mode 100644 owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_participants_compile_suggestion_sync.py delete mode 100644 owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_participants_create_participant_async.py delete mode 100644 owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_participants_create_participant_sync.py delete mode 100644 owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_participants_get_participant_async.py delete mode 100644 owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_participants_get_participant_sync.py delete mode 100644 owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_participants_list_participants_async.py delete mode 100644 owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_participants_list_participants_sync.py delete mode 100644 owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_participants_list_suggestions_async.py delete mode 100644 owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_participants_list_suggestions_sync.py delete mode 100644 owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_participants_streaming_analyze_content_async.py delete mode 100644 owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_participants_streaming_analyze_content_sync.py delete mode 100644 owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_participants_suggest_articles_async.py delete mode 100644 owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_participants_suggest_articles_sync.py delete mode 100644 owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_participants_suggest_faq_answers_async.py delete mode 100644 owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_participants_suggest_faq_answers_sync.py delete mode 100644 owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_participants_suggest_smart_replies_async.py delete mode 100644 owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_participants_suggest_smart_replies_sync.py delete mode 100644 owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_participants_update_participant_async.py delete mode 100644 owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_participants_update_participant_sync.py delete mode 100644 owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_session_entity_types_create_session_entity_type_async.py delete mode 100644 owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_session_entity_types_create_session_entity_type_sync.py delete mode 100644 owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_session_entity_types_delete_session_entity_type_async.py delete mode 100644 owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_session_entity_types_delete_session_entity_type_sync.py delete mode 100644 owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_session_entity_types_get_session_entity_type_async.py delete mode 100644 owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_session_entity_types_get_session_entity_type_sync.py delete mode 100644 owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_session_entity_types_list_session_entity_types_async.py delete mode 100644 owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_session_entity_types_list_session_entity_types_sync.py delete mode 100644 owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_session_entity_types_update_session_entity_type_async.py delete mode 100644 owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_session_entity_types_update_session_entity_type_sync.py delete mode 100644 owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_sessions_detect_intent_async.py delete mode 100644 owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_sessions_detect_intent_sync.py delete mode 100644 owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_sessions_streaming_detect_intent_async.py delete mode 100644 owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_sessions_streaming_detect_intent_sync.py delete mode 100644 owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_versions_create_version_async.py delete mode 100644 owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_versions_create_version_sync.py delete mode 100644 owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_versions_delete_version_async.py delete mode 100644 owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_versions_delete_version_sync.py delete mode 100644 owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_versions_get_version_async.py delete mode 100644 owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_versions_get_version_sync.py delete mode 100644 owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_versions_list_versions_async.py delete mode 100644 owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_versions_list_versions_sync.py delete mode 100644 owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_versions_update_version_async.py delete mode 100644 owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_versions_update_version_sync.py delete mode 100644 owl-bot-staging/v2beta1/samples/generated_samples/snippet_metadata_google.cloud.dialogflow.v2beta1.json delete mode 100644 owl-bot-staging/v2beta1/scripts/fixup_dialogflow_v2beta1_keywords.py delete mode 100644 owl-bot-staging/v2beta1/setup.py delete mode 100644 owl-bot-staging/v2beta1/testing/constraints-3.10.txt delete mode 100644 owl-bot-staging/v2beta1/testing/constraints-3.11.txt delete mode 100644 owl-bot-staging/v2beta1/testing/constraints-3.12.txt delete mode 100644 owl-bot-staging/v2beta1/testing/constraints-3.7.txt delete mode 100644 owl-bot-staging/v2beta1/testing/constraints-3.8.txt delete mode 100644 owl-bot-staging/v2beta1/testing/constraints-3.9.txt delete mode 100644 owl-bot-staging/v2beta1/tests/__init__.py delete mode 100644 owl-bot-staging/v2beta1/tests/unit/__init__.py delete mode 100644 owl-bot-staging/v2beta1/tests/unit/gapic/__init__.py delete mode 100644 owl-bot-staging/v2beta1/tests/unit/gapic/dialogflow_v2beta1/__init__.py delete mode 100644 owl-bot-staging/v2beta1/tests/unit/gapic/dialogflow_v2beta1/test_agents.py delete mode 100644 owl-bot-staging/v2beta1/tests/unit/gapic/dialogflow_v2beta1/test_answer_records.py delete mode 100644 owl-bot-staging/v2beta1/tests/unit/gapic/dialogflow_v2beta1/test_contexts.py delete mode 100644 owl-bot-staging/v2beta1/tests/unit/gapic/dialogflow_v2beta1/test_conversation_profiles.py delete mode 100644 owl-bot-staging/v2beta1/tests/unit/gapic/dialogflow_v2beta1/test_conversations.py delete mode 100644 owl-bot-staging/v2beta1/tests/unit/gapic/dialogflow_v2beta1/test_documents.py delete mode 100644 owl-bot-staging/v2beta1/tests/unit/gapic/dialogflow_v2beta1/test_entity_types.py delete mode 100644 owl-bot-staging/v2beta1/tests/unit/gapic/dialogflow_v2beta1/test_environments.py delete mode 100644 owl-bot-staging/v2beta1/tests/unit/gapic/dialogflow_v2beta1/test_fulfillments.py delete mode 100644 owl-bot-staging/v2beta1/tests/unit/gapic/dialogflow_v2beta1/test_intents.py delete mode 100644 owl-bot-staging/v2beta1/tests/unit/gapic/dialogflow_v2beta1/test_knowledge_bases.py delete mode 100644 owl-bot-staging/v2beta1/tests/unit/gapic/dialogflow_v2beta1/test_participants.py delete mode 100644 owl-bot-staging/v2beta1/tests/unit/gapic/dialogflow_v2beta1/test_session_entity_types.py delete mode 100644 owl-bot-staging/v2beta1/tests/unit/gapic/dialogflow_v2beta1/test_sessions.py delete mode 100644 owl-bot-staging/v2beta1/tests/unit/gapic/dialogflow_v2beta1/test_versions.py diff --git a/google/cloud/dialogflow_v2/services/agents/transports/rest.py b/google/cloud/dialogflow_v2/services/agents/transports/rest.py index eda64e40e..a93c9cec0 100644 --- a/google/cloud/dialogflow_v2/services/agents/transports/rest.py +++ b/google/cloud/dialogflow_v2/services/agents/transports/rest.py @@ -623,7 +623,6 @@ def __call__( request (~.agent.DeleteAgentRequest): The request object. The request message for [Agents.DeleteAgent][google.cloud.dialogflow.v2.Agents.DeleteAgent]. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -703,7 +702,6 @@ def __call__( request (~.agent.ExportAgentRequest): The request object. The request message for [Agents.ExportAgent][google.cloud.dialogflow.v2.Agents.ExportAgent]. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -806,7 +804,6 @@ def __call__( request (~.agent.GetAgentRequest): The request object. The request message for [Agents.GetAgent][google.cloud.dialogflow.v2.Agents.GetAgent]. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -910,7 +907,6 @@ def __call__( request (~.agent.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. @@ -1006,7 +1002,6 @@ def __call__( request (~.agent.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. @@ -1109,7 +1104,6 @@ def __call__( request (~.agent.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. @@ -1212,7 +1206,6 @@ def __call__( request (~.agent.SearchAgentsRequest): The request object. The request message for [Agents.SearchAgents][google.cloud.dialogflow.v2.Agents.SearchAgents]. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -1306,7 +1299,6 @@ def __call__( request (~.gcd_agent.SetAgentRequest): The request object. The request message for [Agents.SetAgent][google.cloud.dialogflow.v2.Agents.SetAgent]. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -1420,7 +1412,6 @@ def __call__( request (~.agent.TrainAgentRequest): The request object. The request message for [Agents.TrainAgent][google.cloud.dialogflow.v2.Agents.TrainAgent]. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. diff --git a/google/cloud/dialogflow_v2/services/answer_records/transports/rest.py b/google/cloud/dialogflow_v2/services/answer_records/transports/rest.py index f679e4297..cc2b5f498 100644 --- a/google/cloud/dialogflow_v2/services/answer_records/transports/rest.py +++ b/google/cloud/dialogflow_v2/services/answer_records/transports/rest.py @@ -373,7 +373,6 @@ def __call__( request (~.answer_record.ListAnswerRecordsRequest): The request object. Request message for [AnswerRecords.ListAnswerRecords][google.cloud.dialogflow.v2.AnswerRecords.ListAnswerRecords]. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -471,7 +470,6 @@ def __call__( request (~.gcd_answer_record.UpdateAnswerRecordRequest): The request object. Request message for [AnswerRecords.UpdateAnswerRecord][google.cloud.dialogflow.v2.AnswerRecords.UpdateAnswerRecord]. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. diff --git a/google/cloud/dialogflow_v2/services/contexts/transports/rest.py b/google/cloud/dialogflow_v2/services/contexts/transports/rest.py index 46a87e428..d9aa30a23 100644 --- a/google/cloud/dialogflow_v2/services/contexts/transports/rest.py +++ b/google/cloud/dialogflow_v2/services/contexts/transports/rest.py @@ -456,7 +456,6 @@ def __call__( request (~.gcd_context.CreateContextRequest): The request object. The request message for [Contexts.CreateContext][google.cloud.dialogflow.v2.Contexts.CreateContext]. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -587,7 +586,6 @@ def __call__( request (~.context.DeleteAllContextsRequest): The request object. The request message for [Contexts.DeleteAllContexts][google.cloud.dialogflow.v2.Contexts.DeleteAllContexts]. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -677,7 +675,6 @@ def __call__( request (~.context.DeleteContextRequest): The request object. The request message for [Contexts.DeleteContext][google.cloud.dialogflow.v2.Contexts.DeleteContext]. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -765,7 +762,6 @@ def __call__( request (~.context.GetContextRequest): The request object. The request message for [Contexts.GetContext][google.cloud.dialogflow.v2.Contexts.GetContext]. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -884,7 +880,6 @@ def __call__( request (~.context.ListContextsRequest): The request object. The request message for [Contexts.ListContexts][google.cloud.dialogflow.v2.Contexts.ListContexts]. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -986,7 +981,6 @@ def __call__( request (~.gcd_context.UpdateContextRequest): The request object. The request message for [Contexts.UpdateContext][google.cloud.dialogflow.v2.Contexts.UpdateContext]. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. diff --git a/google/cloud/dialogflow_v2/services/conversation_datasets/transports/rest.py b/google/cloud/dialogflow_v2/services/conversation_datasets/transports/rest.py index d03cf6922..2e8c67747 100644 --- a/google/cloud/dialogflow_v2/services/conversation_datasets/transports/rest.py +++ b/google/cloud/dialogflow_v2/services/conversation_datasets/transports/rest.py @@ -548,7 +548,6 @@ def __call__( request (~.gcd_conversation_dataset.CreateConversationDatasetRequest): The request object. The request message for [ConversationDatasets.CreateConversationDataset][google.cloud.dialogflow.v2.ConversationDatasets.CreateConversationDataset]. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -651,7 +650,6 @@ def __call__( request (~.conversation_dataset.DeleteConversationDatasetRequest): The request object. The request message for [ConversationDatasets.DeleteConversationDataset][google.cloud.dialogflow.v2.ConversationDatasets.DeleteConversationDataset]. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -744,7 +742,6 @@ def __call__( request (~.conversation_dataset.GetConversationDatasetRequest): The request object. The request message for [ConversationDatasets.GetConversationDataset][google.cloud.dialogflow.v2.ConversationDatasets.GetConversationDataset]. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -845,7 +842,6 @@ def __call__( request (~.conversation_dataset.ImportConversationDataRequest): The request object. The request message for [ConversationDatasets.ImportConversationData][google.cloud.dialogflow.v2.ConversationDatasets.ImportConversationData]. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -951,7 +947,6 @@ def __call__( request (~.conversation_dataset.ListConversationDatasetsRequest): The request object. The request message for [ConversationDatasets.ListConversationDatasets][google.cloud.dialogflow.v2.ConversationDatasets.ListConversationDatasets]. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. diff --git a/google/cloud/dialogflow_v2/services/conversation_models/transports/rest.py b/google/cloud/dialogflow_v2/services/conversation_models/transports/rest.py index 1d4b9a76a..e0347ccde 100644 --- a/google/cloud/dialogflow_v2/services/conversation_models/transports/rest.py +++ b/google/cloud/dialogflow_v2/services/conversation_models/transports/rest.py @@ -679,7 +679,6 @@ def __call__( request (~.gcd_conversation_model.CreateConversationModelRequest): The request object. The request message for [ConversationModels.CreateConversationModel][google.cloud.dialogflow.v2.ConversationModels.CreateConversationModel] - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -787,7 +786,6 @@ def __call__( request (~.conversation_model.CreateConversationModelEvaluationRequest): The request object. The request message for [ConversationModels.CreateConversationModelEvaluation][google.cloud.dialogflow.v2.ConversationModels.CreateConversationModelEvaluation] - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -892,7 +890,6 @@ def __call__( request (~.conversation_model.DeleteConversationModelRequest): The request object. The request message for [ConversationModels.DeleteConversationModel][google.cloud.dialogflow.v2.ConversationModels.DeleteConversationModel] - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -987,7 +984,6 @@ def __call__( request (~.conversation_model.DeployConversationModelRequest): The request object. The request message for [ConversationModels.DeployConversationModel][google.cloud.dialogflow.v2.ConversationModels.DeployConversationModel] - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -1092,7 +1088,6 @@ def __call__( request (~.conversation_model.GetConversationModelRequest): The request object. The request message for [ConversationModels.GetConversationModel][google.cloud.dialogflow.v2.ConversationModels.GetConversationModel] - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -1187,7 +1182,6 @@ def __call__( request (~.conversation_model.GetConversationModelEvaluationRequest): The request object. The request message for [ConversationModels.GetConversationModelEvaluation][google.cloud.dialogflow.v2.ConversationModels.GetConversationModelEvaluation] - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -1286,7 +1280,6 @@ def __call__( request (~.conversation_model.ListConversationModelEvaluationsRequest): The request object. The request message for [ConversationModels.ListConversationModelEvaluations][google.cloud.dialogflow.v2.ConversationModels.ListConversationModelEvaluations] - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -1389,7 +1382,6 @@ def __call__( request (~.conversation_model.ListConversationModelsRequest): The request object. The request message for [ConversationModels.ListConversationModels][google.cloud.dialogflow.v2.ConversationModels.ListConversationModels] - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -1486,7 +1478,6 @@ def __call__( request (~.conversation_model.UndeployConversationModelRequest): The request object. The request message for [ConversationModels.UndeployConversationModel][google.cloud.dialogflow.v2.ConversationModels.UndeployConversationModel] - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. 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 4f0f16172..570cb6b98 100644 --- a/google/cloud/dialogflow_v2/services/conversation_profiles/async_client.py +++ b/google/cloud/dialogflow_v2/services/conversation_profiles/async_client.py @@ -771,6 +771,7 @@ async def sample_delete_conversation_profile(): request (Optional[Union[google.cloud.dialogflow_v2.types.DeleteConversationProfileRequest, dict]]): The request object. The request message for [ConversationProfiles.DeleteConversationProfile][google.cloud.dialogflow.v2.ConversationProfiles.DeleteConversationProfile]. + This operation fails if the conversation profile is still referenced from a phone number. name (:class:`str`): diff --git a/google/cloud/dialogflow_v2/services/conversation_profiles/client.py b/google/cloud/dialogflow_v2/services/conversation_profiles/client.py index 81e9c9caa..2b3cebb3f 100644 --- a/google/cloud/dialogflow_v2/services/conversation_profiles/client.py +++ b/google/cloud/dialogflow_v2/services/conversation_profiles/client.py @@ -1085,6 +1085,7 @@ def sample_delete_conversation_profile(): request (Union[google.cloud.dialogflow_v2.types.DeleteConversationProfileRequest, dict]): The request object. The request message for [ConversationProfiles.DeleteConversationProfile][google.cloud.dialogflow.v2.ConversationProfiles.DeleteConversationProfile]. + This operation fails if the conversation profile is still referenced from a phone number. name (str): diff --git a/google/cloud/dialogflow_v2/services/conversation_profiles/transports/rest.py b/google/cloud/dialogflow_v2/services/conversation_profiles/transports/rest.py index 8cdff3869..e8af00ba6 100644 --- a/google/cloud/dialogflow_v2/services/conversation_profiles/transports/rest.py +++ b/google/cloud/dialogflow_v2/services/conversation_profiles/transports/rest.py @@ -602,7 +602,6 @@ def __call__( request (~.gcd_conversation_profile.ClearSuggestionFeatureConfigRequest): The request object. The request message for [ConversationProfiles.ClearFeature][]. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -710,7 +709,6 @@ def __call__( request (~.gcd_conversation_profile.CreateConversationProfileRequest): The request object. The request message for [ConversationProfiles.CreateConversationProfile][google.cloud.dialogflow.v2.ConversationProfiles.CreateConversationProfile]. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -822,7 +820,6 @@ def __call__( This operation fails if the conversation profile is still referenced from a phone number. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -906,7 +903,6 @@ def __call__( request (~.conversation_profile.GetConversationProfileRequest): The request object. The request message for [ConversationProfiles.GetConversationProfile][google.cloud.dialogflow.v2.ConversationProfiles.GetConversationProfile]. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -1003,7 +999,6 @@ def __call__( request (~.conversation_profile.ListConversationProfilesRequest): The request object. The request message for [ConversationProfiles.ListConversationProfiles][google.cloud.dialogflow.v2.ConversationProfiles.ListConversationProfiles]. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -1102,7 +1097,6 @@ def __call__( request (~.gcd_conversation_profile.SetSuggestionFeatureConfigRequest): The request object. The request message for [ConversationProfiles.SetSuggestionFeature][]. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -1212,7 +1206,6 @@ def __call__( request (~.gcd_conversation_profile.UpdateConversationProfileRequest): The request object. The request message for [ConversationProfiles.UpdateConversationProfile][google.cloud.dialogflow.v2.ConversationProfiles.UpdateConversationProfile]. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. diff --git a/google/cloud/dialogflow_v2/services/conversations/transports/rest.py b/google/cloud/dialogflow_v2/services/conversations/transports/rest.py index f08c20ff0..077977472 100644 --- a/google/cloud/dialogflow_v2/services/conversations/transports/rest.py +++ b/google/cloud/dialogflow_v2/services/conversations/transports/rest.py @@ -499,7 +499,6 @@ def __call__( request (~.conversation.CompleteConversationRequest): The request object. The request message for [Conversations.CompleteConversation][google.cloud.dialogflow.v2.Conversations.CompleteConversation]. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -610,7 +609,6 @@ def __call__( request (~.gcd_conversation.CreateConversationRequest): The request object. The request message for [Conversations.CreateConversation][google.cloud.dialogflow.v2.Conversations.CreateConversation]. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -721,7 +719,6 @@ def __call__( request (~.conversation.GetConversationRequest): The request object. The request message for [Conversations.GetConversation][google.cloud.dialogflow.v2.Conversations.GetConversation]. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -822,7 +819,6 @@ def __call__( request (~.conversation.ListConversationsRequest): The request object. The request message for [Conversations.ListConversations][google.cloud.dialogflow.v2.Conversations.ListConversations]. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -918,7 +914,6 @@ def __call__( request (~.conversation.ListMessagesRequest): The request object. The request message for [Conversations.ListMessages][google.cloud.dialogflow.v2.Conversations.ListMessages]. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -1013,7 +1008,6 @@ def __call__( request (~.gcd_conversation.SuggestConversationSummaryRequest): The request object. The request message for [Conversations.SuggestConversationSummary][google.cloud.dialogflow.v2.Conversations.SuggestConversationSummary]. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. diff --git a/google/cloud/dialogflow_v2/services/documents/transports/rest.py b/google/cloud/dialogflow_v2/services/documents/transports/rest.py index 3be0d4bc5..0c3358488 100644 --- a/google/cloud/dialogflow_v2/services/documents/transports/rest.py +++ b/google/cloud/dialogflow_v2/services/documents/transports/rest.py @@ -622,7 +622,6 @@ def __call__( request (~.gcd_document.CreateDocumentRequest): The request object. Request message for [Documents.CreateDocument][google.cloud.dialogflow.v2.Documents.CreateDocument]. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -730,7 +729,6 @@ def __call__( request (~.document.DeleteDocumentRequest): The request object. Request message for [Documents.DeleteDocument][google.cloud.dialogflow.v2.Documents.DeleteDocument]. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -827,7 +825,6 @@ def __call__( request (~.document.ExportDocumentRequest): The request object. Request message for [Documents.ExportDocument][google.cloud.dialogflow.v2.Documents.ExportDocument]. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -930,7 +927,6 @@ def __call__( request (~.document.GetDocumentRequest): The request object. Request message for [Documents.GetDocument][google.cloud.dialogflow.v2.Documents.GetDocument]. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -1035,7 +1031,6 @@ def __call__( request (~.document.ImportDocumentsRequest): The request object. Request message for [Documents.ImportDocuments][google.cloud.dialogflow.v2.Documents.ImportDocuments]. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -1140,7 +1135,6 @@ def __call__( request (~.document.ListDocumentsRequest): The request object. Request message for [Documents.ListDocuments][google.cloud.dialogflow.v2.Documents.ListDocuments]. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -1238,7 +1232,6 @@ def __call__( request (~.document.ReloadDocumentRequest): The request object. Request message for [Documents.ReloadDocument][google.cloud.dialogflow.v2.Documents.ReloadDocument]. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -1346,7 +1339,6 @@ def __call__( request (~.gcd_document.UpdateDocumentRequest): The request object. Request message for [Documents.UpdateDocument][google.cloud.dialogflow.v2.Documents.UpdateDocument]. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. diff --git a/google/cloud/dialogflow_v2/services/entity_types/transports/rest.py b/google/cloud/dialogflow_v2/services/entity_types/transports/rest.py index 37d006938..bef572e92 100644 --- a/google/cloud/dialogflow_v2/services/entity_types/transports/rest.py +++ b/google/cloud/dialogflow_v2/services/entity_types/transports/rest.py @@ -674,7 +674,6 @@ def __call__( request (~.entity_type.BatchCreateEntitiesRequest): The request object. The request message for [EntityTypes.BatchCreateEntities][google.cloud.dialogflow.v2.EntityTypes.BatchCreateEntities]. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -779,7 +778,6 @@ def __call__( request (~.entity_type.BatchDeleteEntitiesRequest): The request object. The request message for [EntityTypes.BatchDeleteEntities][google.cloud.dialogflow.v2.EntityTypes.BatchDeleteEntities]. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -884,7 +882,6 @@ def __call__( request (~.entity_type.BatchDeleteEntityTypesRequest): The request object. The request message for [EntityTypes.BatchDeleteEntityTypes][google.cloud.dialogflow.v2.EntityTypes.BatchDeleteEntityTypes]. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -989,7 +986,6 @@ def __call__( request (~.entity_type.BatchUpdateEntitiesRequest): The request object. The request message for [EntityTypes.BatchUpdateEntities][google.cloud.dialogflow.v2.EntityTypes.BatchUpdateEntities]. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -1094,7 +1090,6 @@ def __call__( request (~.entity_type.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. @@ -1199,7 +1194,6 @@ def __call__( request (~.gcd_entity_type.CreateEntityTypeRequest): The request object. The request message for [EntityTypes.CreateEntityType][google.cloud.dialogflow.v2.EntityTypes.CreateEntityType]. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -1318,7 +1312,6 @@ def __call__( request (~.entity_type.DeleteEntityTypeRequest): The request object. The request message for [EntityTypes.DeleteEntityType][google.cloud.dialogflow.v2.EntityTypes.DeleteEntityType]. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -1400,7 +1393,6 @@ def __call__( request (~.entity_type.GetEntityTypeRequest): The request object. The request message for [EntityTypes.GetEntityType][google.cloud.dialogflow.v2.EntityTypes.GetEntityType]. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -1507,7 +1499,6 @@ def __call__( request (~.entity_type.ListEntityTypesRequest): The request object. The request message for [EntityTypes.ListEntityTypes][google.cloud.dialogflow.v2.EntityTypes.ListEntityTypes]. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -1603,7 +1594,6 @@ def __call__( request (~.gcd_entity_type.UpdateEntityTypeRequest): The request object. The request message for [EntityTypes.UpdateEntityType][google.cloud.dialogflow.v2.EntityTypes.UpdateEntityType]. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. diff --git a/google/cloud/dialogflow_v2/services/environments/transports/rest.py b/google/cloud/dialogflow_v2/services/environments/transports/rest.py index 05dba86e4..acc055ca4 100644 --- a/google/cloud/dialogflow_v2/services/environments/transports/rest.py +++ b/google/cloud/dialogflow_v2/services/environments/transports/rest.py @@ -485,7 +485,6 @@ def __call__( request (~.environment.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. @@ -608,7 +607,6 @@ def __call__( request (~.environment.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. @@ -690,7 +688,6 @@ def __call__( request (~.environment.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. @@ -801,7 +798,6 @@ def __call__( request (~.environment.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. @@ -897,7 +893,6 @@ def __call__( request (~.environment.ListEnvironmentsRequest): The request object. The request message for [Environments.ListEnvironments][google.cloud.dialogflow.v2.Environments.ListEnvironments]. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -995,7 +990,6 @@ def __call__( request (~.environment.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. diff --git a/google/cloud/dialogflow_v2/services/fulfillments/transports/rest.py b/google/cloud/dialogflow_v2/services/fulfillments/transports/rest.py index ad5f4e2d6..b82998953 100644 --- a/google/cloud/dialogflow_v2/services/fulfillments/transports/rest.py +++ b/google/cloud/dialogflow_v2/services/fulfillments/transports/rest.py @@ -373,7 +373,6 @@ def __call__( request (~.fulfillment.GetFulfillmentRequest): The request object. The request message for [Fulfillments.GetFulfillment][google.cloud.dialogflow.v2.Fulfillments.GetFulfillment]. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -479,7 +478,6 @@ def __call__( request (~.gcd_fulfillment.UpdateFulfillmentRequest): The request object. The request message for [Fulfillments.UpdateFulfillment][google.cloud.dialogflow.v2.Fulfillments.UpdateFulfillment]. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. diff --git a/google/cloud/dialogflow_v2/services/intents/transports/rest.py b/google/cloud/dialogflow_v2/services/intents/transports/rest.py index 1a090149f..f9e84dbfd 100644 --- a/google/cloud/dialogflow_v2/services/intents/transports/rest.py +++ b/google/cloud/dialogflow_v2/services/intents/transports/rest.py @@ -568,7 +568,6 @@ def __call__( request (~.intent.BatchDeleteIntentsRequest): The request object. The request message for [Intents.BatchDeleteIntents][google.cloud.dialogflow.v2.Intents.BatchDeleteIntents]. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -776,7 +775,6 @@ def __call__( request (~.gcd_intent.CreateIntentRequest): The request object. The request message for [Intents.CreateIntent][google.cloud.dialogflow.v2.Intents.CreateIntent]. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -889,7 +887,6 @@ def __call__( request (~.intent.DeleteIntentRequest): The request object. The request message for [Intents.DeleteIntent][google.cloud.dialogflow.v2.Intents.DeleteIntent]. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -969,7 +966,6 @@ def __call__( request (~.intent.GetIntentRequest): The request object. The request message for [Intents.GetIntent][google.cloud.dialogflow.v2.Intents.GetIntent]. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -1072,7 +1068,6 @@ def __call__( request (~.intent.ListIntentsRequest): The request object. The request message for [Intents.ListIntents][google.cloud.dialogflow.v2.Intents.ListIntents]. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -1174,7 +1169,6 @@ def __call__( request (~.gcd_intent.UpdateIntentRequest): The request object. The request message for [Intents.UpdateIntent][google.cloud.dialogflow.v2.Intents.UpdateIntent]. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. diff --git a/google/cloud/dialogflow_v2/services/knowledge_bases/transports/rest.py b/google/cloud/dialogflow_v2/services/knowledge_bases/transports/rest.py index 4cd2cd7e8..980910b84 100644 --- a/google/cloud/dialogflow_v2/services/knowledge_bases/transports/rest.py +++ b/google/cloud/dialogflow_v2/services/knowledge_bases/transports/rest.py @@ -457,7 +457,6 @@ def __call__( request (~.gcd_knowledge_base.CreateKnowledgeBaseRequest): The request object. Request message for [KnowledgeBases.CreateKnowledgeBase][google.cloud.dialogflow.v2.KnowledgeBases.CreateKnowledgeBase]. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -578,7 +577,6 @@ def __call__( request (~.knowledge_base.DeleteKnowledgeBaseRequest): The request object. Request message for [KnowledgeBases.DeleteKnowledgeBase][google.cloud.dialogflow.v2.KnowledgeBases.DeleteKnowledgeBase]. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -664,7 +662,6 @@ def __call__( request (~.knowledge_base.GetKnowledgeBaseRequest): The request object. Request message for [KnowledgeBases.GetKnowledgeBase][google.cloud.dialogflow.v2.KnowledgeBases.GetKnowledgeBase]. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -774,7 +771,6 @@ def __call__( request (~.knowledge_base.ListKnowledgeBasesRequest): The request object. Request message for [KnowledgeBases.ListKnowledgeBases][google.cloud.dialogflow.v2.KnowledgeBases.ListKnowledgeBases]. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -874,7 +870,6 @@ def __call__( request (~.gcd_knowledge_base.UpdateKnowledgeBaseRequest): The request object. Request message for [KnowledgeBases.UpdateKnowledgeBase][google.cloud.dialogflow.v2.KnowledgeBases.UpdateKnowledgeBase]. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. diff --git a/google/cloud/dialogflow_v2/services/participants/async_client.py b/google/cloud/dialogflow_v2/services/participants/async_client.py index 6f4cb7357..7a073125e 100644 --- a/google/cloud/dialogflow_v2/services/participants/async_client.py +++ b/google/cloud/dialogflow_v2/services/participants/async_client.py @@ -883,44 +883,45 @@ def request_generator(): Args: requests (AsyncIterator[`google.cloud.dialogflow_v2.types.StreamingAnalyzeContentRequest`]): - The request object AsyncIterator. The top-level message sent by the - client to the + The request object AsyncIterator. The top-level message sent by the client to the [Participants.StreamingAnalyzeContent][google.cloud.dialogflow.v2.Participants.StreamingAnalyzeContent] method. Multiple request messages should be sent in order: - 1. The first message must contain - [participant][google.cloud.dialogflow.v2.StreamingAnalyzeContentRequest.participant], - [config][google.cloud.dialogflow.v2.StreamingAnalyzeContentRequest.config] - and optionally - [query_params][google.cloud.dialogflow.v2.StreamingAnalyzeContentRequest.query_params]. - If you want to receive an audio response, it should also - contain - [reply_audio_config][google.cloud.dialogflow.v2.StreamingAnalyzeContentRequest.reply_audio_config]. - The message must not contain - [input][google.cloud.dialogflow.v2.StreamingAnalyzeContentRequest.input]. - 2. If - [config][google.cloud.dialogflow.v2.StreamingAnalyzeContentRequest.config] - in the first message - was set to - [audio_config][google.cloud.dialogflow.v2.StreamingAnalyzeContentRequest.audio_config], - all subsequent messages must contain - [input_audio][google.cloud.dialogflow.v2.StreamingAnalyzeContentRequest.input_audio] - to continue with Speech recognition. However, note that: - * Dialogflow will bill you for the audio so far. - * Dialogflow discards all Speech recognition results - in favor of the text input. - - 3. If - [StreamingAnalyzeContentRequest.config][google.cloud.dialogflow.v2.StreamingAnalyzeContentRequest.config] - in the first message was set - to - [StreamingAnalyzeContentRequest.text_config][google.cloud.dialogflow.v2.StreamingAnalyzeContentRequest.text_config], - then the second message must contain only - [input_text][google.cloud.dialogflow.v2.StreamingAnalyzeContentRequest.input_text]. - Moreover, you must not send more than two messages. - After you sent all input, you must half-close or abort + 1. The first message must contain + [participant][google.cloud.dialogflow.v2.StreamingAnalyzeContentRequest.participant], + [config][google.cloud.dialogflow.v2.StreamingAnalyzeContentRequest.config] + and optionally + [query_params][google.cloud.dialogflow.v2.StreamingAnalyzeContentRequest.query_params]. + If you want to receive an audio response, it should + also contain + [reply_audio_config][google.cloud.dialogflow.v2.StreamingAnalyzeContentRequest.reply_audio_config]. + The message must not contain + [input][google.cloud.dialogflow.v2.StreamingAnalyzeContentRequest.input]. + + 2. If + [config][google.cloud.dialogflow.v2.StreamingAnalyzeContentRequest.config] + in the first message was set to + [audio_config][google.cloud.dialogflow.v2.StreamingAnalyzeContentRequest.audio_config], + all subsequent messages must contain + [input_audio][google.cloud.dialogflow.v2.StreamingAnalyzeContentRequest.input_audio] + to continue with Speech recognition. However, note + that: + + - Dialogflow will bill you for the audio so far. + - Dialogflow discards all Speech recognition results + in favor of the text input. + + 3. If + [StreamingAnalyzeContentRequest.config][google.cloud.dialogflow.v2.StreamingAnalyzeContentRequest.config] + in the first message was set to + [StreamingAnalyzeContentRequest.text_config][google.cloud.dialogflow.v2.StreamingAnalyzeContentRequest.text_config], + then the second message must contain only + [input_text][google.cloud.dialogflow.v2.StreamingAnalyzeContentRequest.input_text]. + Moreover, you must not send more than two messages. + + After you sent all input, you must half-close or abort the request stream. retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. diff --git a/google/cloud/dialogflow_v2/services/participants/client.py b/google/cloud/dialogflow_v2/services/participants/client.py index 2df2314cb..4c36c35af 100644 --- a/google/cloud/dialogflow_v2/services/participants/client.py +++ b/google/cloud/dialogflow_v2/services/participants/client.py @@ -1194,44 +1194,45 @@ def request_generator(): Args: requests (Iterator[google.cloud.dialogflow_v2.types.StreamingAnalyzeContentRequest]): - The request object iterator. The top-level message sent by the - client to the + The request object iterator. The top-level message sent by the client to the [Participants.StreamingAnalyzeContent][google.cloud.dialogflow.v2.Participants.StreamingAnalyzeContent] method. Multiple request messages should be sent in order: - 1. The first message must contain - [participant][google.cloud.dialogflow.v2.StreamingAnalyzeContentRequest.participant], - [config][google.cloud.dialogflow.v2.StreamingAnalyzeContentRequest.config] - and optionally - [query_params][google.cloud.dialogflow.v2.StreamingAnalyzeContentRequest.query_params]. - If you want to receive an audio response, it should also - contain - [reply_audio_config][google.cloud.dialogflow.v2.StreamingAnalyzeContentRequest.reply_audio_config]. - The message must not contain - [input][google.cloud.dialogflow.v2.StreamingAnalyzeContentRequest.input]. - 2. If - [config][google.cloud.dialogflow.v2.StreamingAnalyzeContentRequest.config] - in the first message - was set to - [audio_config][google.cloud.dialogflow.v2.StreamingAnalyzeContentRequest.audio_config], - all subsequent messages must contain - [input_audio][google.cloud.dialogflow.v2.StreamingAnalyzeContentRequest.input_audio] - to continue with Speech recognition. However, note that: - * Dialogflow will bill you for the audio so far. - * Dialogflow discards all Speech recognition results - in favor of the text input. - - 3. If - [StreamingAnalyzeContentRequest.config][google.cloud.dialogflow.v2.StreamingAnalyzeContentRequest.config] - in the first message was set - to - [StreamingAnalyzeContentRequest.text_config][google.cloud.dialogflow.v2.StreamingAnalyzeContentRequest.text_config], - then the second message must contain only - [input_text][google.cloud.dialogflow.v2.StreamingAnalyzeContentRequest.input_text]. - Moreover, you must not send more than two messages. - After you sent all input, you must half-close or abort + 1. The first message must contain + [participant][google.cloud.dialogflow.v2.StreamingAnalyzeContentRequest.participant], + [config][google.cloud.dialogflow.v2.StreamingAnalyzeContentRequest.config] + and optionally + [query_params][google.cloud.dialogflow.v2.StreamingAnalyzeContentRequest.query_params]. + If you want to receive an audio response, it should + also contain + [reply_audio_config][google.cloud.dialogflow.v2.StreamingAnalyzeContentRequest.reply_audio_config]. + The message must not contain + [input][google.cloud.dialogflow.v2.StreamingAnalyzeContentRequest.input]. + + 2. If + [config][google.cloud.dialogflow.v2.StreamingAnalyzeContentRequest.config] + in the first message was set to + [audio_config][google.cloud.dialogflow.v2.StreamingAnalyzeContentRequest.audio_config], + all subsequent messages must contain + [input_audio][google.cloud.dialogflow.v2.StreamingAnalyzeContentRequest.input_audio] + to continue with Speech recognition. However, note + that: + + - Dialogflow will bill you for the audio so far. + - Dialogflow discards all Speech recognition results + in favor of the text input. + + 3. If + [StreamingAnalyzeContentRequest.config][google.cloud.dialogflow.v2.StreamingAnalyzeContentRequest.config] + in the first message was set to + [StreamingAnalyzeContentRequest.text_config][google.cloud.dialogflow.v2.StreamingAnalyzeContentRequest.text_config], + then the second message must contain only + [input_text][google.cloud.dialogflow.v2.StreamingAnalyzeContentRequest.input_text]. + Moreover, you must not send more than two messages. + + After you sent all input, you must half-close or abort the request stream. retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. diff --git a/google/cloud/dialogflow_v2/services/participants/transports/rest.py b/google/cloud/dialogflow_v2/services/participants/transports/rest.py index cc66544c4..b958fec0f 100644 --- a/google/cloud/dialogflow_v2/services/participants/transports/rest.py +++ b/google/cloud/dialogflow_v2/services/participants/transports/rest.py @@ -559,7 +559,6 @@ def __call__( request (~.gcd_participant.AnalyzeContentRequest): The request object. The request message for [Participants.AnalyzeContent][google.cloud.dialogflow.v2.Participants.AnalyzeContent]. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -663,7 +662,6 @@ def __call__( request (~.gcd_participant.CreateParticipantRequest): The request object. The request message for [Participants.CreateParticipant][google.cloud.dialogflow.v2.Participants.CreateParticipant]. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -769,7 +767,6 @@ def __call__( request (~.participant.GetParticipantRequest): The request object. The request message for [Participants.GetParticipant][google.cloud.dialogflow.v2.Participants.GetParticipant]. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -863,7 +860,6 @@ def __call__( request (~.participant.ListParticipantsRequest): The request object. The request message for [Participants.ListParticipants][google.cloud.dialogflow.v2.Participants.ListParticipants]. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -975,7 +971,6 @@ def __call__( request (~.participant.SuggestArticlesRequest): The request object. The request message for [Participants.SuggestArticles][google.cloud.dialogflow.v2.Participants.SuggestArticles]. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -1081,7 +1076,6 @@ def __call__( request (~.participant.SuggestFaqAnswersRequest): The request object. The request message for [Participants.SuggestFaqAnswers][google.cloud.dialogflow.v2.Participants.SuggestFaqAnswers]. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -1187,7 +1181,6 @@ def __call__( request (~.participant.SuggestSmartRepliesRequest): The request object. The request message for [Participants.SuggestSmartReplies][google.cloud.dialogflow.v2.Participants.SuggestSmartReplies]. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -1295,7 +1288,6 @@ def __call__( request (~.gcd_participant.UpdateParticipantRequest): The request object. The request message for [Participants.UpdateParticipant][google.cloud.dialogflow.v2.Participants.UpdateParticipant]. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. diff --git a/google/cloud/dialogflow_v2/services/session_entity_types/transports/rest.py b/google/cloud/dialogflow_v2/services/session_entity_types/transports/rest.py index 92016e826..d5254e458 100644 --- a/google/cloud/dialogflow_v2/services/session_entity_types/transports/rest.py +++ b/google/cloud/dialogflow_v2/services/session_entity_types/transports/rest.py @@ -468,7 +468,6 @@ def __call__( request (~.gcd_session_entity_type.CreateSessionEntityTypeRequest): The request object. The request message for [SessionEntityTypes.CreateSessionEntityType][google.cloud.dialogflow.v2.SessionEntityTypes.CreateSessionEntityType]. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -595,7 +594,6 @@ def __call__( request (~.session_entity_type.DeleteSessionEntityTypeRequest): The request object. The request message for [SessionEntityTypes.DeleteSessionEntityType][google.cloud.dialogflow.v2.SessionEntityTypes.DeleteSessionEntityType]. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -685,7 +683,6 @@ def __call__( request (~.session_entity_type.GetSessionEntityTypeRequest): The request object. The request message for [SessionEntityTypes.GetSessionEntityType][google.cloud.dialogflow.v2.SessionEntityTypes.GetSessionEntityType]. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -797,7 +794,6 @@ def __call__( request (~.session_entity_type.ListSessionEntityTypesRequest): The request object. The request message for [SessionEntityTypes.ListSessionEntityTypes][google.cloud.dialogflow.v2.SessionEntityTypes.ListSessionEntityTypes]. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -902,7 +898,6 @@ def __call__( request (~.gcd_session_entity_type.UpdateSessionEntityTypeRequest): The request object. The request message for [SessionEntityTypes.UpdateSessionEntityType][google.cloud.dialogflow.v2.SessionEntityTypes.UpdateSessionEntityType]. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. diff --git a/google/cloud/dialogflow_v2/services/sessions/async_client.py b/google/cloud/dialogflow_v2/services/sessions/async_client.py index f3c562130..4f1c5656c 100644 --- a/google/cloud/dialogflow_v2/services/sessions/async_client.py +++ b/google/cloud/dialogflow_v2/services/sessions/async_client.py @@ -451,41 +451,44 @@ def request_generator(): Args: requests (AsyncIterator[`google.cloud.dialogflow_v2.types.StreamingDetectIntentRequest`]): - The request object AsyncIterator. The top-level message sent by the - client to the + The request object AsyncIterator. The top-level message sent by the client to the [Sessions.StreamingDetectIntent][google.cloud.dialogflow.v2.Sessions.StreamingDetectIntent] method. Multiple request messages should be sent in order: - 1. The first message must contain - [session][google.cloud.dialogflow.v2.StreamingDetectIntentRequest.session], - [query_input][google.cloud.dialogflow.v2.StreamingDetectIntentRequest.query_input] - plus optionally - [query_params][google.cloud.dialogflow.v2.StreamingDetectIntentRequest.query_params]. - If the client wants to receive an audio response, it - should also contain - [output_audio_config][google.cloud.dialogflow.v2.StreamingDetectIntentRequest.output_audio_config]. - The message must not contain - [input_audio][google.cloud.dialogflow.v2.StreamingDetectIntentRequest.input_audio]. - 2. If - [query_input][google.cloud.dialogflow.v2.StreamingDetectIntentRequest.query_input] - was set to - [query_input.audio_config][google.cloud.dialogflow.v2.InputAudioConfig], - all subsequent messages must contain - [input_audio][google.cloud.dialogflow.v2.StreamingDetectIntentRequest.input_audio] - to continue with Speech recognition. If you decide to - rather detect an intent from text input after you - already started Speech recognition, please send a - message with - [query_input.text][google.cloud.dialogflow.v2.QueryInput.text]. - However, note that: - - * Dialogflow will bill you for the audio duration so - far. * Dialogflow discards all Speech recognition - results in favor of the input text. - * Dialogflow will use the language code from the - first message. + 1. The first message must contain + [session][google.cloud.dialogflow.v2.StreamingDetectIntentRequest.session], + [query_input][google.cloud.dialogflow.v2.StreamingDetectIntentRequest.query_input] + plus optionally + [query_params][google.cloud.dialogflow.v2.StreamingDetectIntentRequest.query_params]. + If the client wants to receive an audio response, it + should also contain + [output_audio_config][google.cloud.dialogflow.v2.StreamingDetectIntentRequest.output_audio_config]. + The message must not contain + [input_audio][google.cloud.dialogflow.v2.StreamingDetectIntentRequest.input_audio]. + + 2. If + [query_input][google.cloud.dialogflow.v2.StreamingDetectIntentRequest.query_input] + was set to + [query_input.audio_config][google.cloud.dialogflow.v2.InputAudioConfig], + all subsequent messages must contain + [input_audio][google.cloud.dialogflow.v2.StreamingDetectIntentRequest.input_audio] + to continue with Speech recognition. If you decide to + rather detect an intent from text input after you + already started Speech recognition, please send a + message with + [query_input.text][google.cloud.dialogflow.v2.QueryInput.text]. + + However, note that: + + - Dialogflow will bill you for the audio duration so + far. + - Dialogflow discards all Speech recognition results + in favor of the input text. + - Dialogflow will use the language code from the + first message. + After you sent all input, you must half-close or abort the request stream. retry (google.api_core.retry.Retry): Designation of what errors, if any, diff --git a/google/cloud/dialogflow_v2/services/sessions/client.py b/google/cloud/dialogflow_v2/services/sessions/client.py index ec807833a..a4704444f 100644 --- a/google/cloud/dialogflow_v2/services/sessions/client.py +++ b/google/cloud/dialogflow_v2/services/sessions/client.py @@ -726,41 +726,44 @@ def request_generator(): Args: requests (Iterator[google.cloud.dialogflow_v2.types.StreamingDetectIntentRequest]): - The request object iterator. The top-level message sent by the - client to the + The request object iterator. The top-level message sent by the client to the [Sessions.StreamingDetectIntent][google.cloud.dialogflow.v2.Sessions.StreamingDetectIntent] method. Multiple request messages should be sent in order: - 1. The first message must contain - [session][google.cloud.dialogflow.v2.StreamingDetectIntentRequest.session], - [query_input][google.cloud.dialogflow.v2.StreamingDetectIntentRequest.query_input] - plus optionally - [query_params][google.cloud.dialogflow.v2.StreamingDetectIntentRequest.query_params]. - If the client wants to receive an audio response, it - should also contain - [output_audio_config][google.cloud.dialogflow.v2.StreamingDetectIntentRequest.output_audio_config]. - The message must not contain - [input_audio][google.cloud.dialogflow.v2.StreamingDetectIntentRequest.input_audio]. - 2. If - [query_input][google.cloud.dialogflow.v2.StreamingDetectIntentRequest.query_input] - was set to - [query_input.audio_config][google.cloud.dialogflow.v2.InputAudioConfig], - all subsequent messages must contain - [input_audio][google.cloud.dialogflow.v2.StreamingDetectIntentRequest.input_audio] - to continue with Speech recognition. If you decide to - rather detect an intent from text input after you - already started Speech recognition, please send a - message with - [query_input.text][google.cloud.dialogflow.v2.QueryInput.text]. - However, note that: - - * Dialogflow will bill you for the audio duration so - far. * Dialogflow discards all Speech recognition - results in favor of the input text. - * Dialogflow will use the language code from the - first message. + 1. The first message must contain + [session][google.cloud.dialogflow.v2.StreamingDetectIntentRequest.session], + [query_input][google.cloud.dialogflow.v2.StreamingDetectIntentRequest.query_input] + plus optionally + [query_params][google.cloud.dialogflow.v2.StreamingDetectIntentRequest.query_params]. + If the client wants to receive an audio response, it + should also contain + [output_audio_config][google.cloud.dialogflow.v2.StreamingDetectIntentRequest.output_audio_config]. + The message must not contain + [input_audio][google.cloud.dialogflow.v2.StreamingDetectIntentRequest.input_audio]. + + 2. If + [query_input][google.cloud.dialogflow.v2.StreamingDetectIntentRequest.query_input] + was set to + [query_input.audio_config][google.cloud.dialogflow.v2.InputAudioConfig], + all subsequent messages must contain + [input_audio][google.cloud.dialogflow.v2.StreamingDetectIntentRequest.input_audio] + to continue with Speech recognition. If you decide to + rather detect an intent from text input after you + already started Speech recognition, please send a + message with + [query_input.text][google.cloud.dialogflow.v2.QueryInput.text]. + + However, note that: + + - Dialogflow will bill you for the audio duration so + far. + - Dialogflow discards all Speech recognition results + in favor of the input text. + - Dialogflow will use the language code from the + first message. + After you sent all input, you must half-close or abort the request stream. retry (google.api_core.retry.Retry): Designation of what errors, if any, diff --git a/google/cloud/dialogflow_v2/services/versions/transports/rest.py b/google/cloud/dialogflow_v2/services/versions/transports/rest.py index b89c13d70..105e91f68 100644 --- a/google/cloud/dialogflow_v2/services/versions/transports/rest.py +++ b/google/cloud/dialogflow_v2/services/versions/transports/rest.py @@ -440,7 +440,6 @@ def __call__( request (~.gcd_version.CreateVersionRequest): The request object. The request message for [Versions.CreateVersion][google.cloud.dialogflow.v2.Versions.CreateVersion]. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -561,7 +560,6 @@ def __call__( request (~.version.DeleteVersionRequest): The request object. The request message for [Versions.DeleteVersion][google.cloud.dialogflow.v2.Versions.DeleteVersion]. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -641,7 +639,6 @@ def __call__( request (~.version.GetVersionRequest): The request object. The request message for [Versions.GetVersion][google.cloud.dialogflow.v2.Versions.GetVersion]. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -752,7 +749,6 @@ def __call__( request (~.version.ListVersionsRequest): The request object. The request message for [Versions.ListVersions][google.cloud.dialogflow.v2.Versions.ListVersions]. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -848,7 +844,6 @@ def __call__( request (~.gcd_version.UpdateVersionRequest): The request object. The request message for [Versions.UpdateVersion][google.cloud.dialogflow.v2.Versions.UpdateVersion]. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. diff --git a/google/cloud/dialogflow_v2beta1/services/agents/transports/rest.py b/google/cloud/dialogflow_v2beta1/services/agents/transports/rest.py index 200ff770e..ce2c9f3c3 100644 --- a/google/cloud/dialogflow_v2beta1/services/agents/transports/rest.py +++ b/google/cloud/dialogflow_v2beta1/services/agents/transports/rest.py @@ -624,7 +624,6 @@ def __call__( request (~.agent.DeleteAgentRequest): The request object. The request message for [Agents.DeleteAgent][google.cloud.dialogflow.v2beta1.Agents.DeleteAgent]. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -704,7 +703,6 @@ def __call__( request (~.agent.ExportAgentRequest): The request object. The request message for [Agents.ExportAgent][google.cloud.dialogflow.v2beta1.Agents.ExportAgent]. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -807,7 +805,6 @@ def __call__( request (~.agent.GetAgentRequest): The request object. The request message for [Agents.GetAgent][google.cloud.dialogflow.v2beta1.Agents.GetAgent]. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -911,7 +908,6 @@ def __call__( request (~.agent.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. @@ -1007,7 +1003,6 @@ def __call__( request (~.agent.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. @@ -1110,7 +1105,6 @@ def __call__( request (~.agent.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. @@ -1213,7 +1207,6 @@ def __call__( request (~.agent.SearchAgentsRequest): The request object. The request message for [Agents.SearchAgents][google.cloud.dialogflow.v2beta1.Agents.SearchAgents]. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -1307,7 +1300,6 @@ def __call__( request (~.gcd_agent.SetAgentRequest): The request object. The request message for [Agents.SetAgent][google.cloud.dialogflow.v2beta1.Agents.SetAgent]. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -1421,7 +1413,6 @@ def __call__( request (~.agent.TrainAgentRequest): The request object. The request message for [Agents.TrainAgent][google.cloud.dialogflow.v2beta1.Agents.TrainAgent]. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. diff --git a/google/cloud/dialogflow_v2beta1/services/answer_records/transports/rest.py b/google/cloud/dialogflow_v2beta1/services/answer_records/transports/rest.py index 4056eb6ba..e577b52ad 100644 --- a/google/cloud/dialogflow_v2beta1/services/answer_records/transports/rest.py +++ b/google/cloud/dialogflow_v2beta1/services/answer_records/transports/rest.py @@ -394,7 +394,6 @@ def __call__( request (~.answer_record.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. @@ -508,7 +507,6 @@ def __call__( request (~.answer_record.ListAnswerRecordsRequest): The request object. Request message for [AnswerRecords.ListAnswerRecords][google.cloud.dialogflow.v2beta1.AnswerRecords.ListAnswerRecords]. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -603,7 +601,6 @@ def __call__( request (~.gcd_answer_record.UpdateAnswerRecordRequest): The request object. Request message for [AnswerRecords.UpdateAnswerRecord][google.cloud.dialogflow.v2beta1.AnswerRecords.UpdateAnswerRecord]. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. diff --git a/google/cloud/dialogflow_v2beta1/services/contexts/transports/rest.py b/google/cloud/dialogflow_v2beta1/services/contexts/transports/rest.py index f3d21503e..aa3e675d5 100644 --- a/google/cloud/dialogflow_v2beta1/services/contexts/transports/rest.py +++ b/google/cloud/dialogflow_v2beta1/services/contexts/transports/rest.py @@ -457,7 +457,6 @@ def __call__( request (~.gcd_context.CreateContextRequest): The request object. The request message for [Contexts.CreateContext][google.cloud.dialogflow.v2beta1.Contexts.CreateContext]. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -588,7 +587,6 @@ def __call__( request (~.context.DeleteAllContextsRequest): The request object. The request message for [Contexts.DeleteAllContexts][google.cloud.dialogflow.v2beta1.Contexts.DeleteAllContexts]. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -678,7 +676,6 @@ def __call__( request (~.context.DeleteContextRequest): The request object. The request message for [Contexts.DeleteContext][google.cloud.dialogflow.v2beta1.Contexts.DeleteContext]. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -766,7 +763,6 @@ def __call__( request (~.context.GetContextRequest): The request object. The request message for [Contexts.GetContext][google.cloud.dialogflow.v2beta1.Contexts.GetContext]. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -885,7 +881,6 @@ def __call__( request (~.context.ListContextsRequest): The request object. The request message for [Contexts.ListContexts][google.cloud.dialogflow.v2beta1.Contexts.ListContexts]. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -987,7 +982,6 @@ def __call__( request (~.gcd_context.UpdateContextRequest): The request object. The request message for [Contexts.UpdateContext][google.cloud.dialogflow.v2beta1.Contexts.UpdateContext]. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. 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 d48701f54..2c8614a7c 100644 --- a/google/cloud/dialogflow_v2beta1/services/conversation_profiles/async_client.py +++ b/google/cloud/dialogflow_v2beta1/services/conversation_profiles/async_client.py @@ -771,6 +771,7 @@ async def sample_delete_conversation_profile(): request (Optional[Union[google.cloud.dialogflow_v2beta1.types.DeleteConversationProfileRequest, dict]]): The request object. The request message for [ConversationProfiles.DeleteConversationProfile][google.cloud.dialogflow.v2beta1.ConversationProfiles.DeleteConversationProfile]. + This operation fails if the conversation profile is still referenced from a phone number. name (:class:`str`): diff --git a/google/cloud/dialogflow_v2beta1/services/conversation_profiles/client.py b/google/cloud/dialogflow_v2beta1/services/conversation_profiles/client.py index 1bbaf605c..ae2616687 100644 --- a/google/cloud/dialogflow_v2beta1/services/conversation_profiles/client.py +++ b/google/cloud/dialogflow_v2beta1/services/conversation_profiles/client.py @@ -1085,6 +1085,7 @@ def sample_delete_conversation_profile(): request (Union[google.cloud.dialogflow_v2beta1.types.DeleteConversationProfileRequest, dict]): The request object. The request message for [ConversationProfiles.DeleteConversationProfile][google.cloud.dialogflow.v2beta1.ConversationProfiles.DeleteConversationProfile]. + This operation fails if the conversation profile is still referenced from a phone number. name (str): diff --git a/google/cloud/dialogflow_v2beta1/services/conversation_profiles/transports/rest.py b/google/cloud/dialogflow_v2beta1/services/conversation_profiles/transports/rest.py index 0415d00b2..03822b922 100644 --- a/google/cloud/dialogflow_v2beta1/services/conversation_profiles/transports/rest.py +++ b/google/cloud/dialogflow_v2beta1/services/conversation_profiles/transports/rest.py @@ -602,7 +602,6 @@ def __call__( request (~.gcd_conversation_profile.ClearSuggestionFeatureConfigRequest): The request object. The request message for [ConversationProfiles.ClearFeature][]. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -710,7 +709,6 @@ def __call__( request (~.gcd_conversation_profile.CreateConversationProfileRequest): The request object. The request message for [ConversationProfiles.CreateConversationProfile][google.cloud.dialogflow.v2beta1.ConversationProfiles.CreateConversationProfile]. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -822,7 +820,6 @@ def __call__( This operation fails if the conversation profile is still referenced from a phone number. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -906,7 +903,6 @@ def __call__( request (~.conversation_profile.GetConversationProfileRequest): The request object. The request message for [ConversationProfiles.GetConversationProfile][google.cloud.dialogflow.v2beta1.ConversationProfiles.GetConversationProfile]. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -1003,7 +999,6 @@ def __call__( request (~.conversation_profile.ListConversationProfilesRequest): The request object. The request message for [ConversationProfiles.ListConversationProfiles][google.cloud.dialogflow.v2beta1.ConversationProfiles.ListConversationProfiles]. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -1102,7 +1097,6 @@ def __call__( request (~.gcd_conversation_profile.SetSuggestionFeatureConfigRequest): The request object. The request message for [ConversationProfiles.SetSuggestionFeature][]. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -1212,7 +1206,6 @@ def __call__( request (~.gcd_conversation_profile.UpdateConversationProfileRequest): The request object. The request message for [ConversationProfiles.UpdateConversationProfile][google.cloud.dialogflow.v2beta1.ConversationProfiles.UpdateConversationProfile]. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. diff --git a/google/cloud/dialogflow_v2beta1/services/conversations/transports/rest.py b/google/cloud/dialogflow_v2beta1/services/conversations/transports/rest.py index dc975c352..2684c880a 100644 --- a/google/cloud/dialogflow_v2beta1/services/conversations/transports/rest.py +++ b/google/cloud/dialogflow_v2beta1/services/conversations/transports/rest.py @@ -530,7 +530,6 @@ def __call__( request (~.conversation.BatchCreateMessagesRequest): The request object. The request message for [Conversations.BatchCreateMessagesRequest][]. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -636,7 +635,6 @@ def __call__( request (~.conversation.CompleteConversationRequest): The request object. The request message for [Conversations.CompleteConversation][google.cloud.dialogflow.v2beta1.Conversations.CompleteConversation]. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -747,7 +745,6 @@ def __call__( request (~.gcd_conversation.CreateConversationRequest): The request object. The request message for [Conversations.CreateConversation][google.cloud.dialogflow.v2beta1.Conversations.CreateConversation]. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -858,7 +855,6 @@ def __call__( request (~.conversation.GetConversationRequest): The request object. The request message for [Conversations.GetConversation][google.cloud.dialogflow.v2beta1.Conversations.GetConversation]. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -959,7 +955,6 @@ def __call__( request (~.conversation.ListConversationsRequest): The request object. The request message for [Conversations.ListConversations][google.cloud.dialogflow.v2beta1.Conversations.ListConversations]. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -1055,7 +1050,6 @@ def __call__( request (~.conversation.ListMessagesRequest): The request object. The request message for [Conversations.ListMessages][google.cloud.dialogflow.v2beta1.Conversations.ListMessages]. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -1150,7 +1144,6 @@ def __call__( request (~.gcd_conversation.SuggestConversationSummaryRequest): The request object. The request message for [Conversations.SuggestConversationSummary][google.cloud.dialogflow.v2beta1.Conversations.SuggestConversationSummary]. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. diff --git a/google/cloud/dialogflow_v2beta1/services/documents/transports/rest.py b/google/cloud/dialogflow_v2beta1/services/documents/transports/rest.py index d00311d77..7c34cb37f 100644 --- a/google/cloud/dialogflow_v2beta1/services/documents/transports/rest.py +++ b/google/cloud/dialogflow_v2beta1/services/documents/transports/rest.py @@ -591,7 +591,6 @@ def __call__( request (~.gcd_document.CreateDocumentRequest): The request object. Request message for [Documents.CreateDocument][google.cloud.dialogflow.v2beta1.Documents.CreateDocument]. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -699,7 +698,6 @@ def __call__( request (~.document.DeleteDocumentRequest): The request object. Request message for [Documents.DeleteDocument][google.cloud.dialogflow.v2beta1.Documents.DeleteDocument]. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -796,7 +794,6 @@ def __call__( request (~.document.GetDocumentRequest): The request object. Request message for [Documents.GetDocument][google.cloud.dialogflow.v2beta1.Documents.GetDocument]. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -901,7 +898,6 @@ def __call__( request (~.document.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. @@ -1006,7 +1002,6 @@ def __call__( request (~.document.ListDocumentsRequest): The request object. Request message for [Documents.ListDocuments][google.cloud.dialogflow.v2beta1.Documents.ListDocuments]. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -1104,7 +1099,6 @@ def __call__( request (~.document.ReloadDocumentRequest): The request object. Request message for [Documents.ReloadDocument][google.cloud.dialogflow.v2beta1.Documents.ReloadDocument]. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -1212,7 +1206,6 @@ def __call__( request (~.gcd_document.UpdateDocumentRequest): The request object. Request message for [Documents.UpdateDocument][google.cloud.dialogflow.v2beta1.Documents.UpdateDocument]. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. diff --git a/google/cloud/dialogflow_v2beta1/services/entity_types/transports/rest.py b/google/cloud/dialogflow_v2beta1/services/entity_types/transports/rest.py index 9f8407b52..c9044fdc9 100644 --- a/google/cloud/dialogflow_v2beta1/services/entity_types/transports/rest.py +++ b/google/cloud/dialogflow_v2beta1/services/entity_types/transports/rest.py @@ -674,7 +674,6 @@ def __call__( request (~.entity_type.BatchCreateEntitiesRequest): The request object. The request message for [EntityTypes.BatchCreateEntities][google.cloud.dialogflow.v2beta1.EntityTypes.BatchCreateEntities]. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -779,7 +778,6 @@ def __call__( request (~.entity_type.BatchDeleteEntitiesRequest): The request object. The request message for [EntityTypes.BatchDeleteEntities][google.cloud.dialogflow.v2beta1.EntityTypes.BatchDeleteEntities]. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -884,7 +882,6 @@ def __call__( request (~.entity_type.BatchDeleteEntityTypesRequest): The request object. The request message for [EntityTypes.BatchDeleteEntityTypes][google.cloud.dialogflow.v2beta1.EntityTypes.BatchDeleteEntityTypes]. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -989,7 +986,6 @@ def __call__( request (~.entity_type.BatchUpdateEntitiesRequest): The request object. The request message for [EntityTypes.BatchUpdateEntities][google.cloud.dialogflow.v2beta1.EntityTypes.BatchUpdateEntities]. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -1094,7 +1090,6 @@ def __call__( request (~.entity_type.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. @@ -1199,7 +1194,6 @@ def __call__( request (~.gcd_entity_type.CreateEntityTypeRequest): The request object. The request message for [EntityTypes.CreateEntityType][google.cloud.dialogflow.v2beta1.EntityTypes.CreateEntityType]. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -1318,7 +1312,6 @@ def __call__( request (~.entity_type.DeleteEntityTypeRequest): The request object. The request message for [EntityTypes.DeleteEntityType][google.cloud.dialogflow.v2beta1.EntityTypes.DeleteEntityType]. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -1400,7 +1393,6 @@ def __call__( request (~.entity_type.GetEntityTypeRequest): The request object. The request message for [EntityTypes.GetEntityType][google.cloud.dialogflow.v2beta1.EntityTypes.GetEntityType]. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -1507,7 +1499,6 @@ def __call__( request (~.entity_type.ListEntityTypesRequest): The request object. The request message for [EntityTypes.ListEntityTypes][google.cloud.dialogflow.v2beta1.EntityTypes.ListEntityTypes]. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -1603,7 +1594,6 @@ def __call__( request (~.gcd_entity_type.UpdateEntityTypeRequest): The request object. The request message for [EntityTypes.UpdateEntityType][google.cloud.dialogflow.v2beta1.EntityTypes.UpdateEntityType]. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. diff --git a/google/cloud/dialogflow_v2beta1/services/environments/transports/rest.py b/google/cloud/dialogflow_v2beta1/services/environments/transports/rest.py index 5b1c14391..8841797ef 100644 --- a/google/cloud/dialogflow_v2beta1/services/environments/transports/rest.py +++ b/google/cloud/dialogflow_v2beta1/services/environments/transports/rest.py @@ -485,7 +485,6 @@ def __call__( request (~.environment.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. @@ -608,7 +607,6 @@ def __call__( request (~.environment.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. @@ -690,7 +688,6 @@ def __call__( request (~.environment.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. @@ -801,7 +798,6 @@ def __call__( request (~.environment.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. @@ -897,7 +893,6 @@ def __call__( request (~.environment.ListEnvironmentsRequest): The request object. The request message for [Environments.ListEnvironments][google.cloud.dialogflow.v2beta1.Environments.ListEnvironments]. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -995,7 +990,6 @@ def __call__( request (~.environment.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. diff --git a/google/cloud/dialogflow_v2beta1/services/fulfillments/transports/rest.py b/google/cloud/dialogflow_v2beta1/services/fulfillments/transports/rest.py index b06d6244b..a1c336419 100644 --- a/google/cloud/dialogflow_v2beta1/services/fulfillments/transports/rest.py +++ b/google/cloud/dialogflow_v2beta1/services/fulfillments/transports/rest.py @@ -373,7 +373,6 @@ def __call__( request (~.fulfillment.GetFulfillmentRequest): The request object. The request message for [Fulfillments.GetFulfillment][google.cloud.dialogflow.v2beta1.Fulfillments.GetFulfillment]. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -479,7 +478,6 @@ def __call__( request (~.gcd_fulfillment.UpdateFulfillmentRequest): The request object. The request message for [Fulfillments.UpdateFulfillment][google.cloud.dialogflow.v2beta1.Fulfillments.UpdateFulfillment]. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. diff --git a/google/cloud/dialogflow_v2beta1/services/intents/transports/rest.py b/google/cloud/dialogflow_v2beta1/services/intents/transports/rest.py index 8b98c7f15..1aea5981e 100644 --- a/google/cloud/dialogflow_v2beta1/services/intents/transports/rest.py +++ b/google/cloud/dialogflow_v2beta1/services/intents/transports/rest.py @@ -569,7 +569,6 @@ def __call__( request (~.intent.BatchDeleteIntentsRequest): The request object. The request message for [Intents.BatchDeleteIntents][google.cloud.dialogflow.v2beta1.Intents.BatchDeleteIntents]. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -674,7 +673,6 @@ def __call__( request (~.intent.BatchUpdateIntentsRequest): The request object. The request message for [Intents.BatchUpdateIntents][google.cloud.dialogflow.v2beta1.Intents.BatchUpdateIntents]. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -779,7 +777,6 @@ def __call__( request (~.gcd_intent.CreateIntentRequest): The request object. The request message for [Intents.CreateIntent][google.cloud.dialogflow.v2beta1.Intents.CreateIntent]. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -892,7 +889,6 @@ def __call__( request (~.intent.DeleteIntentRequest): The request object. The request message for [Intents.DeleteIntent][google.cloud.dialogflow.v2beta1.Intents.DeleteIntent]. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -972,7 +968,6 @@ def __call__( request (~.intent.GetIntentRequest): The request object. The request message for [Intents.GetIntent][google.cloud.dialogflow.v2beta1.Intents.GetIntent]. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -1075,7 +1070,6 @@ def __call__( request (~.intent.ListIntentsRequest): The request object. The request message for [Intents.ListIntents][google.cloud.dialogflow.v2beta1.Intents.ListIntents]. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -1177,7 +1171,6 @@ def __call__( request (~.gcd_intent.UpdateIntentRequest): The request object. The request message for [Intents.UpdateIntent][google.cloud.dialogflow.v2beta1.Intents.UpdateIntent]. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. diff --git a/google/cloud/dialogflow_v2beta1/services/knowledge_bases/transports/rest.py b/google/cloud/dialogflow_v2beta1/services/knowledge_bases/transports/rest.py index 02ddb3db2..c5e3f7a16 100644 --- a/google/cloud/dialogflow_v2beta1/services/knowledge_bases/transports/rest.py +++ b/google/cloud/dialogflow_v2beta1/services/knowledge_bases/transports/rest.py @@ -457,7 +457,6 @@ def __call__( request (~.gcd_knowledge_base.CreateKnowledgeBaseRequest): The request object. Request message for [KnowledgeBases.CreateKnowledgeBase][google.cloud.dialogflow.v2beta1.KnowledgeBases.CreateKnowledgeBase]. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -578,7 +577,6 @@ def __call__( request (~.knowledge_base.DeleteKnowledgeBaseRequest): The request object. Request message for [KnowledgeBases.DeleteKnowledgeBase][google.cloud.dialogflow.v2beta1.KnowledgeBases.DeleteKnowledgeBase]. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -664,7 +662,6 @@ def __call__( request (~.knowledge_base.GetKnowledgeBaseRequest): The request object. Request message for [KnowledgeBases.GetKnowledgeBase][google.cloud.dialogflow.v2beta1.KnowledgeBases.GetKnowledgeBase]. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -774,7 +771,6 @@ def __call__( request (~.knowledge_base.ListKnowledgeBasesRequest): The request object. Request message for [KnowledgeBases.ListKnowledgeBases][google.cloud.dialogflow.v2beta1.KnowledgeBases.ListKnowledgeBases]. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -874,7 +870,6 @@ def __call__( request (~.gcd_knowledge_base.UpdateKnowledgeBaseRequest): The request object. Request message for [KnowledgeBases.UpdateKnowledgeBase][google.cloud.dialogflow.v2beta1.KnowledgeBases.UpdateKnowledgeBase]. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. diff --git a/google/cloud/dialogflow_v2beta1/services/participants/async_client.py b/google/cloud/dialogflow_v2beta1/services/participants/async_client.py index 5475ffda3..8999d1fda 100644 --- a/google/cloud/dialogflow_v2beta1/services/participants/async_client.py +++ b/google/cloud/dialogflow_v2beta1/services/participants/async_client.py @@ -890,49 +890,49 @@ def request_generator(): Args: requests (AsyncIterator[`google.cloud.dialogflow_v2beta1.types.StreamingAnalyzeContentRequest`]): - The request object AsyncIterator. The top-level message sent by the - client to the + The request object AsyncIterator. The top-level message sent by the client to the [Participants.StreamingAnalyzeContent][google.cloud.dialogflow.v2beta1.Participants.StreamingAnalyzeContent] method. Multiple request messages should be sent in order: - 1. The first message must contain - [participant][google.cloud.dialogflow.v2beta1.StreamingAnalyzeContentRequest.participant], - [config][google.cloud.dialogflow.v2beta1.StreamingAnalyzeContentRequest.config] - and optionally - [query_params][google.cloud.dialogflow.v2beta1.StreamingAnalyzeContentRequest.query_params]. - If you want to receive an audio response, it should also - contain - [reply_audio_config][google.cloud.dialogflow.v2beta1.StreamingAnalyzeContentRequest.reply_audio_config]. - The message must not contain - [input][google.cloud.dialogflow.v2beta1.StreamingAnalyzeContentRequest.input]. - 2. If - [config][google.cloud.dialogflow.v2beta1.StreamingAnalyzeContentRequest.config] - in the first message - was set to - [audio_config][google.cloud.dialogflow.v2beta1.StreamingAnalyzeContentRequest.audio_config], - all subsequent messages must contain - [input_audio][google.cloud.dialogflow.v2beta1.StreamingAnalyzeContentRequest.input_audio] - to continue with Speech recognition. If you decide to - rather analyze text input after you already started - Speech recognition, please send a message with - [StreamingAnalyzeContentRequest.input_text][google.cloud.dialogflow.v2beta1.StreamingAnalyzeContentRequest.input_text]. - However, note that: - - * Dialogflow will bill you for the audio so far. - * Dialogflow discards all Speech recognition results - in favor of the text input. - - 3. If - [StreamingAnalyzeContentRequest.config][google.cloud.dialogflow.v2beta1.StreamingAnalyzeContentRequest.config] - in the first message was set - to - [StreamingAnalyzeContentRequest.text_config][google.cloud.dialogflow.v2beta1.StreamingAnalyzeContentRequest.text_config], - then the second message must contain only - [input_text][google.cloud.dialogflow.v2beta1.StreamingAnalyzeContentRequest.input_text]. - Moreover, you must not send more than two messages. - After you sent all input, you must half-close or abort + 1. The first message must contain + [participant][google.cloud.dialogflow.v2beta1.StreamingAnalyzeContentRequest.participant], + [config][google.cloud.dialogflow.v2beta1.StreamingAnalyzeContentRequest.config] + and optionally + [query_params][google.cloud.dialogflow.v2beta1.StreamingAnalyzeContentRequest.query_params]. + If you want to receive an audio response, it should + also contain + [reply_audio_config][google.cloud.dialogflow.v2beta1.StreamingAnalyzeContentRequest.reply_audio_config]. + The message must not contain + [input][google.cloud.dialogflow.v2beta1.StreamingAnalyzeContentRequest.input]. + + 2. If + [config][google.cloud.dialogflow.v2beta1.StreamingAnalyzeContentRequest.config] + in the first message was set to + [audio_config][google.cloud.dialogflow.v2beta1.StreamingAnalyzeContentRequest.audio_config], + all subsequent messages must contain + [input_audio][google.cloud.dialogflow.v2beta1.StreamingAnalyzeContentRequest.input_audio] + to continue with Speech recognition. If you decide to + rather analyze text input after you already started + Speech recognition, please send a message with + [StreamingAnalyzeContentRequest.input_text][google.cloud.dialogflow.v2beta1.StreamingAnalyzeContentRequest.input_text]. + + However, note that: + + - Dialogflow will bill you for the audio so far. + - Dialogflow discards all Speech recognition results + in favor of the text input. + + 3. If + [StreamingAnalyzeContentRequest.config][google.cloud.dialogflow.v2beta1.StreamingAnalyzeContentRequest.config] + in the first message was set to + [StreamingAnalyzeContentRequest.text_config][google.cloud.dialogflow.v2beta1.StreamingAnalyzeContentRequest.text_config], + then the second message must contain only + [input_text][google.cloud.dialogflow.v2beta1.StreamingAnalyzeContentRequest.input_text]. + Moreover, you must not send more than two messages. + + After you sent all input, you must half-close or abort the request stream. retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. diff --git a/google/cloud/dialogflow_v2beta1/services/participants/client.py b/google/cloud/dialogflow_v2beta1/services/participants/client.py index 29cbfa3fc..62d288577 100644 --- a/google/cloud/dialogflow_v2beta1/services/participants/client.py +++ b/google/cloud/dialogflow_v2beta1/services/participants/client.py @@ -1221,49 +1221,49 @@ def request_generator(): Args: requests (Iterator[google.cloud.dialogflow_v2beta1.types.StreamingAnalyzeContentRequest]): - The request object iterator. The top-level message sent by the - client to the + The request object iterator. The top-level message sent by the client to the [Participants.StreamingAnalyzeContent][google.cloud.dialogflow.v2beta1.Participants.StreamingAnalyzeContent] method. Multiple request messages should be sent in order: - 1. The first message must contain - [participant][google.cloud.dialogflow.v2beta1.StreamingAnalyzeContentRequest.participant], - [config][google.cloud.dialogflow.v2beta1.StreamingAnalyzeContentRequest.config] - and optionally - [query_params][google.cloud.dialogflow.v2beta1.StreamingAnalyzeContentRequest.query_params]. - If you want to receive an audio response, it should also - contain - [reply_audio_config][google.cloud.dialogflow.v2beta1.StreamingAnalyzeContentRequest.reply_audio_config]. - The message must not contain - [input][google.cloud.dialogflow.v2beta1.StreamingAnalyzeContentRequest.input]. - 2. If - [config][google.cloud.dialogflow.v2beta1.StreamingAnalyzeContentRequest.config] - in the first message - was set to - [audio_config][google.cloud.dialogflow.v2beta1.StreamingAnalyzeContentRequest.audio_config], - all subsequent messages must contain - [input_audio][google.cloud.dialogflow.v2beta1.StreamingAnalyzeContentRequest.input_audio] - to continue with Speech recognition. If you decide to - rather analyze text input after you already started - Speech recognition, please send a message with - [StreamingAnalyzeContentRequest.input_text][google.cloud.dialogflow.v2beta1.StreamingAnalyzeContentRequest.input_text]. - However, note that: - - * Dialogflow will bill you for the audio so far. - * Dialogflow discards all Speech recognition results - in favor of the text input. - - 3. If - [StreamingAnalyzeContentRequest.config][google.cloud.dialogflow.v2beta1.StreamingAnalyzeContentRequest.config] - in the first message was set - to - [StreamingAnalyzeContentRequest.text_config][google.cloud.dialogflow.v2beta1.StreamingAnalyzeContentRequest.text_config], - then the second message must contain only - [input_text][google.cloud.dialogflow.v2beta1.StreamingAnalyzeContentRequest.input_text]. - Moreover, you must not send more than two messages. - After you sent all input, you must half-close or abort + 1. The first message must contain + [participant][google.cloud.dialogflow.v2beta1.StreamingAnalyzeContentRequest.participant], + [config][google.cloud.dialogflow.v2beta1.StreamingAnalyzeContentRequest.config] + and optionally + [query_params][google.cloud.dialogflow.v2beta1.StreamingAnalyzeContentRequest.query_params]. + If you want to receive an audio response, it should + also contain + [reply_audio_config][google.cloud.dialogflow.v2beta1.StreamingAnalyzeContentRequest.reply_audio_config]. + The message must not contain + [input][google.cloud.dialogflow.v2beta1.StreamingAnalyzeContentRequest.input]. + + 2. If + [config][google.cloud.dialogflow.v2beta1.StreamingAnalyzeContentRequest.config] + in the first message was set to + [audio_config][google.cloud.dialogflow.v2beta1.StreamingAnalyzeContentRequest.audio_config], + all subsequent messages must contain + [input_audio][google.cloud.dialogflow.v2beta1.StreamingAnalyzeContentRequest.input_audio] + to continue with Speech recognition. If you decide to + rather analyze text input after you already started + Speech recognition, please send a message with + [StreamingAnalyzeContentRequest.input_text][google.cloud.dialogflow.v2beta1.StreamingAnalyzeContentRequest.input_text]. + + However, note that: + + - Dialogflow will bill you for the audio so far. + - Dialogflow discards all Speech recognition results + in favor of the text input. + + 3. If + [StreamingAnalyzeContentRequest.config][google.cloud.dialogflow.v2beta1.StreamingAnalyzeContentRequest.config] + in the first message was set to + [StreamingAnalyzeContentRequest.text_config][google.cloud.dialogflow.v2beta1.StreamingAnalyzeContentRequest.text_config], + then the second message must contain only + [input_text][google.cloud.dialogflow.v2beta1.StreamingAnalyzeContentRequest.input_text]. + Moreover, you must not send more than two messages. + + After you sent all input, you must half-close or abort the request stream. retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. diff --git a/google/cloud/dialogflow_v2beta1/services/participants/transports/rest.py b/google/cloud/dialogflow_v2beta1/services/participants/transports/rest.py index 222c34671..338bdea12 100644 --- a/google/cloud/dialogflow_v2beta1/services/participants/transports/rest.py +++ b/google/cloud/dialogflow_v2beta1/services/participants/transports/rest.py @@ -621,7 +621,6 @@ def __call__( request (~.gcd_participant.AnalyzeContentRequest): The request object. The request message for [Participants.AnalyzeContent][google.cloud.dialogflow.v2beta1.Participants.AnalyzeContent]. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -715,7 +714,6 @@ def __call__( request (~.participant.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. @@ -815,7 +813,6 @@ def __call__( request (~.gcd_participant.CreateParticipantRequest): The request object. The request message for [Participants.CreateParticipant][google.cloud.dialogflow.v2beta1.Participants.CreateParticipant]. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -921,7 +918,6 @@ def __call__( request (~.participant.GetParticipantRequest): The request object. The request message for [Participants.GetParticipant][google.cloud.dialogflow.v2beta1.Participants.GetParticipant]. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -1015,7 +1011,6 @@ def __call__( request (~.participant.ListParticipantsRequest): The request object. The request message for [Participants.ListParticipants][google.cloud.dialogflow.v2beta1.Participants.ListParticipants]. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -1101,7 +1096,6 @@ def __call__( request (~.participant.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. @@ -1208,7 +1202,6 @@ def __call__( request (~.participant.SuggestArticlesRequest): The request object. The request message for [Participants.SuggestArticles][google.cloud.dialogflow.v2beta1.Participants.SuggestArticles]. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -1314,7 +1307,6 @@ def __call__( request (~.participant.SuggestFaqAnswersRequest): The request object. The request message for [Participants.SuggestFaqAnswers][google.cloud.dialogflow.v2beta1.Participants.SuggestFaqAnswers]. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -1420,7 +1412,6 @@ def __call__( request (~.participant.SuggestSmartRepliesRequest): The request object. The request message for [Participants.SuggestSmartReplies][google.cloud.dialogflow.v2beta1.Participants.SuggestSmartReplies]. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -1528,7 +1519,6 @@ def __call__( request (~.gcd_participant.UpdateParticipantRequest): The request object. The request message for [Participants.UpdateParticipant][google.cloud.dialogflow.v2beta1.Participants.UpdateParticipant]. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. diff --git a/google/cloud/dialogflow_v2beta1/services/session_entity_types/transports/rest.py b/google/cloud/dialogflow_v2beta1/services/session_entity_types/transports/rest.py index 47e4d5d15..af7377f2a 100644 --- a/google/cloud/dialogflow_v2beta1/services/session_entity_types/transports/rest.py +++ b/google/cloud/dialogflow_v2beta1/services/session_entity_types/transports/rest.py @@ -468,7 +468,6 @@ def __call__( request (~.gcd_session_entity_type.CreateSessionEntityTypeRequest): The request object. The request message for [SessionEntityTypes.CreateSessionEntityType][google.cloud.dialogflow.v2beta1.SessionEntityTypes.CreateSessionEntityType]. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -595,7 +594,6 @@ def __call__( request (~.session_entity_type.DeleteSessionEntityTypeRequest): The request object. The request message for [SessionEntityTypes.DeleteSessionEntityType][google.cloud.dialogflow.v2beta1.SessionEntityTypes.DeleteSessionEntityType]. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -685,7 +683,6 @@ def __call__( request (~.session_entity_type.GetSessionEntityTypeRequest): The request object. The request message for [SessionEntityTypes.GetSessionEntityType][google.cloud.dialogflow.v2beta1.SessionEntityTypes.GetSessionEntityType]. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -797,7 +794,6 @@ def __call__( request (~.session_entity_type.ListSessionEntityTypesRequest): The request object. The request message for [SessionEntityTypes.ListSessionEntityTypes][google.cloud.dialogflow.v2beta1.SessionEntityTypes.ListSessionEntityTypes]. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -902,7 +898,6 @@ def __call__( request (~.gcd_session_entity_type.UpdateSessionEntityTypeRequest): The request object. The request message for [SessionEntityTypes.UpdateSessionEntityType][google.cloud.dialogflow.v2beta1.SessionEntityTypes.UpdateSessionEntityType]. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. diff --git a/google/cloud/dialogflow_v2beta1/services/sessions/async_client.py b/google/cloud/dialogflow_v2beta1/services/sessions/async_client.py index 479c6d820..f931f3a84 100644 --- a/google/cloud/dialogflow_v2beta1/services/sessions/async_client.py +++ b/google/cloud/dialogflow_v2beta1/services/sessions/async_client.py @@ -457,41 +457,44 @@ def request_generator(): Args: requests (AsyncIterator[`google.cloud.dialogflow_v2beta1.types.StreamingDetectIntentRequest`]): - The request object AsyncIterator. The top-level message sent by the - client to the + The request object AsyncIterator. The top-level message sent by the client to the [Sessions.StreamingDetectIntent][google.cloud.dialogflow.v2beta1.Sessions.StreamingDetectIntent] method. Multiple request messages should be sent in order: - 1. The first message must contain - [session][google.cloud.dialogflow.v2beta1.StreamingDetectIntentRequest.session], - [query_input][google.cloud.dialogflow.v2beta1.StreamingDetectIntentRequest.query_input] - plus optionally - [query_params][google.cloud.dialogflow.v2beta1.StreamingDetectIntentRequest.query_params]. - If the client wants to receive an audio response, it - should also contain - [output_audio_config][google.cloud.dialogflow.v2beta1.StreamingDetectIntentRequest.output_audio_config]. - The message must not contain - [input_audio][google.cloud.dialogflow.v2beta1.StreamingDetectIntentRequest.input_audio]. - 2. If - [query_input][google.cloud.dialogflow.v2beta1.StreamingDetectIntentRequest.query_input] - was set to - [query_input.audio_config][google.cloud.dialogflow.v2beta1.InputAudioConfig], - all subsequent messages must contain - [input_audio][google.cloud.dialogflow.v2beta1.StreamingDetectIntentRequest.input_audio] - to continue with Speech recognition. If you decide to - rather detect an intent from text input after you - already started Speech recognition, please send a - message with - [query_input.text][google.cloud.dialogflow.v2beta1.QueryInput.text]. - However, note that: - - * Dialogflow will bill you for the audio duration so - far. * Dialogflow discards all Speech recognition - results in favor of the input text. - * Dialogflow will use the language code from the - first message. + 1. The first message must contain + [session][google.cloud.dialogflow.v2beta1.StreamingDetectIntentRequest.session], + [query_input][google.cloud.dialogflow.v2beta1.StreamingDetectIntentRequest.query_input] + plus optionally + [query_params][google.cloud.dialogflow.v2beta1.StreamingDetectIntentRequest.query_params]. + If the client wants to receive an audio response, it + should also contain + [output_audio_config][google.cloud.dialogflow.v2beta1.StreamingDetectIntentRequest.output_audio_config]. + The message must not contain + [input_audio][google.cloud.dialogflow.v2beta1.StreamingDetectIntentRequest.input_audio]. + + 2. If + [query_input][google.cloud.dialogflow.v2beta1.StreamingDetectIntentRequest.query_input] + was set to + [query_input.audio_config][google.cloud.dialogflow.v2beta1.InputAudioConfig], + all subsequent messages must contain + [input_audio][google.cloud.dialogflow.v2beta1.StreamingDetectIntentRequest.input_audio] + to continue with Speech recognition. If you decide to + rather detect an intent from text input after you + already started Speech recognition, please send a + message with + [query_input.text][google.cloud.dialogflow.v2beta1.QueryInput.text]. + + However, note that: + + - Dialogflow will bill you for the audio duration so + far. + - Dialogflow discards all Speech recognition results + in favor of the input text. + - Dialogflow will use the language code from the + first message. + After you sent all input, you must half-close or abort the request stream. retry (google.api_core.retry.Retry): Designation of what errors, if any, diff --git a/google/cloud/dialogflow_v2beta1/services/sessions/client.py b/google/cloud/dialogflow_v2beta1/services/sessions/client.py index 1395bc915..5f8c61b54 100644 --- a/google/cloud/dialogflow_v2beta1/services/sessions/client.py +++ b/google/cloud/dialogflow_v2beta1/services/sessions/client.py @@ -752,41 +752,44 @@ def request_generator(): Args: requests (Iterator[google.cloud.dialogflow_v2beta1.types.StreamingDetectIntentRequest]): - The request object iterator. The top-level message sent by the - client to the + The request object iterator. The top-level message sent by the client to the [Sessions.StreamingDetectIntent][google.cloud.dialogflow.v2beta1.Sessions.StreamingDetectIntent] method. Multiple request messages should be sent in order: - 1. The first message must contain - [session][google.cloud.dialogflow.v2beta1.StreamingDetectIntentRequest.session], - [query_input][google.cloud.dialogflow.v2beta1.StreamingDetectIntentRequest.query_input] - plus optionally - [query_params][google.cloud.dialogflow.v2beta1.StreamingDetectIntentRequest.query_params]. - If the client wants to receive an audio response, it - should also contain - [output_audio_config][google.cloud.dialogflow.v2beta1.StreamingDetectIntentRequest.output_audio_config]. - The message must not contain - [input_audio][google.cloud.dialogflow.v2beta1.StreamingDetectIntentRequest.input_audio]. - 2. If - [query_input][google.cloud.dialogflow.v2beta1.StreamingDetectIntentRequest.query_input] - was set to - [query_input.audio_config][google.cloud.dialogflow.v2beta1.InputAudioConfig], - all subsequent messages must contain - [input_audio][google.cloud.dialogflow.v2beta1.StreamingDetectIntentRequest.input_audio] - to continue with Speech recognition. If you decide to - rather detect an intent from text input after you - already started Speech recognition, please send a - message with - [query_input.text][google.cloud.dialogflow.v2beta1.QueryInput.text]. - However, note that: - - * Dialogflow will bill you for the audio duration so - far. * Dialogflow discards all Speech recognition - results in favor of the input text. - * Dialogflow will use the language code from the - first message. + 1. The first message must contain + [session][google.cloud.dialogflow.v2beta1.StreamingDetectIntentRequest.session], + [query_input][google.cloud.dialogflow.v2beta1.StreamingDetectIntentRequest.query_input] + plus optionally + [query_params][google.cloud.dialogflow.v2beta1.StreamingDetectIntentRequest.query_params]. + If the client wants to receive an audio response, it + should also contain + [output_audio_config][google.cloud.dialogflow.v2beta1.StreamingDetectIntentRequest.output_audio_config]. + The message must not contain + [input_audio][google.cloud.dialogflow.v2beta1.StreamingDetectIntentRequest.input_audio]. + + 2. If + [query_input][google.cloud.dialogflow.v2beta1.StreamingDetectIntentRequest.query_input] + was set to + [query_input.audio_config][google.cloud.dialogflow.v2beta1.InputAudioConfig], + all subsequent messages must contain + [input_audio][google.cloud.dialogflow.v2beta1.StreamingDetectIntentRequest.input_audio] + to continue with Speech recognition. If you decide to + rather detect an intent from text input after you + already started Speech recognition, please send a + message with + [query_input.text][google.cloud.dialogflow.v2beta1.QueryInput.text]. + + However, note that: + + - Dialogflow will bill you for the audio duration so + far. + - Dialogflow discards all Speech recognition results + in favor of the input text. + - Dialogflow will use the language code from the + first message. + After you sent all input, you must half-close or abort the request stream. retry (google.api_core.retry.Retry): Designation of what errors, if any, diff --git a/google/cloud/dialogflow_v2beta1/services/versions/transports/rest.py b/google/cloud/dialogflow_v2beta1/services/versions/transports/rest.py index 3d1b0509d..551316c7b 100644 --- a/google/cloud/dialogflow_v2beta1/services/versions/transports/rest.py +++ b/google/cloud/dialogflow_v2beta1/services/versions/transports/rest.py @@ -441,7 +441,6 @@ def __call__( request (~.gcd_version.CreateVersionRequest): The request object. The request message for [Versions.CreateVersion][google.cloud.dialogflow.v2beta1.Versions.CreateVersion]. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -562,7 +561,6 @@ def __call__( request (~.version.DeleteVersionRequest): The request object. The request message for [Versions.DeleteVersion][google.cloud.dialogflow.v2beta1.Versions.DeleteVersion]. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -642,7 +640,6 @@ def __call__( request (~.version.GetVersionRequest): The request object. The request message for [Versions.GetVersion][google.cloud.dialogflow.v2beta1.Versions.GetVersion]. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -753,7 +750,6 @@ def __call__( request (~.version.ListVersionsRequest): The request object. The request message for [Versions.ListVersions][google.cloud.dialogflow.v2beta1.Versions.ListVersions]. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -849,7 +845,6 @@ def __call__( request (~.gcd_version.UpdateVersionRequest): The request object. The request message for [Versions.UpdateVersion][google.cloud.dialogflow.v2beta1.Versions.UpdateVersion]. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. diff --git a/owl-bot-staging/v2/.coveragerc b/owl-bot-staging/v2/.coveragerc deleted file mode 100644 index 3e1752c7a..000000000 --- a/owl-bot-staging/v2/.coveragerc +++ /dev/null @@ -1,13 +0,0 @@ -[run] -branch = True - -[report] -show_missing = True -omit = - google/cloud/dialogflow/__init__.py - google/cloud/dialogflow/gapic_version.py -exclude_lines = - # Re-enable the standard pragma - pragma: NO COVER - # Ignore debug-only repr - def __repr__ diff --git a/owl-bot-staging/v2/.flake8 b/owl-bot-staging/v2/.flake8 deleted file mode 100644 index 29227d4cf..000000000 --- a/owl-bot-staging/v2/.flake8 +++ /dev/null @@ -1,33 +0,0 @@ -# -*- 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 -# -# https://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -# Generated by synthtool. DO NOT EDIT! -[flake8] -ignore = E203, E266, E501, W503 -exclude = - # Exclude generated code. - **/proto/** - **/gapic/** - **/services/** - **/types/** - *_pb2.py - - # Standard linting exemptions. - **/.nox/** - __pycache__, - .git, - *.pyc, - conf.py diff --git a/owl-bot-staging/v2/MANIFEST.in b/owl-bot-staging/v2/MANIFEST.in deleted file mode 100644 index e6fb0b1cd..000000000 --- a/owl-bot-staging/v2/MANIFEST.in +++ /dev/null @@ -1,2 +0,0 @@ -recursive-include google/cloud/dialogflow *.py -recursive-include google/cloud/dialogflow_v2 *.py diff --git a/owl-bot-staging/v2/README.rst b/owl-bot-staging/v2/README.rst deleted file mode 100644 index 6a2fa7289..000000000 --- a/owl-bot-staging/v2/README.rst +++ /dev/null @@ -1,49 +0,0 @@ -Python Client for Google Cloud Dialogflow API -================================================= - -Quick Start ------------ - -In order to use this library, you first need to go through the following steps: - -1. `Select or create a Cloud Platform project.`_ -2. `Enable billing for your project.`_ -3. Enable the Google Cloud Dialogflow API. -4. `Setup Authentication.`_ - -.. _Select or create a Cloud Platform project.: https://console.cloud.google.com/project -.. _Enable billing for your project.: https://cloud.google.com/billing/docs/how-to/modify-project#enable_billing_for_a_project -.. _Setup Authentication.: https://googleapis.dev/python/google-api-core/latest/auth.html - -Installation -~~~~~~~~~~~~ - -Install this library in a `virtualenv`_ using pip. `virtualenv`_ is a tool to -create isolated Python environments. The basic problem it addresses is one of -dependencies and versions, and indirectly permissions. - -With `virtualenv`_, it's possible to install this library without needing system -install permissions, and without clashing with the installed system -dependencies. - -.. _`virtualenv`: https://virtualenv.pypa.io/en/latest/ - - -Mac/Linux -^^^^^^^^^ - -.. code-block:: console - - python3 -m venv - source /bin/activate - /bin/pip install /path/to/library - - -Windows -^^^^^^^ - -.. code-block:: console - - python3 -m venv - \Scripts\activate - \Scripts\pip.exe install \path\to\library diff --git a/owl-bot-staging/v2/docs/conf.py b/owl-bot-staging/v2/docs/conf.py deleted file mode 100644 index 269123c63..000000000 --- a/owl-bot-staging/v2/docs/conf.py +++ /dev/null @@ -1,376 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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. -# -# -# google-cloud-dialogflow documentation build configuration file -# -# This file is execfile()d with the current directory set to its -# containing dir. -# -# Note that not all possible configuration values are present in this -# autogenerated file. -# -# All configuration values have a default; values that are commented out -# serve to show the default. - -import sys -import os -import shlex - -# If extensions (or modules to document with autodoc) are in another directory, -# add these directories to sys.path here. If the directory is relative to the -# documentation root, use os.path.abspath to make it absolute, like shown here. -sys.path.insert(0, os.path.abspath("..")) - -__version__ = "0.1.0" - -# -- General configuration ------------------------------------------------ - -# If your documentation needs a minimal Sphinx version, state it here. -needs_sphinx = "4.0.1" - -# Add any Sphinx extension module names here, as strings. They can be -# extensions coming with Sphinx (named 'sphinx.ext.*') or your custom -# ones. -extensions = [ - "sphinx.ext.autodoc", - "sphinx.ext.autosummary", - "sphinx.ext.intersphinx", - "sphinx.ext.coverage", - "sphinx.ext.napoleon", - "sphinx.ext.todo", - "sphinx.ext.viewcode", -] - -# autodoc/autosummary flags -autoclass_content = "both" -autodoc_default_flags = ["members"] -autosummary_generate = True - - -# Add any paths that contain templates here, relative to this directory. -templates_path = ["_templates"] - -# Allow markdown includes (so releases.md can include CHANGLEOG.md) -# http://www.sphinx-doc.org/en/master/markdown.html -source_parsers = {".md": "recommonmark.parser.CommonMarkParser"} - -# The suffix(es) of source filenames. -# You can specify multiple suffix as a list of string: -source_suffix = [".rst", ".md"] - -# The encoding of source files. -# source_encoding = 'utf-8-sig' - -# The root toctree document. -root_doc = "index" - -# General information about the project. -project = u"google-cloud-dialogflow" -copyright = u"2022, Google, LLC" -author = u"Google APIs" # TODO: autogenerate this bit - -# The version info for the project you're documenting, acts as replacement for -# |version| and |release|, also used in various other places throughout the -# built documents. -# -# The full version, including alpha/beta/rc tags. -release = __version__ -# The short X.Y version. -version = ".".join(release.split(".")[0:2]) - -# The language for content autogenerated by Sphinx. Refer to documentation -# for a list of supported languages. -# -# This is also used if you do content translation via gettext catalogs. -# Usually you set "language" from the command line for these cases. -language = None - -# There are two options for replacing |today|: either, you set today to some -# non-false value, then it is used: -# today = '' -# Else, today_fmt is used as the format for a strftime call. -# today_fmt = '%B %d, %Y' - -# List of patterns, relative to source directory, that match files and -# directories to ignore when looking for source files. -exclude_patterns = ["_build"] - -# The reST default role (used for this markup: `text`) to use for all -# documents. -# default_role = None - -# If true, '()' will be appended to :func: etc. cross-reference text. -# add_function_parentheses = True - -# If true, the current module name will be prepended to all description -# unit titles (such as .. function::). -# add_module_names = True - -# If true, sectionauthor and moduleauthor directives will be shown in the -# output. They are ignored by default. -# show_authors = False - -# The name of the Pygments (syntax highlighting) style to use. -pygments_style = "sphinx" - -# A list of ignored prefixes for module index sorting. -# modindex_common_prefix = [] - -# If true, keep warnings as "system message" paragraphs in the built documents. -# keep_warnings = False - -# If true, `todo` and `todoList` produce output, else they produce nothing. -todo_include_todos = True - - -# -- Options for HTML output ---------------------------------------------- - -# The theme to use for HTML and HTML Help pages. See the documentation for -# a list of builtin themes. -html_theme = "alabaster" - -# Theme options are theme-specific and customize the look and feel of a theme -# further. For a list of options available for each theme, see the -# documentation. -html_theme_options = { - "description": "Google Cloud Client Libraries for Python", - "github_user": "googleapis", - "github_repo": "google-cloud-python", - "github_banner": True, - "font_family": "'Roboto', Georgia, sans", - "head_font_family": "'Roboto', Georgia, serif", - "code_font_family": "'Roboto Mono', 'Consolas', monospace", -} - -# Add any paths that contain custom themes here, relative to this directory. -# html_theme_path = [] - -# The name for this set of Sphinx documents. If None, it defaults to -# " v documentation". -# html_title = None - -# A shorter title for the navigation bar. Default is the same as html_title. -# html_short_title = None - -# The name of an image file (relative to this directory) to place at the top -# of the sidebar. -# html_logo = None - -# The name of an image file (within the static path) to use as favicon of the -# docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32 -# pixels large. -# html_favicon = None - -# Add any paths that contain custom static files (such as style sheets) here, -# relative to this directory. They are copied after the builtin static files, -# so a file named "default.css" will overwrite the builtin "default.css". -html_static_path = ["_static"] - -# Add any extra paths that contain custom files (such as robots.txt or -# .htaccess) here, relative to this directory. These files are copied -# directly to the root of the documentation. -# html_extra_path = [] - -# If not '', a 'Last updated on:' timestamp is inserted at every page bottom, -# using the given strftime format. -# html_last_updated_fmt = '%b %d, %Y' - -# If true, SmartyPants will be used to convert quotes and dashes to -# typographically correct entities. -# html_use_smartypants = True - -# Custom sidebar templates, maps document names to template names. -# html_sidebars = {} - -# Additional templates that should be rendered to pages, maps page names to -# template names. -# html_additional_pages = {} - -# If false, no module index is generated. -# html_domain_indices = True - -# If false, no index is generated. -# html_use_index = True - -# If true, the index is split into individual pages for each letter. -# html_split_index = False - -# If true, links to the reST sources are added to the pages. -# html_show_sourcelink = True - -# If true, "Created using Sphinx" is shown in the HTML footer. Default is True. -# html_show_sphinx = True - -# If true, "(C) Copyright ..." is shown in the HTML footer. Default is True. -# html_show_copyright = True - -# If true, an OpenSearch description file will be output, and all pages will -# contain a tag referring to it. The value of this option must be the -# base URL from which the finished HTML is served. -# html_use_opensearch = '' - -# This is the file name suffix for HTML files (e.g. ".xhtml"). -# html_file_suffix = None - -# Language to be used for generating the HTML full-text search index. -# Sphinx supports the following languages: -# 'da', 'de', 'en', 'es', 'fi', 'fr', 'hu', 'it', 'ja' -# 'nl', 'no', 'pt', 'ro', 'ru', 'sv', 'tr' -# html_search_language = 'en' - -# A dictionary with options for the search language support, empty by default. -# Now only 'ja' uses this config value -# html_search_options = {'type': 'default'} - -# The name of a javascript file (relative to the configuration directory) that -# implements a search results scorer. If empty, the default will be used. -# html_search_scorer = 'scorer.js' - -# Output file base name for HTML help builder. -htmlhelp_basename = "google-cloud-dialogflow-doc" - -# -- Options for warnings ------------------------------------------------------ - - -suppress_warnings = [ - # Temporarily suppress this to avoid "more than one target found for - # cross-reference" warning, which are intractable for us to avoid while in - # a mono-repo. - # See https://github.com/sphinx-doc/sphinx/blob - # /2a65ffeef5c107c19084fabdd706cdff3f52d93c/sphinx/domains/python.py#L843 - "ref.python" -] - -# -- Options for LaTeX output --------------------------------------------- - -latex_elements = { - # The paper size ('letterpaper' or 'a4paper'). - # 'papersize': 'letterpaper', - # The font size ('10pt', '11pt' or '12pt'). - # 'pointsize': '10pt', - # Additional stuff for the LaTeX preamble. - # 'preamble': '', - # Latex figure (float) alignment - # 'figure_align': 'htbp', -} - -# Grouping the document tree into LaTeX files. List of tuples -# (source start file, target name, title, -# author, documentclass [howto, manual, or own class]). -latex_documents = [ - ( - root_doc, - "google-cloud-dialogflow.tex", - u"google-cloud-dialogflow Documentation", - author, - "manual", - ) -] - -# The name of an image file (relative to this directory) to place at the top of -# the title page. -# latex_logo = None - -# For "manual" documents, if this is true, then toplevel headings are parts, -# not chapters. -# latex_use_parts = False - -# If true, show page references after internal links. -# latex_show_pagerefs = False - -# If true, show URL addresses after external links. -# latex_show_urls = False - -# Documents to append as an appendix to all manuals. -# latex_appendices = [] - -# If false, no module index is generated. -# latex_domain_indices = True - - -# -- Options for manual page output --------------------------------------- - -# One entry per manual page. List of tuples -# (source start file, name, description, authors, manual section). -man_pages = [ - ( - root_doc, - "google-cloud-dialogflow", - u"Google Cloud Dialogflow Documentation", - [author], - 1, - ) -] - -# If true, show URL addresses after external links. -# man_show_urls = False - - -# -- Options for Texinfo output ------------------------------------------- - -# Grouping the document tree into Texinfo files. List of tuples -# (source start file, target name, title, author, -# dir menu entry, description, category) -texinfo_documents = [ - ( - root_doc, - "google-cloud-dialogflow", - u"google-cloud-dialogflow Documentation", - author, - "google-cloud-dialogflow", - "GAPIC library for Google Cloud Dialogflow API", - "APIs", - ) -] - -# Documents to append as an appendix to all manuals. -# texinfo_appendices = [] - -# If false, no module index is generated. -# texinfo_domain_indices = True - -# How to display URL addresses: 'footnote', 'no', or 'inline'. -# texinfo_show_urls = 'footnote' - -# If true, do not generate a @detailmenu in the "Top" node's menu. -# texinfo_no_detailmenu = False - - -# Example configuration for intersphinx: refer to the Python standard library. -intersphinx_mapping = { - "python": ("http://python.readthedocs.org/en/latest/", None), - "gax": ("https://gax-python.readthedocs.org/en/latest/", None), - "google-auth": ("https://google-auth.readthedocs.io/en/stable", None), - "google-gax": ("https://gax-python.readthedocs.io/en/latest/", None), - "google.api_core": ("https://googleapis.dev/python/google-api-core/latest/", None), - "grpc": ("https://grpc.io/grpc/python/", None), - "requests": ("http://requests.kennethreitz.org/en/stable/", None), - "proto": ("https://proto-plus-python.readthedocs.io/en/stable", None), - "protobuf": ("https://googleapis.dev/python/protobuf/latest/", None), -} - - -# Napoleon settings -napoleon_google_docstring = True -napoleon_numpy_docstring = True -napoleon_include_private_with_doc = False -napoleon_include_special_with_doc = True -napoleon_use_admonition_for_examples = False -napoleon_use_admonition_for_notes = False -napoleon_use_admonition_for_references = False -napoleon_use_ivar = False -napoleon_use_param = True -napoleon_use_rtype = True diff --git a/owl-bot-staging/v2/docs/dialogflow_v2/agents.rst b/owl-bot-staging/v2/docs/dialogflow_v2/agents.rst deleted file mode 100644 index 8661ecd44..000000000 --- a/owl-bot-staging/v2/docs/dialogflow_v2/agents.rst +++ /dev/null @@ -1,10 +0,0 @@ -Agents ------------------------- - -.. automodule:: google.cloud.dialogflow_v2.services.agents - :members: - :inherited-members: - -.. automodule:: google.cloud.dialogflow_v2.services.agents.pagers - :members: - :inherited-members: diff --git a/owl-bot-staging/v2/docs/dialogflow_v2/answer_records.rst b/owl-bot-staging/v2/docs/dialogflow_v2/answer_records.rst deleted file mode 100644 index 20345f618..000000000 --- a/owl-bot-staging/v2/docs/dialogflow_v2/answer_records.rst +++ /dev/null @@ -1,10 +0,0 @@ -AnswerRecords -------------------------------- - -.. automodule:: google.cloud.dialogflow_v2.services.answer_records - :members: - :inherited-members: - -.. automodule:: google.cloud.dialogflow_v2.services.answer_records.pagers - :members: - :inherited-members: diff --git a/owl-bot-staging/v2/docs/dialogflow_v2/contexts.rst b/owl-bot-staging/v2/docs/dialogflow_v2/contexts.rst deleted file mode 100644 index ab27d7b1e..000000000 --- a/owl-bot-staging/v2/docs/dialogflow_v2/contexts.rst +++ /dev/null @@ -1,10 +0,0 @@ -Contexts --------------------------- - -.. automodule:: google.cloud.dialogflow_v2.services.contexts - :members: - :inherited-members: - -.. automodule:: google.cloud.dialogflow_v2.services.contexts.pagers - :members: - :inherited-members: diff --git a/owl-bot-staging/v2/docs/dialogflow_v2/conversation_datasets.rst b/owl-bot-staging/v2/docs/dialogflow_v2/conversation_datasets.rst deleted file mode 100644 index d0510a1fc..000000000 --- a/owl-bot-staging/v2/docs/dialogflow_v2/conversation_datasets.rst +++ /dev/null @@ -1,10 +0,0 @@ -ConversationDatasets --------------------------------------- - -.. automodule:: google.cloud.dialogflow_v2.services.conversation_datasets - :members: - :inherited-members: - -.. automodule:: google.cloud.dialogflow_v2.services.conversation_datasets.pagers - :members: - :inherited-members: diff --git a/owl-bot-staging/v2/docs/dialogflow_v2/conversation_models.rst b/owl-bot-staging/v2/docs/dialogflow_v2/conversation_models.rst deleted file mode 100644 index 2c1565841..000000000 --- a/owl-bot-staging/v2/docs/dialogflow_v2/conversation_models.rst +++ /dev/null @@ -1,10 +0,0 @@ -ConversationModels ------------------------------------- - -.. automodule:: google.cloud.dialogflow_v2.services.conversation_models - :members: - :inherited-members: - -.. automodule:: google.cloud.dialogflow_v2.services.conversation_models.pagers - :members: - :inherited-members: diff --git a/owl-bot-staging/v2/docs/dialogflow_v2/conversation_profiles.rst b/owl-bot-staging/v2/docs/dialogflow_v2/conversation_profiles.rst deleted file mode 100644 index e5c4cda45..000000000 --- a/owl-bot-staging/v2/docs/dialogflow_v2/conversation_profiles.rst +++ /dev/null @@ -1,10 +0,0 @@ -ConversationProfiles --------------------------------------- - -.. automodule:: google.cloud.dialogflow_v2.services.conversation_profiles - :members: - :inherited-members: - -.. automodule:: google.cloud.dialogflow_v2.services.conversation_profiles.pagers - :members: - :inherited-members: diff --git a/owl-bot-staging/v2/docs/dialogflow_v2/conversations.rst b/owl-bot-staging/v2/docs/dialogflow_v2/conversations.rst deleted file mode 100644 index a288e3783..000000000 --- a/owl-bot-staging/v2/docs/dialogflow_v2/conversations.rst +++ /dev/null @@ -1,10 +0,0 @@ -Conversations -------------------------------- - -.. automodule:: google.cloud.dialogflow_v2.services.conversations - :members: - :inherited-members: - -.. automodule:: google.cloud.dialogflow_v2.services.conversations.pagers - :members: - :inherited-members: diff --git a/owl-bot-staging/v2/docs/dialogflow_v2/documents.rst b/owl-bot-staging/v2/docs/dialogflow_v2/documents.rst deleted file mode 100644 index c95415ace..000000000 --- a/owl-bot-staging/v2/docs/dialogflow_v2/documents.rst +++ /dev/null @@ -1,10 +0,0 @@ -Documents ---------------------------- - -.. automodule:: google.cloud.dialogflow_v2.services.documents - :members: - :inherited-members: - -.. automodule:: google.cloud.dialogflow_v2.services.documents.pagers - :members: - :inherited-members: diff --git a/owl-bot-staging/v2/docs/dialogflow_v2/entity_types.rst b/owl-bot-staging/v2/docs/dialogflow_v2/entity_types.rst deleted file mode 100644 index 82634156b..000000000 --- a/owl-bot-staging/v2/docs/dialogflow_v2/entity_types.rst +++ /dev/null @@ -1,10 +0,0 @@ -EntityTypes ------------------------------ - -.. automodule:: google.cloud.dialogflow_v2.services.entity_types - :members: - :inherited-members: - -.. automodule:: google.cloud.dialogflow_v2.services.entity_types.pagers - :members: - :inherited-members: diff --git a/owl-bot-staging/v2/docs/dialogflow_v2/environments.rst b/owl-bot-staging/v2/docs/dialogflow_v2/environments.rst deleted file mode 100644 index e0ca6f7f7..000000000 --- a/owl-bot-staging/v2/docs/dialogflow_v2/environments.rst +++ /dev/null @@ -1,10 +0,0 @@ -Environments ------------------------------- - -.. automodule:: google.cloud.dialogflow_v2.services.environments - :members: - :inherited-members: - -.. automodule:: google.cloud.dialogflow_v2.services.environments.pagers - :members: - :inherited-members: diff --git a/owl-bot-staging/v2/docs/dialogflow_v2/fulfillments.rst b/owl-bot-staging/v2/docs/dialogflow_v2/fulfillments.rst deleted file mode 100644 index 27f77aa3a..000000000 --- a/owl-bot-staging/v2/docs/dialogflow_v2/fulfillments.rst +++ /dev/null @@ -1,6 +0,0 @@ -Fulfillments ------------------------------- - -.. automodule:: google.cloud.dialogflow_v2.services.fulfillments - :members: - :inherited-members: diff --git a/owl-bot-staging/v2/docs/dialogflow_v2/intents.rst b/owl-bot-staging/v2/docs/dialogflow_v2/intents.rst deleted file mode 100644 index 8418cb20d..000000000 --- a/owl-bot-staging/v2/docs/dialogflow_v2/intents.rst +++ /dev/null @@ -1,10 +0,0 @@ -Intents -------------------------- - -.. automodule:: google.cloud.dialogflow_v2.services.intents - :members: - :inherited-members: - -.. automodule:: google.cloud.dialogflow_v2.services.intents.pagers - :members: - :inherited-members: diff --git a/owl-bot-staging/v2/docs/dialogflow_v2/knowledge_bases.rst b/owl-bot-staging/v2/docs/dialogflow_v2/knowledge_bases.rst deleted file mode 100644 index 7440330af..000000000 --- a/owl-bot-staging/v2/docs/dialogflow_v2/knowledge_bases.rst +++ /dev/null @@ -1,10 +0,0 @@ -KnowledgeBases --------------------------------- - -.. automodule:: google.cloud.dialogflow_v2.services.knowledge_bases - :members: - :inherited-members: - -.. automodule:: google.cloud.dialogflow_v2.services.knowledge_bases.pagers - :members: - :inherited-members: diff --git a/owl-bot-staging/v2/docs/dialogflow_v2/participants.rst b/owl-bot-staging/v2/docs/dialogflow_v2/participants.rst deleted file mode 100644 index 6ce8a2c52..000000000 --- a/owl-bot-staging/v2/docs/dialogflow_v2/participants.rst +++ /dev/null @@ -1,10 +0,0 @@ -Participants ------------------------------- - -.. automodule:: google.cloud.dialogflow_v2.services.participants - :members: - :inherited-members: - -.. automodule:: google.cloud.dialogflow_v2.services.participants.pagers - :members: - :inherited-members: diff --git a/owl-bot-staging/v2/docs/dialogflow_v2/services.rst b/owl-bot-staging/v2/docs/dialogflow_v2/services.rst deleted file mode 100644 index c6039fcaf..000000000 --- a/owl-bot-staging/v2/docs/dialogflow_v2/services.rst +++ /dev/null @@ -1,22 +0,0 @@ -Services for Google Cloud Dialogflow v2 API -=========================================== -.. toctree:: - :maxdepth: 2 - - agents - answer_records - contexts - conversation_datasets - conversation_models - conversation_profiles - conversations - documents - entity_types - environments - fulfillments - intents - knowledge_bases - participants - session_entity_types - sessions - versions diff --git a/owl-bot-staging/v2/docs/dialogflow_v2/session_entity_types.rst b/owl-bot-staging/v2/docs/dialogflow_v2/session_entity_types.rst deleted file mode 100644 index e1d7bd321..000000000 --- a/owl-bot-staging/v2/docs/dialogflow_v2/session_entity_types.rst +++ /dev/null @@ -1,10 +0,0 @@ -SessionEntityTypes ------------------------------------- - -.. automodule:: google.cloud.dialogflow_v2.services.session_entity_types - :members: - :inherited-members: - -.. automodule:: google.cloud.dialogflow_v2.services.session_entity_types.pagers - :members: - :inherited-members: diff --git a/owl-bot-staging/v2/docs/dialogflow_v2/sessions.rst b/owl-bot-staging/v2/docs/dialogflow_v2/sessions.rst deleted file mode 100644 index 1da650e33..000000000 --- a/owl-bot-staging/v2/docs/dialogflow_v2/sessions.rst +++ /dev/null @@ -1,6 +0,0 @@ -Sessions --------------------------- - -.. automodule:: google.cloud.dialogflow_v2.services.sessions - :members: - :inherited-members: diff --git a/owl-bot-staging/v2/docs/dialogflow_v2/types.rst b/owl-bot-staging/v2/docs/dialogflow_v2/types.rst deleted file mode 100644 index 3d0f4eb3c..000000000 --- a/owl-bot-staging/v2/docs/dialogflow_v2/types.rst +++ /dev/null @@ -1,6 +0,0 @@ -Types for Google Cloud Dialogflow v2 API -======================================== - -.. automodule:: google.cloud.dialogflow_v2.types - :members: - :show-inheritance: diff --git a/owl-bot-staging/v2/docs/dialogflow_v2/versions.rst b/owl-bot-staging/v2/docs/dialogflow_v2/versions.rst deleted file mode 100644 index af34a4719..000000000 --- a/owl-bot-staging/v2/docs/dialogflow_v2/versions.rst +++ /dev/null @@ -1,10 +0,0 @@ -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/owl-bot-staging/v2/docs/index.rst b/owl-bot-staging/v2/docs/index.rst deleted file mode 100644 index 79b49743a..000000000 --- a/owl-bot-staging/v2/docs/index.rst +++ /dev/null @@ -1,7 +0,0 @@ -API Reference -------------- -.. toctree:: - :maxdepth: 2 - - dialogflow_v2/services - dialogflow_v2/types diff --git a/owl-bot-staging/v2/google/cloud/dialogflow/__init__.py b/owl-bot-staging/v2/google/cloud/dialogflow/__init__.py deleted file mode 100644 index 7b7172601..000000000 --- a/owl-bot-staging/v2/google/cloud/dialogflow/__init__.py +++ /dev/null @@ -1,547 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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 google.cloud.dialogflow import gapic_version as package_version - -__version__ = package_version.__version__ - - -from google.cloud.dialogflow_v2.services.agents.client import AgentsClient -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.answer_records.async_client import AnswerRecordsAsyncClient -from google.cloud.dialogflow_v2.services.contexts.client import ContextsClient -from google.cloud.dialogflow_v2.services.contexts.async_client import ContextsAsyncClient -from google.cloud.dialogflow_v2.services.conversation_datasets.client import ConversationDatasetsClient -from google.cloud.dialogflow_v2.services.conversation_datasets.async_client import ConversationDatasetsAsyncClient -from google.cloud.dialogflow_v2.services.conversation_models.client import ConversationModelsClient -from google.cloud.dialogflow_v2.services.conversation_models.async_client import ConversationModelsAsyncClient -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.documents.client import DocumentsClient -from google.cloud.dialogflow_v2.services.documents.async_client import DocumentsAsyncClient -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.environments.client import EnvironmentsClient -from google.cloud.dialogflow_v2.services.environments.async_client import EnvironmentsAsyncClient -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.knowledge_bases.async_client import KnowledgeBasesAsyncClient -from google.cloud.dialogflow_v2.services.participants.client import ParticipantsClient -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.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 -from google.cloud.dialogflow_v2.types.agent import ExportAgentResponse -from google.cloud.dialogflow_v2.types.agent import GetAgentRequest -from google.cloud.dialogflow_v2.types.agent import GetValidationResultRequest -from google.cloud.dialogflow_v2.types.agent import ImportAgentRequest -from google.cloud.dialogflow_v2.types.agent import RestoreAgentRequest -from google.cloud.dialogflow_v2.types.agent import SearchAgentsRequest -from google.cloud.dialogflow_v2.types.agent import SearchAgentsResponse -from google.cloud.dialogflow_v2.types.agent import SetAgentRequest -from google.cloud.dialogflow_v2.types.agent import TrainAgentRequest -from google.cloud.dialogflow_v2.types.answer_record import AgentAssistantFeedback -from google.cloud.dialogflow_v2.types.answer_record import AgentAssistantRecord -from google.cloud.dialogflow_v2.types.answer_record import AnswerFeedback -from google.cloud.dialogflow_v2.types.answer_record import AnswerRecord -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 InputAudioConfig -from google.cloud.dialogflow_v2.types.audio_config import OutputAudioConfig -from google.cloud.dialogflow_v2.types.audio_config import SpeechContext -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 SynthesizeSpeechConfig -from google.cloud.dialogflow_v2.types.audio_config import TelephonyDtmfEvents -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.audio_config import TelephonyDtmf -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 -from google.cloud.dialogflow_v2.types.context import DeleteContextRequest -from google.cloud.dialogflow_v2.types.context import GetContextRequest -from google.cloud.dialogflow_v2.types.context import ListContextsRequest -from google.cloud.dialogflow_v2.types.context import ListContextsResponse -from google.cloud.dialogflow_v2.types.context import UpdateContextRequest -from google.cloud.dialogflow_v2.types.conversation import CompleteConversationRequest -from google.cloud.dialogflow_v2.types.conversation import Conversation -from google.cloud.dialogflow_v2.types.conversation import ConversationPhoneNumber -from google.cloud.dialogflow_v2.types.conversation import CreateConversationRequest -from google.cloud.dialogflow_v2.types.conversation import GetConversationRequest -from google.cloud.dialogflow_v2.types.conversation import ListConversationsRequest -from google.cloud.dialogflow_v2.types.conversation import ListConversationsResponse -from google.cloud.dialogflow_v2.types.conversation import ListMessagesRequest -from google.cloud.dialogflow_v2.types.conversation import ListMessagesResponse -from google.cloud.dialogflow_v2.types.conversation import SuggestConversationSummaryRequest -from google.cloud.dialogflow_v2.types.conversation import SuggestConversationSummaryResponse -from google.cloud.dialogflow_v2.types.conversation_dataset import ConversationDataset -from google.cloud.dialogflow_v2.types.conversation_dataset import ConversationInfo -from google.cloud.dialogflow_v2.types.conversation_dataset import CreateConversationDatasetOperationMetadata -from google.cloud.dialogflow_v2.types.conversation_dataset import CreateConversationDatasetRequest -from google.cloud.dialogflow_v2.types.conversation_dataset import DeleteConversationDatasetOperationMetadata -from google.cloud.dialogflow_v2.types.conversation_dataset import DeleteConversationDatasetRequest -from google.cloud.dialogflow_v2.types.conversation_dataset import GetConversationDatasetRequest -from google.cloud.dialogflow_v2.types.conversation_dataset import ImportConversationDataOperationMetadata -from google.cloud.dialogflow_v2.types.conversation_dataset import ImportConversationDataOperationResponse -from google.cloud.dialogflow_v2.types.conversation_dataset import ImportConversationDataRequest -from google.cloud.dialogflow_v2.types.conversation_dataset import InputConfig -from google.cloud.dialogflow_v2.types.conversation_dataset import ListConversationDatasetsRequest -from google.cloud.dialogflow_v2.types.conversation_dataset import ListConversationDatasetsResponse -from google.cloud.dialogflow_v2.types.conversation_event import ConversationEvent -from google.cloud.dialogflow_v2.types.conversation_model import ArticleSuggestionModelMetadata -from google.cloud.dialogflow_v2.types.conversation_model import ConversationModel -from google.cloud.dialogflow_v2.types.conversation_model import ConversationModelEvaluation -from google.cloud.dialogflow_v2.types.conversation_model import CreateConversationModelEvaluationOperationMetadata -from google.cloud.dialogflow_v2.types.conversation_model import CreateConversationModelEvaluationRequest -from google.cloud.dialogflow_v2.types.conversation_model import CreateConversationModelOperationMetadata -from google.cloud.dialogflow_v2.types.conversation_model import CreateConversationModelRequest -from google.cloud.dialogflow_v2.types.conversation_model import DeleteConversationModelOperationMetadata -from google.cloud.dialogflow_v2.types.conversation_model import DeleteConversationModelRequest -from google.cloud.dialogflow_v2.types.conversation_model import DeployConversationModelOperationMetadata -from google.cloud.dialogflow_v2.types.conversation_model import DeployConversationModelRequest -from google.cloud.dialogflow_v2.types.conversation_model import EvaluationConfig -from google.cloud.dialogflow_v2.types.conversation_model import GetConversationModelEvaluationRequest -from google.cloud.dialogflow_v2.types.conversation_model import GetConversationModelRequest -from google.cloud.dialogflow_v2.types.conversation_model import InputDataset -from google.cloud.dialogflow_v2.types.conversation_model import ListConversationModelEvaluationsRequest -from google.cloud.dialogflow_v2.types.conversation_model import ListConversationModelEvaluationsResponse -from google.cloud.dialogflow_v2.types.conversation_model import ListConversationModelsRequest -from google.cloud.dialogflow_v2.types.conversation_model import ListConversationModelsResponse -from google.cloud.dialogflow_v2.types.conversation_model import SmartReplyMetrics -from google.cloud.dialogflow_v2.types.conversation_model import SmartReplyModelMetadata -from google.cloud.dialogflow_v2.types.conversation_model import UndeployConversationModelOperationMetadata -from google.cloud.dialogflow_v2.types.conversation_model import UndeployConversationModelRequest -from google.cloud.dialogflow_v2.types.conversation_profile import AutomatedAgentConfig -from google.cloud.dialogflow_v2.types.conversation_profile import ClearSuggestionFeatureConfigOperationMetadata -from google.cloud.dialogflow_v2.types.conversation_profile import ClearSuggestionFeatureConfigRequest -from google.cloud.dialogflow_v2.types.conversation_profile import ConversationProfile -from google.cloud.dialogflow_v2.types.conversation_profile import CreateConversationProfileRequest -from google.cloud.dialogflow_v2.types.conversation_profile import DeleteConversationProfileRequest -from google.cloud.dialogflow_v2.types.conversation_profile import GetConversationProfileRequest -from google.cloud.dialogflow_v2.types.conversation_profile import HumanAgentAssistantConfig -from google.cloud.dialogflow_v2.types.conversation_profile import HumanAgentHandoffConfig -from google.cloud.dialogflow_v2.types.conversation_profile import ListConversationProfilesRequest -from google.cloud.dialogflow_v2.types.conversation_profile import ListConversationProfilesResponse -from google.cloud.dialogflow_v2.types.conversation_profile import LoggingConfig -from google.cloud.dialogflow_v2.types.conversation_profile import NotificationConfig -from google.cloud.dialogflow_v2.types.conversation_profile import SetSuggestionFeatureConfigOperationMetadata -from google.cloud.dialogflow_v2.types.conversation_profile import SetSuggestionFeatureConfigRequest -from google.cloud.dialogflow_v2.types.conversation_profile import SuggestionFeature -from google.cloud.dialogflow_v2.types.conversation_profile import UpdateConversationProfileRequest -from google.cloud.dialogflow_v2.types.document import CreateDocumentRequest -from google.cloud.dialogflow_v2.types.document import DeleteDocumentRequest -from google.cloud.dialogflow_v2.types.document import Document -from google.cloud.dialogflow_v2.types.document import ExportDocumentRequest -from google.cloud.dialogflow_v2.types.document import ExportOperationMetadata -from google.cloud.dialogflow_v2.types.document import GetDocumentRequest -from google.cloud.dialogflow_v2.types.document import ImportDocumentsRequest -from google.cloud.dialogflow_v2.types.document import ImportDocumentsResponse -from google.cloud.dialogflow_v2.types.document import ImportDocumentTemplate -from google.cloud.dialogflow_v2.types.document import KnowledgeOperationMetadata -from google.cloud.dialogflow_v2.types.document import ListDocumentsRequest -from google.cloud.dialogflow_v2.types.document import ListDocumentsResponse -from google.cloud.dialogflow_v2.types.document import ReloadDocumentRequest -from google.cloud.dialogflow_v2.types.document import UpdateDocumentRequest -from google.cloud.dialogflow_v2.types.entity_type import BatchCreateEntitiesRequest -from google.cloud.dialogflow_v2.types.entity_type import BatchDeleteEntitiesRequest -from google.cloud.dialogflow_v2.types.entity_type import BatchDeleteEntityTypesRequest -from google.cloud.dialogflow_v2.types.entity_type import BatchUpdateEntitiesRequest -from google.cloud.dialogflow_v2.types.entity_type import BatchUpdateEntityTypesRequest -from google.cloud.dialogflow_v2.types.entity_type import BatchUpdateEntityTypesResponse -from google.cloud.dialogflow_v2.types.entity_type import CreateEntityTypeRequest -from google.cloud.dialogflow_v2.types.entity_type import DeleteEntityTypeRequest -from google.cloud.dialogflow_v2.types.entity_type import EntityType -from google.cloud.dialogflow_v2.types.entity_type import EntityTypeBatch -from google.cloud.dialogflow_v2.types.entity_type import GetEntityTypeRequest -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.gcs import GcsDestination -from google.cloud.dialogflow_v2.types.gcs import GcsSources -from google.cloud.dialogflow_v2.types.human_agent_assistant_event import HumanAgentAssistantEvent -from google.cloud.dialogflow_v2.types.intent import BatchDeleteIntentsRequest -from google.cloud.dialogflow_v2.types.intent import BatchUpdateIntentsRequest -from google.cloud.dialogflow_v2.types.intent import BatchUpdateIntentsResponse -from google.cloud.dialogflow_v2.types.intent import CreateIntentRequest -from google.cloud.dialogflow_v2.types.intent import DeleteIntentRequest -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 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 -from google.cloud.dialogflow_v2.types.knowledge_base import KnowledgeBase -from google.cloud.dialogflow_v2.types.knowledge_base import ListKnowledgeBasesRequest -from google.cloud.dialogflow_v2.types.knowledge_base import ListKnowledgeBasesResponse -from google.cloud.dialogflow_v2.types.knowledge_base import UpdateKnowledgeBaseRequest -from google.cloud.dialogflow_v2.types.participant import AnalyzeContentRequest -from google.cloud.dialogflow_v2.types.participant import AnalyzeContentResponse -from google.cloud.dialogflow_v2.types.participant import AnnotatedMessagePart -from google.cloud.dialogflow_v2.types.participant import ArticleAnswer -from google.cloud.dialogflow_v2.types.participant import AssistQueryParameters -from google.cloud.dialogflow_v2.types.participant import AutomatedAgentReply -from google.cloud.dialogflow_v2.types.participant import CreateParticipantRequest -from google.cloud.dialogflow_v2.types.participant import DtmfParameters -from google.cloud.dialogflow_v2.types.participant import FaqAnswer -from google.cloud.dialogflow_v2.types.participant import GetParticipantRequest -from google.cloud.dialogflow_v2.types.participant import InputTextConfig -from google.cloud.dialogflow_v2.types.participant import ListParticipantsRequest -from google.cloud.dialogflow_v2.types.participant import ListParticipantsResponse -from google.cloud.dialogflow_v2.types.participant import Message -from google.cloud.dialogflow_v2.types.participant import MessageAnnotation -from google.cloud.dialogflow_v2.types.participant import OutputAudio -from google.cloud.dialogflow_v2.types.participant import Participant -from google.cloud.dialogflow_v2.types.participant import SmartReplyAnswer -from google.cloud.dialogflow_v2.types.participant import StreamingAnalyzeContentRequest -from google.cloud.dialogflow_v2.types.participant import StreamingAnalyzeContentResponse -from google.cloud.dialogflow_v2.types.participant import SuggestArticlesRequest -from google.cloud.dialogflow_v2.types.participant import SuggestArticlesResponse -from google.cloud.dialogflow_v2.types.participant import SuggestFaqAnswersRequest -from google.cloud.dialogflow_v2.types.participant import SuggestFaqAnswersResponse -from google.cloud.dialogflow_v2.types.participant import SuggestionResult -from google.cloud.dialogflow_v2.types.participant import SuggestSmartRepliesRequest -from google.cloud.dialogflow_v2.types.participant import SuggestSmartRepliesResponse -from google.cloud.dialogflow_v2.types.participant import UpdateParticipantRequest -from google.cloud.dialogflow_v2.types.session import DetectIntentRequest -from google.cloud.dialogflow_v2.types.session import DetectIntentResponse -from google.cloud.dialogflow_v2.types.session import EventInput -from google.cloud.dialogflow_v2.types.session import QueryInput -from google.cloud.dialogflow_v2.types.session import QueryParameters -from google.cloud.dialogflow_v2.types.session import QueryResult -from google.cloud.dialogflow_v2.types.session import Sentiment -from google.cloud.dialogflow_v2.types.session import SentimentAnalysisRequestConfig -from google.cloud.dialogflow_v2.types.session import SentimentAnalysisResult -from google.cloud.dialogflow_v2.types.session import StreamingDetectIntentRequest -from google.cloud.dialogflow_v2.types.session import StreamingDetectIntentResponse -from google.cloud.dialogflow_v2.types.session import StreamingRecognitionResult -from google.cloud.dialogflow_v2.types.session import TextInput -from google.cloud.dialogflow_v2.types.session_entity_type import CreateSessionEntityTypeRequest -from google.cloud.dialogflow_v2.types.session_entity_type import DeleteSessionEntityTypeRequest -from google.cloud.dialogflow_v2.types.session_entity_type import GetSessionEntityTypeRequest -from google.cloud.dialogflow_v2.types.session_entity_type import ListSessionEntityTypesRequest -from google.cloud.dialogflow_v2.types.session_entity_type import ListSessionEntityTypesResponse -from google.cloud.dialogflow_v2.types.session_entity_type import SessionEntityType -from google.cloud.dialogflow_v2.types.session_entity_type import UpdateSessionEntityTypeRequest -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__ = ('AgentsClient', - 'AgentsAsyncClient', - 'AnswerRecordsClient', - 'AnswerRecordsAsyncClient', - 'ContextsClient', - 'ContextsAsyncClient', - 'ConversationDatasetsClient', - 'ConversationDatasetsAsyncClient', - 'ConversationModelsClient', - 'ConversationModelsAsyncClient', - 'ConversationProfilesClient', - 'ConversationProfilesAsyncClient', - 'ConversationsClient', - 'ConversationsAsyncClient', - 'DocumentsClient', - 'DocumentsAsyncClient', - 'EntityTypesClient', - 'EntityTypesAsyncClient', - 'EnvironmentsClient', - 'EnvironmentsAsyncClient', - 'FulfillmentsClient', - 'FulfillmentsAsyncClient', - 'IntentsClient', - 'IntentsAsyncClient', - 'KnowledgeBasesClient', - 'KnowledgeBasesAsyncClient', - 'ParticipantsClient', - 'ParticipantsAsyncClient', - 'SessionEntityTypesClient', - 'SessionEntityTypesAsyncClient', - 'SessionsClient', - 'SessionsAsyncClient', - 'VersionsClient', - 'VersionsAsyncClient', - 'Agent', - 'DeleteAgentRequest', - 'ExportAgentRequest', - 'ExportAgentResponse', - 'GetAgentRequest', - 'GetValidationResultRequest', - 'ImportAgentRequest', - 'RestoreAgentRequest', - 'SearchAgentsRequest', - 'SearchAgentsResponse', - 'SetAgentRequest', - 'TrainAgentRequest', - 'AgentAssistantFeedback', - 'AgentAssistantRecord', - 'AnswerFeedback', - 'AnswerRecord', - 'ListAnswerRecordsRequest', - 'ListAnswerRecordsResponse', - 'UpdateAnswerRecordRequest', - 'InputAudioConfig', - 'OutputAudioConfig', - 'SpeechContext', - 'SpeechToTextConfig', - 'SpeechWordInfo', - 'SynthesizeSpeechConfig', - 'TelephonyDtmfEvents', - 'VoiceSelectionParams', - 'AudioEncoding', - 'OutputAudioEncoding', - 'SpeechModelVariant', - 'SsmlVoiceGender', - 'TelephonyDtmf', - 'Context', - 'CreateContextRequest', - 'DeleteAllContextsRequest', - 'DeleteContextRequest', - 'GetContextRequest', - 'ListContextsRequest', - 'ListContextsResponse', - 'UpdateContextRequest', - 'CompleteConversationRequest', - 'Conversation', - 'ConversationPhoneNumber', - 'CreateConversationRequest', - 'GetConversationRequest', - 'ListConversationsRequest', - 'ListConversationsResponse', - 'ListMessagesRequest', - 'ListMessagesResponse', - 'SuggestConversationSummaryRequest', - 'SuggestConversationSummaryResponse', - 'ConversationDataset', - 'ConversationInfo', - 'CreateConversationDatasetOperationMetadata', - 'CreateConversationDatasetRequest', - 'DeleteConversationDatasetOperationMetadata', - 'DeleteConversationDatasetRequest', - 'GetConversationDatasetRequest', - 'ImportConversationDataOperationMetadata', - 'ImportConversationDataOperationResponse', - 'ImportConversationDataRequest', - 'InputConfig', - 'ListConversationDatasetsRequest', - 'ListConversationDatasetsResponse', - 'ConversationEvent', - 'ArticleSuggestionModelMetadata', - 'ConversationModel', - 'ConversationModelEvaluation', - 'CreateConversationModelEvaluationOperationMetadata', - 'CreateConversationModelEvaluationRequest', - 'CreateConversationModelOperationMetadata', - 'CreateConversationModelRequest', - 'DeleteConversationModelOperationMetadata', - 'DeleteConversationModelRequest', - 'DeployConversationModelOperationMetadata', - 'DeployConversationModelRequest', - 'EvaluationConfig', - 'GetConversationModelEvaluationRequest', - 'GetConversationModelRequest', - 'InputDataset', - 'ListConversationModelEvaluationsRequest', - 'ListConversationModelEvaluationsResponse', - 'ListConversationModelsRequest', - 'ListConversationModelsResponse', - 'SmartReplyMetrics', - 'SmartReplyModelMetadata', - 'UndeployConversationModelOperationMetadata', - 'UndeployConversationModelRequest', - 'AutomatedAgentConfig', - 'ClearSuggestionFeatureConfigOperationMetadata', - 'ClearSuggestionFeatureConfigRequest', - 'ConversationProfile', - 'CreateConversationProfileRequest', - 'DeleteConversationProfileRequest', - 'GetConversationProfileRequest', - 'HumanAgentAssistantConfig', - 'HumanAgentHandoffConfig', - 'ListConversationProfilesRequest', - 'ListConversationProfilesResponse', - 'LoggingConfig', - 'NotificationConfig', - 'SetSuggestionFeatureConfigOperationMetadata', - 'SetSuggestionFeatureConfigRequest', - 'SuggestionFeature', - 'UpdateConversationProfileRequest', - 'CreateDocumentRequest', - 'DeleteDocumentRequest', - 'Document', - 'ExportDocumentRequest', - 'ExportOperationMetadata', - 'GetDocumentRequest', - 'ImportDocumentsRequest', - 'ImportDocumentsResponse', - 'ImportDocumentTemplate', - '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', - 'GcsDestination', - 'GcsSources', - 'HumanAgentAssistantEvent', - 'BatchDeleteIntentsRequest', - 'BatchUpdateIntentsRequest', - 'BatchUpdateIntentsResponse', - 'CreateIntentRequest', - 'DeleteIntentRequest', - 'GetIntentRequest', - 'Intent', - 'IntentBatch', - 'ListIntentsRequest', - 'ListIntentsResponse', - 'UpdateIntentRequest', - 'IntentView', - 'CreateKnowledgeBaseRequest', - 'DeleteKnowledgeBaseRequest', - 'GetKnowledgeBaseRequest', - 'KnowledgeBase', - 'ListKnowledgeBasesRequest', - 'ListKnowledgeBasesResponse', - 'UpdateKnowledgeBaseRequest', - 'AnalyzeContentRequest', - 'AnalyzeContentResponse', - 'AnnotatedMessagePart', - 'ArticleAnswer', - 'AssistQueryParameters', - 'AutomatedAgentReply', - 'CreateParticipantRequest', - 'DtmfParameters', - 'FaqAnswer', - 'GetParticipantRequest', - 'InputTextConfig', - 'ListParticipantsRequest', - 'ListParticipantsResponse', - 'Message', - 'MessageAnnotation', - 'OutputAudio', - 'Participant', - 'SmartReplyAnswer', - 'StreamingAnalyzeContentRequest', - 'StreamingAnalyzeContentResponse', - 'SuggestArticlesRequest', - 'SuggestArticlesResponse', - 'SuggestFaqAnswersRequest', - 'SuggestFaqAnswersResponse', - 'SuggestionResult', - 'SuggestSmartRepliesRequest', - 'SuggestSmartRepliesResponse', - 'UpdateParticipantRequest', - 'DetectIntentRequest', - 'DetectIntentResponse', - 'EventInput', - 'QueryInput', - 'QueryParameters', - 'QueryResult', - 'Sentiment', - 'SentimentAnalysisRequestConfig', - 'SentimentAnalysisResult', - 'StreamingDetectIntentRequest', - 'StreamingDetectIntentResponse', - 'StreamingRecognitionResult', - 'TextInput', - 'CreateSessionEntityTypeRequest', - 'DeleteSessionEntityTypeRequest', - 'GetSessionEntityTypeRequest', - 'ListSessionEntityTypesRequest', - 'ListSessionEntityTypesResponse', - 'SessionEntityType', - 'UpdateSessionEntityTypeRequest', - 'ValidationError', - 'ValidationResult', - 'CreateVersionRequest', - 'DeleteVersionRequest', - 'GetVersionRequest', - 'ListVersionsRequest', - 'ListVersionsResponse', - 'UpdateVersionRequest', - 'Version', - 'OriginalDetectIntentRequest', - 'WebhookRequest', - 'WebhookResponse', -) diff --git a/owl-bot-staging/v2/google/cloud/dialogflow/gapic_version.py b/owl-bot-staging/v2/google/cloud/dialogflow/gapic_version.py deleted file mode 100644 index 405b1cebc..000000000 --- a/owl-bot-staging/v2/google/cloud/dialogflow/gapic_version.py +++ /dev/null @@ -1,16 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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. -# -__version__ = "0.1.0" # {x-release-please-version} diff --git a/owl-bot-staging/v2/google/cloud/dialogflow/py.typed b/owl-bot-staging/v2/google/cloud/dialogflow/py.typed deleted file mode 100644 index 2c6e5af62..000000000 --- a/owl-bot-staging/v2/google/cloud/dialogflow/py.typed +++ /dev/null @@ -1,2 +0,0 @@ -# Marker file for PEP 561. -# The google-cloud-dialogflow package uses inline types. diff --git a/owl-bot-staging/v2/google/cloud/dialogflow_v2/__init__.py b/owl-bot-staging/v2/google/cloud/dialogflow_v2/__init__.py deleted file mode 100644 index 2d726401d..000000000 --- a/owl-bot-staging/v2/google/cloud/dialogflow_v2/__init__.py +++ /dev/null @@ -1,548 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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 google.cloud.dialogflow_v2 import gapic_version as package_version - -__version__ = package_version.__version__ - - -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_datasets import ConversationDatasetsClient -from .services.conversation_datasets import ConversationDatasetsAsyncClient -from .services.conversation_models import ConversationModelsClient -from .services.conversation_models import ConversationModelsAsyncClient -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 -from .types.agent import ExportAgentResponse -from .types.agent import GetAgentRequest -from .types.agent import GetValidationResultRequest -from .types.agent import ImportAgentRequest -from .types.agent import RestoreAgentRequest -from .types.agent import SearchAgentsRequest -from .types.agent import SearchAgentsResponse -from .types.agent import SetAgentRequest -from .types.agent import TrainAgentRequest -from .types.answer_record import AgentAssistantFeedback -from .types.answer_record import AgentAssistantRecord -from .types.answer_record import AnswerFeedback -from .types.answer_record import AnswerRecord -from .types.answer_record import ListAnswerRecordsRequest -from .types.answer_record import ListAnswerRecordsResponse -from .types.answer_record import UpdateAnswerRecordRequest -from .types.audio_config import InputAudioConfig -from .types.audio_config import OutputAudioConfig -from .types.audio_config import SpeechContext -from .types.audio_config import SpeechToTextConfig -from .types.audio_config import SpeechWordInfo -from .types.audio_config import SynthesizeSpeechConfig -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 -from .types.context import DeleteContextRequest -from .types.context import GetContextRequest -from .types.context import ListContextsRequest -from .types.context import ListContextsResponse -from .types.context import UpdateContextRequest -from .types.conversation import CompleteConversationRequest -from .types.conversation import Conversation -from .types.conversation import ConversationPhoneNumber -from .types.conversation import CreateConversationRequest -from .types.conversation import GetConversationRequest -from .types.conversation import ListConversationsRequest -from .types.conversation import ListConversationsResponse -from .types.conversation import ListMessagesRequest -from .types.conversation import ListMessagesResponse -from .types.conversation import SuggestConversationSummaryRequest -from .types.conversation import SuggestConversationSummaryResponse -from .types.conversation_dataset import ConversationDataset -from .types.conversation_dataset import ConversationInfo -from .types.conversation_dataset import CreateConversationDatasetOperationMetadata -from .types.conversation_dataset import CreateConversationDatasetRequest -from .types.conversation_dataset import DeleteConversationDatasetOperationMetadata -from .types.conversation_dataset import DeleteConversationDatasetRequest -from .types.conversation_dataset import GetConversationDatasetRequest -from .types.conversation_dataset import ImportConversationDataOperationMetadata -from .types.conversation_dataset import ImportConversationDataOperationResponse -from .types.conversation_dataset import ImportConversationDataRequest -from .types.conversation_dataset import InputConfig -from .types.conversation_dataset import ListConversationDatasetsRequest -from .types.conversation_dataset import ListConversationDatasetsResponse -from .types.conversation_event import ConversationEvent -from .types.conversation_model import ArticleSuggestionModelMetadata -from .types.conversation_model import ConversationModel -from .types.conversation_model import ConversationModelEvaluation -from .types.conversation_model import CreateConversationModelEvaluationOperationMetadata -from .types.conversation_model import CreateConversationModelEvaluationRequest -from .types.conversation_model import CreateConversationModelOperationMetadata -from .types.conversation_model import CreateConversationModelRequest -from .types.conversation_model import DeleteConversationModelOperationMetadata -from .types.conversation_model import DeleteConversationModelRequest -from .types.conversation_model import DeployConversationModelOperationMetadata -from .types.conversation_model import DeployConversationModelRequest -from .types.conversation_model import EvaluationConfig -from .types.conversation_model import GetConversationModelEvaluationRequest -from .types.conversation_model import GetConversationModelRequest -from .types.conversation_model import InputDataset -from .types.conversation_model import ListConversationModelEvaluationsRequest -from .types.conversation_model import ListConversationModelEvaluationsResponse -from .types.conversation_model import ListConversationModelsRequest -from .types.conversation_model import ListConversationModelsResponse -from .types.conversation_model import SmartReplyMetrics -from .types.conversation_model import SmartReplyModelMetadata -from .types.conversation_model import UndeployConversationModelOperationMetadata -from .types.conversation_model import UndeployConversationModelRequest -from .types.conversation_profile import AutomatedAgentConfig -from .types.conversation_profile import ClearSuggestionFeatureConfigOperationMetadata -from .types.conversation_profile import ClearSuggestionFeatureConfigRequest -from .types.conversation_profile import ConversationProfile -from .types.conversation_profile import CreateConversationProfileRequest -from .types.conversation_profile import DeleteConversationProfileRequest -from .types.conversation_profile import GetConversationProfileRequest -from .types.conversation_profile import HumanAgentAssistantConfig -from .types.conversation_profile import HumanAgentHandoffConfig -from .types.conversation_profile import ListConversationProfilesRequest -from .types.conversation_profile import ListConversationProfilesResponse -from .types.conversation_profile import LoggingConfig -from .types.conversation_profile import NotificationConfig -from .types.conversation_profile import SetSuggestionFeatureConfigOperationMetadata -from .types.conversation_profile import SetSuggestionFeatureConfigRequest -from .types.conversation_profile import SuggestionFeature -from .types.conversation_profile import UpdateConversationProfileRequest -from .types.document import CreateDocumentRequest -from .types.document import DeleteDocumentRequest -from .types.document import Document -from .types.document import ExportDocumentRequest -from .types.document import ExportOperationMetadata -from .types.document import GetDocumentRequest -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 -from .types.document import ReloadDocumentRequest -from .types.document import UpdateDocumentRequest -from .types.entity_type import BatchCreateEntitiesRequest -from .types.entity_type import BatchDeleteEntitiesRequest -from .types.entity_type import BatchDeleteEntityTypesRequest -from .types.entity_type import BatchUpdateEntitiesRequest -from .types.entity_type import BatchUpdateEntityTypesRequest -from .types.entity_type import BatchUpdateEntityTypesResponse -from .types.entity_type import CreateEntityTypeRequest -from .types.entity_type import DeleteEntityTypeRequest -from .types.entity_type import EntityType -from .types.entity_type import EntityTypeBatch -from .types.entity_type import GetEntityTypeRequest -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 GcsDestination -from .types.gcs import GcsSources -from .types.human_agent_assistant_event import HumanAgentAssistantEvent -from .types.intent import BatchDeleteIntentsRequest -from .types.intent import BatchUpdateIntentsRequest -from .types.intent import BatchUpdateIntentsResponse -from .types.intent import CreateIntentRequest -from .types.intent import DeleteIntentRequest -from .types.intent import GetIntentRequest -from .types.intent import Intent -from .types.intent import IntentBatch -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 -from .types.knowledge_base import KnowledgeBase -from .types.knowledge_base import ListKnowledgeBasesRequest -from .types.knowledge_base import ListKnowledgeBasesResponse -from .types.knowledge_base import UpdateKnowledgeBaseRequest -from .types.participant import AnalyzeContentRequest -from .types.participant import AnalyzeContentResponse -from .types.participant import AnnotatedMessagePart -from .types.participant import ArticleAnswer -from .types.participant import AssistQueryParameters -from .types.participant import AutomatedAgentReply -from .types.participant import CreateParticipantRequest -from .types.participant import DtmfParameters -from .types.participant import FaqAnswer -from .types.participant import GetParticipantRequest -from .types.participant import InputTextConfig -from .types.participant import ListParticipantsRequest -from .types.participant import ListParticipantsResponse -from .types.participant import Message -from .types.participant import MessageAnnotation -from .types.participant import OutputAudio -from .types.participant import Participant -from .types.participant import SmartReplyAnswer -from .types.participant import StreamingAnalyzeContentRequest -from .types.participant import StreamingAnalyzeContentResponse -from .types.participant import SuggestArticlesRequest -from .types.participant import SuggestArticlesResponse -from .types.participant import SuggestFaqAnswersRequest -from .types.participant import SuggestFaqAnswersResponse -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 -from .types.session import EventInput -from .types.session import QueryInput -from .types.session import QueryParameters -from .types.session import QueryResult -from .types.session import Sentiment -from .types.session import SentimentAnalysisRequestConfig -from .types.session import SentimentAnalysisResult -from .types.session import StreamingDetectIntentRequest -from .types.session import StreamingDetectIntentResponse -from .types.session import StreamingRecognitionResult -from .types.session import TextInput -from .types.session_entity_type import CreateSessionEntityTypeRequest -from .types.session_entity_type import DeleteSessionEntityTypeRequest -from .types.session_entity_type import GetSessionEntityTypeRequest -from .types.session_entity_type import ListSessionEntityTypesRequest -from .types.session_entity_type import ListSessionEntityTypesResponse -from .types.session_entity_type import SessionEntityType -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__ = ( - 'AgentsAsyncClient', - 'AnswerRecordsAsyncClient', - 'ContextsAsyncClient', - 'ConversationDatasetsAsyncClient', - 'ConversationModelsAsyncClient', - 'ConversationProfilesAsyncClient', - 'ConversationsAsyncClient', - 'DocumentsAsyncClient', - 'EntityTypesAsyncClient', - 'EnvironmentsAsyncClient', - 'FulfillmentsAsyncClient', - 'IntentsAsyncClient', - 'KnowledgeBasesAsyncClient', - 'ParticipantsAsyncClient', - 'SessionEntityTypesAsyncClient', - 'SessionsAsyncClient', - 'VersionsAsyncClient', -'Agent', -'AgentAssistantFeedback', -'AgentAssistantRecord', -'AgentsClient', -'AnalyzeContentRequest', -'AnalyzeContentResponse', -'AnnotatedMessagePart', -'AnswerFeedback', -'AnswerRecord', -'AnswerRecordsClient', -'ArticleAnswer', -'ArticleSuggestionModelMetadata', -'AssistQueryParameters', -'AudioEncoding', -'AutomatedAgentConfig', -'AutomatedAgentReply', -'BatchCreateEntitiesRequest', -'BatchDeleteEntitiesRequest', -'BatchDeleteEntityTypesRequest', -'BatchDeleteIntentsRequest', -'BatchUpdateEntitiesRequest', -'BatchUpdateEntityTypesRequest', -'BatchUpdateEntityTypesResponse', -'BatchUpdateIntentsRequest', -'BatchUpdateIntentsResponse', -'ClearSuggestionFeatureConfigOperationMetadata', -'ClearSuggestionFeatureConfigRequest', -'CompleteConversationRequest', -'Context', -'ContextsClient', -'Conversation', -'ConversationDataset', -'ConversationDatasetsClient', -'ConversationEvent', -'ConversationInfo', -'ConversationModel', -'ConversationModelEvaluation', -'ConversationModelsClient', -'ConversationPhoneNumber', -'ConversationProfile', -'ConversationProfilesClient', -'ConversationsClient', -'CreateContextRequest', -'CreateConversationDatasetOperationMetadata', -'CreateConversationDatasetRequest', -'CreateConversationModelEvaluationOperationMetadata', -'CreateConversationModelEvaluationRequest', -'CreateConversationModelOperationMetadata', -'CreateConversationModelRequest', -'CreateConversationProfileRequest', -'CreateConversationRequest', -'CreateDocumentRequest', -'CreateEntityTypeRequest', -'CreateEnvironmentRequest', -'CreateIntentRequest', -'CreateKnowledgeBaseRequest', -'CreateParticipantRequest', -'CreateSessionEntityTypeRequest', -'CreateVersionRequest', -'DeleteAgentRequest', -'DeleteAllContextsRequest', -'DeleteContextRequest', -'DeleteConversationDatasetOperationMetadata', -'DeleteConversationDatasetRequest', -'DeleteConversationModelOperationMetadata', -'DeleteConversationModelRequest', -'DeleteConversationProfileRequest', -'DeleteDocumentRequest', -'DeleteEntityTypeRequest', -'DeleteEnvironmentRequest', -'DeleteIntentRequest', -'DeleteKnowledgeBaseRequest', -'DeleteSessionEntityTypeRequest', -'DeleteVersionRequest', -'DeployConversationModelOperationMetadata', -'DeployConversationModelRequest', -'DetectIntentRequest', -'DetectIntentResponse', -'Document', -'DocumentsClient', -'DtmfParameters', -'EntityType', -'EntityTypeBatch', -'EntityTypesClient', -'Environment', -'EnvironmentHistory', -'EnvironmentsClient', -'EvaluationConfig', -'EventInput', -'ExportAgentRequest', -'ExportAgentResponse', -'ExportDocumentRequest', -'ExportOperationMetadata', -'FaqAnswer', -'Fulfillment', -'FulfillmentsClient', -'GcsDestination', -'GcsSources', -'GetAgentRequest', -'GetContextRequest', -'GetConversationDatasetRequest', -'GetConversationModelEvaluationRequest', -'GetConversationModelRequest', -'GetConversationProfileRequest', -'GetConversationRequest', -'GetDocumentRequest', -'GetEntityTypeRequest', -'GetEnvironmentHistoryRequest', -'GetEnvironmentRequest', -'GetFulfillmentRequest', -'GetIntentRequest', -'GetKnowledgeBaseRequest', -'GetParticipantRequest', -'GetSessionEntityTypeRequest', -'GetValidationResultRequest', -'GetVersionRequest', -'HumanAgentAssistantConfig', -'HumanAgentAssistantEvent', -'HumanAgentHandoffConfig', -'ImportAgentRequest', -'ImportConversationDataOperationMetadata', -'ImportConversationDataOperationResponse', -'ImportConversationDataRequest', -'ImportDocumentTemplate', -'ImportDocumentsRequest', -'ImportDocumentsResponse', -'InputAudioConfig', -'InputConfig', -'InputDataset', -'InputTextConfig', -'Intent', -'IntentBatch', -'IntentView', -'IntentsClient', -'KnowledgeBase', -'KnowledgeBasesClient', -'KnowledgeOperationMetadata', -'ListAnswerRecordsRequest', -'ListAnswerRecordsResponse', -'ListContextsRequest', -'ListContextsResponse', -'ListConversationDatasetsRequest', -'ListConversationDatasetsResponse', -'ListConversationModelEvaluationsRequest', -'ListConversationModelEvaluationsResponse', -'ListConversationModelsRequest', -'ListConversationModelsResponse', -'ListConversationProfilesRequest', -'ListConversationProfilesResponse', -'ListConversationsRequest', -'ListConversationsResponse', -'ListDocumentsRequest', -'ListDocumentsResponse', -'ListEntityTypesRequest', -'ListEntityTypesResponse', -'ListEnvironmentsRequest', -'ListEnvironmentsResponse', -'ListIntentsRequest', -'ListIntentsResponse', -'ListKnowledgeBasesRequest', -'ListKnowledgeBasesResponse', -'ListMessagesRequest', -'ListMessagesResponse', -'ListParticipantsRequest', -'ListParticipantsResponse', -'ListSessionEntityTypesRequest', -'ListSessionEntityTypesResponse', -'ListVersionsRequest', -'ListVersionsResponse', -'LoggingConfig', -'Message', -'MessageAnnotation', -'NotificationConfig', -'OriginalDetectIntentRequest', -'OutputAudio', -'OutputAudioConfig', -'OutputAudioEncoding', -'Participant', -'ParticipantsClient', -'QueryInput', -'QueryParameters', -'QueryResult', -'ReloadDocumentRequest', -'RestoreAgentRequest', -'SearchAgentsRequest', -'SearchAgentsResponse', -'Sentiment', -'SentimentAnalysisRequestConfig', -'SentimentAnalysisResult', -'SessionEntityType', -'SessionEntityTypesClient', -'SessionsClient', -'SetAgentRequest', -'SetSuggestionFeatureConfigOperationMetadata', -'SetSuggestionFeatureConfigRequest', -'SmartReplyAnswer', -'SmartReplyMetrics', -'SmartReplyModelMetadata', -'SpeechContext', -'SpeechModelVariant', -'SpeechToTextConfig', -'SpeechWordInfo', -'SsmlVoiceGender', -'StreamingAnalyzeContentRequest', -'StreamingAnalyzeContentResponse', -'StreamingDetectIntentRequest', -'StreamingDetectIntentResponse', -'StreamingRecognitionResult', -'SuggestArticlesRequest', -'SuggestArticlesResponse', -'SuggestConversationSummaryRequest', -'SuggestConversationSummaryResponse', -'SuggestFaqAnswersRequest', -'SuggestFaqAnswersResponse', -'SuggestSmartRepliesRequest', -'SuggestSmartRepliesResponse', -'SuggestionFeature', -'SuggestionResult', -'SynthesizeSpeechConfig', -'TelephonyDtmf', -'TelephonyDtmfEvents', -'TextInput', -'TextToSpeechSettings', -'TrainAgentRequest', -'UndeployConversationModelOperationMetadata', -'UndeployConversationModelRequest', -'UpdateAnswerRecordRequest', -'UpdateContextRequest', -'UpdateConversationProfileRequest', -'UpdateDocumentRequest', -'UpdateEntityTypeRequest', -'UpdateEnvironmentRequest', -'UpdateFulfillmentRequest', -'UpdateIntentRequest', -'UpdateKnowledgeBaseRequest', -'UpdateParticipantRequest', -'UpdateSessionEntityTypeRequest', -'UpdateVersionRequest', -'ValidationError', -'ValidationResult', -'Version', -'VersionsClient', -'VoiceSelectionParams', -'WebhookRequest', -'WebhookResponse', -) diff --git a/owl-bot-staging/v2/google/cloud/dialogflow_v2/gapic_metadata.json b/owl-bot-staging/v2/google/cloud/dialogflow_v2/gapic_metadata.json deleted file mode 100644 index 59e9b0fa5..000000000 --- a/owl-bot-staging/v2/google/cloud/dialogflow_v2/gapic_metadata.json +++ /dev/null @@ -1,1877 +0,0 @@ - { - "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" - ] - } - } - }, - "rest": { - "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" - ] - } - } - } - } - }, - "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" - ] - } - } - }, - "rest": { - "libraryClient": "AnswerRecordsClient", - "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" - ] - } - } - }, - "rest": { - "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" - ] - } - } - } - } - }, - "ConversationDatasets": { - "clients": { - "grpc": { - "libraryClient": "ConversationDatasetsClient", - "rpcs": { - "CreateConversationDataset": { - "methods": [ - "create_conversation_dataset" - ] - }, - "DeleteConversationDataset": { - "methods": [ - "delete_conversation_dataset" - ] - }, - "GetConversationDataset": { - "methods": [ - "get_conversation_dataset" - ] - }, - "ImportConversationData": { - "methods": [ - "import_conversation_data" - ] - }, - "ListConversationDatasets": { - "methods": [ - "list_conversation_datasets" - ] - } - } - }, - "grpc-async": { - "libraryClient": "ConversationDatasetsAsyncClient", - "rpcs": { - "CreateConversationDataset": { - "methods": [ - "create_conversation_dataset" - ] - }, - "DeleteConversationDataset": { - "methods": [ - "delete_conversation_dataset" - ] - }, - "GetConversationDataset": { - "methods": [ - "get_conversation_dataset" - ] - }, - "ImportConversationData": { - "methods": [ - "import_conversation_data" - ] - }, - "ListConversationDatasets": { - "methods": [ - "list_conversation_datasets" - ] - } - } - }, - "rest": { - "libraryClient": "ConversationDatasetsClient", - "rpcs": { - "CreateConversationDataset": { - "methods": [ - "create_conversation_dataset" - ] - }, - "DeleteConversationDataset": { - "methods": [ - "delete_conversation_dataset" - ] - }, - "GetConversationDataset": { - "methods": [ - "get_conversation_dataset" - ] - }, - "ImportConversationData": { - "methods": [ - "import_conversation_data" - ] - }, - "ListConversationDatasets": { - "methods": [ - "list_conversation_datasets" - ] - } - } - } - } - }, - "ConversationModels": { - "clients": { - "grpc": { - "libraryClient": "ConversationModelsClient", - "rpcs": { - "CreateConversationModel": { - "methods": [ - "create_conversation_model" - ] - }, - "CreateConversationModelEvaluation": { - "methods": [ - "create_conversation_model_evaluation" - ] - }, - "DeleteConversationModel": { - "methods": [ - "delete_conversation_model" - ] - }, - "DeployConversationModel": { - "methods": [ - "deploy_conversation_model" - ] - }, - "GetConversationModel": { - "methods": [ - "get_conversation_model" - ] - }, - "GetConversationModelEvaluation": { - "methods": [ - "get_conversation_model_evaluation" - ] - }, - "ListConversationModelEvaluations": { - "methods": [ - "list_conversation_model_evaluations" - ] - }, - "ListConversationModels": { - "methods": [ - "list_conversation_models" - ] - }, - "UndeployConversationModel": { - "methods": [ - "undeploy_conversation_model" - ] - } - } - }, - "grpc-async": { - "libraryClient": "ConversationModelsAsyncClient", - "rpcs": { - "CreateConversationModel": { - "methods": [ - "create_conversation_model" - ] - }, - "CreateConversationModelEvaluation": { - "methods": [ - "create_conversation_model_evaluation" - ] - }, - "DeleteConversationModel": { - "methods": [ - "delete_conversation_model" - ] - }, - "DeployConversationModel": { - "methods": [ - "deploy_conversation_model" - ] - }, - "GetConversationModel": { - "methods": [ - "get_conversation_model" - ] - }, - "GetConversationModelEvaluation": { - "methods": [ - "get_conversation_model_evaluation" - ] - }, - "ListConversationModelEvaluations": { - "methods": [ - "list_conversation_model_evaluations" - ] - }, - "ListConversationModels": { - "methods": [ - "list_conversation_models" - ] - }, - "UndeployConversationModel": { - "methods": [ - "undeploy_conversation_model" - ] - } - } - }, - "rest": { - "libraryClient": "ConversationModelsClient", - "rpcs": { - "CreateConversationModel": { - "methods": [ - "create_conversation_model" - ] - }, - "CreateConversationModelEvaluation": { - "methods": [ - "create_conversation_model_evaluation" - ] - }, - "DeleteConversationModel": { - "methods": [ - "delete_conversation_model" - ] - }, - "DeployConversationModel": { - "methods": [ - "deploy_conversation_model" - ] - }, - "GetConversationModel": { - "methods": [ - "get_conversation_model" - ] - }, - "GetConversationModelEvaluation": { - "methods": [ - "get_conversation_model_evaluation" - ] - }, - "ListConversationModelEvaluations": { - "methods": [ - "list_conversation_model_evaluations" - ] - }, - "ListConversationModels": { - "methods": [ - "list_conversation_models" - ] - }, - "UndeployConversationModel": { - "methods": [ - "undeploy_conversation_model" - ] - } - } - } - } - }, - "ConversationProfiles": { - "clients": { - "grpc": { - "libraryClient": "ConversationProfilesClient", - "rpcs": { - "ClearSuggestionFeatureConfig": { - "methods": [ - "clear_suggestion_feature_config" - ] - }, - "CreateConversationProfile": { - "methods": [ - "create_conversation_profile" - ] - }, - "DeleteConversationProfile": { - "methods": [ - "delete_conversation_profile" - ] - }, - "GetConversationProfile": { - "methods": [ - "get_conversation_profile" - ] - }, - "ListConversationProfiles": { - "methods": [ - "list_conversation_profiles" - ] - }, - "SetSuggestionFeatureConfig": { - "methods": [ - "set_suggestion_feature_config" - ] - }, - "UpdateConversationProfile": { - "methods": [ - "update_conversation_profile" - ] - } - } - }, - "grpc-async": { - "libraryClient": "ConversationProfilesAsyncClient", - "rpcs": { - "ClearSuggestionFeatureConfig": { - "methods": [ - "clear_suggestion_feature_config" - ] - }, - "CreateConversationProfile": { - "methods": [ - "create_conversation_profile" - ] - }, - "DeleteConversationProfile": { - "methods": [ - "delete_conversation_profile" - ] - }, - "GetConversationProfile": { - "methods": [ - "get_conversation_profile" - ] - }, - "ListConversationProfiles": { - "methods": [ - "list_conversation_profiles" - ] - }, - "SetSuggestionFeatureConfig": { - "methods": [ - "set_suggestion_feature_config" - ] - }, - "UpdateConversationProfile": { - "methods": [ - "update_conversation_profile" - ] - } - } - }, - "rest": { - "libraryClient": "ConversationProfilesClient", - "rpcs": { - "ClearSuggestionFeatureConfig": { - "methods": [ - "clear_suggestion_feature_config" - ] - }, - "CreateConversationProfile": { - "methods": [ - "create_conversation_profile" - ] - }, - "DeleteConversationProfile": { - "methods": [ - "delete_conversation_profile" - ] - }, - "GetConversationProfile": { - "methods": [ - "get_conversation_profile" - ] - }, - "ListConversationProfiles": { - "methods": [ - "list_conversation_profiles" - ] - }, - "SetSuggestionFeatureConfig": { - "methods": [ - "set_suggestion_feature_config" - ] - }, - "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" - ] - }, - "SuggestConversationSummary": { - "methods": [ - "suggest_conversation_summary" - ] - } - } - }, - "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" - ] - }, - "SuggestConversationSummary": { - "methods": [ - "suggest_conversation_summary" - ] - } - } - }, - "rest": { - "libraryClient": "ConversationsClient", - "rpcs": { - "CompleteConversation": { - "methods": [ - "complete_conversation" - ] - }, - "CreateConversation": { - "methods": [ - "create_conversation" - ] - }, - "GetConversation": { - "methods": [ - "get_conversation" - ] - }, - "ListConversations": { - "methods": [ - "list_conversations" - ] - }, - "ListMessages": { - "methods": [ - "list_messages" - ] - }, - "SuggestConversationSummary": { - "methods": [ - "suggest_conversation_summary" - ] - } - } - } - } - }, - "Documents": { - "clients": { - "grpc": { - "libraryClient": "DocumentsClient", - "rpcs": { - "CreateDocument": { - "methods": [ - "create_document" - ] - }, - "DeleteDocument": { - "methods": [ - "delete_document" - ] - }, - "ExportDocument": { - "methods": [ - "export_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" - ] - }, - "ExportDocument": { - "methods": [ - "export_document" - ] - }, - "GetDocument": { - "methods": [ - "get_document" - ] - }, - "ImportDocuments": { - "methods": [ - "import_documents" - ] - }, - "ListDocuments": { - "methods": [ - "list_documents" - ] - }, - "ReloadDocument": { - "methods": [ - "reload_document" - ] - }, - "UpdateDocument": { - "methods": [ - "update_document" - ] - } - } - }, - "rest": { - "libraryClient": "DocumentsClient", - "rpcs": { - "CreateDocument": { - "methods": [ - "create_document" - ] - }, - "DeleteDocument": { - "methods": [ - "delete_document" - ] - }, - "ExportDocument": { - "methods": [ - "export_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" - ] - } - } - }, - "rest": { - "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" - ] - } - } - } - } - }, - "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" - ] - } - } - }, - "rest": { - "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" - ] - } - } - } - } - }, - "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" - ] - } - } - }, - "rest": { - "libraryClient": "FulfillmentsClient", - "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" - ] - } - } - }, - "rest": { - "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" - ] - } - } - } - } - }, - "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" - ] - } - } - }, - "rest": { - "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" - ] - } - } - } - } - }, - "Participants": { - "clients": { - "grpc": { - "libraryClient": "ParticipantsClient", - "rpcs": { - "AnalyzeContent": { - "methods": [ - "analyze_content" - ] - }, - "CreateParticipant": { - "methods": [ - "create_participant" - ] - }, - "GetParticipant": { - "methods": [ - "get_participant" - ] - }, - "ListParticipants": { - "methods": [ - "list_participants" - ] - }, - "StreamingAnalyzeContent": { - "methods": [ - "streaming_analyze_content" - ] - }, - "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" - ] - }, - "CreateParticipant": { - "methods": [ - "create_participant" - ] - }, - "GetParticipant": { - "methods": [ - "get_participant" - ] - }, - "ListParticipants": { - "methods": [ - "list_participants" - ] - }, - "StreamingAnalyzeContent": { - "methods": [ - "streaming_analyze_content" - ] - }, - "SuggestArticles": { - "methods": [ - "suggest_articles" - ] - }, - "SuggestFaqAnswers": { - "methods": [ - "suggest_faq_answers" - ] - }, - "SuggestSmartReplies": { - "methods": [ - "suggest_smart_replies" - ] - }, - "UpdateParticipant": { - "methods": [ - "update_participant" - ] - } - } - }, - "rest": { - "libraryClient": "ParticipantsClient", - "rpcs": { - "AnalyzeContent": { - "methods": [ - "analyze_content" - ] - }, - "CreateParticipant": { - "methods": [ - "create_participant" - ] - }, - "GetParticipant": { - "methods": [ - "get_participant" - ] - }, - "ListParticipants": { - "methods": [ - "list_participants" - ] - }, - "StreamingAnalyzeContent": { - "methods": [ - "streaming_analyze_content" - ] - }, - "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" - ] - } - } - }, - "rest": { - "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" - ] - } - } - } - } - }, - "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" - ] - } - } - }, - "rest": { - "libraryClient": "SessionsClient", - "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" - ] - } - } - }, - "rest": { - "libraryClient": "VersionsClient", - "rpcs": { - "CreateVersion": { - "methods": [ - "create_version" - ] - }, - "DeleteVersion": { - "methods": [ - "delete_version" - ] - }, - "GetVersion": { - "methods": [ - "get_version" - ] - }, - "ListVersions": { - "methods": [ - "list_versions" - ] - }, - "UpdateVersion": { - "methods": [ - "update_version" - ] - } - } - } - } - } - } -} diff --git a/owl-bot-staging/v2/google/cloud/dialogflow_v2/gapic_version.py b/owl-bot-staging/v2/google/cloud/dialogflow_v2/gapic_version.py deleted file mode 100644 index 405b1cebc..000000000 --- a/owl-bot-staging/v2/google/cloud/dialogflow_v2/gapic_version.py +++ /dev/null @@ -1,16 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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. -# -__version__ = "0.1.0" # {x-release-please-version} diff --git a/owl-bot-staging/v2/google/cloud/dialogflow_v2/py.typed b/owl-bot-staging/v2/google/cloud/dialogflow_v2/py.typed deleted file mode 100644 index 2c6e5af62..000000000 --- a/owl-bot-staging/v2/google/cloud/dialogflow_v2/py.typed +++ /dev/null @@ -1,2 +0,0 @@ -# Marker file for PEP 561. -# The google-cloud-dialogflow package uses inline types. diff --git a/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/__init__.py b/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/__init__.py deleted file mode 100644 index e8e1c3845..000000000 --- a/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/__init__.py +++ /dev/null @@ -1,15 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/agents/__init__.py b/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/agents/__init__.py deleted file mode 100644 index 59831995e..000000000 --- a/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/agents/__init__.py +++ /dev/null @@ -1,22 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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 AgentsClient -from .async_client import AgentsAsyncClient - -__all__ = ( - 'AgentsClient', - 'AgentsAsyncClient', -) diff --git a/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/agents/async_client.py b/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/agents/async_client.py deleted file mode 100644 index 597f387f1..000000000 --- a/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/agents/async_client.py +++ /dev/null @@ -1,1505 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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, Mapping, MutableMapping, MutableSequence, Optional, Sequence, Tuple, Type, Union - -from google.cloud.dialogflow_v2 import gapic_version as package_version - -from google.api_core.client_options import ClientOptions -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import retry as retries -from google.auth import credentials as ga_credentials # type: ignore -from google.oauth2 import service_account # type: ignore - -try: - OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] -except AttributeError: # pragma: NO COVER - OptionalRetry = Union[retries.Retry, object] # type: ignore - -from google.api_core import operation # type: ignore -from google.api_core import operation_async # type: ignore -from google.cloud.dialogflow_v2.services.agents import pagers -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.cloud.location import locations_pb2 # type: ignore -from google.longrunning import operations_pb2 -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 - - -class AgentsAsyncClient: - """Service for managing [Agents][google.cloud.dialogflow.v2.Agent].""" - - _client: AgentsClient - - DEFAULT_ENDPOINT = AgentsClient.DEFAULT_ENDPOINT - DEFAULT_MTLS_ENDPOINT = AgentsClient.DEFAULT_MTLS_ENDPOINT - - 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) - - @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: - AgentsAsyncClient: The constructed client. - """ - return AgentsClient.from_service_account_info.__func__(AgentsAsyncClient, 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: - AgentsAsyncClient: The constructed client. - """ - return AgentsClient.from_service_account_file.__func__(AgentsAsyncClient, filename, *args, **kwargs) # type: ignore - - from_service_account_json = from_service_account_file - - @classmethod - def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[ClientOptions] = None): - """Return the API endpoint and client cert source for mutual TLS. - - The client cert source is determined in the following order: - (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the - client cert source is None. - (2) if `client_options.client_cert_source` is provided, use the provided one; if the - default client cert source exists, use the default one; otherwise the client cert - source is None. - - The API endpoint is determined in the following order: - (1) if `client_options.api_endpoint` if provided, use the provided one. - (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the - default mTLS endpoint; if the environment variable is "never", use the default API - endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise - use the default API endpoint. - - More details can be found at https://google.aip.dev/auth/4114. - - Args: - client_options (google.api_core.client_options.ClientOptions): Custom options for the - client. Only the `api_endpoint` and `client_cert_source` properties may be used - in this method. - - Returns: - Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the - client cert source to use. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If any errors happen. - """ - return AgentsClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore - - @property - def transport(self) -> AgentsTransport: - """Returns the transport used by the client instance. - - Returns: - AgentsTransport: The transport used by the client instance. - """ - return self._client.transport - - get_transport_class = functools.partial(type(AgentsClient).get_transport_class, type(AgentsClient)) - - def __init__(self, *, - credentials: Optional[ga_credentials.Credentials] = None, - transport: Union[str, AgentsTransport] = "grpc_asyncio", - client_options: Optional[ClientOptions] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the agents 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, ~.AgentsTransport]): 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 = AgentsClient( - credentials=credentials, - transport=transport, - client_options=client_options, - client_info=client_info, - - ) - - async def get_agent(self, - request: Optional[Union[agent.GetAgentRequest, dict]] = None, - *, - parent: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> agent.Agent: - r"""Retrieves the specified agent. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import dialogflow_v2 - - async def sample_get_agent(): - # Create a client - client = dialogflow_v2.AgentsAsyncClient() - - # Initialize request argument(s) - request = dialogflow_v2.GetAgentRequest( - parent="parent_value", - ) - - # Make the request - response = await client.get_agent(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.dialogflow_v2.types.GetAgentRequest, dict]]): - The request object. The request message for - [Agents.GetAgent][google.cloud.dialogflow.v2.Agents.GetAgent]. - parent (:class:`str`): - Required. The project that the agent to fetch is - associated with. Format: ``projects/``. - - 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.types.Agent: - A Dialogflow agent is a virtual agent that handles conversations with your - end-users. It is a natural language understanding - module that understands the nuances of human - language. Dialogflow translates end-user text or - audio during a conversation to structured data that - your apps and services can understand. You design and - build a Dialogflow agent to handle the types of - conversations required for your system. - - For more information about agents, see the [Agent - guide](\ https://cloud.google.com/dialogflow/docs/agents-overview). - - """ - # Create or coerce a protobuf request object. - # Quick 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 = agent.GetAgentRequest(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.get_agent, - 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 set_agent(self, - request: Optional[Union[gcd_agent.SetAgentRequest, dict]] = None, - *, - agent: Optional[gcd_agent.Agent] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gcd_agent.Agent: - r"""Creates/updates the specified agent. - - Note: You should always train an agent prior to sending it - queries. See the `training - documentation `__. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import dialogflow_v2 - - async def sample_set_agent(): - # Create a client - client = dialogflow_v2.AgentsAsyncClient() - - # Initialize request argument(s) - agent = dialogflow_v2.Agent() - agent.parent = "parent_value" - agent.display_name = "display_name_value" - agent.default_language_code = "default_language_code_value" - agent.time_zone = "time_zone_value" - - request = dialogflow_v2.SetAgentRequest( - agent=agent, - ) - - # Make the request - response = await client.set_agent(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.dialogflow_v2.types.SetAgentRequest, dict]]): - The request object. The request message for - [Agents.SetAgent][google.cloud.dialogflow.v2.Agents.SetAgent]. - agent (:class:`google.cloud.dialogflow_v2.types.Agent`): - Required. The agent to update. - 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. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.dialogflow_v2.types.Agent: - A Dialogflow agent is a virtual agent that handles conversations with your - end-users. It is a natural language understanding - module that understands the nuances of human - language. Dialogflow translates end-user text or - audio during a conversation to structured data that - your apps and services can understand. You design and - build a Dialogflow agent to handle the types of - conversations required for your system. - - For more information about agents, see the [Agent - guide](\ https://cloud.google.com/dialogflow/docs/agents-overview). - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([agent]) - 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_agent.SetAgentRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if agent is not None: - request.agent = agent - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.set_agent, - 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(( - ("agent.parent", request.agent.parent), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def delete_agent(self, - request: Optional[Union[agent.DeleteAgentRequest, dict]] = None, - *, - parent: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> None: - r"""Deletes the specified agent. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import dialogflow_v2 - - async def sample_delete_agent(): - # Create a client - client = dialogflow_v2.AgentsAsyncClient() - - # Initialize request argument(s) - request = dialogflow_v2.DeleteAgentRequest( - parent="parent_value", - ) - - # Make the request - await client.delete_agent(request=request) - - Args: - request (Optional[Union[google.cloud.dialogflow_v2.types.DeleteAgentRequest, dict]]): - The request object. The request message for - [Agents.DeleteAgent][google.cloud.dialogflow.v2.Agents.DeleteAgent]. - parent (:class:`str`): - Required. The project that the agent to delete is - associated with. Format: ``projects/``. - - 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. - """ - # Create or coerce a protobuf request object. - # Quick 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 = agent.DeleteAgentRequest(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.delete_agent, - 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. - await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - async def search_agents(self, - request: Optional[Union[agent.SearchAgentsRequest, dict]] = None, - *, - parent: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.SearchAgentsAsyncPager: - r"""Returns the list of agents. - - Since there is at most one conversational agent per project, - this method is useful primarily for listing all agents across - projects the caller has access to. One can achieve that with a - wildcard project collection id "-". Refer to `List - Sub-Collections `__. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import dialogflow_v2 - - async def sample_search_agents(): - # Create a client - client = dialogflow_v2.AgentsAsyncClient() - - # Initialize request argument(s) - request = dialogflow_v2.SearchAgentsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.search_agents(request=request) - - # Handle the response - async for response in page_result: - print(response) - - Args: - request (Optional[Union[google.cloud.dialogflow_v2.types.SearchAgentsRequest, dict]]): - The request object. The request message for - [Agents.SearchAgents][google.cloud.dialogflow.v2.Agents.SearchAgents]. - parent (:class:`str`): - Required. The project to list agents from. Format: - ``projects/``. - - 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.agents.pagers.SearchAgentsAsyncPager: - The response message for - [Agents.SearchAgents][google.cloud.dialogflow.v2.Agents.SearchAgents]. - - Iterating over this object will yield results and - resolve additional pages automatically. - - """ - # Create or coerce a protobuf request object. - # Quick 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 = agent.SearchAgentsRequest(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.search_agents, - 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.SearchAgentsAsyncPager( - method=rpc, - request=request, - response=response, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def train_agent(self, - request: Optional[Union[agent.TrainAgentRequest, dict]] = None, - *, - parent: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation_async.AsyncOperation: - r"""Trains the specified agent. - - This method is a `long-running - operation `__. - The returned ``Operation`` type has the following - method-specific fields: - - - ``metadata``: An empty `Struct - message `__ - - ``response``: An `Empty - message `__ - - Note: You should always train an agent prior to sending it - queries. See the `training - documentation `__. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import dialogflow_v2 - - async def sample_train_agent(): - # Create a client - client = dialogflow_v2.AgentsAsyncClient() - - # Initialize request argument(s) - request = dialogflow_v2.TrainAgentRequest( - parent="parent_value", - ) - - # Make the request - operation = client.train_agent(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.dialogflow_v2.types.TrainAgentRequest, dict]]): - The request object. The request message for - [Agents.TrainAgent][google.cloud.dialogflow.v2.Agents.TrainAgent]. - parent (:class:`str`): - Required. The project that the agent to train is - associated with. Format: ``projects/``. - - 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.api_core.operation_async.AsyncOperation: - An object representing a long-running operation. - - The result type for the operation will be :class:`google.protobuf.empty_pb2.Empty` A generic empty message that you can re-use to avoid defining duplicated - empty messages in your APIs. A typical example is to - use it as the request or the response type of an API - method. For instance: - - service Foo { - rpc Bar(google.protobuf.Empty) returns - (google.protobuf.Empty); - - } - - """ - # Create or coerce a protobuf request object. - # Quick 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 = agent.TrainAgentRequest(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.train_agent, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Wrap the response in an operation future. - response = operation_async.from_gapic( - response, - self._client._transport.operations_client, - empty_pb2.Empty, - metadata_type=struct_pb2.Struct, - ) - - # Done; return the response. - return response - - async def export_agent(self, - request: Optional[Union[agent.ExportAgentRequest, dict]] = None, - *, - parent: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation_async.AsyncOperation: - r"""Exports the specified agent to a ZIP file. - - This method is a `long-running - operation `__. - The returned ``Operation`` type has the following - method-specific fields: - - - ``metadata``: An empty `Struct - message `__ - - ``response``: - [ExportAgentResponse][google.cloud.dialogflow.v2.ExportAgentResponse] - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import dialogflow_v2 - - async def sample_export_agent(): - # Create a client - client = dialogflow_v2.AgentsAsyncClient() - - # Initialize request argument(s) - request = dialogflow_v2.ExportAgentRequest( - parent="parent_value", - agent_uri="agent_uri_value", - ) - - # Make the request - operation = client.export_agent(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.dialogflow_v2.types.ExportAgentRequest, dict]]): - The request object. The request message for - [Agents.ExportAgent][google.cloud.dialogflow.v2.Agents.ExportAgent]. - parent (:class:`str`): - Required. The project that the agent to export is - associated with. Format: ``projects/``. - - 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.api_core.operation_async.AsyncOperation: - An object representing a long-running operation. - - The result type for the operation will be :class:`google.cloud.dialogflow_v2.types.ExportAgentResponse` The response message for - [Agents.ExportAgent][google.cloud.dialogflow.v2.Agents.ExportAgent]. - - """ - # Create or coerce a protobuf request object. - # Quick 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 = agent.ExportAgentRequest(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.export_agent, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Wrap the response in an operation future. - response = operation_async.from_gapic( - response, - self._client._transport.operations_client, - agent.ExportAgentResponse, - metadata_type=struct_pb2.Struct, - ) - - # Done; return the response. - return response - - async def import_agent(self, - request: Optional[Union[agent.ImportAgentRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation_async.AsyncOperation: - r"""Imports the specified agent from a ZIP file. - - Uploads new intents and entity types without deleting the - existing ones. Intents and entity types with the same name are - replaced with the new versions from - [ImportAgentRequest][google.cloud.dialogflow.v2.ImportAgentRequest]. - After the import, the imported draft agent will be trained - automatically (unless disabled in agent settings). However, once - the import is done, training may not be completed yet. Please - call [TrainAgent][google.cloud.dialogflow.v2.Agents.TrainAgent] - and wait for the operation it returns in order to train - explicitly. - - This method is a `long-running - operation `__. - The returned ``Operation`` type has the following - method-specific fields: - - - ``metadata``: An empty `Struct - message `__ - - ``response``: An `Empty - message `__ - - The operation only tracks when importing is complete, not when - it is done training. - - Note: You should always train an agent prior to sending it - queries. See the `training - documentation `__. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import dialogflow_v2 - - async def sample_import_agent(): - # Create a client - client = dialogflow_v2.AgentsAsyncClient() - - # Initialize request argument(s) - request = dialogflow_v2.ImportAgentRequest( - agent_uri="agent_uri_value", - parent="parent_value", - ) - - # Make the request - operation = client.import_agent(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.dialogflow_v2.types.ImportAgentRequest, dict]]): - 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. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.api_core.operation_async.AsyncOperation: - An object representing a long-running operation. - - The result type for the operation will be :class:`google.protobuf.empty_pb2.Empty` A generic empty message that you can re-use to avoid defining duplicated - empty messages in your APIs. A typical example is to - use it as the request or the response type of an API - method. For instance: - - service Foo { - rpc Bar(google.protobuf.Empty) returns - (google.protobuf.Empty); - - } - - """ - # Create or coerce a protobuf request object. - request = agent.ImportAgentRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.import_agent, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Wrap the response in an operation future. - response = operation_async.from_gapic( - response, - self._client._transport.operations_client, - empty_pb2.Empty, - metadata_type=struct_pb2.Struct, - ) - - # Done; return the response. - return response - - async def restore_agent(self, - request: Optional[Union[agent.RestoreAgentRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation_async.AsyncOperation: - r"""Restores the specified agent from a ZIP file. - - Replaces the current agent version with a new one. All the - intents and entity types in the older version are deleted. After - the restore, the restored draft agent will be trained - automatically (unless disabled in agent settings). However, once - the restore is done, training may not be completed yet. Please - call [TrainAgent][google.cloud.dialogflow.v2.Agents.TrainAgent] - and wait for the operation it returns in order to train - explicitly. - - This method is a `long-running - operation `__. - The returned ``Operation`` type has the following - method-specific fields: - - - ``metadata``: An empty `Struct - message `__ - - ``response``: An `Empty - message `__ - - The operation only tracks when restoring is complete, not when - it is done training. - - Note: You should always train an agent prior to sending it - queries. See the `training - documentation `__. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import dialogflow_v2 - - async def sample_restore_agent(): - # Create a client - client = dialogflow_v2.AgentsAsyncClient() - - # Initialize request argument(s) - request = dialogflow_v2.RestoreAgentRequest( - agent_uri="agent_uri_value", - parent="parent_value", - ) - - # Make the request - operation = client.restore_agent(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.dialogflow_v2.types.RestoreAgentRequest, dict]]): - 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. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.api_core.operation_async.AsyncOperation: - An object representing a long-running operation. - - The result type for the operation will be :class:`google.protobuf.empty_pb2.Empty` A generic empty message that you can re-use to avoid defining duplicated - empty messages in your APIs. A typical example is to - use it as the request or the response type of an API - method. For instance: - - service Foo { - rpc Bar(google.protobuf.Empty) returns - (google.protobuf.Empty); - - } - - """ - # Create or coerce a protobuf request object. - request = agent.RestoreAgentRequest(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.restore_agent, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Wrap the response in an operation future. - response = operation_async.from_gapic( - response, - self._client._transport.operations_client, - empty_pb2.Empty, - metadata_type=struct_pb2.Struct, - ) - - # Done; return the response. - return response - - async def get_validation_result(self, - request: Optional[Union[agent.GetValidationResultRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> validation_result.ValidationResult: - r"""Gets agent validation result. Agent validation is - performed during training time and is updated - automatically when training is completed. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import dialogflow_v2 - - async def sample_get_validation_result(): - # Create a client - client = dialogflow_v2.AgentsAsyncClient() - - # Initialize request argument(s) - request = dialogflow_v2.GetValidationResultRequest( - parent="parent_value", - ) - - # Make the request - response = await client.get_validation_result(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.dialogflow_v2.types.GetValidationResultRequest, dict]]): - 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. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.dialogflow_v2.types.ValidationResult: - Represents the output of agent - validation. - - """ - # Create or coerce a protobuf request object. - request = agent.GetValidationResultRequest(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_validation_result, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def list_operations( - self, - request: Optional[operations_pb2.ListOperationsRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operations_pb2.ListOperationsResponse: - r"""Lists operations that match the specified filter in the request. - - Args: - request (:class:`~.operations_pb2.ListOperationsRequest`): - The request object. Request message for - `ListOperations` method. - 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: - ~.operations_pb2.ListOperationsResponse: - Response message for ``ListOperations`` method. - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = operations_pb2.ListOperationsRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._client._transport.list_operations, - 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 get_operation( - self, - request: Optional[operations_pb2.GetOperationRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operations_pb2.Operation: - r"""Gets the latest state of a long-running operation. - - Args: - request (:class:`~.operations_pb2.GetOperationRequest`): - The request object. Request message for - `GetOperation` method. - 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: - ~.operations_pb2.Operation: - An ``Operation`` object. - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = operations_pb2.GetOperationRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._client._transport.get_operation, - 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 cancel_operation( - self, - request: Optional[operations_pb2.CancelOperationRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> None: - r"""Starts asynchronous cancellation on a long-running operation. - - The server makes a best effort to cancel the operation, but success - is not guaranteed. If the server doesn't support this method, it returns - `google.rpc.Code.UNIMPLEMENTED`. - - Args: - request (:class:`~.operations_pb2.CancelOperationRequest`): - The request object. Request message for - `CancelOperation` method. - 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: - None - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = operations_pb2.CancelOperationRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._client._transport.cancel_operation, - 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_location( - self, - request: Optional[locations_pb2.GetLocationRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> locations_pb2.Location: - r"""Gets information about a location. - - Args: - request (:class:`~.location_pb2.GetLocationRequest`): - The request object. Request message for - `GetLocation` method. - 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: - ~.location_pb2.Location: - Location object. - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = locations_pb2.GetLocationRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._client._transport.get_location, - 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 list_locations( - self, - request: Optional[locations_pb2.ListLocationsRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> locations_pb2.ListLocationsResponse: - r"""Lists information about the supported locations for this service. - - Args: - request (:class:`~.location_pb2.ListLocationsRequest`): - The request object. Request message for - `ListLocations` method. - 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: - ~.location_pb2.ListLocationsResponse: - Response message for ``ListLocations`` method. - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = locations_pb2.ListLocationsRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._client._transport.list_locations, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("name", request.name),)), - ) - - # Send the request. - response = await rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - async def __aenter__(self): - return self - - async def __aexit__(self, exc_type, exc, tb): - await self.transport.close() - -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) - - -__all__ = ( - "AgentsAsyncClient", -) diff --git a/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/agents/client.py b/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/agents/client.py deleted file mode 100644 index 8d906118d..000000000 --- a/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/agents/client.py +++ /dev/null @@ -1,1707 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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 os -import re -from typing import Dict, Mapping, MutableMapping, MutableSequence, Optional, Sequence, Tuple, Type, Union, cast - -from google.cloud.dialogflow_v2 import gapic_version as package_version - -from google.api_core import client_options as client_options_lib -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import retry as retries -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 - -try: - OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] -except AttributeError: # pragma: NO COVER - OptionalRetry = Union[retries.Retry, object] # type: ignore - -from google.api_core import operation # type: ignore -from google.api_core import operation_async # type: ignore -from google.cloud.dialogflow_v2.services.agents import pagers -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.cloud.location import locations_pb2 # type: ignore -from google.longrunning import operations_pb2 -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 -from .transports.rest import AgentsRestTransport - - -class AgentsClientMeta(type): - """Metaclass for the Agents 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[AgentsTransport]] - _transport_registry["grpc"] = AgentsGrpcTransport - _transport_registry["grpc_asyncio"] = AgentsGrpcAsyncIOTransport - _transport_registry["rest"] = AgentsRestTransport - - def get_transport_class(cls, - label: Optional[str] = None, - ) -> Type[AgentsTransport]: - """Returns an appropriate transport class. - - Args: - label: The name of the desired transport. If none is - provided, then the first transport in the registry is used. - - Returns: - The transport class to use. - """ - # If a specific transport is requested, return that one. - if label: - return cls._transport_registry[label] - - # No transport is requested; return the default (that is, the first one - # in the dictionary). - return next(iter(cls._transport_registry.values())) - - -class AgentsClient(metaclass=AgentsClientMeta): - """Service for managing [Agents][google.cloud.dialogflow.v2.Agent].""" - - @staticmethod - def _get_default_mtls_endpoint(api_endpoint): - """Converts api endpoint to mTLS endpoint. - - Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to - "*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively. - Args: - api_endpoint (Optional[str]): the api endpoint to convert. - Returns: - str: converted mTLS api endpoint. - """ - if not api_endpoint: - return api_endpoint - - mtls_endpoint_re = re.compile( - r"(?P[^.]+)(?P\.mtls)?(?P\.sandbox)?(?P\.googleapis\.com)?" - ) - - m = mtls_endpoint_re.match(api_endpoint) - name, mtls, sandbox, googledomain = m.groups() - if mtls or not googledomain: - return api_endpoint - - if sandbox: - return api_endpoint.replace( - "sandbox.googleapis.com", "mtls.sandbox.googleapis.com" - ) - - return api_endpoint.replace(".googleapis.com", ".mtls.googleapis.com") - - DEFAULT_ENDPOINT = "dialogflow.googleapis.com" - DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore - DEFAULT_ENDPOINT - ) - - @classmethod - def from_service_account_info(cls, info: dict, *args, **kwargs): - """Creates an instance of this client using the provided credentials - info. - - Args: - info (dict): The service account private key info. - args: Additional arguments to pass to the constructor. - kwargs: Additional arguments to pass to the constructor. - - Returns: - AgentsClient: 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: - AgentsClient: 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) -> AgentsTransport: - """Returns the transport used by the client instance. - - Returns: - AgentsTransport: The transport used by the client - instance. - """ - return self._transport - - @staticmethod - def agent_path(project: str,) -> str: - """Returns a fully-qualified agent string.""" - return "projects/{project}/agent".format(project=project, ) - - @staticmethod - def parse_agent_path(path: str) -> Dict[str,str]: - """Parses a agent path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/agent$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_billing_account_path(billing_account: str, ) -> str: - """Returns a fully-qualified billing_account string.""" - return "billingAccounts/{billing_account}".format(billing_account=billing_account, ) - - @staticmethod - def parse_common_billing_account_path(path: str) -> Dict[str,str]: - """Parse a billing_account path into its component segments.""" - m = re.match(r"^billingAccounts/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_folder_path(folder: str, ) -> str: - """Returns a fully-qualified folder string.""" - return "folders/{folder}".format(folder=folder, ) - - @staticmethod - def parse_common_folder_path(path: str) -> Dict[str,str]: - """Parse a folder path into its component segments.""" - m = re.match(r"^folders/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_organization_path(organization: str, ) -> str: - """Returns a fully-qualified organization string.""" - return "organizations/{organization}".format(organization=organization, ) - - @staticmethod - def parse_common_organization_path(path: str) -> Dict[str,str]: - """Parse a organization path into its component segments.""" - m = re.match(r"^organizations/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_project_path(project: str, ) -> str: - """Returns a fully-qualified project string.""" - return "projects/{project}".format(project=project, ) - - @staticmethod - def parse_common_project_path(path: str) -> Dict[str,str]: - """Parse a project path into its component segments.""" - m = re.match(r"^projects/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_location_path(project: str, location: str, ) -> str: - """Returns a fully-qualified location string.""" - return "projects/{project}/locations/{location}".format(project=project, location=location, ) - - @staticmethod - def parse_common_location_path(path: str) -> Dict[str,str]: - """Parse a location path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)$", path) - return m.groupdict() if m else {} - - @classmethod - def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[client_options_lib.ClientOptions] = None): - """Return the API endpoint and client cert source for mutual TLS. - - The client cert source is determined in the following order: - (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the - client cert source is None. - (2) if `client_options.client_cert_source` is provided, use the provided one; if the - default client cert source exists, use the default one; otherwise the client cert - source is None. - - The API endpoint is determined in the following order: - (1) if `client_options.api_endpoint` if provided, use the provided one. - (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the - default mTLS endpoint; if the environment variable is "never", use the default API - endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise - use the default API endpoint. - - More details can be found at https://google.aip.dev/auth/4114. - - Args: - client_options (google.api_core.client_options.ClientOptions): Custom options for the - client. Only the `api_endpoint` and `client_cert_source` properties may be used - in this method. - - Returns: - Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the - client cert source to use. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If any errors happen. - """ - if client_options is None: - client_options = client_options_lib.ClientOptions() - use_client_cert = os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false") - use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") - if use_client_cert not in ("true", "false"): - raise ValueError("Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`") - if use_mtls_endpoint not in ("auto", "never", "always"): - raise MutualTLSChannelError("Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`") - - # Figure out the client cert source to use. - client_cert_source = None - if use_client_cert == "true": - if client_options.client_cert_source: - client_cert_source = client_options.client_cert_source - elif mtls.has_default_client_cert_source(): - client_cert_source = mtls.default_client_cert_source() - - # Figure out which api endpoint to use. - if client_options.api_endpoint is not None: - api_endpoint = client_options.api_endpoint - elif use_mtls_endpoint == "always" or (use_mtls_endpoint == "auto" and client_cert_source): - api_endpoint = cls.DEFAULT_MTLS_ENDPOINT - else: - api_endpoint = cls.DEFAULT_ENDPOINT - - return api_endpoint, client_cert_source - - def __init__(self, *, - credentials: Optional[ga_credentials.Credentials] = None, - transport: Optional[Union[str, AgentsTransport]] = None, - client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the agents 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, AgentsTransport]): The - transport to use. If set to None, a transport is chosen - automatically. - client_options (Optional[Union[google.api_core.client_options.ClientOptions, dict]]): 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() - client_options = cast(client_options_lib.ClientOptions, client_options) - - api_endpoint, client_cert_source_func = self.get_mtls_endpoint_and_cert_source(client_options) - - api_key_value = getattr(client_options, "api_key", None) - if api_key_value and credentials: - raise ValueError("client_options.api_key and credentials are mutually exclusive") - - # 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, AgentsTransport): - # transport is a AgentsTransport instance. - if credentials or client_options.credentials_file or api_key_value: - 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: - import google.auth._default # type: ignore - - if api_key_value and hasattr(google.auth._default, "get_api_key_credentials"): - credentials = google.auth._default.get_api_key_credentials(api_key_value) - - Transport = type(self).get_transport_class(transport) - self._transport = Transport( - credentials=credentials, - credentials_file=client_options.credentials_file, - host=api_endpoint, - scopes=client_options.scopes, - client_cert_source_for_mtls=client_cert_source_func, - quota_project_id=client_options.quota_project_id, - client_info=client_info, - always_use_jwt_access=True, - api_audience=client_options.api_audience, - ) - - def get_agent(self, - request: Optional[Union[agent.GetAgentRequest, dict]] = None, - *, - parent: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> agent.Agent: - r"""Retrieves the specified agent. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import dialogflow_v2 - - def sample_get_agent(): - # Create a client - client = dialogflow_v2.AgentsClient() - - # Initialize request argument(s) - request = dialogflow_v2.GetAgentRequest( - parent="parent_value", - ) - - # Make the request - response = client.get_agent(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.dialogflow_v2.types.GetAgentRequest, dict]): - The request object. The request message for - [Agents.GetAgent][google.cloud.dialogflow.v2.Agents.GetAgent]. - parent (str): - Required. The project that the agent to fetch is - associated with. Format: ``projects/``. - - 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.types.Agent: - A Dialogflow agent is a virtual agent that handles conversations with your - end-users. It is a natural language understanding - module that understands the nuances of human - language. Dialogflow translates end-user text or - audio during a conversation to structured data that - your apps and services can understand. You design and - build a Dialogflow agent to handle the types of - conversations required for your system. - - For more information about agents, see the [Agent - guide](\ https://cloud.google.com/dialogflow/docs/agents-overview). - - """ - # Create or coerce a protobuf request object. - # Quick 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 agent.GetAgentRequest. - # There's no risk of modifying the input as we've already verified - # 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 - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.get_agent] - - # 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 set_agent(self, - request: Optional[Union[gcd_agent.SetAgentRequest, dict]] = None, - *, - agent: Optional[gcd_agent.Agent] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gcd_agent.Agent: - r"""Creates/updates the specified agent. - - Note: You should always train an agent prior to sending it - queries. See the `training - documentation `__. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import dialogflow_v2 - - def sample_set_agent(): - # Create a client - client = dialogflow_v2.AgentsClient() - - # Initialize request argument(s) - agent = dialogflow_v2.Agent() - agent.parent = "parent_value" - agent.display_name = "display_name_value" - agent.default_language_code = "default_language_code_value" - agent.time_zone = "time_zone_value" - - request = dialogflow_v2.SetAgentRequest( - agent=agent, - ) - - # Make the request - response = client.set_agent(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.dialogflow_v2.types.SetAgentRequest, dict]): - The request object. The request message for - [Agents.SetAgent][google.cloud.dialogflow.v2.Agents.SetAgent]. - agent (google.cloud.dialogflow_v2.types.Agent): - Required. The agent to update. - 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. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.dialogflow_v2.types.Agent: - A Dialogflow agent is a virtual agent that handles conversations with your - end-users. It is a natural language understanding - module that understands the nuances of human - language. Dialogflow translates end-user text or - audio during a conversation to structured data that - your apps and services can understand. You design and - build a Dialogflow agent to handle the types of - conversations required for your system. - - For more information about agents, see the [Agent - guide](\ https://cloud.google.com/dialogflow/docs/agents-overview). - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([agent]) - 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_agent.SetAgentRequest. - # There's no risk of modifying the input as we've already verified - # 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 - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.set_agent] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("agent.parent", request.agent.parent), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def delete_agent(self, - request: Optional[Union[agent.DeleteAgentRequest, dict]] = None, - *, - parent: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> None: - r"""Deletes the specified agent. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import dialogflow_v2 - - def sample_delete_agent(): - # Create a client - client = dialogflow_v2.AgentsClient() - - # Initialize request argument(s) - request = dialogflow_v2.DeleteAgentRequest( - parent="parent_value", - ) - - # Make the request - client.delete_agent(request=request) - - Args: - request (Union[google.cloud.dialogflow_v2.types.DeleteAgentRequest, dict]): - The request object. The request message for - [Agents.DeleteAgent][google.cloud.dialogflow.v2.Agents.DeleteAgent]. - parent (str): - Required. The project that the agent to delete is - associated with. Format: ``projects/``. - - 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. - """ - # Create or coerce a protobuf request object. - # Quick 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 agent.DeleteAgentRequest. - # There's no risk of modifying the input as we've already verified - # 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 - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.delete_agent] - - # 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. - rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - def search_agents(self, - request: Optional[Union[agent.SearchAgentsRequest, dict]] = None, - *, - parent: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.SearchAgentsPager: - r"""Returns the list of agents. - - Since there is at most one conversational agent per project, - this method is useful primarily for listing all agents across - projects the caller has access to. One can achieve that with a - wildcard project collection id "-". Refer to `List - Sub-Collections `__. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import dialogflow_v2 - - def sample_search_agents(): - # Create a client - client = dialogflow_v2.AgentsClient() - - # Initialize request argument(s) - request = dialogflow_v2.SearchAgentsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.search_agents(request=request) - - # Handle the response - for response in page_result: - print(response) - - Args: - request (Union[google.cloud.dialogflow_v2.types.SearchAgentsRequest, dict]): - The request object. The request message for - [Agents.SearchAgents][google.cloud.dialogflow.v2.Agents.SearchAgents]. - parent (str): - Required. The project to list agents from. Format: - ``projects/``. - - 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.agents.pagers.SearchAgentsPager: - The response message for - [Agents.SearchAgents][google.cloud.dialogflow.v2.Agents.SearchAgents]. - - Iterating over this object will yield results and - resolve additional pages automatically. - - """ - # Create or coerce a protobuf request object. - # Quick 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 agent.SearchAgentsRequest. - # There's no risk of modifying the input as we've already verified - # 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 - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.search_agents] - - # 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.SearchAgentsPager( - method=rpc, - request=request, - response=response, - metadata=metadata, - ) - - # Done; return the response. - return response - - def train_agent(self, - request: Optional[Union[agent.TrainAgentRequest, dict]] = None, - *, - parent: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation.Operation: - r"""Trains the specified agent. - - This method is a `long-running - operation `__. - The returned ``Operation`` type has the following - method-specific fields: - - - ``metadata``: An empty `Struct - message `__ - - ``response``: An `Empty - message `__ - - Note: You should always train an agent prior to sending it - queries. See the `training - documentation `__. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import dialogflow_v2 - - def sample_train_agent(): - # Create a client - client = dialogflow_v2.AgentsClient() - - # Initialize request argument(s) - request = dialogflow_v2.TrainAgentRequest( - parent="parent_value", - ) - - # Make the request - operation = client.train_agent(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.dialogflow_v2.types.TrainAgentRequest, dict]): - The request object. The request message for - [Agents.TrainAgent][google.cloud.dialogflow.v2.Agents.TrainAgent]. - parent (str): - Required. The project that the agent to train is - associated with. Format: ``projects/``. - - 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.api_core.operation.Operation: - An object representing a long-running operation. - - The result type for the operation will be :class:`google.protobuf.empty_pb2.Empty` A generic empty message that you can re-use to avoid defining duplicated - empty messages in your APIs. A typical example is to - use it as the request or the response type of an API - method. For instance: - - service Foo { - rpc Bar(google.protobuf.Empty) returns - (google.protobuf.Empty); - - } - - """ - # Create or coerce a protobuf request object. - # Quick 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 agent.TrainAgentRequest. - # There's no risk of modifying the input as we've already verified - # 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 - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.train_agent] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Wrap the response in an operation future. - response = operation.from_gapic( - response, - self._transport.operations_client, - empty_pb2.Empty, - metadata_type=struct_pb2.Struct, - ) - - # Done; return the response. - return response - - def export_agent(self, - request: Optional[Union[agent.ExportAgentRequest, dict]] = None, - *, - parent: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation.Operation: - r"""Exports the specified agent to a ZIP file. - - This method is a `long-running - operation `__. - The returned ``Operation`` type has the following - method-specific fields: - - - ``metadata``: An empty `Struct - message `__ - - ``response``: - [ExportAgentResponse][google.cloud.dialogflow.v2.ExportAgentResponse] - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import dialogflow_v2 - - def sample_export_agent(): - # Create a client - client = dialogflow_v2.AgentsClient() - - # Initialize request argument(s) - request = dialogflow_v2.ExportAgentRequest( - parent="parent_value", - agent_uri="agent_uri_value", - ) - - # Make the request - operation = client.export_agent(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.dialogflow_v2.types.ExportAgentRequest, dict]): - The request object. The request message for - [Agents.ExportAgent][google.cloud.dialogflow.v2.Agents.ExportAgent]. - parent (str): - Required. The project that the agent to export is - associated with. Format: ``projects/``. - - 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.api_core.operation.Operation: - An object representing a long-running operation. - - The result type for the operation will be :class:`google.cloud.dialogflow_v2.types.ExportAgentResponse` The response message for - [Agents.ExportAgent][google.cloud.dialogflow.v2.Agents.ExportAgent]. - - """ - # Create or coerce a protobuf request object. - # Quick 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 agent.ExportAgentRequest. - # There's no risk of modifying the input as we've already verified - # 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 - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.export_agent] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Wrap the response in an operation future. - response = operation.from_gapic( - response, - self._transport.operations_client, - agent.ExportAgentResponse, - metadata_type=struct_pb2.Struct, - ) - - # Done; return the response. - return response - - def import_agent(self, - request: Optional[Union[agent.ImportAgentRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation.Operation: - r"""Imports the specified agent from a ZIP file. - - Uploads new intents and entity types without deleting the - existing ones. Intents and entity types with the same name are - replaced with the new versions from - [ImportAgentRequest][google.cloud.dialogflow.v2.ImportAgentRequest]. - After the import, the imported draft agent will be trained - automatically (unless disabled in agent settings). However, once - the import is done, training may not be completed yet. Please - call [TrainAgent][google.cloud.dialogflow.v2.Agents.TrainAgent] - and wait for the operation it returns in order to train - explicitly. - - This method is a `long-running - operation `__. - The returned ``Operation`` type has the following - method-specific fields: - - - ``metadata``: An empty `Struct - message `__ - - ``response``: An `Empty - message `__ - - The operation only tracks when importing is complete, not when - it is done training. - - Note: You should always train an agent prior to sending it - queries. See the `training - documentation `__. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import dialogflow_v2 - - def sample_import_agent(): - # Create a client - client = dialogflow_v2.AgentsClient() - - # Initialize request argument(s) - request = dialogflow_v2.ImportAgentRequest( - agent_uri="agent_uri_value", - parent="parent_value", - ) - - # Make the request - operation = client.import_agent(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.dialogflow_v2.types.ImportAgentRequest, dict]): - 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. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.api_core.operation.Operation: - An object representing a long-running operation. - - The result type for the operation will be :class:`google.protobuf.empty_pb2.Empty` A generic empty message that you can re-use to avoid defining duplicated - empty messages in your APIs. A typical example is to - use it as the request or the response type of an API - method. For instance: - - service Foo { - rpc Bar(google.protobuf.Empty) returns - (google.protobuf.Empty); - - } - - """ - # 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 - # there are no flattened fields. - if not isinstance(request, agent.ImportAgentRequest): - request = agent.ImportAgentRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.import_agent] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Wrap the response in an operation future. - response = operation.from_gapic( - response, - self._transport.operations_client, - empty_pb2.Empty, - metadata_type=struct_pb2.Struct, - ) - - # Done; return the response. - return response - - def restore_agent(self, - request: Optional[Union[agent.RestoreAgentRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation.Operation: - r"""Restores the specified agent from a ZIP file. - - Replaces the current agent version with a new one. All the - intents and entity types in the older version are deleted. After - the restore, the restored draft agent will be trained - automatically (unless disabled in agent settings). However, once - the restore is done, training may not be completed yet. Please - call [TrainAgent][google.cloud.dialogflow.v2.Agents.TrainAgent] - and wait for the operation it returns in order to train - explicitly. - - This method is a `long-running - operation `__. - The returned ``Operation`` type has the following - method-specific fields: - - - ``metadata``: An empty `Struct - message `__ - - ``response``: An `Empty - message `__ - - The operation only tracks when restoring is complete, not when - it is done training. - - Note: You should always train an agent prior to sending it - queries. See the `training - documentation `__. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import dialogflow_v2 - - def sample_restore_agent(): - # Create a client - client = dialogflow_v2.AgentsClient() - - # Initialize request argument(s) - request = dialogflow_v2.RestoreAgentRequest( - agent_uri="agent_uri_value", - parent="parent_value", - ) - - # Make the request - operation = client.restore_agent(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.dialogflow_v2.types.RestoreAgentRequest, dict]): - 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. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.api_core.operation.Operation: - An object representing a long-running operation. - - The result type for the operation will be :class:`google.protobuf.empty_pb2.Empty` A generic empty message that you can re-use to avoid defining duplicated - empty messages in your APIs. A typical example is to - use it as the request or the response type of an API - method. For instance: - - service Foo { - rpc Bar(google.protobuf.Empty) returns - (google.protobuf.Empty); - - } - - """ - # 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 - # there are no flattened fields. - if not isinstance(request, agent.RestoreAgentRequest): - request = agent.RestoreAgentRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.restore_agent] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Wrap the response in an operation future. - response = operation.from_gapic( - response, - self._transport.operations_client, - empty_pb2.Empty, - metadata_type=struct_pb2.Struct, - ) - - # Done; return the response. - return response - - def get_validation_result(self, - request: Optional[Union[agent.GetValidationResultRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> validation_result.ValidationResult: - r"""Gets agent validation result. Agent validation is - performed during training time and is updated - automatically when training is completed. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import dialogflow_v2 - - def sample_get_validation_result(): - # Create a client - client = dialogflow_v2.AgentsClient() - - # Initialize request argument(s) - request = dialogflow_v2.GetValidationResultRequest( - parent="parent_value", - ) - - # Make the request - response = client.get_validation_result(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.dialogflow_v2.types.GetValidationResultRequest, dict]): - 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. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.dialogflow_v2.types.ValidationResult: - Represents the output of agent - validation. - - """ - # 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 - # there are no flattened fields. - if not isinstance(request, agent.GetValidationResultRequest): - request = agent.GetValidationResultRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.get_validation_result] - - # 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 __enter__(self) -> "AgentsClient": - return self - - def __exit__(self, type, value, traceback): - """Releases underlying transport's resources. - - .. warning:: - ONLY use as a context manager if the transport is NOT shared - with other clients! Exiting the with block will CLOSE the transport - and may cause errors in other clients! - """ - self.transport.close() - - def list_operations( - self, - request: Optional[operations_pb2.ListOperationsRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operations_pb2.ListOperationsResponse: - r"""Lists operations that match the specified filter in the request. - - Args: - request (:class:`~.operations_pb2.ListOperationsRequest`): - The request object. Request message for - `ListOperations` method. - 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: - ~.operations_pb2.ListOperationsResponse: - Response message for ``ListOperations`` method. - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = operations_pb2.ListOperationsRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._transport.list_operations, - 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 = rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - def get_operation( - self, - request: Optional[operations_pb2.GetOperationRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operations_pb2.Operation: - r"""Gets the latest state of a long-running operation. - - Args: - request (:class:`~.operations_pb2.GetOperationRequest`): - The request object. Request message for - `GetOperation` method. - 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: - ~.operations_pb2.Operation: - An ``Operation`` object. - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = operations_pb2.GetOperationRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._transport.get_operation, - 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 = rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - def cancel_operation( - self, - request: Optional[operations_pb2.CancelOperationRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> None: - r"""Starts asynchronous cancellation on a long-running operation. - - The server makes a best effort to cancel the operation, but success - is not guaranteed. If the server doesn't support this method, it returns - `google.rpc.Code.UNIMPLEMENTED`. - - Args: - request (:class:`~.operations_pb2.CancelOperationRequest`): - The request object. Request message for - `CancelOperation` method. - 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: - None - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = operations_pb2.CancelOperationRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._transport.cancel_operation, - 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. - rpc(request, retry=retry, timeout=timeout, metadata=metadata,) - - def get_location( - self, - request: Optional[locations_pb2.GetLocationRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> locations_pb2.Location: - r"""Gets information about a location. - - Args: - request (:class:`~.location_pb2.GetLocationRequest`): - The request object. Request message for - `GetLocation` method. - 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: - ~.location_pb2.Location: - Location object. - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = locations_pb2.GetLocationRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._transport.get_location, - 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 = rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - def list_locations( - self, - request: Optional[locations_pb2.ListLocationsRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> locations_pb2.ListLocationsResponse: - r"""Lists information about the supported locations for this service. - - Args: - request (:class:`~.location_pb2.ListLocationsRequest`): - The request object. Request message for - `ListLocations` method. - 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: - ~.location_pb2.ListLocationsResponse: - Response message for ``ListLocations`` method. - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = locations_pb2.ListLocationsRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._transport.list_locations, - 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 = rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) - - -__all__ = ( - "AgentsClient", -) diff --git a/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/agents/pagers.py b/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/agents/pagers.py deleted file mode 100644 index 1a76229ac..000000000 --- a/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/agents/pagers.py +++ /dev/null @@ -1,139 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from typing import Any, AsyncIterator, Awaitable, Callable, Sequence, Tuple, Optional, Iterator - -from google.cloud.dialogflow_v2.types import agent - - -class SearchAgentsPager: - """A pager for iterating through ``search_agents`` requests. - - This class thinly wraps an initial - :class:`google.cloud.dialogflow_v2.types.SearchAgentsResponse` object, and - provides an ``__iter__`` method to iterate through its - ``agents`` field. - - If there are more pages, the ``__iter__`` method will make additional - ``SearchAgents`` requests and continue to iterate - through the ``agents`` field on the - corresponding responses. - - All the usual :class:`google.cloud.dialogflow_v2.types.SearchAgentsResponse` - 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[..., agent.SearchAgentsResponse], - request: agent.SearchAgentsRequest, - response: agent.SearchAgentsResponse, - *, - 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.SearchAgentsRequest): - The initial request object. - response (google.cloud.dialogflow_v2.types.SearchAgentsResponse): - 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 = agent.SearchAgentsRequest(request) - self._response = response - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - def pages(self) -> Iterator[agent.SearchAgentsResponse]: - yield self._response - while self._response.next_page_token: - self._request.page_token = self._response.next_page_token - self._response = self._method(self._request, metadata=self._metadata) - yield self._response - - def __iter__(self) -> Iterator[agent.Agent]: - for page in self.pages: - yield from page.agents - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class SearchAgentsAsyncPager: - """A pager for iterating through ``search_agents`` requests. - - This class thinly wraps an initial - :class:`google.cloud.dialogflow_v2.types.SearchAgentsResponse` object, and - provides an ``__aiter__`` method to iterate through its - ``agents`` field. - - If there are more pages, the ``__aiter__`` method will make additional - ``SearchAgents`` requests and continue to iterate - through the ``agents`` field on the - corresponding responses. - - All the usual :class:`google.cloud.dialogflow_v2.types.SearchAgentsResponse` - 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[agent.SearchAgentsResponse]], - request: agent.SearchAgentsRequest, - response: agent.SearchAgentsResponse, - *, - metadata: Sequence[Tuple[str, str]] = ()): - """Instantiates the pager. - - Args: - method (Callable): The method that was originally called, and - which instantiated this pager. - request (google.cloud.dialogflow_v2.types.SearchAgentsRequest): - The initial request object. - response (google.cloud.dialogflow_v2.types.SearchAgentsResponse): - 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 = agent.SearchAgentsRequest(request) - self._response = response - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - async def pages(self) -> AsyncIterator[agent.SearchAgentsResponse]: - yield self._response - while self._response.next_page_token: - self._request.page_token = self._response.next_page_token - self._response = await self._method(self._request, metadata=self._metadata) - yield self._response - def __aiter__(self) -> AsyncIterator[agent.Agent]: - async def async_generator(): - async for page in self.pages: - for response in page.agents: - yield response - - return async_generator() - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) diff --git a/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/agents/transports/__init__.py b/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/agents/transports/__init__.py deleted file mode 100644 index dc2a4d0f8..000000000 --- a/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/agents/transports/__init__.py +++ /dev/null @@ -1,38 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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 AgentsTransport -from .grpc import AgentsGrpcTransport -from .grpc_asyncio import AgentsGrpcAsyncIOTransport -from .rest import AgentsRestTransport -from .rest import AgentsRestInterceptor - - -# Compile a registry of transports. -_transport_registry = OrderedDict() # type: Dict[str, Type[AgentsTransport]] -_transport_registry['grpc'] = AgentsGrpcTransport -_transport_registry['grpc_asyncio'] = AgentsGrpcAsyncIOTransport -_transport_registry['rest'] = AgentsRestTransport - -__all__ = ( - 'AgentsTransport', - 'AgentsGrpcTransport', - 'AgentsGrpcAsyncIOTransport', - 'AgentsRestTransport', - 'AgentsRestInterceptor', -) diff --git a/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/agents/transports/base.py b/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/agents/transports/base.py deleted file mode 100644 index 47457d811..000000000 --- a/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/agents/transports/base.py +++ /dev/null @@ -1,316 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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 - -from google.cloud.dialogflow_v2 import gapic_version as package_version - -import google.auth # type: ignore -import google.api_core -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import retry as retries -from google.api_core import operations_v1 -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 agent -from google.cloud.dialogflow_v2.types import agent as gcd_agent -from google.cloud.dialogflow_v2.types import validation_result -from google.cloud.location import locations_pb2 # type: ignore -from google.longrunning import operations_pb2 -from google.longrunning import operations_pb2 # type: ignore -from google.protobuf import empty_pb2 # type: ignore - -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) - - -class AgentsTransport(abc.ABC): - """Abstract transport class for Agents.""" - - 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: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - api_audience: Optional[str] = None, - **kwargs, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. - scopes (Optional[Sequence[str]]): A list of scopes. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - """ - - scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} - - # Save the scopes. - self._scopes = scopes - - # If no credentials are provided, then determine the appropriate - # defaults. - if credentials and credentials_file: - raise core_exceptions.DuplicateCredentialArgs("'credentials_file' and 'credentials' are mutually exclusive") - - if credentials_file is not None: - credentials, _ = google.auth.load_credentials_from_file( - credentials_file, - **scopes_kwargs, - quota_project_id=quota_project_id - ) - elif credentials is None: - credentials, _ = google.auth.default(**scopes_kwargs, quota_project_id=quota_project_id) - # Don't apply audience if the credentials file passed from user. - if hasattr(credentials, "with_gdch_audience"): - credentials = credentials.with_gdch_audience(api_audience if api_audience else host) - - # If the credentials are service account credentials, then always try to use self signed JWT. - if always_use_jwt_access and isinstance(credentials, service_account.Credentials) and hasattr(service_account.Credentials, "with_always_use_jwt_access"): - credentials = credentials.with_always_use_jwt_access(True) - - # Save the credentials. - self._credentials = credentials - - # Save the hostname. Default to port 443 (HTTPS) if none is specified. - if ':' not in host: - host += ':443' - self._host = host - - def _prep_wrapped_messages(self, client_info): - # Precompute the wrapped methods. - self._wrapped_methods = { - self.get_agent: gapic_v1.method.wrap_method( - self.get_agent, - default_timeout=None, - client_info=client_info, - ), - self.set_agent: gapic_v1.method.wrap_method( - self.set_agent, - default_timeout=None, - client_info=client_info, - ), - self.delete_agent: gapic_v1.method.wrap_method( - self.delete_agent, - default_timeout=None, - client_info=client_info, - ), - self.search_agents: gapic_v1.method.wrap_method( - self.search_agents, - default_timeout=None, - client_info=client_info, - ), - self.train_agent: gapic_v1.method.wrap_method( - self.train_agent, - default_timeout=None, - client_info=client_info, - ), - self.export_agent: gapic_v1.method.wrap_method( - self.export_agent, - default_timeout=None, - client_info=client_info, - ), - self.import_agent: gapic_v1.method.wrap_method( - self.import_agent, - default_timeout=None, - client_info=client_info, - ), - self.restore_agent: gapic_v1.method.wrap_method( - self.restore_agent, - default_timeout=None, - client_info=client_info, - ), - self.get_validation_result: gapic_v1.method.wrap_method( - self.get_validation_result, - default_timeout=None, - client_info=client_info, - ), - } - - def close(self): - """Closes resources associated with the transport. - - .. warning:: - Only call this method if the transport is NOT shared - with other clients - this may cause errors in other clients! - """ - raise NotImplementedError() - - @property - def operations_client(self): - """Return the client designed to process long-running operations.""" - raise NotImplementedError() - - @property - def get_agent(self) -> Callable[ - [agent.GetAgentRequest], - Union[ - agent.Agent, - Awaitable[agent.Agent] - ]]: - raise NotImplementedError() - - @property - def set_agent(self) -> Callable[ - [gcd_agent.SetAgentRequest], - Union[ - gcd_agent.Agent, - Awaitable[gcd_agent.Agent] - ]]: - raise NotImplementedError() - - @property - def delete_agent(self) -> Callable[ - [agent.DeleteAgentRequest], - Union[ - empty_pb2.Empty, - Awaitable[empty_pb2.Empty] - ]]: - raise NotImplementedError() - - @property - def search_agents(self) -> Callable[ - [agent.SearchAgentsRequest], - Union[ - agent.SearchAgentsResponse, - Awaitable[agent.SearchAgentsResponse] - ]]: - raise NotImplementedError() - - @property - def train_agent(self) -> Callable[ - [agent.TrainAgentRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: - raise NotImplementedError() - - @property - def export_agent(self) -> Callable[ - [agent.ExportAgentRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: - raise NotImplementedError() - - @property - def import_agent(self) -> Callable[ - [agent.ImportAgentRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: - raise NotImplementedError() - - @property - def restore_agent(self) -> Callable[ - [agent.RestoreAgentRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: - raise NotImplementedError() - - @property - def get_validation_result(self) -> Callable[ - [agent.GetValidationResultRequest], - Union[ - validation_result.ValidationResult, - Awaitable[validation_result.ValidationResult] - ]]: - raise NotImplementedError() - - @property - def list_operations( - self, - ) -> Callable[ - [operations_pb2.ListOperationsRequest], - Union[operations_pb2.ListOperationsResponse, Awaitable[operations_pb2.ListOperationsResponse]], - ]: - raise NotImplementedError() - - @property - def get_operation( - self, - ) -> Callable[ - [operations_pb2.GetOperationRequest], - Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], - ]: - raise NotImplementedError() - - @property - def cancel_operation( - self, - ) -> Callable[ - [operations_pb2.CancelOperationRequest], - None, - ]: - raise NotImplementedError() - - @property - def get_location(self, - ) -> Callable[ - [locations_pb2.GetLocationRequest], - Union[locations_pb2.Location, Awaitable[locations_pb2.Location]], - ]: - raise NotImplementedError() - - @property - def list_locations(self, - ) -> Callable[ - [locations_pb2.ListLocationsRequest], - Union[locations_pb2.ListLocationsResponse, Awaitable[locations_pb2.ListLocationsResponse]], - ]: - raise NotImplementedError() - - @property - def kind(self) -> str: - raise NotImplementedError() - - -__all__ = ( - 'AgentsTransport', -) diff --git a/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/agents/transports/grpc.py b/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/agents/transports/grpc.py deleted file mode 100644 index a1b93e2f7..000000000 --- a/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/agents/transports/grpc.py +++ /dev/null @@ -1,676 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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 -from google.api_core import operations_v1 -from google.api_core import gapic_v1 -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 agent -from google.cloud.dialogflow_v2.types import agent as gcd_agent -from google.cloud.dialogflow_v2.types import validation_result -from google.cloud.location import locations_pb2 # type: ignore -from google.longrunning import operations_pb2 -from google.longrunning import operations_pb2 # type: ignore -from google.protobuf import empty_pb2 # type: ignore -from .base import AgentsTransport, DEFAULT_CLIENT_INFO - - -class AgentsGrpcTransport(AgentsTransport): - """gRPC backend transport for Agents. - - Service for managing [Agents][google.cloud.dialogflow.v2.Agent]. - - 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: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - channel: Optional[grpc.Channel] = None, - api_mtls_endpoint: Optional[str] = None, - client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, - ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, - client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - api_audience: Optional[str] = None, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - This argument is ignored if ``channel`` is provided. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional(Sequence[str])): A list of scopes. This argument is - ignored if ``channel`` is provided. - channel (Optional[grpc.Channel]): A ``Channel`` instance through - which to make calls. - api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. - If provided, it overrides the ``host`` argument and tries to create - a mutual TLS channel with client SSL credentials from - ``client_cert_source`` or application default SSL credentials. - client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): - Deprecated. A callback to provide client SSL certificate bytes and - private key bytes, both in PEM format. It is ignored if - ``api_mtls_endpoint`` is None. - ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials - for the grpc channel. It is ignored if ``channel`` is provided. - client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): - A callback to provide client certificate bytes and private key bytes, - both in PEM format. It is used to configure a mutual TLS channel. It is - ignored if ``channel`` or ``ssl_channel_credentials`` is provided. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport - creation failed for any reason. - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - self._grpc_channel = None - self._ssl_channel_credentials = ssl_channel_credentials - self._stubs: Dict[str, Callable] = {} - self._operations_client: Optional[operations_v1.OperationsClient] = None - - if api_mtls_endpoint: - warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) - if client_cert_source: - warnings.warn("client_cert_source is deprecated", DeprecationWarning) - - if channel: - # Ignore credentials if a channel was passed. - credentials = False - # If a channel was explicitly provided, set it. - self._grpc_channel = channel - self._ssl_channel_credentials = None - - else: - if api_mtls_endpoint: - host = api_mtls_endpoint - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - self._ssl_channel_credentials = SslCredentials().ssl_credentials - - else: - if client_cert_source_for_mtls and not ssl_channel_credentials: - cert, key = client_cert_source_for_mtls() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - - # The base transport sets the host, credentials and scopes - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes, - quota_project_id=quota_project_id, - client_info=client_info, - always_use_jwt_access=always_use_jwt_access, - api_audience=api_audience, - ) - - if not self._grpc_channel: - self._grpc_channel = type(self).create_channel( - self._host, - # use the credentials which are saved - credentials=self._credentials, - # Set ``credentials_file`` to ``None`` here as - # the credentials that we saved earlier should be used. - credentials_file=None, - 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: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - **kwargs) -> grpc.Channel: - """Create and return a gRPC channel object. - Args: - host (Optional[str]): The host for the channel to use. - credentials (Optional[~.Credentials]): The - authorization credentials to attach to requests. These - credentials identify this application to the service. If - none are specified, the client will attempt to ascertain - the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - kwargs (Optional[dict]): Keyword arguments, which are passed to the - channel creation. - Returns: - grpc.Channel: A gRPC channel object. - - Raises: - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - - return grpc_helpers.create_channel( - host, - credentials=credentials, - credentials_file=credentials_file, - quota_project_id=quota_project_id, - default_scopes=cls.AUTH_SCOPES, - scopes=scopes, - default_host=cls.DEFAULT_HOST, - **kwargs - ) - - @property - def grpc_channel(self) -> grpc.Channel: - """Return the channel designed to connect to this service. - """ - return self._grpc_channel - - @property - def operations_client(self) -> operations_v1.OperationsClient: - """Create the client designed to process long-running operations. - - This property caches on the instance; repeated calls return the same - client. - """ - # Quick check: Only create a new client if we do not already have one. - if self._operations_client is None: - self._operations_client = operations_v1.OperationsClient( - self.grpc_channel - ) - - # Return the client from cache. - return self._operations_client - - @property - def get_agent(self) -> Callable[ - [agent.GetAgentRequest], - agent.Agent]: - r"""Return a callable for the get agent method over gRPC. - - Retrieves the specified agent. - - Returns: - Callable[[~.GetAgentRequest], - ~.Agent]: - 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_agent' not in self._stubs: - self._stubs['get_agent'] = self.grpc_channel.unary_unary( - '/google.cloud.dialogflow.v2.Agents/GetAgent', - request_serializer=agent.GetAgentRequest.serialize, - response_deserializer=agent.Agent.deserialize, - ) - return self._stubs['get_agent'] - - @property - def set_agent(self) -> Callable[ - [gcd_agent.SetAgentRequest], - gcd_agent.Agent]: - r"""Return a callable for the set agent method over gRPC. - - Creates/updates the specified agent. - - Note: You should always train an agent prior to sending it - queries. See the `training - documentation `__. - - Returns: - Callable[[~.SetAgentRequest], - ~.Agent]: - 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 'set_agent' not in self._stubs: - self._stubs['set_agent'] = self.grpc_channel.unary_unary( - '/google.cloud.dialogflow.v2.Agents/SetAgent', - request_serializer=gcd_agent.SetAgentRequest.serialize, - response_deserializer=gcd_agent.Agent.deserialize, - ) - return self._stubs['set_agent'] - - @property - 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. - - Returns: - Callable[[~.DeleteAgentRequest], - ~.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_agent' not in self._stubs: - self._stubs['delete_agent'] = self.grpc_channel.unary_unary( - '/google.cloud.dialogflow.v2.Agents/DeleteAgent', - request_serializer=agent.DeleteAgentRequest.serialize, - response_deserializer=empty_pb2.Empty.FromString, - ) - return self._stubs['delete_agent'] - - @property - def search_agents(self) -> Callable[ - [agent.SearchAgentsRequest], - agent.SearchAgentsResponse]: - r"""Return a callable for the search agents method over gRPC. - - Returns the list of agents. - - Since there is at most one conversational agent per project, - this method is useful primarily for listing all agents across - projects the caller has access to. One can achieve that with a - wildcard project collection id "-". Refer to `List - Sub-Collections `__. - - Returns: - Callable[[~.SearchAgentsRequest], - ~.SearchAgentsResponse]: - 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 'search_agents' not in self._stubs: - self._stubs['search_agents'] = self.grpc_channel.unary_unary( - '/google.cloud.dialogflow.v2.Agents/SearchAgents', - request_serializer=agent.SearchAgentsRequest.serialize, - response_deserializer=agent.SearchAgentsResponse.deserialize, - ) - return self._stubs['search_agents'] - - @property - 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. - - This method is a `long-running - operation `__. - The returned ``Operation`` type has the following - method-specific fields: - - - ``metadata``: An empty `Struct - message `__ - - ``response``: An `Empty - message `__ - - Note: You should always train an agent prior to sending it - queries. See the `training - documentation `__. - - Returns: - Callable[[~.TrainAgentRequest], - ~.Operation]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'train_agent' not in self._stubs: - self._stubs['train_agent'] = self.grpc_channel.unary_unary( - '/google.cloud.dialogflow.v2.Agents/TrainAgent', - request_serializer=agent.TrainAgentRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['train_agent'] - - @property - def export_agent(self) -> 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. - - This method is a `long-running - operation `__. - The returned ``Operation`` type has the following - method-specific fields: - - - ``metadata``: An empty `Struct - message `__ - - ``response``: - [ExportAgentResponse][google.cloud.dialogflow.v2.ExportAgentResponse] - - Returns: - Callable[[~.ExportAgentRequest], - ~.Operation]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'export_agent' not in self._stubs: - self._stubs['export_agent'] = self.grpc_channel.unary_unary( - '/google.cloud.dialogflow.v2.Agents/ExportAgent', - request_serializer=agent.ExportAgentRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['export_agent'] - - @property - def import_agent(self) -> 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. - - Uploads new intents and entity types without deleting the - existing ones. Intents and entity types with the same name are - replaced with the new versions from - [ImportAgentRequest][google.cloud.dialogflow.v2.ImportAgentRequest]. - After the import, the imported draft agent will be trained - automatically (unless disabled in agent settings). However, once - the import is done, training may not be completed yet. Please - call [TrainAgent][google.cloud.dialogflow.v2.Agents.TrainAgent] - and wait for the operation it returns in order to train - explicitly. - - This method is a `long-running - operation `__. - The returned ``Operation`` type has the following - method-specific fields: - - - ``metadata``: An empty `Struct - message `__ - - ``response``: An `Empty - message `__ - - The operation only tracks when importing is complete, not when - it is done training. - - Note: You should always train an agent prior to sending it - queries. See the `training - documentation `__. - - Returns: - Callable[[~.ImportAgentRequest], - ~.Operation]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'import_agent' not in self._stubs: - self._stubs['import_agent'] = self.grpc_channel.unary_unary( - '/google.cloud.dialogflow.v2.Agents/ImportAgent', - request_serializer=agent.ImportAgentRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['import_agent'] - - @property - def restore_agent(self) -> 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. - - Replaces the current agent version with a new one. All the - intents and entity types in the older version are deleted. After - the restore, the restored draft agent will be trained - automatically (unless disabled in agent settings). However, once - the restore is done, training may not be completed yet. Please - call [TrainAgent][google.cloud.dialogflow.v2.Agents.TrainAgent] - and wait for the operation it returns in order to train - explicitly. - - This method is a `long-running - operation `__. - The returned ``Operation`` type has the following - method-specific fields: - - - ``metadata``: An empty `Struct - message `__ - - ``response``: An `Empty - message `__ - - The operation only tracks when restoring is complete, not when - it is done training. - - Note: You should always train an agent prior to sending it - queries. See the `training - documentation `__. - - Returns: - Callable[[~.RestoreAgentRequest], - ~.Operation]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'restore_agent' not in self._stubs: - self._stubs['restore_agent'] = self.grpc_channel.unary_unary( - '/google.cloud.dialogflow.v2.Agents/RestoreAgent', - request_serializer=agent.RestoreAgentRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['restore_agent'] - - @property - def get_validation_result(self) -> Callable[ - [agent.GetValidationResultRequest], - validation_result.ValidationResult]: - r"""Return a callable for the get validation result method over gRPC. - - Gets agent validation result. Agent validation is - performed during training time and is updated - automatically when training is completed. - - Returns: - Callable[[~.GetValidationResultRequest], - ~.ValidationResult]: - 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_validation_result' not in self._stubs: - self._stubs['get_validation_result'] = self.grpc_channel.unary_unary( - '/google.cloud.dialogflow.v2.Agents/GetValidationResult', - request_serializer=agent.GetValidationResultRequest.serialize, - response_deserializer=validation_result.ValidationResult.deserialize, - ) - return self._stubs['get_validation_result'] - - def close(self): - self.grpc_channel.close() - - @property - def cancel_operation( - self, - ) -> Callable[[operations_pb2.CancelOperationRequest], None]: - r"""Return a callable for the cancel_operation method over gRPC. - """ - # 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 "cancel_operation" not in self._stubs: - self._stubs["cancel_operation"] = self.grpc_channel.unary_unary( - "/google.longrunning.Operations/CancelOperation", - request_serializer=operations_pb2.CancelOperationRequest.SerializeToString, - response_deserializer=None, - ) - return self._stubs["cancel_operation"] - - @property - def get_operation( - self, - ) -> Callable[[operations_pb2.GetOperationRequest], operations_pb2.Operation]: - r"""Return a callable for the get_operation method over gRPC. - """ - # 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_operation" not in self._stubs: - self._stubs["get_operation"] = self.grpc_channel.unary_unary( - "/google.longrunning.Operations/GetOperation", - request_serializer=operations_pb2.GetOperationRequest.SerializeToString, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs["get_operation"] - - @property - def list_operations( - self, - ) -> Callable[[operations_pb2.ListOperationsRequest], operations_pb2.ListOperationsResponse]: - r"""Return a callable for the list_operations method over gRPC. - """ - # 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_operations" not in self._stubs: - self._stubs["list_operations"] = self.grpc_channel.unary_unary( - "/google.longrunning.Operations/ListOperations", - request_serializer=operations_pb2.ListOperationsRequest.SerializeToString, - response_deserializer=operations_pb2.ListOperationsResponse.FromString, - ) - return self._stubs["list_operations"] - - @property - def list_locations( - self, - ) -> Callable[[locations_pb2.ListLocationsRequest], locations_pb2.ListLocationsResponse]: - r"""Return a callable for the list locations method over gRPC. - """ - # 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_locations" not in self._stubs: - self._stubs["list_locations"] = self.grpc_channel.unary_unary( - "/google.cloud.location.Locations/ListLocations", - request_serializer=locations_pb2.ListLocationsRequest.SerializeToString, - response_deserializer=locations_pb2.ListLocationsResponse.FromString, - ) - return self._stubs["list_locations"] - - @property - def get_location( - self, - ) -> Callable[[locations_pb2.GetLocationRequest], locations_pb2.Location]: - r"""Return a callable for the list locations method over gRPC. - """ - # 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_location" not in self._stubs: - self._stubs["get_location"] = self.grpc_channel.unary_unary( - "/google.cloud.location.Locations/GetLocation", - request_serializer=locations_pb2.GetLocationRequest.SerializeToString, - response_deserializer=locations_pb2.Location.FromString, - ) - return self._stubs["get_location"] - - @property - def kind(self) -> str: - return "grpc" - - -__all__ = ( - 'AgentsGrpcTransport', -) diff --git a/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/agents/transports/grpc_asyncio.py b/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/agents/transports/grpc_asyncio.py deleted file mode 100644 index be6455d42..000000000 --- a/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/agents/transports/grpc_asyncio.py +++ /dev/null @@ -1,675 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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 -from google.api_core import grpc_helpers_async -from google.api_core import operations_v1 -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore - -import grpc # type: ignore -from grpc.experimental import aio # type: ignore - -from google.cloud.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.cloud.location import locations_pb2 # type: ignore -from google.longrunning import operations_pb2 -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 - - -class AgentsGrpcAsyncIOTransport(AgentsTransport): - """gRPC AsyncIO backend transport for Agents. - - Service for managing [Agents][google.cloud.dialogflow.v2.Agent]. - - 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: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - **kwargs) -> aio.Channel: - """Create and return a gRPC AsyncIO channel object. - Args: - host (Optional[str]): The host for the channel to use. - credentials (Optional[~.Credentials]): The - authorization credentials to attach to requests. These - credentials identify this application to the service. If - none are specified, the client will attempt to ascertain - the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - kwargs (Optional[dict]): Keyword arguments, which are passed to the - channel creation. - Returns: - aio.Channel: A gRPC AsyncIO channel object. - """ - - return grpc_helpers_async.create_channel( - host, - credentials=credentials, - credentials_file=credentials_file, - quota_project_id=quota_project_id, - default_scopes=cls.AUTH_SCOPES, - scopes=scopes, - default_host=cls.DEFAULT_HOST, - **kwargs - ) - - def __init__(self, *, - host: str = 'dialogflow.googleapis.com', - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - channel: Optional[aio.Channel] = None, - api_mtls_endpoint: Optional[str] = None, - client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, - ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, - client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - api_audience: Optional[str] = None, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - This argument is ignored if ``channel`` is provided. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - channel (Optional[aio.Channel]): A ``Channel`` instance through - which to make calls. - api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. - If provided, it overrides the ``host`` argument and tries to create - a mutual TLS channel with client SSL credentials from - ``client_cert_source`` or application default SSL credentials. - client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): - Deprecated. A callback to provide client SSL certificate bytes and - private key bytes, both in PEM format. It is ignored if - ``api_mtls_endpoint`` is None. - ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials - for the grpc channel. It is ignored if ``channel`` is provided. - client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): - A callback to provide client certificate bytes and private key bytes, - both in PEM format. It is used to configure a mutual TLS channel. It is - ignored if ``channel`` or ``ssl_channel_credentials`` is provided. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - - Raises: - google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport - creation failed for any reason. - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - self._grpc_channel = None - self._ssl_channel_credentials = ssl_channel_credentials - self._stubs: Dict[str, Callable] = {} - self._operations_client: Optional[operations_v1.OperationsAsyncClient] = None - - if api_mtls_endpoint: - warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) - if client_cert_source: - warnings.warn("client_cert_source is deprecated", DeprecationWarning) - - if channel: - # Ignore credentials if a channel was passed. - credentials = False - # If a channel was explicitly provided, set it. - self._grpc_channel = channel - self._ssl_channel_credentials = None - else: - if api_mtls_endpoint: - host = api_mtls_endpoint - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - self._ssl_channel_credentials = SslCredentials().ssl_credentials - - else: - if client_cert_source_for_mtls and not ssl_channel_credentials: - cert, key = client_cert_source_for_mtls() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - - # The base transport sets the host, credentials and scopes - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes, - quota_project_id=quota_project_id, - client_info=client_info, - always_use_jwt_access=always_use_jwt_access, - api_audience=api_audience, - ) - - if not self._grpc_channel: - self._grpc_channel = type(self).create_channel( - self._host, - # use the credentials which are saved - credentials=self._credentials, - # Set ``credentials_file`` to ``None`` here as - # the credentials that we saved earlier should be used. - credentials_file=None, - 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 operations_client(self) -> operations_v1.OperationsAsyncClient: - """Create the client designed to process long-running operations. - - This property caches on the instance; repeated calls return the same - client. - """ - # Quick check: Only create a new client if we do not already have one. - if self._operations_client is None: - self._operations_client = operations_v1.OperationsAsyncClient( - self.grpc_channel - ) - - # Return the client from cache. - return self._operations_client - - @property - def get_agent(self) -> Callable[ - [agent.GetAgentRequest], - Awaitable[agent.Agent]]: - r"""Return a callable for the get agent method over gRPC. - - Retrieves the specified agent. - - Returns: - Callable[[~.GetAgentRequest], - Awaitable[~.Agent]]: - 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_agent' not in self._stubs: - self._stubs['get_agent'] = self.grpc_channel.unary_unary( - '/google.cloud.dialogflow.v2.Agents/GetAgent', - request_serializer=agent.GetAgentRequest.serialize, - response_deserializer=agent.Agent.deserialize, - ) - return self._stubs['get_agent'] - - @property - def set_agent(self) -> Callable[ - [gcd_agent.SetAgentRequest], - Awaitable[gcd_agent.Agent]]: - r"""Return a callable for the set agent method over gRPC. - - Creates/updates the specified agent. - - Note: You should always train an agent prior to sending it - queries. See the `training - documentation `__. - - Returns: - Callable[[~.SetAgentRequest], - Awaitable[~.Agent]]: - 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 'set_agent' not in self._stubs: - self._stubs['set_agent'] = self.grpc_channel.unary_unary( - '/google.cloud.dialogflow.v2.Agents/SetAgent', - request_serializer=gcd_agent.SetAgentRequest.serialize, - response_deserializer=gcd_agent.Agent.deserialize, - ) - return self._stubs['set_agent'] - - @property - def delete_agent(self) -> Callable[ - [agent.DeleteAgentRequest], - Awaitable[empty_pb2.Empty]]: - r"""Return a callable for the delete agent method over gRPC. - - Deletes the specified agent. - - Returns: - Callable[[~.DeleteAgentRequest], - 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_agent' not in self._stubs: - self._stubs['delete_agent'] = self.grpc_channel.unary_unary( - '/google.cloud.dialogflow.v2.Agents/DeleteAgent', - request_serializer=agent.DeleteAgentRequest.serialize, - response_deserializer=empty_pb2.Empty.FromString, - ) - return self._stubs['delete_agent'] - - @property - def search_agents(self) -> Callable[ - [agent.SearchAgentsRequest], - Awaitable[agent.SearchAgentsResponse]]: - r"""Return a callable for the search agents method over gRPC. - - Returns the list of agents. - - Since there is at most one conversational agent per project, - this method is useful primarily for listing all agents across - projects the caller has access to. One can achieve that with a - wildcard project collection id "-". Refer to `List - Sub-Collections `__. - - Returns: - Callable[[~.SearchAgentsRequest], - Awaitable[~.SearchAgentsResponse]]: - 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 'search_agents' not in self._stubs: - self._stubs['search_agents'] = self.grpc_channel.unary_unary( - '/google.cloud.dialogflow.v2.Agents/SearchAgents', - request_serializer=agent.SearchAgentsRequest.serialize, - response_deserializer=agent.SearchAgentsResponse.deserialize, - ) - return self._stubs['search_agents'] - - @property - def train_agent(self) -> Callable[ - [agent.TrainAgentRequest], - Awaitable[operations_pb2.Operation]]: - r"""Return a callable for the train agent method over gRPC. - - Trains the specified agent. - - This method is a `long-running - operation `__. - The returned ``Operation`` type has the following - method-specific fields: - - - ``metadata``: An empty `Struct - message `__ - - ``response``: An `Empty - message `__ - - Note: You should always train an agent prior to sending it - queries. See the `training - documentation `__. - - Returns: - Callable[[~.TrainAgentRequest], - Awaitable[~.Operation]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'train_agent' not in self._stubs: - self._stubs['train_agent'] = self.grpc_channel.unary_unary( - '/google.cloud.dialogflow.v2.Agents/TrainAgent', - request_serializer=agent.TrainAgentRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['train_agent'] - - @property - def export_agent(self) -> 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. - - This method is a `long-running - operation `__. - The returned ``Operation`` type has the following - method-specific fields: - - - ``metadata``: An empty `Struct - message `__ - - ``response``: - [ExportAgentResponse][google.cloud.dialogflow.v2.ExportAgentResponse] - - Returns: - Callable[[~.ExportAgentRequest], - Awaitable[~.Operation]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'export_agent' not in self._stubs: - self._stubs['export_agent'] = self.grpc_channel.unary_unary( - '/google.cloud.dialogflow.v2.Agents/ExportAgent', - request_serializer=agent.ExportAgentRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['export_agent'] - - @property - def import_agent(self) -> 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. - - Uploads new intents and entity types without deleting the - existing ones. Intents and entity types with the same name are - replaced with the new versions from - [ImportAgentRequest][google.cloud.dialogflow.v2.ImportAgentRequest]. - After the import, the imported draft agent will be trained - automatically (unless disabled in agent settings). However, once - the import is done, training may not be completed yet. Please - call [TrainAgent][google.cloud.dialogflow.v2.Agents.TrainAgent] - and wait for the operation it returns in order to train - explicitly. - - This method is a `long-running - operation `__. - The returned ``Operation`` type has the following - method-specific fields: - - - ``metadata``: An empty `Struct - message `__ - - ``response``: An `Empty - message `__ - - The operation only tracks when importing is complete, not when - it is done training. - - Note: You should always train an agent prior to sending it - queries. See the `training - documentation `__. - - Returns: - Callable[[~.ImportAgentRequest], - Awaitable[~.Operation]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'import_agent' not in self._stubs: - self._stubs['import_agent'] = self.grpc_channel.unary_unary( - '/google.cloud.dialogflow.v2.Agents/ImportAgent', - request_serializer=agent.ImportAgentRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['import_agent'] - - @property - def restore_agent(self) -> 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. - - Replaces the current agent version with a new one. All the - intents and entity types in the older version are deleted. After - the restore, the restored draft agent will be trained - automatically (unless disabled in agent settings). However, once - the restore is done, training may not be completed yet. Please - call [TrainAgent][google.cloud.dialogflow.v2.Agents.TrainAgent] - and wait for the operation it returns in order to train - explicitly. - - This method is a `long-running - operation `__. - The returned ``Operation`` type has the following - method-specific fields: - - - ``metadata``: An empty `Struct - message `__ - - ``response``: An `Empty - message `__ - - The operation only tracks when restoring is complete, not when - it is done training. - - Note: You should always train an agent prior to sending it - queries. See the `training - documentation `__. - - Returns: - Callable[[~.RestoreAgentRequest], - Awaitable[~.Operation]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'restore_agent' not in self._stubs: - self._stubs['restore_agent'] = self.grpc_channel.unary_unary( - '/google.cloud.dialogflow.v2.Agents/RestoreAgent', - request_serializer=agent.RestoreAgentRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['restore_agent'] - - @property - def get_validation_result(self) -> Callable[ - [agent.GetValidationResultRequest], - Awaitable[validation_result.ValidationResult]]: - r"""Return a callable for the get validation result method over gRPC. - - Gets agent validation result. Agent validation is - performed during training time and is updated - automatically when training is completed. - - Returns: - Callable[[~.GetValidationResultRequest], - Awaitable[~.ValidationResult]]: - 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_validation_result' not in self._stubs: - self._stubs['get_validation_result'] = self.grpc_channel.unary_unary( - '/google.cloud.dialogflow.v2.Agents/GetValidationResult', - request_serializer=agent.GetValidationResultRequest.serialize, - response_deserializer=validation_result.ValidationResult.deserialize, - ) - return self._stubs['get_validation_result'] - - def close(self): - return self.grpc_channel.close() - - @property - def cancel_operation( - self, - ) -> Callable[[operations_pb2.CancelOperationRequest], None]: - r"""Return a callable for the cancel_operation method over gRPC. - """ - # 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 "cancel_operation" not in self._stubs: - self._stubs["cancel_operation"] = self.grpc_channel.unary_unary( - "/google.longrunning.Operations/CancelOperation", - request_serializer=operations_pb2.CancelOperationRequest.SerializeToString, - response_deserializer=None, - ) - return self._stubs["cancel_operation"] - - @property - def get_operation( - self, - ) -> Callable[[operations_pb2.GetOperationRequest], operations_pb2.Operation]: - r"""Return a callable for the get_operation method over gRPC. - """ - # 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_operation" not in self._stubs: - self._stubs["get_operation"] = self.grpc_channel.unary_unary( - "/google.longrunning.Operations/GetOperation", - request_serializer=operations_pb2.GetOperationRequest.SerializeToString, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs["get_operation"] - - @property - def list_operations( - self, - ) -> Callable[[operations_pb2.ListOperationsRequest], operations_pb2.ListOperationsResponse]: - r"""Return a callable for the list_operations method over gRPC. - """ - # 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_operations" not in self._stubs: - self._stubs["list_operations"] = self.grpc_channel.unary_unary( - "/google.longrunning.Operations/ListOperations", - request_serializer=operations_pb2.ListOperationsRequest.SerializeToString, - response_deserializer=operations_pb2.ListOperationsResponse.FromString, - ) - return self._stubs["list_operations"] - - @property - def list_locations( - self, - ) -> Callable[[locations_pb2.ListLocationsRequest], locations_pb2.ListLocationsResponse]: - r"""Return a callable for the list locations method over gRPC. - """ - # 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_locations" not in self._stubs: - self._stubs["list_locations"] = self.grpc_channel.unary_unary( - "/google.cloud.location.Locations/ListLocations", - request_serializer=locations_pb2.ListLocationsRequest.SerializeToString, - response_deserializer=locations_pb2.ListLocationsResponse.FromString, - ) - return self._stubs["list_locations"] - - @property - def get_location( - self, - ) -> Callable[[locations_pb2.GetLocationRequest], locations_pb2.Location]: - r"""Return a callable for the list locations method over gRPC. - """ - # 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_location" not in self._stubs: - self._stubs["get_location"] = self.grpc_channel.unary_unary( - "/google.cloud.location.Locations/GetLocation", - request_serializer=locations_pb2.GetLocationRequest.SerializeToString, - response_deserializer=locations_pb2.Location.FromString, - ) - return self._stubs["get_location"] - - -__all__ = ( - 'AgentsGrpcAsyncIOTransport', -) diff --git a/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/agents/transports/rest.py b/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/agents/transports/rest.py deleted file mode 100644 index 0b5c10637..000000000 --- a/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/agents/transports/rest.py +++ /dev/null @@ -1,1766 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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 google.auth.transport.requests import AuthorizedSession # type: ignore -import json # type: ignore -import grpc # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore -from google.auth import credentials as ga_credentials # type: ignore -from google.api_core import exceptions as core_exceptions -from google.api_core import retry as retries -from google.api_core import rest_helpers -from google.api_core import rest_streaming -from google.api_core import path_template -from google.api_core import gapic_v1 - -from google.protobuf import json_format -from google.api_core import operations_v1 -from google.cloud.location import locations_pb2 # type: ignore -from google.longrunning import operations_pb2 -from requests import __version__ as requests_version -import dataclasses -import re -from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union -import warnings - -try: - OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] -except AttributeError: # pragma: NO COVER - OptionalRetry = Union[retries.Retry, object] # 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 # type: ignore -from google.protobuf import empty_pb2 # type: ignore - -from .base import AgentsTransport, DEFAULT_CLIENT_INFO as BASE_DEFAULT_CLIENT_INFO - - -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=BASE_DEFAULT_CLIENT_INFO.gapic_version, - grpc_version=None, - rest_version=requests_version, -) - - -class AgentsRestInterceptor: - """Interceptor for Agents. - - Interceptors are used to manipulate requests, request metadata, and responses - in arbitrary ways. - Example use cases include: - * Logging - * Verifying requests according to service or custom semantics - * Stripping extraneous information from responses - - These use cases and more can be enabled by injecting an - instance of a custom subclass when constructing the AgentsRestTransport. - - .. code-block:: python - class MyCustomAgentsInterceptor(AgentsRestInterceptor): - def pre_delete_agent(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def pre_export_agent(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_export_agent(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_get_agent(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_get_agent(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_get_validation_result(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_get_validation_result(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_import_agent(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_import_agent(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_restore_agent(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_restore_agent(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_search_agents(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_search_agents(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_set_agent(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_set_agent(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_train_agent(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_train_agent(self, response): - logging.log(f"Received response: {response}") - return response - - transport = AgentsRestTransport(interceptor=MyCustomAgentsInterceptor()) - client = AgentsClient(transport=transport) - - - """ - def pre_delete_agent(self, request: agent.DeleteAgentRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[agent.DeleteAgentRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for delete_agent - - Override in a subclass to manipulate the request or metadata - before they are sent to the Agents server. - """ - return request, metadata - - def pre_export_agent(self, request: agent.ExportAgentRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[agent.ExportAgentRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for export_agent - - Override in a subclass to manipulate the request or metadata - before they are sent to the Agents server. - """ - return request, metadata - - def post_export_agent(self, response: operations_pb2.Operation) -> operations_pb2.Operation: - """Post-rpc interceptor for export_agent - - Override in a subclass to manipulate the response - after it is returned by the Agents server but before - it is returned to user code. - """ - return response - def pre_get_agent(self, request: agent.GetAgentRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[agent.GetAgentRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for get_agent - - Override in a subclass to manipulate the request or metadata - before they are sent to the Agents server. - """ - return request, metadata - - def post_get_agent(self, response: agent.Agent) -> agent.Agent: - """Post-rpc interceptor for get_agent - - Override in a subclass to manipulate the response - after it is returned by the Agents server but before - it is returned to user code. - """ - return response - def pre_get_validation_result(self, request: agent.GetValidationResultRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[agent.GetValidationResultRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for get_validation_result - - Override in a subclass to manipulate the request or metadata - before they are sent to the Agents server. - """ - return request, metadata - - def post_get_validation_result(self, response: validation_result.ValidationResult) -> validation_result.ValidationResult: - """Post-rpc interceptor for get_validation_result - - Override in a subclass to manipulate the response - after it is returned by the Agents server but before - it is returned to user code. - """ - return response - def pre_import_agent(self, request: agent.ImportAgentRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[agent.ImportAgentRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for import_agent - - Override in a subclass to manipulate the request or metadata - before they are sent to the Agents server. - """ - return request, metadata - - def post_import_agent(self, response: operations_pb2.Operation) -> operations_pb2.Operation: - """Post-rpc interceptor for import_agent - - Override in a subclass to manipulate the response - after it is returned by the Agents server but before - it is returned to user code. - """ - return response - def pre_restore_agent(self, request: agent.RestoreAgentRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[agent.RestoreAgentRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for restore_agent - - Override in a subclass to manipulate the request or metadata - before they are sent to the Agents server. - """ - return request, metadata - - def post_restore_agent(self, response: operations_pb2.Operation) -> operations_pb2.Operation: - """Post-rpc interceptor for restore_agent - - Override in a subclass to manipulate the response - after it is returned by the Agents server but before - it is returned to user code. - """ - return response - def pre_search_agents(self, request: agent.SearchAgentsRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[agent.SearchAgentsRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for search_agents - - Override in a subclass to manipulate the request or metadata - before they are sent to the Agents server. - """ - return request, metadata - - def post_search_agents(self, response: agent.SearchAgentsResponse) -> agent.SearchAgentsResponse: - """Post-rpc interceptor for search_agents - - Override in a subclass to manipulate the response - after it is returned by the Agents server but before - it is returned to user code. - """ - return response - def pre_set_agent(self, request: gcd_agent.SetAgentRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[gcd_agent.SetAgentRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for set_agent - - Override in a subclass to manipulate the request or metadata - before they are sent to the Agents server. - """ - return request, metadata - - def post_set_agent(self, response: gcd_agent.Agent) -> gcd_agent.Agent: - """Post-rpc interceptor for set_agent - - Override in a subclass to manipulate the response - after it is returned by the Agents server but before - it is returned to user code. - """ - return response - def pre_train_agent(self, request: agent.TrainAgentRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[agent.TrainAgentRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for train_agent - - Override in a subclass to manipulate the request or metadata - before they are sent to the Agents server. - """ - return request, metadata - - def post_train_agent(self, response: operations_pb2.Operation) -> operations_pb2.Operation: - """Post-rpc interceptor for train_agent - - Override in a subclass to manipulate the response - after it is returned by the Agents server but before - it is returned to user code. - """ - return response - - def pre_get_location( - self, request: locations_pb2.GetLocationRequest, metadata: Sequence[Tuple[str, str]] - ) -> Tuple[locations_pb2.GetLocationRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for get_location - - Override in a subclass to manipulate the request or metadata - before they are sent to the Agents server. - """ - return request, metadata - - def post_get_location( - self, response: locations_pb2.Location - ) -> locations_pb2.Location: - """Post-rpc interceptor for get_location - - Override in a subclass to manipulate the response - after it is returned by the Agents server but before - it is returned to user code. - """ - return response - def pre_list_locations( - self, request: locations_pb2.ListLocationsRequest, metadata: Sequence[Tuple[str, str]] - ) -> Tuple[locations_pb2.ListLocationsRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for list_locations - - Override in a subclass to manipulate the request or metadata - before they are sent to the Agents server. - """ - return request, metadata - - def post_list_locations( - self, response: locations_pb2.ListLocationsResponse - ) -> locations_pb2.ListLocationsResponse: - """Post-rpc interceptor for list_locations - - Override in a subclass to manipulate the response - after it is returned by the Agents server but before - it is returned to user code. - """ - return response - def pre_cancel_operation( - self, request: operations_pb2.CancelOperationRequest, metadata: Sequence[Tuple[str, str]] - ) -> Tuple[operations_pb2.CancelOperationRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for cancel_operation - - Override in a subclass to manipulate the request or metadata - before they are sent to the Agents server. - """ - return request, metadata - - def post_cancel_operation( - self, response: None - ) -> None: - """Post-rpc interceptor for cancel_operation - - Override in a subclass to manipulate the response - after it is returned by the Agents server but before - it is returned to user code. - """ - return response - def pre_get_operation( - self, request: operations_pb2.GetOperationRequest, metadata: Sequence[Tuple[str, str]] - ) -> Tuple[operations_pb2.GetOperationRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for get_operation - - Override in a subclass to manipulate the request or metadata - before they are sent to the Agents server. - """ - return request, metadata - - def post_get_operation( - self, response: operations_pb2.Operation - ) -> operations_pb2.Operation: - """Post-rpc interceptor for get_operation - - Override in a subclass to manipulate the response - after it is returned by the Agents server but before - it is returned to user code. - """ - return response - def pre_list_operations( - self, request: operations_pb2.ListOperationsRequest, metadata: Sequence[Tuple[str, str]] - ) -> Tuple[operations_pb2.ListOperationsRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for list_operations - - Override in a subclass to manipulate the request or metadata - before they are sent to the Agents server. - """ - return request, metadata - - def post_list_operations( - self, response: operations_pb2.ListOperationsResponse - ) -> operations_pb2.ListOperationsResponse: - """Post-rpc interceptor for list_operations - - Override in a subclass to manipulate the response - after it is returned by the Agents server but before - it is returned to user code. - """ - return response - - -@dataclasses.dataclass -class AgentsRestStub: - _session: AuthorizedSession - _host: str - _interceptor: AgentsRestInterceptor - - -class AgentsRestTransport(AgentsTransport): - """REST backend transport for Agents. - - Service for managing [Agents][google.cloud.dialogflow.v2.Agent]. - - 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 JSON representations of protocol buffers over HTTP/1.1 - - """ - - def __init__(self, *, - host: str = 'dialogflow.googleapis.com', - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - client_cert_source_for_mtls: Optional[Callable[[ - ], Tuple[bytes, bytes]]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - url_scheme: str = 'https', - interceptor: Optional[AgentsRestInterceptor] = None, - api_audience: Optional[str] = None, - ) -> 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 ignored if ``channel`` is provided. - scopes (Optional(Sequence[str])): A list of scopes. This argument is - ignored if ``channel`` is provided. - client_cert_source_for_mtls (Callable[[], Tuple[bytes, bytes]]): Client - certificate to configure mutual TLS HTTP channel. It is ignored - if ``channel`` is provided. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you are developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - url_scheme: the protocol scheme for the API endpoint. Normally - "https", but for testing or local servers, - "http" can be specified. - """ - # Run the base constructor - # TODO(yon-mg): resolve other ctor params i.e. scopes, quota, etc. - # TODO: When custom host (api_endpoint) is set, `scopes` must *also* be set on the - # credentials object - maybe_url_match = re.match("^(?Phttp(?:s)?://)?(?P.*)$", host) - if maybe_url_match is None: - raise ValueError(f"Unexpected hostname structure: {host}") # pragma: NO COVER - - url_match_items = maybe_url_match.groupdict() - - host = f"{url_scheme}://{host}" if not url_match_items["scheme"] else host - - super().__init__( - host=host, - credentials=credentials, - client_info=client_info, - always_use_jwt_access=always_use_jwt_access, - api_audience=api_audience - ) - self._session = AuthorizedSession( - self._credentials, default_host=self.DEFAULT_HOST) - self._operations_client: Optional[operations_v1.AbstractOperationsClient] = None - if client_cert_source_for_mtls: - self._session.configure_mtls_channel(client_cert_source_for_mtls) - self._interceptor = interceptor or AgentsRestInterceptor() - self._prep_wrapped_messages(client_info) - - @property - def operations_client(self) -> operations_v1.AbstractOperationsClient: - """Create the client designed to process long-running operations. - - This property caches on the instance; repeated calls return the same - client. - """ - # Only create a new client if we do not already have one. - if self._operations_client is None: - http_options: Dict[str, List[Dict[str, str]]] = { - 'google.longrunning.Operations.CancelOperation': [ - { - 'method': 'post', - 'uri': '/v2/{name=projects/*/operations/*}:cancel', - }, - { - 'method': 'post', - 'uri': '/v2/{name=projects/*/locations/*/operations/*}:cancel', - }, - ], - 'google.longrunning.Operations.GetOperation': [ - { - 'method': 'get', - 'uri': '/v2/{name=projects/*/operations/*}', - }, - { - 'method': 'get', - 'uri': '/v2/{name=projects/*/locations/*/operations/*}', - }, - ], - 'google.longrunning.Operations.ListOperations': [ - { - 'method': 'get', - 'uri': '/v2/{name=projects/*}/operations', - }, - { - 'method': 'get', - 'uri': '/v2/{name=projects/*/locations/*}/operations', - }, - ], - } - - rest_transport = operations_v1.OperationsRestTransport( - host=self._host, - # use the credentials which are saved - credentials=self._credentials, - scopes=self._scopes, - http_options=http_options, - path_prefix="v2") - - self._operations_client = operations_v1.AbstractOperationsClient(transport=rest_transport) - - # Return the client from cache. - return self._operations_client - - class _DeleteAgent(AgentsRestStub): - def __hash__(self): - return hash("DeleteAgent") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: agent.DeleteAgentRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ): - r"""Call the delete agent method over HTTP. - - Args: - request (~.agent.DeleteAgentRequest): - The request object. The request message for - [Agents.DeleteAgent][google.cloud.dialogflow.v2.Agents.DeleteAgent]. - 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. - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'delete', - 'uri': '/v2/{parent=projects/*}/agent', - }, -{ - 'method': 'delete', - 'uri': '/v2/{parent=projects/*/locations/*}/agent', - }, - ] - request, metadata = self._interceptor.pre_delete_agent(request, metadata) - pb_request = agent.DeleteAgentRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - including_default_value_fields=False, - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - class _ExportAgent(AgentsRestStub): - def __hash__(self): - return hash("ExportAgent") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: agent.ExportAgentRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> operations_pb2.Operation: - r"""Call the export agent method over HTTP. - - Args: - request (~.agent.ExportAgentRequest): - The request object. The request message for - [Agents.ExportAgent][google.cloud.dialogflow.v2.Agents.ExportAgent]. - 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: - ~.operations_pb2.Operation: - This resource represents a - long-running operation that is the - result of a network API call. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'post', - 'uri': '/v2/{parent=projects/*}/agent:export', - 'body': '*', - }, -{ - 'method': 'post', - 'uri': '/v2/{parent=projects/*/locations/*}/agent:export', - 'body': '*', - }, - ] - request, metadata = self._interceptor.pre_export_agent(request, metadata) - pb_request = agent.ExportAgentRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request['body'], - including_default_value_fields=False, - use_integers_for_enums=True - ) - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - including_default_value_fields=False, - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = operations_pb2.Operation() - json_format.Parse(response.content, resp, ignore_unknown_fields=True) - resp = self._interceptor.post_export_agent(resp) - return resp - - class _GetAgent(AgentsRestStub): - def __hash__(self): - return hash("GetAgent") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: agent.GetAgentRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> agent.Agent: - r"""Call the get agent method over HTTP. - - Args: - request (~.agent.GetAgentRequest): - The request object. The request message for - [Agents.GetAgent][google.cloud.dialogflow.v2.Agents.GetAgent]. - 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: - ~.agent.Agent: - A Dialogflow agent is a virtual agent that handles - conversations with your end-users. It is a natural - language understanding module that understands the - nuances of human language. Dialogflow translates - end-user text or audio during a conversation to - structured data that your apps and services can - understand. You design and build a Dialogflow agent to - handle the types of conversations required for your - system. - - For more information about agents, see the `Agent - guide `__. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v2/{parent=projects/*}/agent', - }, -{ - 'method': 'get', - 'uri': '/v2/{parent=projects/*/locations/*}/agent', - }, - ] - request, metadata = self._interceptor.pre_get_agent(request, metadata) - pb_request = agent.GetAgentRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - including_default_value_fields=False, - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = agent.Agent() - pb_resp = agent.Agent.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_get_agent(resp) - return resp - - class _GetValidationResult(AgentsRestStub): - def __hash__(self): - return hash("GetValidationResult") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: agent.GetValidationResultRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> validation_result.ValidationResult: - r"""Call the get validation result method over HTTP. - - Args: - request (~.agent.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. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.validation_result.ValidationResult: - Represents the output of agent - validation. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v2/{parent=projects/*}/agent/validationResult', - }, -{ - 'method': 'get', - 'uri': '/v2/{parent=projects/*/locations/*}/agent/validationResult', - }, - ] - request, metadata = self._interceptor.pre_get_validation_result(request, metadata) - pb_request = agent.GetValidationResultRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - including_default_value_fields=False, - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = validation_result.ValidationResult() - pb_resp = validation_result.ValidationResult.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_get_validation_result(resp) - return resp - - class _ImportAgent(AgentsRestStub): - def __hash__(self): - return hash("ImportAgent") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: agent.ImportAgentRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> operations_pb2.Operation: - r"""Call the import agent method over HTTP. - - Args: - request (~.agent.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. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.operations_pb2.Operation: - This resource represents a - long-running operation that is the - result of a network API call. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'post', - 'uri': '/v2/{parent=projects/*}/agent:import', - 'body': '*', - }, -{ - 'method': 'post', - 'uri': '/v2/{parent=projects/*/locations/*}/agent:import', - 'body': '*', - }, - ] - request, metadata = self._interceptor.pre_import_agent(request, metadata) - pb_request = agent.ImportAgentRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request['body'], - including_default_value_fields=False, - use_integers_for_enums=True - ) - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - including_default_value_fields=False, - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = operations_pb2.Operation() - json_format.Parse(response.content, resp, ignore_unknown_fields=True) - resp = self._interceptor.post_import_agent(resp) - return resp - - class _RestoreAgent(AgentsRestStub): - def __hash__(self): - return hash("RestoreAgent") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: agent.RestoreAgentRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> operations_pb2.Operation: - r"""Call the restore agent method over HTTP. - - Args: - request (~.agent.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. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.operations_pb2.Operation: - This resource represents a - long-running operation that is the - result of a network API call. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'post', - 'uri': '/v2/{parent=projects/*}/agent:restore', - 'body': '*', - }, -{ - 'method': 'post', - 'uri': '/v2/{parent=projects/*/locations/*}/agent:restore', - 'body': '*', - }, - ] - request, metadata = self._interceptor.pre_restore_agent(request, metadata) - pb_request = agent.RestoreAgentRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request['body'], - including_default_value_fields=False, - use_integers_for_enums=True - ) - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - including_default_value_fields=False, - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = operations_pb2.Operation() - json_format.Parse(response.content, resp, ignore_unknown_fields=True) - resp = self._interceptor.post_restore_agent(resp) - return resp - - class _SearchAgents(AgentsRestStub): - def __hash__(self): - return hash("SearchAgents") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: agent.SearchAgentsRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> agent.SearchAgentsResponse: - r"""Call the search agents method over HTTP. - - Args: - request (~.agent.SearchAgentsRequest): - The request object. The request message for - [Agents.SearchAgents][google.cloud.dialogflow.v2.Agents.SearchAgents]. - 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: - ~.agent.SearchAgentsResponse: - The response message for - [Agents.SearchAgents][google.cloud.dialogflow.v2.Agents.SearchAgents]. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v2/{parent=projects/*}/agent:search', - }, -{ - 'method': 'get', - 'uri': '/v2/{parent=projects/*/locations/*}/agent:search', - }, - ] - request, metadata = self._interceptor.pre_search_agents(request, metadata) - pb_request = agent.SearchAgentsRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - including_default_value_fields=False, - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = agent.SearchAgentsResponse() - pb_resp = agent.SearchAgentsResponse.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_search_agents(resp) - return resp - - class _SetAgent(AgentsRestStub): - def __hash__(self): - return hash("SetAgent") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: gcd_agent.SetAgentRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> gcd_agent.Agent: - r"""Call the set agent method over HTTP. - - Args: - request (~.gcd_agent.SetAgentRequest): - The request object. The request message for - [Agents.SetAgent][google.cloud.dialogflow.v2.Agents.SetAgent]. - 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: - ~.gcd_agent.Agent: - A Dialogflow agent is a virtual agent that handles - conversations with your end-users. It is a natural - language understanding module that understands the - nuances of human language. Dialogflow translates - end-user text or audio during a conversation to - structured data that your apps and services can - understand. You design and build a Dialogflow agent to - handle the types of conversations required for your - system. - - For more information about agents, see the `Agent - guide `__. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'post', - 'uri': '/v2/{agent.parent=projects/*}/agent', - 'body': 'agent', - }, -{ - 'method': 'post', - 'uri': '/v2/{agent.parent=projects/*/locations/*}/agent', - 'body': 'agent', - }, - ] - request, metadata = self._interceptor.pre_set_agent(request, metadata) - pb_request = gcd_agent.SetAgentRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request['body'], - including_default_value_fields=False, - use_integers_for_enums=True - ) - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - including_default_value_fields=False, - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = gcd_agent.Agent() - pb_resp = gcd_agent.Agent.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_set_agent(resp) - return resp - - class _TrainAgent(AgentsRestStub): - def __hash__(self): - return hash("TrainAgent") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: agent.TrainAgentRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> operations_pb2.Operation: - r"""Call the train agent method over HTTP. - - Args: - request (~.agent.TrainAgentRequest): - The request object. The request message for - [Agents.TrainAgent][google.cloud.dialogflow.v2.Agents.TrainAgent]. - 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: - ~.operations_pb2.Operation: - This resource represents a - long-running operation that is the - result of a network API call. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'post', - 'uri': '/v2/{parent=projects/*}/agent:train', - 'body': '*', - }, -{ - 'method': 'post', - 'uri': '/v2/{parent=projects/*/locations/*}/agent:train', - 'body': '*', - }, - ] - request, metadata = self._interceptor.pre_train_agent(request, metadata) - pb_request = agent.TrainAgentRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request['body'], - including_default_value_fields=False, - use_integers_for_enums=True - ) - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - including_default_value_fields=False, - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = operations_pb2.Operation() - json_format.Parse(response.content, resp, ignore_unknown_fields=True) - resp = self._interceptor.post_train_agent(resp) - return resp - - @property - def delete_agent(self) -> Callable[ - [agent.DeleteAgentRequest], - empty_pb2.Empty]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._DeleteAgent(self._session, self._host, self._interceptor) # type: ignore - - @property - def export_agent(self) -> Callable[ - [agent.ExportAgentRequest], - operations_pb2.Operation]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._ExportAgent(self._session, self._host, self._interceptor) # type: ignore - - @property - def get_agent(self) -> Callable[ - [agent.GetAgentRequest], - agent.Agent]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._GetAgent(self._session, self._host, self._interceptor) # type: ignore - - @property - def get_validation_result(self) -> Callable[ - [agent.GetValidationResultRequest], - validation_result.ValidationResult]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._GetValidationResult(self._session, self._host, self._interceptor) # type: ignore - - @property - def import_agent(self) -> Callable[ - [agent.ImportAgentRequest], - operations_pb2.Operation]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._ImportAgent(self._session, self._host, self._interceptor) # type: ignore - - @property - def restore_agent(self) -> Callable[ - [agent.RestoreAgentRequest], - operations_pb2.Operation]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._RestoreAgent(self._session, self._host, self._interceptor) # type: ignore - - @property - def search_agents(self) -> Callable[ - [agent.SearchAgentsRequest], - agent.SearchAgentsResponse]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._SearchAgents(self._session, self._host, self._interceptor) # type: ignore - - @property - def set_agent(self) -> Callable[ - [gcd_agent.SetAgentRequest], - gcd_agent.Agent]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._SetAgent(self._session, self._host, self._interceptor) # type: ignore - - @property - def train_agent(self) -> Callable[ - [agent.TrainAgentRequest], - operations_pb2.Operation]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._TrainAgent(self._session, self._host, self._interceptor) # type: ignore - - @property - def get_location(self): - return self._GetLocation(self._session, self._host, self._interceptor) # type: ignore - - class _GetLocation(AgentsRestStub): - def __call__(self, - request: locations_pb2.GetLocationRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> locations_pb2.Location: - - r"""Call the get location method over HTTP. - - Args: - request (locations_pb2.GetLocationRequest): - The request object for GetLocation method. - 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: - locations_pb2.Location: Response from GetLocation method. - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v2/{name=projects/*/locations/*}', - }, - ] - - request, metadata = self._interceptor.pre_get_location(request, metadata) - request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode( - http_options, **request_kwargs) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json.dumps(transcoded_request['query_params'])) - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - resp = locations_pb2.Location() - resp = json_format.Parse(response.content.decode("utf-8"), resp) - resp = self._interceptor.post_get_location(resp) - return resp - - @property - def list_locations(self): - return self._ListLocations(self._session, self._host, self._interceptor) # type: ignore - - class _ListLocations(AgentsRestStub): - def __call__(self, - request: locations_pb2.ListLocationsRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> locations_pb2.ListLocationsResponse: - - r"""Call the list locations method over HTTP. - - Args: - request (locations_pb2.ListLocationsRequest): - The request object for ListLocations method. - 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: - locations_pb2.ListLocationsResponse: Response from ListLocations method. - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v2/{name=projects/*}/locations', - }, - ] - - request, metadata = self._interceptor.pre_list_locations(request, metadata) - request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode( - http_options, **request_kwargs) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json.dumps(transcoded_request['query_params'])) - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - resp = locations_pb2.ListLocationsResponse() - resp = json_format.Parse(response.content.decode("utf-8"), resp) - resp = self._interceptor.post_list_locations(resp) - return resp - - @property - def cancel_operation(self): - return self._CancelOperation(self._session, self._host, self._interceptor) # type: ignore - - class _CancelOperation(AgentsRestStub): - def __call__(self, - request: operations_pb2.CancelOperationRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> None: - - r"""Call the cancel operation method over HTTP. - - Args: - request (operations_pb2.CancelOperationRequest): - The request object for CancelOperation method. - 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. - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'post', - 'uri': '/v2/{name=projects/*/operations/*}:cancel', - }, -{ - 'method': 'post', - 'uri': '/v2/{name=projects/*/locations/*/operations/*}:cancel', - }, - ] - - request, metadata = self._interceptor.pre_cancel_operation(request, metadata) - request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode( - http_options, **request_kwargs) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json.dumps(transcoded_request['query_params'])) - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - return self._interceptor.post_cancel_operation(None) - - @property - def get_operation(self): - return self._GetOperation(self._session, self._host, self._interceptor) # type: ignore - - class _GetOperation(AgentsRestStub): - def __call__(self, - request: operations_pb2.GetOperationRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> operations_pb2.Operation: - - r"""Call the get operation method over HTTP. - - Args: - request (operations_pb2.GetOperationRequest): - The request object for GetOperation method. - 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: - operations_pb2.Operation: Response from GetOperation method. - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v2/{name=projects/*/operations/*}', - }, -{ - 'method': 'get', - 'uri': '/v2/{name=projects/*/locations/*/operations/*}', - }, - ] - - request, metadata = self._interceptor.pre_get_operation(request, metadata) - request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode( - http_options, **request_kwargs) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json.dumps(transcoded_request['query_params'])) - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - resp = operations_pb2.Operation() - resp = json_format.Parse(response.content.decode("utf-8"), resp) - resp = self._interceptor.post_get_operation(resp) - return resp - - @property - def list_operations(self): - return self._ListOperations(self._session, self._host, self._interceptor) # type: ignore - - class _ListOperations(AgentsRestStub): - def __call__(self, - request: operations_pb2.ListOperationsRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> operations_pb2.ListOperationsResponse: - - r"""Call the list operations method over HTTP. - - Args: - request (operations_pb2.ListOperationsRequest): - The request object for ListOperations method. - 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: - operations_pb2.ListOperationsResponse: Response from ListOperations method. - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v2/{name=projects/*}/operations', - }, -{ - 'method': 'get', - 'uri': '/v2/{name=projects/*/locations/*}/operations', - }, - ] - - request, metadata = self._interceptor.pre_list_operations(request, metadata) - request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode( - http_options, **request_kwargs) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json.dumps(transcoded_request['query_params'])) - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - resp = operations_pb2.ListOperationsResponse() - resp = json_format.Parse(response.content.decode("utf-8"), resp) - resp = self._interceptor.post_list_operations(resp) - return resp - - @property - def kind(self) -> str: - return "rest" - - def close(self): - self._session.close() - - -__all__=( - 'AgentsRestTransport', -) diff --git a/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/answer_records/__init__.py b/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/answer_records/__init__.py deleted file mode 100644 index cb89fc95a..000000000 --- a/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/answer_records/__init__.py +++ /dev/null @@ -1,22 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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 AnswerRecordsClient -from .async_client import AnswerRecordsAsyncClient - -__all__ = ( - 'AnswerRecordsClient', - 'AnswerRecordsAsyncClient', -) diff --git a/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/answer_records/async_client.py b/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/answer_records/async_client.py deleted file mode 100644 index 4d426e073..000000000 --- a/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/answer_records/async_client.py +++ /dev/null @@ -1,714 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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, Mapping, MutableMapping, MutableSequence, Optional, Sequence, Tuple, Type, Union - -from google.cloud.dialogflow_v2 import gapic_version as package_version - -from google.api_core.client_options import ClientOptions -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import retry as retries -from google.auth import credentials as ga_credentials # type: ignore -from google.oauth2 import service_account # type: ignore - -try: - OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] -except AttributeError: # pragma: NO COVER - OptionalRetry = Union[retries.Retry, object] # 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.cloud.location import locations_pb2 # type: ignore -from google.longrunning import operations_pb2 -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 - - -class AnswerRecordsAsyncClient: - """Service for managing - [AnswerRecords][google.cloud.dialogflow.v2.AnswerRecord]. - """ - - _client: AnswerRecordsClient - - DEFAULT_ENDPOINT = AnswerRecordsClient.DEFAULT_ENDPOINT - DEFAULT_MTLS_ENDPOINT = AnswerRecordsClient.DEFAULT_MTLS_ENDPOINT - - answer_record_path = staticmethod(AnswerRecordsClient.answer_record_path) - 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) - - @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: - AnswerRecordsAsyncClient: The constructed client. - """ - return AnswerRecordsClient.from_service_account_info.__func__(AnswerRecordsAsyncClient, 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: - AnswerRecordsAsyncClient: The constructed client. - """ - return AnswerRecordsClient.from_service_account_file.__func__(AnswerRecordsAsyncClient, filename, *args, **kwargs) # type: ignore - - from_service_account_json = from_service_account_file - - @classmethod - def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[ClientOptions] = None): - """Return the API endpoint and client cert source for mutual TLS. - - The client cert source is determined in the following order: - (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the - client cert source is None. - (2) if `client_options.client_cert_source` is provided, use the provided one; if the - default client cert source exists, use the default one; otherwise the client cert - source is None. - - The API endpoint is determined in the following order: - (1) if `client_options.api_endpoint` if provided, use the provided one. - (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the - default mTLS endpoint; if the environment variable is "never", use the default API - endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise - use the default API endpoint. - - More details can be found at https://google.aip.dev/auth/4114. - - Args: - client_options (google.api_core.client_options.ClientOptions): Custom options for the - client. Only the `api_endpoint` and `client_cert_source` properties may be used - in this method. - - Returns: - Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the - client cert source to use. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If any errors happen. - """ - return AnswerRecordsClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore - - @property - def transport(self) -> AnswerRecordsTransport: - """Returns the transport used by the client instance. - - Returns: - AnswerRecordsTransport: The transport used by the client instance. - """ - return self._client.transport - - get_transport_class = functools.partial(type(AnswerRecordsClient).get_transport_class, type(AnswerRecordsClient)) - - def __init__(self, *, - credentials: Optional[ga_credentials.Credentials] = None, - transport: Union[str, AnswerRecordsTransport] = "grpc_asyncio", - client_options: Optional[ClientOptions] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the answer records 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, ~.AnswerRecordsTransport]): 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 = AnswerRecordsClient( - credentials=credentials, - transport=transport, - client_options=client_options, - client_info=client_info, - - ) - - async def list_answer_records(self, - request: Optional[Union[answer_record.ListAnswerRecordsRequest, dict]] = None, - *, - parent: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListAnswerRecordsAsyncPager: - r"""Returns the list of all answer records in the - specified project in reverse chronological order. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import dialogflow_v2 - - async def sample_list_answer_records(): - # Create a client - client = dialogflow_v2.AnswerRecordsAsyncClient() - - # Initialize request argument(s) - request = dialogflow_v2.ListAnswerRecordsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_answer_records(request=request) - - # Handle the response - async for response in page_result: - print(response) - - Args: - request (Optional[Union[google.cloud.dialogflow_v2.types.ListAnswerRecordsRequest, dict]]): - The request object. Request message for - [AnswerRecords.ListAnswerRecords][google.cloud.dialogflow.v2.AnswerRecords.ListAnswerRecords]. - parent (:class:`str`): - Required. The project to list all answer records for in - reverse chronological order. Format: - ``projects//locations/``. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.dialogflow_v2.services.answer_records.pagers.ListAnswerRecordsAsyncPager: - Response message for - [AnswerRecords.ListAnswerRecords][google.cloud.dialogflow.v2.AnswerRecords.ListAnswerRecords]. - - Iterating over this object will yield results and - resolve additional pages automatically. - - """ - # Create or coerce a protobuf request object. - # Quick 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 = 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 - - # 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_answer_records, - 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.ListAnswerRecordsAsyncPager( - method=rpc, - request=request, - response=response, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def update_answer_record(self, - request: Optional[Union[gcd_answer_record.UpdateAnswerRecordRequest, dict]] = None, - *, - answer_record: Optional[gcd_answer_record.AnswerRecord] = None, - update_mask: Optional[field_mask_pb2.FieldMask] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gcd_answer_record.AnswerRecord: - r"""Updates the specified answer record. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import dialogflow_v2 - - async def sample_update_answer_record(): - # Create a client - client = dialogflow_v2.AnswerRecordsAsyncClient() - - # Initialize request argument(s) - request = dialogflow_v2.UpdateAnswerRecordRequest( - ) - - # Make the request - response = await client.update_answer_record(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.dialogflow_v2.types.UpdateAnswerRecordRequest, dict]]): - The request object. Request message for - [AnswerRecords.UpdateAnswerRecord][google.cloud.dialogflow.v2.AnswerRecords.UpdateAnswerRecord]. - answer_record (:class:`google.cloud.dialogflow_v2.types.AnswerRecord`): - Required. Answer record to update. - This corresponds to the ``answer_record`` 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.AnswerRecord: - Answer records are records to manage answer history and feedbacks for - Dialogflow. - - Currently, answer record includes: - - - human agent assistant article suggestion - - human agent assistant faq article - - It doesn't include: - - - DetectIntent intent matching - - DetectIntent knowledge - - Answer records are not related to the conversation - history in the Dialogflow Console. A Record is - generated even when the end-user disables - conversation history in the console. Records are - created when there's a human agent assistant - suggestion generated. - - A typical workflow for customers provide feedback to - an answer is: - - 1. For human agent assistant, customers get - suggestion via ListSuggestions API. Together with - 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. - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([answer_record, 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_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: - 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_answer_record, - 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(( - ("answer_record.name", request.answer_record.name), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def list_operations( - self, - request: Optional[operations_pb2.ListOperationsRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operations_pb2.ListOperationsResponse: - r"""Lists operations that match the specified filter in the request. - - Args: - request (:class:`~.operations_pb2.ListOperationsRequest`): - The request object. Request message for - `ListOperations` method. - 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: - ~.operations_pb2.ListOperationsResponse: - Response message for ``ListOperations`` method. - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = operations_pb2.ListOperationsRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._client._transport.list_operations, - 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 get_operation( - self, - request: Optional[operations_pb2.GetOperationRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operations_pb2.Operation: - r"""Gets the latest state of a long-running operation. - - Args: - request (:class:`~.operations_pb2.GetOperationRequest`): - The request object. Request message for - `GetOperation` method. - 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: - ~.operations_pb2.Operation: - An ``Operation`` object. - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = operations_pb2.GetOperationRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._client._transport.get_operation, - 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 cancel_operation( - self, - request: Optional[operations_pb2.CancelOperationRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> None: - r"""Starts asynchronous cancellation on a long-running operation. - - The server makes a best effort to cancel the operation, but success - is not guaranteed. If the server doesn't support this method, it returns - `google.rpc.Code.UNIMPLEMENTED`. - - Args: - request (:class:`~.operations_pb2.CancelOperationRequest`): - The request object. Request message for - `CancelOperation` method. - 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: - None - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = operations_pb2.CancelOperationRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._client._transport.cancel_operation, - 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_location( - self, - request: Optional[locations_pb2.GetLocationRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> locations_pb2.Location: - r"""Gets information about a location. - - Args: - request (:class:`~.location_pb2.GetLocationRequest`): - The request object. Request message for - `GetLocation` method. - 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: - ~.location_pb2.Location: - Location object. - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = locations_pb2.GetLocationRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._client._transport.get_location, - 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 list_locations( - self, - request: Optional[locations_pb2.ListLocationsRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> locations_pb2.ListLocationsResponse: - r"""Lists information about the supported locations for this service. - - Args: - request (:class:`~.location_pb2.ListLocationsRequest`): - The request object. Request message for - `ListLocations` method. - 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: - ~.location_pb2.ListLocationsResponse: - Response message for ``ListLocations`` method. - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = locations_pb2.ListLocationsRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._client._transport.list_locations, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("name", request.name),)), - ) - - # Send the request. - response = await rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - async def __aenter__(self): - return self - - async def __aexit__(self, exc_type, exc, tb): - await self.transport.close() - -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) - - -__all__ = ( - "AnswerRecordsAsyncClient", -) diff --git a/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/answer_records/client.py b/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/answer_records/client.py deleted file mode 100644 index 89f25daba..000000000 --- a/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/answer_records/client.py +++ /dev/null @@ -1,913 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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 os -import re -from typing import Dict, Mapping, MutableMapping, MutableSequence, Optional, Sequence, Tuple, Type, Union, cast - -from google.cloud.dialogflow_v2 import gapic_version as package_version - -from google.api_core import client_options as client_options_lib -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import retry as retries -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 - -try: - OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] -except AttributeError: # pragma: NO COVER - OptionalRetry = Union[retries.Retry, object] # 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.cloud.location import locations_pb2 # type: ignore -from google.longrunning import operations_pb2 -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 -from .transports.rest import AnswerRecordsRestTransport - - -class AnswerRecordsClientMeta(type): - """Metaclass for the AnswerRecords 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[AnswerRecordsTransport]] - _transport_registry["grpc"] = AnswerRecordsGrpcTransport - _transport_registry["grpc_asyncio"] = AnswerRecordsGrpcAsyncIOTransport - _transport_registry["rest"] = AnswerRecordsRestTransport - - def get_transport_class(cls, - label: Optional[str] = None, - ) -> Type[AnswerRecordsTransport]: - """Returns an appropriate transport class. - - Args: - label: The name of the desired transport. If none is - provided, then the first transport in the registry is used. - - Returns: - The transport class to use. - """ - # If a specific transport is requested, return that one. - if label: - return cls._transport_registry[label] - - # No transport is requested; return the default (that is, the first one - # in the dictionary). - return next(iter(cls._transport_registry.values())) - - -class AnswerRecordsClient(metaclass=AnswerRecordsClientMeta): - """Service for managing - [AnswerRecords][google.cloud.dialogflow.v2.AnswerRecord]. - """ - - @staticmethod - def _get_default_mtls_endpoint(api_endpoint): - """Converts api endpoint to mTLS endpoint. - - Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to - "*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively. - Args: - api_endpoint (Optional[str]): the api endpoint to convert. - Returns: - str: converted mTLS api endpoint. - """ - if not api_endpoint: - return api_endpoint - - mtls_endpoint_re = re.compile( - r"(?P[^.]+)(?P\.mtls)?(?P\.sandbox)?(?P\.googleapis\.com)?" - ) - - m = mtls_endpoint_re.match(api_endpoint) - name, mtls, sandbox, googledomain = m.groups() - if mtls or not googledomain: - return api_endpoint - - if sandbox: - return api_endpoint.replace( - "sandbox.googleapis.com", "mtls.sandbox.googleapis.com" - ) - - return api_endpoint.replace(".googleapis.com", ".mtls.googleapis.com") - - DEFAULT_ENDPOINT = "dialogflow.googleapis.com" - DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore - DEFAULT_ENDPOINT - ) - - @classmethod - def from_service_account_info(cls, info: dict, *args, **kwargs): - """Creates an instance of this client using the provided credentials - info. - - Args: - info (dict): The service account private key info. - args: Additional arguments to pass to the constructor. - kwargs: Additional arguments to pass to the constructor. - - Returns: - AnswerRecordsClient: 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: - AnswerRecordsClient: 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) -> AnswerRecordsTransport: - """Returns the transport used by the client instance. - - Returns: - AnswerRecordsTransport: The transport used by the client - instance. - """ - return self._transport - - @staticmethod - def answer_record_path(project: str,answer_record: str,) -> str: - """Returns a fully-qualified answer_record string.""" - return "projects/{project}/answerRecords/{answer_record}".format(project=project, answer_record=answer_record, ) - - @staticmethod - def parse_answer_record_path(path: str) -> Dict[str,str]: - """Parses a answer_record path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/answerRecords/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_billing_account_path(billing_account: str, ) -> str: - """Returns a fully-qualified billing_account string.""" - return "billingAccounts/{billing_account}".format(billing_account=billing_account, ) - - @staticmethod - def parse_common_billing_account_path(path: str) -> Dict[str,str]: - """Parse a billing_account path into its component segments.""" - m = re.match(r"^billingAccounts/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_folder_path(folder: str, ) -> str: - """Returns a fully-qualified folder string.""" - return "folders/{folder}".format(folder=folder, ) - - @staticmethod - def parse_common_folder_path(path: str) -> Dict[str,str]: - """Parse a folder path into its component segments.""" - m = re.match(r"^folders/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_organization_path(organization: str, ) -> str: - """Returns a fully-qualified organization string.""" - return "organizations/{organization}".format(organization=organization, ) - - @staticmethod - def parse_common_organization_path(path: str) -> Dict[str,str]: - """Parse a organization path into its component segments.""" - m = re.match(r"^organizations/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_project_path(project: str, ) -> str: - """Returns a fully-qualified project string.""" - return "projects/{project}".format(project=project, ) - - @staticmethod - def parse_common_project_path(path: str) -> Dict[str,str]: - """Parse a project path into its component segments.""" - m = re.match(r"^projects/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_location_path(project: str, location: str, ) -> str: - """Returns a fully-qualified location string.""" - return "projects/{project}/locations/{location}".format(project=project, location=location, ) - - @staticmethod - def parse_common_location_path(path: str) -> Dict[str,str]: - """Parse a location path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)$", path) - return m.groupdict() if m else {} - - @classmethod - def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[client_options_lib.ClientOptions] = None): - """Return the API endpoint and client cert source for mutual TLS. - - The client cert source is determined in the following order: - (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the - client cert source is None. - (2) if `client_options.client_cert_source` is provided, use the provided one; if the - default client cert source exists, use the default one; otherwise the client cert - source is None. - - The API endpoint is determined in the following order: - (1) if `client_options.api_endpoint` if provided, use the provided one. - (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the - default mTLS endpoint; if the environment variable is "never", use the default API - endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise - use the default API endpoint. - - More details can be found at https://google.aip.dev/auth/4114. - - Args: - client_options (google.api_core.client_options.ClientOptions): Custom options for the - client. Only the `api_endpoint` and `client_cert_source` properties may be used - in this method. - - Returns: - Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the - client cert source to use. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If any errors happen. - """ - if client_options is None: - client_options = client_options_lib.ClientOptions() - use_client_cert = os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false") - use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") - if use_client_cert not in ("true", "false"): - raise ValueError("Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`") - if use_mtls_endpoint not in ("auto", "never", "always"): - raise MutualTLSChannelError("Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`") - - # Figure out the client cert source to use. - client_cert_source = None - if use_client_cert == "true": - if client_options.client_cert_source: - client_cert_source = client_options.client_cert_source - elif mtls.has_default_client_cert_source(): - client_cert_source = mtls.default_client_cert_source() - - # Figure out which api endpoint to use. - if client_options.api_endpoint is not None: - api_endpoint = client_options.api_endpoint - elif use_mtls_endpoint == "always" or (use_mtls_endpoint == "auto" and client_cert_source): - api_endpoint = cls.DEFAULT_MTLS_ENDPOINT - else: - api_endpoint = cls.DEFAULT_ENDPOINT - - return api_endpoint, client_cert_source - - def __init__(self, *, - credentials: Optional[ga_credentials.Credentials] = None, - transport: Optional[Union[str, AnswerRecordsTransport]] = None, - client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the answer records 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, AnswerRecordsTransport]): The - transport to use. If set to None, a transport is chosen - automatically. - client_options (Optional[Union[google.api_core.client_options.ClientOptions, dict]]): 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() - client_options = cast(client_options_lib.ClientOptions, client_options) - - api_endpoint, client_cert_source_func = self.get_mtls_endpoint_and_cert_source(client_options) - - api_key_value = getattr(client_options, "api_key", None) - if api_key_value and credentials: - raise ValueError("client_options.api_key and credentials are mutually exclusive") - - # 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, AnswerRecordsTransport): - # transport is a AnswerRecordsTransport instance. - if credentials or client_options.credentials_file or api_key_value: - 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: - import google.auth._default # type: ignore - - if api_key_value and hasattr(google.auth._default, "get_api_key_credentials"): - credentials = google.auth._default.get_api_key_credentials(api_key_value) - - Transport = type(self).get_transport_class(transport) - self._transport = Transport( - credentials=credentials, - credentials_file=client_options.credentials_file, - host=api_endpoint, - scopes=client_options.scopes, - client_cert_source_for_mtls=client_cert_source_func, - quota_project_id=client_options.quota_project_id, - client_info=client_info, - always_use_jwt_access=True, - api_audience=client_options.api_audience, - ) - - def list_answer_records(self, - request: Optional[Union[answer_record.ListAnswerRecordsRequest, dict]] = None, - *, - parent: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListAnswerRecordsPager: - r"""Returns the list of all answer records in the - specified project in reverse chronological order. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import dialogflow_v2 - - def sample_list_answer_records(): - # Create a client - client = dialogflow_v2.AnswerRecordsClient() - - # Initialize request argument(s) - request = dialogflow_v2.ListAnswerRecordsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_answer_records(request=request) - - # Handle the response - for response in page_result: - print(response) - - Args: - request (Union[google.cloud.dialogflow_v2.types.ListAnswerRecordsRequest, dict]): - The request object. Request message for - [AnswerRecords.ListAnswerRecords][google.cloud.dialogflow.v2.AnswerRecords.ListAnswerRecords]. - parent (str): - Required. The project to list all answer records for in - reverse chronological order. Format: - ``projects//locations/``. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.dialogflow_v2.services.answer_records.pagers.ListAnswerRecordsPager: - Response message for - [AnswerRecords.ListAnswerRecords][google.cloud.dialogflow.v2.AnswerRecords.ListAnswerRecords]. - - Iterating over this object will yield results and - resolve additional pages automatically. - - """ - # Create or coerce a protobuf request object. - # Quick 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 answer_record.ListAnswerRecordsRequest. - # There's no risk of modifying the input as we've already verified - # 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 - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.list_answer_records] - - # 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.ListAnswerRecordsPager( - method=rpc, - request=request, - response=response, - metadata=metadata, - ) - - # Done; return the response. - return response - - def update_answer_record(self, - request: Optional[Union[gcd_answer_record.UpdateAnswerRecordRequest, dict]] = None, - *, - answer_record: Optional[gcd_answer_record.AnswerRecord] = None, - update_mask: Optional[field_mask_pb2.FieldMask] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gcd_answer_record.AnswerRecord: - r"""Updates the specified answer record. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import dialogflow_v2 - - def sample_update_answer_record(): - # Create a client - client = dialogflow_v2.AnswerRecordsClient() - - # Initialize request argument(s) - request = dialogflow_v2.UpdateAnswerRecordRequest( - ) - - # Make the request - response = client.update_answer_record(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.dialogflow_v2.types.UpdateAnswerRecordRequest, dict]): - The request object. Request message for - [AnswerRecords.UpdateAnswerRecord][google.cloud.dialogflow.v2.AnswerRecords.UpdateAnswerRecord]. - answer_record (google.cloud.dialogflow_v2.types.AnswerRecord): - Required. Answer record to update. - This corresponds to the ``answer_record`` 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.AnswerRecord: - Answer records are records to manage answer history and feedbacks for - Dialogflow. - - Currently, answer record includes: - - - human agent assistant article suggestion - - human agent assistant faq article - - It doesn't include: - - - DetectIntent intent matching - - DetectIntent knowledge - - Answer records are not related to the conversation - history in the Dialogflow Console. A Record is - generated even when the end-user disables - conversation history in the console. Records are - created when there's a human agent assistant - suggestion generated. - - A typical workflow for customers provide feedback to - an answer is: - - 1. For human agent assistant, customers get - suggestion via ListSuggestions API. Together with - 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. - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([answer_record, 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_answer_record.UpdateAnswerRecordRequest. - # There's no risk of modifying the input as we've already verified - # 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: - 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_answer_record] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("answer_record.name", request.answer_record.name), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def __enter__(self) -> "AnswerRecordsClient": - return self - - def __exit__(self, type, value, traceback): - """Releases underlying transport's resources. - - .. warning:: - ONLY use as a context manager if the transport is NOT shared - with other clients! Exiting the with block will CLOSE the transport - and may cause errors in other clients! - """ - self.transport.close() - - def list_operations( - self, - request: Optional[operations_pb2.ListOperationsRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operations_pb2.ListOperationsResponse: - r"""Lists operations that match the specified filter in the request. - - Args: - request (:class:`~.operations_pb2.ListOperationsRequest`): - The request object. Request message for - `ListOperations` method. - 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: - ~.operations_pb2.ListOperationsResponse: - Response message for ``ListOperations`` method. - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = operations_pb2.ListOperationsRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._transport.list_operations, - 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 = rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - def get_operation( - self, - request: Optional[operations_pb2.GetOperationRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operations_pb2.Operation: - r"""Gets the latest state of a long-running operation. - - Args: - request (:class:`~.operations_pb2.GetOperationRequest`): - The request object. Request message for - `GetOperation` method. - 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: - ~.operations_pb2.Operation: - An ``Operation`` object. - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = operations_pb2.GetOperationRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._transport.get_operation, - 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 = rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - def cancel_operation( - self, - request: Optional[operations_pb2.CancelOperationRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> None: - r"""Starts asynchronous cancellation on a long-running operation. - - The server makes a best effort to cancel the operation, but success - is not guaranteed. If the server doesn't support this method, it returns - `google.rpc.Code.UNIMPLEMENTED`. - - Args: - request (:class:`~.operations_pb2.CancelOperationRequest`): - The request object. Request message for - `CancelOperation` method. - 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: - None - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = operations_pb2.CancelOperationRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._transport.cancel_operation, - 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. - rpc(request, retry=retry, timeout=timeout, metadata=metadata,) - - def get_location( - self, - request: Optional[locations_pb2.GetLocationRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> locations_pb2.Location: - r"""Gets information about a location. - - Args: - request (:class:`~.location_pb2.GetLocationRequest`): - The request object. Request message for - `GetLocation` method. - 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: - ~.location_pb2.Location: - Location object. - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = locations_pb2.GetLocationRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._transport.get_location, - 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 = rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - def list_locations( - self, - request: Optional[locations_pb2.ListLocationsRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> locations_pb2.ListLocationsResponse: - r"""Lists information about the supported locations for this service. - - Args: - request (:class:`~.location_pb2.ListLocationsRequest`): - The request object. Request message for - `ListLocations` method. - 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: - ~.location_pb2.ListLocationsResponse: - Response message for ``ListLocations`` method. - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = locations_pb2.ListLocationsRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._transport.list_locations, - 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 = rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) - - -__all__ = ( - "AnswerRecordsClient", -) diff --git a/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/answer_records/pagers.py b/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/answer_records/pagers.py deleted file mode 100644 index 7ec1cbb0f..000000000 --- a/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/answer_records/pagers.py +++ /dev/null @@ -1,139 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from typing import Any, AsyncIterator, Awaitable, Callable, Sequence, Tuple, Optional, Iterator - -from google.cloud.dialogflow_v2.types import answer_record - - -class ListAnswerRecordsPager: - """A pager for iterating through ``list_answer_records`` requests. - - This class thinly wraps an initial - :class:`google.cloud.dialogflow_v2.types.ListAnswerRecordsResponse` object, and - provides an ``__iter__`` method to iterate through its - ``answer_records`` field. - - If there are more pages, the ``__iter__`` method will make additional - ``ListAnswerRecords`` requests and continue to iterate - through the ``answer_records`` field on the - corresponding responses. - - All the usual :class:`google.cloud.dialogflow_v2.types.ListAnswerRecordsResponse` - 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[..., answer_record.ListAnswerRecordsResponse], - request: answer_record.ListAnswerRecordsRequest, - response: answer_record.ListAnswerRecordsResponse, - *, - 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.ListAnswerRecordsRequest): - The initial request object. - response (google.cloud.dialogflow_v2.types.ListAnswerRecordsResponse): - 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 = answer_record.ListAnswerRecordsRequest(request) - self._response = response - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - def pages(self) -> Iterator[answer_record.ListAnswerRecordsResponse]: - yield self._response - while self._response.next_page_token: - self._request.page_token = self._response.next_page_token - self._response = self._method(self._request, metadata=self._metadata) - yield self._response - - def __iter__(self) -> Iterator[answer_record.AnswerRecord]: - for page in self.pages: - yield from page.answer_records - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListAnswerRecordsAsyncPager: - """A pager for iterating through ``list_answer_records`` requests. - - This class thinly wraps an initial - :class:`google.cloud.dialogflow_v2.types.ListAnswerRecordsResponse` object, and - provides an ``__aiter__`` method to iterate through its - ``answer_records`` field. - - If there are more pages, the ``__aiter__`` method will make additional - ``ListAnswerRecords`` requests and continue to iterate - through the ``answer_records`` field on the - corresponding responses. - - All the usual :class:`google.cloud.dialogflow_v2.types.ListAnswerRecordsResponse` - 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[answer_record.ListAnswerRecordsResponse]], - request: answer_record.ListAnswerRecordsRequest, - response: answer_record.ListAnswerRecordsResponse, - *, - metadata: Sequence[Tuple[str, str]] = ()): - """Instantiates the pager. - - Args: - method (Callable): The method that was originally called, and - which instantiated this pager. - request (google.cloud.dialogflow_v2.types.ListAnswerRecordsRequest): - The initial request object. - response (google.cloud.dialogflow_v2.types.ListAnswerRecordsResponse): - 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 = answer_record.ListAnswerRecordsRequest(request) - self._response = response - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - async def pages(self) -> AsyncIterator[answer_record.ListAnswerRecordsResponse]: - yield self._response - while self._response.next_page_token: - self._request.page_token = self._response.next_page_token - self._response = await self._method(self._request, metadata=self._metadata) - yield self._response - def __aiter__(self) -> AsyncIterator[answer_record.AnswerRecord]: - async def async_generator(): - async for page in self.pages: - for response in page.answer_records: - yield response - - return async_generator() - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) diff --git a/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/answer_records/transports/__init__.py b/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/answer_records/transports/__init__.py deleted file mode 100644 index 1285a3133..000000000 --- a/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/answer_records/transports/__init__.py +++ /dev/null @@ -1,38 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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 AnswerRecordsTransport -from .grpc import AnswerRecordsGrpcTransport -from .grpc_asyncio import AnswerRecordsGrpcAsyncIOTransport -from .rest import AnswerRecordsRestTransport -from .rest import AnswerRecordsRestInterceptor - - -# Compile a registry of transports. -_transport_registry = OrderedDict() # type: Dict[str, Type[AnswerRecordsTransport]] -_transport_registry['grpc'] = AnswerRecordsGrpcTransport -_transport_registry['grpc_asyncio'] = AnswerRecordsGrpcAsyncIOTransport -_transport_registry['rest'] = AnswerRecordsRestTransport - -__all__ = ( - 'AnswerRecordsTransport', - 'AnswerRecordsGrpcTransport', - 'AnswerRecordsGrpcAsyncIOTransport', - 'AnswerRecordsRestTransport', - 'AnswerRecordsRestInterceptor', -) diff --git a/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/answer_records/transports/base.py b/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/answer_records/transports/base.py deleted file mode 100644 index d5e846218..000000000 --- a/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/answer_records/transports/base.py +++ /dev/null @@ -1,209 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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 - -from google.cloud.dialogflow_v2 import gapic_version as package_version - -import google.auth # type: ignore -import google.api_core -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import retry as retries -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 answer_record -from google.cloud.dialogflow_v2.types import answer_record as gcd_answer_record -from google.cloud.location import locations_pb2 # type: ignore -from google.longrunning import operations_pb2 - -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) - - -class AnswerRecordsTransport(abc.ABC): - """Abstract transport class for AnswerRecords.""" - - 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: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - api_audience: Optional[str] = None, - **kwargs, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. - scopes (Optional[Sequence[str]]): A list of scopes. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - """ - - scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} - - # Save the scopes. - self._scopes = scopes - - # If no credentials are provided, then determine the appropriate - # defaults. - if credentials and credentials_file: - raise core_exceptions.DuplicateCredentialArgs("'credentials_file' and 'credentials' are mutually exclusive") - - if credentials_file is not None: - credentials, _ = google.auth.load_credentials_from_file( - credentials_file, - **scopes_kwargs, - quota_project_id=quota_project_id - ) - elif credentials is None: - credentials, _ = google.auth.default(**scopes_kwargs, quota_project_id=quota_project_id) - # Don't apply audience if the credentials file passed from user. - if hasattr(credentials, "with_gdch_audience"): - credentials = credentials.with_gdch_audience(api_audience if api_audience else host) - - # If the credentials are service account credentials, then always try to use self signed JWT. - if always_use_jwt_access and isinstance(credentials, service_account.Credentials) and hasattr(service_account.Credentials, "with_always_use_jwt_access"): - credentials = credentials.with_always_use_jwt_access(True) - - # Save the credentials. - self._credentials = credentials - - # Save the hostname. Default to port 443 (HTTPS) if none is specified. - if ':' not in host: - host += ':443' - self._host = host - - def _prep_wrapped_messages(self, client_info): - # Precompute the wrapped methods. - self._wrapped_methods = { - self.list_answer_records: gapic_v1.method.wrap_method( - self.list_answer_records, - default_timeout=None, - client_info=client_info, - ), - self.update_answer_record: gapic_v1.method.wrap_method( - self.update_answer_record, - default_timeout=None, - client_info=client_info, - ), - } - - def close(self): - """Closes resources associated with the transport. - - .. warning:: - Only call this method if the transport is NOT shared - with other clients - this may cause errors in other clients! - """ - raise NotImplementedError() - - @property - def list_answer_records(self) -> Callable[ - [answer_record.ListAnswerRecordsRequest], - Union[ - answer_record.ListAnswerRecordsResponse, - Awaitable[answer_record.ListAnswerRecordsResponse] - ]]: - raise NotImplementedError() - - @property - def update_answer_record(self) -> Callable[ - [gcd_answer_record.UpdateAnswerRecordRequest], - Union[ - gcd_answer_record.AnswerRecord, - Awaitable[gcd_answer_record.AnswerRecord] - ]]: - raise NotImplementedError() - - @property - def list_operations( - self, - ) -> Callable[ - [operations_pb2.ListOperationsRequest], - Union[operations_pb2.ListOperationsResponse, Awaitable[operations_pb2.ListOperationsResponse]], - ]: - raise NotImplementedError() - - @property - def get_operation( - self, - ) -> Callable[ - [operations_pb2.GetOperationRequest], - Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], - ]: - raise NotImplementedError() - - @property - def cancel_operation( - self, - ) -> Callable[ - [operations_pb2.CancelOperationRequest], - None, - ]: - raise NotImplementedError() - - @property - def get_location(self, - ) -> Callable[ - [locations_pb2.GetLocationRequest], - Union[locations_pb2.Location, Awaitable[locations_pb2.Location]], - ]: - raise NotImplementedError() - - @property - def list_locations(self, - ) -> Callable[ - [locations_pb2.ListLocationsRequest], - Union[locations_pb2.ListLocationsResponse, Awaitable[locations_pb2.ListLocationsResponse]], - ]: - raise NotImplementedError() - - @property - def kind(self) -> str: - raise NotImplementedError() - - -__all__ = ( - 'AnswerRecordsTransport', -) diff --git a/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/answer_records/transports/grpc.py b/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/answer_records/transports/grpc.py deleted file mode 100644 index 98ef604e6..000000000 --- a/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/answer_records/transports/grpc.py +++ /dev/null @@ -1,385 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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 -from google.api_core import gapic_v1 -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 google.cloud.location import locations_pb2 # type: ignore -from google.longrunning import operations_pb2 -from .base import AnswerRecordsTransport, DEFAULT_CLIENT_INFO - - -class AnswerRecordsGrpcTransport(AnswerRecordsTransport): - """gRPC backend transport for AnswerRecords. - - Service for managing - [AnswerRecords][google.cloud.dialogflow.v2.AnswerRecord]. - - 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: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - channel: Optional[grpc.Channel] = None, - api_mtls_endpoint: Optional[str] = None, - client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, - ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, - client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - api_audience: Optional[str] = None, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - This argument is ignored if ``channel`` is provided. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional(Sequence[str])): A list of scopes. This argument is - ignored if ``channel`` is provided. - channel (Optional[grpc.Channel]): A ``Channel`` instance through - which to make calls. - api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. - If provided, it overrides the ``host`` argument and tries to create - a mutual TLS channel with client SSL credentials from - ``client_cert_source`` or application default SSL credentials. - client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): - Deprecated. A callback to provide client SSL certificate bytes and - private key bytes, both in PEM format. It is ignored if - ``api_mtls_endpoint`` is None. - ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials - for the grpc channel. It is ignored if ``channel`` is provided. - client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): - A callback to provide client certificate bytes and private key bytes, - both in PEM format. It is used to configure a mutual TLS channel. It is - ignored if ``channel`` or ``ssl_channel_credentials`` is provided. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport - creation failed for any reason. - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - self._grpc_channel = None - self._ssl_channel_credentials = ssl_channel_credentials - self._stubs: Dict[str, Callable] = {} - - if api_mtls_endpoint: - warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) - if client_cert_source: - warnings.warn("client_cert_source is deprecated", DeprecationWarning) - - if channel: - # Ignore credentials if a channel was passed. - credentials = False - # If a channel was explicitly provided, set it. - self._grpc_channel = channel - self._ssl_channel_credentials = None - - else: - if api_mtls_endpoint: - host = api_mtls_endpoint - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - self._ssl_channel_credentials = SslCredentials().ssl_credentials - - else: - if client_cert_source_for_mtls and not ssl_channel_credentials: - cert, key = client_cert_source_for_mtls() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - - # The base transport sets the host, credentials and scopes - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes, - quota_project_id=quota_project_id, - client_info=client_info, - always_use_jwt_access=always_use_jwt_access, - api_audience=api_audience, - ) - - if not self._grpc_channel: - self._grpc_channel = type(self).create_channel( - self._host, - # use the credentials which are saved - credentials=self._credentials, - # Set ``credentials_file`` to ``None`` here as - # the credentials that we saved earlier should be used. - credentials_file=None, - 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: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - **kwargs) -> grpc.Channel: - """Create and return a gRPC channel object. - Args: - host (Optional[str]): The host for the channel to use. - credentials (Optional[~.Credentials]): The - authorization credentials to attach to requests. These - credentials identify this application to the service. If - none are specified, the client will attempt to ascertain - the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - kwargs (Optional[dict]): Keyword arguments, which are passed to the - channel creation. - Returns: - grpc.Channel: A gRPC channel object. - - Raises: - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - - return grpc_helpers.create_channel( - host, - credentials=credentials, - credentials_file=credentials_file, - quota_project_id=quota_project_id, - default_scopes=cls.AUTH_SCOPES, - scopes=scopes, - default_host=cls.DEFAULT_HOST, - **kwargs - ) - - @property - def grpc_channel(self) -> grpc.Channel: - """Return the channel designed to connect to this service. - """ - return self._grpc_channel - - @property - def list_answer_records(self) -> Callable[ - [answer_record.ListAnswerRecordsRequest], - answer_record.ListAnswerRecordsResponse]: - r"""Return a callable for the list answer records method over gRPC. - - Returns the list of all answer records in the - specified project in reverse chronological order. - - Returns: - Callable[[~.ListAnswerRecordsRequest], - ~.ListAnswerRecordsResponse]: - 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_answer_records' not in self._stubs: - self._stubs['list_answer_records'] = self.grpc_channel.unary_unary( - '/google.cloud.dialogflow.v2.AnswerRecords/ListAnswerRecords', - request_serializer=answer_record.ListAnswerRecordsRequest.serialize, - response_deserializer=answer_record.ListAnswerRecordsResponse.deserialize, - ) - return self._stubs['list_answer_records'] - - @property - def update_answer_record(self) -> Callable[ - [gcd_answer_record.UpdateAnswerRecordRequest], - gcd_answer_record.AnswerRecord]: - r"""Return a callable for the update answer record method over gRPC. - - Updates the specified answer record. - - Returns: - Callable[[~.UpdateAnswerRecordRequest], - ~.AnswerRecord]: - 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_answer_record' not in self._stubs: - self._stubs['update_answer_record'] = self.grpc_channel.unary_unary( - '/google.cloud.dialogflow.v2.AnswerRecords/UpdateAnswerRecord', - request_serializer=gcd_answer_record.UpdateAnswerRecordRequest.serialize, - response_deserializer=gcd_answer_record.AnswerRecord.deserialize, - ) - return self._stubs['update_answer_record'] - - def close(self): - self.grpc_channel.close() - - @property - def cancel_operation( - self, - ) -> Callable[[operations_pb2.CancelOperationRequest], None]: - r"""Return a callable for the cancel_operation method over gRPC. - """ - # 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 "cancel_operation" not in self._stubs: - self._stubs["cancel_operation"] = self.grpc_channel.unary_unary( - "/google.longrunning.Operations/CancelOperation", - request_serializer=operations_pb2.CancelOperationRequest.SerializeToString, - response_deserializer=None, - ) - return self._stubs["cancel_operation"] - - @property - def get_operation( - self, - ) -> Callable[[operations_pb2.GetOperationRequest], operations_pb2.Operation]: - r"""Return a callable for the get_operation method over gRPC. - """ - # 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_operation" not in self._stubs: - self._stubs["get_operation"] = self.grpc_channel.unary_unary( - "/google.longrunning.Operations/GetOperation", - request_serializer=operations_pb2.GetOperationRequest.SerializeToString, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs["get_operation"] - - @property - def list_operations( - self, - ) -> Callable[[operations_pb2.ListOperationsRequest], operations_pb2.ListOperationsResponse]: - r"""Return a callable for the list_operations method over gRPC. - """ - # 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_operations" not in self._stubs: - self._stubs["list_operations"] = self.grpc_channel.unary_unary( - "/google.longrunning.Operations/ListOperations", - request_serializer=operations_pb2.ListOperationsRequest.SerializeToString, - response_deserializer=operations_pb2.ListOperationsResponse.FromString, - ) - return self._stubs["list_operations"] - - @property - def list_locations( - self, - ) -> Callable[[locations_pb2.ListLocationsRequest], locations_pb2.ListLocationsResponse]: - r"""Return a callable for the list locations method over gRPC. - """ - # 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_locations" not in self._stubs: - self._stubs["list_locations"] = self.grpc_channel.unary_unary( - "/google.cloud.location.Locations/ListLocations", - request_serializer=locations_pb2.ListLocationsRequest.SerializeToString, - response_deserializer=locations_pb2.ListLocationsResponse.FromString, - ) - return self._stubs["list_locations"] - - @property - def get_location( - self, - ) -> Callable[[locations_pb2.GetLocationRequest], locations_pb2.Location]: - r"""Return a callable for the list locations method over gRPC. - """ - # 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_location" not in self._stubs: - self._stubs["get_location"] = self.grpc_channel.unary_unary( - "/google.cloud.location.Locations/GetLocation", - request_serializer=locations_pb2.GetLocationRequest.SerializeToString, - response_deserializer=locations_pb2.Location.FromString, - ) - return self._stubs["get_location"] - - @property - def kind(self) -> str: - return "grpc" - - -__all__ = ( - 'AnswerRecordsGrpcTransport', -) diff --git a/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/answer_records/transports/grpc_asyncio.py b/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/answer_records/transports/grpc_asyncio.py deleted file mode 100644 index e87333fd9..000000000 --- a/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/answer_records/transports/grpc_asyncio.py +++ /dev/null @@ -1,384 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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 -from google.api_core import grpc_helpers_async -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore - -import grpc # type: ignore -from grpc.experimental import aio # type: ignore - -from google.cloud.dialogflow_v2.types import answer_record -from google.cloud.dialogflow_v2.types import answer_record as gcd_answer_record -from google.cloud.location import locations_pb2 # type: ignore -from google.longrunning import operations_pb2 -from .base import AnswerRecordsTransport, DEFAULT_CLIENT_INFO -from .grpc import AnswerRecordsGrpcTransport - - -class AnswerRecordsGrpcAsyncIOTransport(AnswerRecordsTransport): - """gRPC AsyncIO backend transport for AnswerRecords. - - Service for managing - [AnswerRecords][google.cloud.dialogflow.v2.AnswerRecord]. - - 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: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - **kwargs) -> aio.Channel: - """Create and return a gRPC AsyncIO channel object. - Args: - host (Optional[str]): The host for the channel to use. - credentials (Optional[~.Credentials]): The - authorization credentials to attach to requests. These - credentials identify this application to the service. If - none are specified, the client will attempt to ascertain - the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - kwargs (Optional[dict]): Keyword arguments, which are passed to the - channel creation. - Returns: - aio.Channel: A gRPC AsyncIO channel object. - """ - - return grpc_helpers_async.create_channel( - host, - credentials=credentials, - credentials_file=credentials_file, - quota_project_id=quota_project_id, - default_scopes=cls.AUTH_SCOPES, - scopes=scopes, - default_host=cls.DEFAULT_HOST, - **kwargs - ) - - def __init__(self, *, - host: str = 'dialogflow.googleapis.com', - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - channel: Optional[aio.Channel] = None, - api_mtls_endpoint: Optional[str] = None, - client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, - ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, - client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - api_audience: Optional[str] = None, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - This argument is ignored if ``channel`` is provided. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - channel (Optional[aio.Channel]): A ``Channel`` instance through - which to make calls. - api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. - If provided, it overrides the ``host`` argument and tries to create - a mutual TLS channel with client SSL credentials from - ``client_cert_source`` or application default SSL credentials. - client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): - Deprecated. A callback to provide client SSL certificate bytes and - private key bytes, both in PEM format. It is ignored if - ``api_mtls_endpoint`` is None. - ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials - for the grpc channel. It is ignored if ``channel`` is provided. - client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): - A callback to provide client certificate bytes and private key bytes, - both in PEM format. It is used to configure a mutual TLS channel. It is - ignored if ``channel`` or ``ssl_channel_credentials`` is provided. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - - Raises: - google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport - creation failed for any reason. - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - self._grpc_channel = None - self._ssl_channel_credentials = ssl_channel_credentials - self._stubs: Dict[str, Callable] = {} - - if api_mtls_endpoint: - warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) - if client_cert_source: - warnings.warn("client_cert_source is deprecated", DeprecationWarning) - - if channel: - # Ignore credentials if a channel was passed. - credentials = False - # If a channel was explicitly provided, set it. - self._grpc_channel = channel - self._ssl_channel_credentials = None - else: - if api_mtls_endpoint: - host = api_mtls_endpoint - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - self._ssl_channel_credentials = SslCredentials().ssl_credentials - - else: - if client_cert_source_for_mtls and not ssl_channel_credentials: - cert, key = client_cert_source_for_mtls() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - - # The base transport sets the host, credentials and scopes - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes, - quota_project_id=quota_project_id, - client_info=client_info, - always_use_jwt_access=always_use_jwt_access, - api_audience=api_audience, - ) - - if not self._grpc_channel: - self._grpc_channel = type(self).create_channel( - self._host, - # use the credentials which are saved - credentials=self._credentials, - # Set ``credentials_file`` to ``None`` here as - # the credentials that we saved earlier should be used. - credentials_file=None, - 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_answer_records(self) -> Callable[ - [answer_record.ListAnswerRecordsRequest], - Awaitable[answer_record.ListAnswerRecordsResponse]]: - r"""Return a callable for the list answer records method over gRPC. - - Returns the list of all answer records in the - specified project in reverse chronological order. - - Returns: - Callable[[~.ListAnswerRecordsRequest], - Awaitable[~.ListAnswerRecordsResponse]]: - 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_answer_records' not in self._stubs: - self._stubs['list_answer_records'] = self.grpc_channel.unary_unary( - '/google.cloud.dialogflow.v2.AnswerRecords/ListAnswerRecords', - request_serializer=answer_record.ListAnswerRecordsRequest.serialize, - response_deserializer=answer_record.ListAnswerRecordsResponse.deserialize, - ) - return self._stubs['list_answer_records'] - - @property - def update_answer_record(self) -> Callable[ - [gcd_answer_record.UpdateAnswerRecordRequest], - Awaitable[gcd_answer_record.AnswerRecord]]: - r"""Return a callable for the update answer record method over gRPC. - - Updates the specified answer record. - - Returns: - Callable[[~.UpdateAnswerRecordRequest], - Awaitable[~.AnswerRecord]]: - 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_answer_record' not in self._stubs: - self._stubs['update_answer_record'] = self.grpc_channel.unary_unary( - '/google.cloud.dialogflow.v2.AnswerRecords/UpdateAnswerRecord', - request_serializer=gcd_answer_record.UpdateAnswerRecordRequest.serialize, - response_deserializer=gcd_answer_record.AnswerRecord.deserialize, - ) - return self._stubs['update_answer_record'] - - def close(self): - return self.grpc_channel.close() - - @property - def cancel_operation( - self, - ) -> Callable[[operations_pb2.CancelOperationRequest], None]: - r"""Return a callable for the cancel_operation method over gRPC. - """ - # 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 "cancel_operation" not in self._stubs: - self._stubs["cancel_operation"] = self.grpc_channel.unary_unary( - "/google.longrunning.Operations/CancelOperation", - request_serializer=operations_pb2.CancelOperationRequest.SerializeToString, - response_deserializer=None, - ) - return self._stubs["cancel_operation"] - - @property - def get_operation( - self, - ) -> Callable[[operations_pb2.GetOperationRequest], operations_pb2.Operation]: - r"""Return a callable for the get_operation method over gRPC. - """ - # 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_operation" not in self._stubs: - self._stubs["get_operation"] = self.grpc_channel.unary_unary( - "/google.longrunning.Operations/GetOperation", - request_serializer=operations_pb2.GetOperationRequest.SerializeToString, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs["get_operation"] - - @property - def list_operations( - self, - ) -> Callable[[operations_pb2.ListOperationsRequest], operations_pb2.ListOperationsResponse]: - r"""Return a callable for the list_operations method over gRPC. - """ - # 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_operations" not in self._stubs: - self._stubs["list_operations"] = self.grpc_channel.unary_unary( - "/google.longrunning.Operations/ListOperations", - request_serializer=operations_pb2.ListOperationsRequest.SerializeToString, - response_deserializer=operations_pb2.ListOperationsResponse.FromString, - ) - return self._stubs["list_operations"] - - @property - def list_locations( - self, - ) -> Callable[[locations_pb2.ListLocationsRequest], locations_pb2.ListLocationsResponse]: - r"""Return a callable for the list locations method over gRPC. - """ - # 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_locations" not in self._stubs: - self._stubs["list_locations"] = self.grpc_channel.unary_unary( - "/google.cloud.location.Locations/ListLocations", - request_serializer=locations_pb2.ListLocationsRequest.SerializeToString, - response_deserializer=locations_pb2.ListLocationsResponse.FromString, - ) - return self._stubs["list_locations"] - - @property - def get_location( - self, - ) -> Callable[[locations_pb2.GetLocationRequest], locations_pb2.Location]: - r"""Return a callable for the list locations method over gRPC. - """ - # 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_location" not in self._stubs: - self._stubs["get_location"] = self.grpc_channel.unary_unary( - "/google.cloud.location.Locations/GetLocation", - request_serializer=locations_pb2.GetLocationRequest.SerializeToString, - response_deserializer=locations_pb2.Location.FromString, - ) - return self._stubs["get_location"] - - -__all__ = ( - 'AnswerRecordsGrpcAsyncIOTransport', -) diff --git a/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/answer_records/transports/rest.py b/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/answer_records/transports/rest.py deleted file mode 100644 index 9773b3ea1..000000000 --- a/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/answer_records/transports/rest.py +++ /dev/null @@ -1,887 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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 google.auth.transport.requests import AuthorizedSession # type: ignore -import json # type: ignore -import grpc # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore -from google.auth import credentials as ga_credentials # type: ignore -from google.api_core import exceptions as core_exceptions -from google.api_core import retry as retries -from google.api_core import rest_helpers -from google.api_core import rest_streaming -from google.api_core import path_template -from google.api_core import gapic_v1 - -from google.protobuf import json_format -from google.cloud.location import locations_pb2 # type: ignore -from google.longrunning import operations_pb2 -from requests import __version__ as requests_version -import dataclasses -import re -from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union -import warnings - -try: - OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] -except AttributeError: # pragma: NO COVER - OptionalRetry = Union[retries.Retry, object] # 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 as BASE_DEFAULT_CLIENT_INFO - - -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=BASE_DEFAULT_CLIENT_INFO.gapic_version, - grpc_version=None, - rest_version=requests_version, -) - - -class AnswerRecordsRestInterceptor: - """Interceptor for AnswerRecords. - - Interceptors are used to manipulate requests, request metadata, and responses - in arbitrary ways. - Example use cases include: - * Logging - * Verifying requests according to service or custom semantics - * Stripping extraneous information from responses - - These use cases and more can be enabled by injecting an - instance of a custom subclass when constructing the AnswerRecordsRestTransport. - - .. code-block:: python - class MyCustomAnswerRecordsInterceptor(AnswerRecordsRestInterceptor): - def pre_list_answer_records(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_list_answer_records(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_update_answer_record(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_update_answer_record(self, response): - logging.log(f"Received response: {response}") - return response - - transport = AnswerRecordsRestTransport(interceptor=MyCustomAnswerRecordsInterceptor()) - client = AnswerRecordsClient(transport=transport) - - - """ - def pre_list_answer_records(self, request: answer_record.ListAnswerRecordsRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[answer_record.ListAnswerRecordsRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for list_answer_records - - Override in a subclass to manipulate the request or metadata - before they are sent to the AnswerRecords server. - """ - return request, metadata - - def post_list_answer_records(self, response: answer_record.ListAnswerRecordsResponse) -> answer_record.ListAnswerRecordsResponse: - """Post-rpc interceptor for list_answer_records - - Override in a subclass to manipulate the response - after it is returned by the AnswerRecords server but before - it is returned to user code. - """ - return response - def pre_update_answer_record(self, request: gcd_answer_record.UpdateAnswerRecordRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[gcd_answer_record.UpdateAnswerRecordRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for update_answer_record - - Override in a subclass to manipulate the request or metadata - before they are sent to the AnswerRecords server. - """ - return request, metadata - - def post_update_answer_record(self, response: gcd_answer_record.AnswerRecord) -> gcd_answer_record.AnswerRecord: - """Post-rpc interceptor for update_answer_record - - Override in a subclass to manipulate the response - after it is returned by the AnswerRecords server but before - it is returned to user code. - """ - return response - - def pre_get_location( - self, request: locations_pb2.GetLocationRequest, metadata: Sequence[Tuple[str, str]] - ) -> Tuple[locations_pb2.GetLocationRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for get_location - - Override in a subclass to manipulate the request or metadata - before they are sent to the AnswerRecords server. - """ - return request, metadata - - def post_get_location( - self, response: locations_pb2.Location - ) -> locations_pb2.Location: - """Post-rpc interceptor for get_location - - Override in a subclass to manipulate the response - after it is returned by the AnswerRecords server but before - it is returned to user code. - """ - return response - def pre_list_locations( - self, request: locations_pb2.ListLocationsRequest, metadata: Sequence[Tuple[str, str]] - ) -> Tuple[locations_pb2.ListLocationsRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for list_locations - - Override in a subclass to manipulate the request or metadata - before they are sent to the AnswerRecords server. - """ - return request, metadata - - def post_list_locations( - self, response: locations_pb2.ListLocationsResponse - ) -> locations_pb2.ListLocationsResponse: - """Post-rpc interceptor for list_locations - - Override in a subclass to manipulate the response - after it is returned by the AnswerRecords server but before - it is returned to user code. - """ - return response - def pre_cancel_operation( - self, request: operations_pb2.CancelOperationRequest, metadata: Sequence[Tuple[str, str]] - ) -> Tuple[operations_pb2.CancelOperationRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for cancel_operation - - Override in a subclass to manipulate the request or metadata - before they are sent to the AnswerRecords server. - """ - return request, metadata - - def post_cancel_operation( - self, response: None - ) -> None: - """Post-rpc interceptor for cancel_operation - - Override in a subclass to manipulate the response - after it is returned by the AnswerRecords server but before - it is returned to user code. - """ - return response - def pre_get_operation( - self, request: operations_pb2.GetOperationRequest, metadata: Sequence[Tuple[str, str]] - ) -> Tuple[operations_pb2.GetOperationRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for get_operation - - Override in a subclass to manipulate the request or metadata - before they are sent to the AnswerRecords server. - """ - return request, metadata - - def post_get_operation( - self, response: operations_pb2.Operation - ) -> operations_pb2.Operation: - """Post-rpc interceptor for get_operation - - Override in a subclass to manipulate the response - after it is returned by the AnswerRecords server but before - it is returned to user code. - """ - return response - def pre_list_operations( - self, request: operations_pb2.ListOperationsRequest, metadata: Sequence[Tuple[str, str]] - ) -> Tuple[operations_pb2.ListOperationsRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for list_operations - - Override in a subclass to manipulate the request or metadata - before they are sent to the AnswerRecords server. - """ - return request, metadata - - def post_list_operations( - self, response: operations_pb2.ListOperationsResponse - ) -> operations_pb2.ListOperationsResponse: - """Post-rpc interceptor for list_operations - - Override in a subclass to manipulate the response - after it is returned by the AnswerRecords server but before - it is returned to user code. - """ - return response - - -@dataclasses.dataclass -class AnswerRecordsRestStub: - _session: AuthorizedSession - _host: str - _interceptor: AnswerRecordsRestInterceptor - - -class AnswerRecordsRestTransport(AnswerRecordsTransport): - """REST backend transport for AnswerRecords. - - Service for managing - [AnswerRecords][google.cloud.dialogflow.v2.AnswerRecord]. - - 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 JSON representations of protocol buffers over HTTP/1.1 - - """ - - def __init__(self, *, - host: str = 'dialogflow.googleapis.com', - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - client_cert_source_for_mtls: Optional[Callable[[ - ], Tuple[bytes, bytes]]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - url_scheme: str = 'https', - interceptor: Optional[AnswerRecordsRestInterceptor] = None, - api_audience: Optional[str] = None, - ) -> 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 ignored if ``channel`` is provided. - scopes (Optional(Sequence[str])): A list of scopes. This argument is - ignored if ``channel`` is provided. - client_cert_source_for_mtls (Callable[[], Tuple[bytes, bytes]]): Client - certificate to configure mutual TLS HTTP channel. It is ignored - if ``channel`` is provided. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you are developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - url_scheme: the protocol scheme for the API endpoint. Normally - "https", but for testing or local servers, - "http" can be specified. - """ - # Run the base constructor - # TODO(yon-mg): resolve other ctor params i.e. scopes, quota, etc. - # TODO: When custom host (api_endpoint) is set, `scopes` must *also* be set on the - # credentials object - maybe_url_match = re.match("^(?Phttp(?:s)?://)?(?P.*)$", host) - if maybe_url_match is None: - raise ValueError(f"Unexpected hostname structure: {host}") # pragma: NO COVER - - url_match_items = maybe_url_match.groupdict() - - host = f"{url_scheme}://{host}" if not url_match_items["scheme"] else host - - super().__init__( - host=host, - credentials=credentials, - client_info=client_info, - always_use_jwt_access=always_use_jwt_access, - api_audience=api_audience - ) - self._session = AuthorizedSession( - self._credentials, default_host=self.DEFAULT_HOST) - if client_cert_source_for_mtls: - self._session.configure_mtls_channel(client_cert_source_for_mtls) - self._interceptor = interceptor or AnswerRecordsRestInterceptor() - self._prep_wrapped_messages(client_info) - - class _ListAnswerRecords(AnswerRecordsRestStub): - def __hash__(self): - return hash("ListAnswerRecords") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: answer_record.ListAnswerRecordsRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> answer_record.ListAnswerRecordsResponse: - r"""Call the list answer records method over HTTP. - - Args: - request (~.answer_record.ListAnswerRecordsRequest): - The request object. Request message for - [AnswerRecords.ListAnswerRecords][google.cloud.dialogflow.v2.AnswerRecords.ListAnswerRecords]. - 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: - ~.answer_record.ListAnswerRecordsResponse: - Response message for - [AnswerRecords.ListAnswerRecords][google.cloud.dialogflow.v2.AnswerRecords.ListAnswerRecords]. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v2/{parent=projects/*}/answerRecords', - }, -{ - 'method': 'get', - 'uri': '/v2/{parent=projects/*/locations/*}/answerRecords', - }, - ] - request, metadata = self._interceptor.pre_list_answer_records(request, metadata) - pb_request = answer_record.ListAnswerRecordsRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - including_default_value_fields=False, - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = answer_record.ListAnswerRecordsResponse() - pb_resp = answer_record.ListAnswerRecordsResponse.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_list_answer_records(resp) - return resp - - class _UpdateAnswerRecord(AnswerRecordsRestStub): - def __hash__(self): - return hash("UpdateAnswerRecord") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - "updateMask" : {}, } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: gcd_answer_record.UpdateAnswerRecordRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> gcd_answer_record.AnswerRecord: - r"""Call the update answer record method over HTTP. - - Args: - request (~.gcd_answer_record.UpdateAnswerRecordRequest): - The request object. Request message for - [AnswerRecords.UpdateAnswerRecord][google.cloud.dialogflow.v2.AnswerRecords.UpdateAnswerRecord]. - 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: - ~.gcd_answer_record.AnswerRecord: - Answer records are records to manage answer history and - feedbacks for Dialogflow. - - Currently, answer record includes: - - - human agent assistant article suggestion - - human agent assistant faq article - - It doesn't include: - - - ``DetectIntent`` intent matching - - ``DetectIntent`` knowledge - - Answer records are not related to the conversation - history in the Dialogflow Console. A Record is generated - even when the end-user disables conversation history in - the console. Records are created when there's a human - agent assistant suggestion generated. - - A typical workflow for customers provide feedback to an - answer is: - - 1. For human agent assistant, customers get suggestion - via ListSuggestions API. Together with 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. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'patch', - 'uri': '/v2/{answer_record.name=projects/*/answerRecords/*}', - 'body': 'answer_record', - }, -{ - 'method': 'patch', - 'uri': '/v2/{answer_record.name=projects/*/locations/*/answerRecords/*}', - 'body': 'answer_record', - }, - ] - request, metadata = self._interceptor.pre_update_answer_record(request, metadata) - pb_request = gcd_answer_record.UpdateAnswerRecordRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request['body'], - including_default_value_fields=False, - use_integers_for_enums=True - ) - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - including_default_value_fields=False, - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = gcd_answer_record.AnswerRecord() - pb_resp = gcd_answer_record.AnswerRecord.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_update_answer_record(resp) - return resp - - @property - def list_answer_records(self) -> Callable[ - [answer_record.ListAnswerRecordsRequest], - answer_record.ListAnswerRecordsResponse]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._ListAnswerRecords(self._session, self._host, self._interceptor) # type: ignore - - @property - def update_answer_record(self) -> Callable[ - [gcd_answer_record.UpdateAnswerRecordRequest], - gcd_answer_record.AnswerRecord]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._UpdateAnswerRecord(self._session, self._host, self._interceptor) # type: ignore - - @property - def get_location(self): - return self._GetLocation(self._session, self._host, self._interceptor) # type: ignore - - class _GetLocation(AnswerRecordsRestStub): - def __call__(self, - request: locations_pb2.GetLocationRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> locations_pb2.Location: - - r"""Call the get location method over HTTP. - - Args: - request (locations_pb2.GetLocationRequest): - The request object for GetLocation method. - 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: - locations_pb2.Location: Response from GetLocation method. - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v2/{name=projects/*/locations/*}', - }, - ] - - request, metadata = self._interceptor.pre_get_location(request, metadata) - request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode( - http_options, **request_kwargs) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json.dumps(transcoded_request['query_params'])) - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - resp = locations_pb2.Location() - resp = json_format.Parse(response.content.decode("utf-8"), resp) - resp = self._interceptor.post_get_location(resp) - return resp - - @property - def list_locations(self): - return self._ListLocations(self._session, self._host, self._interceptor) # type: ignore - - class _ListLocations(AnswerRecordsRestStub): - def __call__(self, - request: locations_pb2.ListLocationsRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> locations_pb2.ListLocationsResponse: - - r"""Call the list locations method over HTTP. - - Args: - request (locations_pb2.ListLocationsRequest): - The request object for ListLocations method. - 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: - locations_pb2.ListLocationsResponse: Response from ListLocations method. - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v2/{name=projects/*}/locations', - }, - ] - - request, metadata = self._interceptor.pre_list_locations(request, metadata) - request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode( - http_options, **request_kwargs) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json.dumps(transcoded_request['query_params'])) - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - resp = locations_pb2.ListLocationsResponse() - resp = json_format.Parse(response.content.decode("utf-8"), resp) - resp = self._interceptor.post_list_locations(resp) - return resp - - @property - def cancel_operation(self): - return self._CancelOperation(self._session, self._host, self._interceptor) # type: ignore - - class _CancelOperation(AnswerRecordsRestStub): - def __call__(self, - request: operations_pb2.CancelOperationRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> None: - - r"""Call the cancel operation method over HTTP. - - Args: - request (operations_pb2.CancelOperationRequest): - The request object for CancelOperation method. - 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. - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'post', - 'uri': '/v2/{name=projects/*/operations/*}:cancel', - }, -{ - 'method': 'post', - 'uri': '/v2/{name=projects/*/locations/*/operations/*}:cancel', - }, - ] - - request, metadata = self._interceptor.pre_cancel_operation(request, metadata) - request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode( - http_options, **request_kwargs) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json.dumps(transcoded_request['query_params'])) - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - return self._interceptor.post_cancel_operation(None) - - @property - def get_operation(self): - return self._GetOperation(self._session, self._host, self._interceptor) # type: ignore - - class _GetOperation(AnswerRecordsRestStub): - def __call__(self, - request: operations_pb2.GetOperationRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> operations_pb2.Operation: - - r"""Call the get operation method over HTTP. - - Args: - request (operations_pb2.GetOperationRequest): - The request object for GetOperation method. - 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: - operations_pb2.Operation: Response from GetOperation method. - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v2/{name=projects/*/operations/*}', - }, -{ - 'method': 'get', - 'uri': '/v2/{name=projects/*/locations/*/operations/*}', - }, - ] - - request, metadata = self._interceptor.pre_get_operation(request, metadata) - request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode( - http_options, **request_kwargs) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json.dumps(transcoded_request['query_params'])) - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - resp = operations_pb2.Operation() - resp = json_format.Parse(response.content.decode("utf-8"), resp) - resp = self._interceptor.post_get_operation(resp) - return resp - - @property - def list_operations(self): - return self._ListOperations(self._session, self._host, self._interceptor) # type: ignore - - class _ListOperations(AnswerRecordsRestStub): - def __call__(self, - request: operations_pb2.ListOperationsRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> operations_pb2.ListOperationsResponse: - - r"""Call the list operations method over HTTP. - - Args: - request (operations_pb2.ListOperationsRequest): - The request object for ListOperations method. - 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: - operations_pb2.ListOperationsResponse: Response from ListOperations method. - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v2/{name=projects/*}/operations', - }, -{ - 'method': 'get', - 'uri': '/v2/{name=projects/*/locations/*}/operations', - }, - ] - - request, metadata = self._interceptor.pre_list_operations(request, metadata) - request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode( - http_options, **request_kwargs) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json.dumps(transcoded_request['query_params'])) - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - resp = operations_pb2.ListOperationsResponse() - resp = json_format.Parse(response.content.decode("utf-8"), resp) - resp = self._interceptor.post_list_operations(resp) - return resp - - @property - def kind(self) -> str: - return "rest" - - def close(self): - self._session.close() - - -__all__=( - 'AnswerRecordsRestTransport', -) diff --git a/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/contexts/__init__.py b/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/contexts/__init__.py deleted file mode 100644 index 3d4b75847..000000000 --- a/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/contexts/__init__.py +++ /dev/null @@ -1,22 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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 ContextsClient -from .async_client import ContextsAsyncClient - -__all__ = ( - 'ContextsClient', - 'ContextsAsyncClient', -) diff --git a/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/contexts/async_client.py b/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/contexts/async_client.py deleted file mode 100644 index a54299f33..000000000 --- a/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/contexts/async_client.py +++ /dev/null @@ -1,1152 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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, Mapping, MutableMapping, MutableSequence, Optional, Sequence, Tuple, Type, Union - -from google.cloud.dialogflow_v2 import gapic_version as package_version - -from google.api_core.client_options import ClientOptions -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import retry as retries -from google.auth import credentials as ga_credentials # type: ignore -from google.oauth2 import service_account # type: ignore - -try: - OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] -except AttributeError: # pragma: NO COVER - OptionalRetry = Union[retries.Retry, object] # 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.cloud.location import locations_pb2 # type: ignore -from google.longrunning import operations_pb2 -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 - - -class ContextsAsyncClient: - """Service for managing [Contexts][google.cloud.dialogflow.v2.Context].""" - - _client: ContextsClient - - DEFAULT_ENDPOINT = ContextsClient.DEFAULT_ENDPOINT - DEFAULT_MTLS_ENDPOINT = ContextsClient.DEFAULT_MTLS_ENDPOINT - - 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) - - @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: - ContextsAsyncClient: The constructed client. - """ - return ContextsClient.from_service_account_info.__func__(ContextsAsyncClient, 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: - ContextsAsyncClient: The constructed client. - """ - return ContextsClient.from_service_account_file.__func__(ContextsAsyncClient, filename, *args, **kwargs) # type: ignore - - from_service_account_json = from_service_account_file - - @classmethod - def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[ClientOptions] = None): - """Return the API endpoint and client cert source for mutual TLS. - - The client cert source is determined in the following order: - (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the - client cert source is None. - (2) if `client_options.client_cert_source` is provided, use the provided one; if the - default client cert source exists, use the default one; otherwise the client cert - source is None. - - The API endpoint is determined in the following order: - (1) if `client_options.api_endpoint` if provided, use the provided one. - (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the - default mTLS endpoint; if the environment variable is "never", use the default API - endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise - use the default API endpoint. - - More details can be found at https://google.aip.dev/auth/4114. - - Args: - client_options (google.api_core.client_options.ClientOptions): Custom options for the - client. Only the `api_endpoint` and `client_cert_source` properties may be used - in this method. - - Returns: - Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the - client cert source to use. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If any errors happen. - """ - return ContextsClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore - - @property - def transport(self) -> ContextsTransport: - """Returns the transport used by the client instance. - - Returns: - ContextsTransport: The transport used by the client instance. - """ - return self._client.transport - - get_transport_class = functools.partial(type(ContextsClient).get_transport_class, type(ContextsClient)) - - def __init__(self, *, - credentials: Optional[ga_credentials.Credentials] = None, - transport: Union[str, ContextsTransport] = "grpc_asyncio", - client_options: Optional[ClientOptions] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the contexts 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, ~.ContextsTransport]): 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 = ContextsClient( - credentials=credentials, - transport=transport, - client_options=client_options, - client_info=client_info, - - ) - - async def list_contexts(self, - request: Optional[Union[context.ListContextsRequest, dict]] = None, - *, - parent: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListContextsAsyncPager: - r"""Returns the list of all contexts in the specified - session. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import dialogflow_v2 - - async def sample_list_contexts(): - # Create a client - client = dialogflow_v2.ContextsAsyncClient() - - # Initialize request argument(s) - request = dialogflow_v2.ListContextsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_contexts(request=request) - - # Handle the response - async for response in page_result: - print(response) - - Args: - request (Optional[Union[google.cloud.dialogflow_v2.types.ListContextsRequest, dict]]): - The request object. The request message for - [Contexts.ListContexts][google.cloud.dialogflow.v2.Contexts.ListContexts]. - parent (:class:`str`): - Required. The session to list all contexts from. Format: - ``projects//agent/sessions/`` or - ``projects//agent/environments//users//sessions/``. - If ``Environment ID`` is not specified, we assume - default 'draft' environment. If ``User ID`` is not - specified, we assume default '-' user. - - 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.contexts.pagers.ListContextsAsyncPager: - The response message for - [Contexts.ListContexts][google.cloud.dialogflow.v2.Contexts.ListContexts]. - - Iterating over this object will yield results and - resolve additional pages automatically. - - """ - # Create or coerce a protobuf request object. - # Quick 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 = context.ListContextsRequest(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_contexts, - 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.ListContextsAsyncPager( - method=rpc, - request=request, - response=response, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def get_context(self, - request: Optional[Union[context.GetContextRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> context.Context: - r"""Retrieves the specified context. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import dialogflow_v2 - - async def sample_get_context(): - # Create a client - client = dialogflow_v2.ContextsAsyncClient() - - # Initialize request argument(s) - request = dialogflow_v2.GetContextRequest( - name="name_value", - ) - - # Make the request - response = await client.get_context(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.dialogflow_v2.types.GetContextRequest, dict]]): - The request object. The request message for - [Contexts.GetContext][google.cloud.dialogflow.v2.Contexts.GetContext]. - name (:class:`str`): - Required. The name of the context. Format: - ``projects//agent/sessions//contexts/`` - or - ``projects//agent/environments//users//sessions//contexts/``. - If ``Environment ID`` is not specified, we assume - default 'draft' environment. If ``User ID`` is not - specified, we assume default '-' user. - - 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.Context: - Dialogflow contexts are similar to natural language context. If a person says - to you "they are orange", you need context in order - to understand what "they" is referring to. Similarly, - for Dialogflow to handle an end-user expression like - that, it needs to be provided with context in order - to correctly match an intent. - - Using contexts, you can control the flow of a - conversation. You can configure contexts for an - intent by setting input and output contexts, which - are identified by string names. When an intent is - matched, any configured output contexts for that - intent become active. While any contexts are active, - Dialogflow is more likely to match intents that are - configured with input contexts that correspond to the - currently active contexts. - - For more information about context, see the [Contexts - guide](\ https://cloud.google.com/dialogflow/docs/contexts-overview). - - """ - # Create or coerce a protobuf request object. - # Quick 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 = context.GetContextRequest(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_context, - 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_context(self, - request: Optional[Union[gcd_context.CreateContextRequest, dict]] = None, - *, - parent: Optional[str] = None, - context: Optional[gcd_context.Context] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gcd_context.Context: - r"""Creates a context. - If the specified context already exists, overrides the - context. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import dialogflow_v2 - - async def sample_create_context(): - # Create a client - client = dialogflow_v2.ContextsAsyncClient() - - # Initialize request argument(s) - context = dialogflow_v2.Context() - context.name = "name_value" - - request = dialogflow_v2.CreateContextRequest( - parent="parent_value", - context=context, - ) - - # Make the request - response = await client.create_context(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.dialogflow_v2.types.CreateContextRequest, dict]]): - The request object. The request message for - [Contexts.CreateContext][google.cloud.dialogflow.v2.Contexts.CreateContext]. - parent (:class:`str`): - Required. The session to create a context for. Format: - ``projects//agent/sessions/`` or - ``projects//agent/environments//users//sessions/``. - If ``Environment ID`` is not specified, we assume - default 'draft' environment. If ``User ID`` is not - specified, we assume default '-' user. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - context (:class:`google.cloud.dialogflow_v2.types.Context`): - Required. The context to create. - 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. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.dialogflow_v2.types.Context: - Dialogflow contexts are similar to natural language context. If a person says - to you "they are orange", you need context in order - to understand what "they" is referring to. Similarly, - for Dialogflow to handle an end-user expression like - that, it needs to be provided with context in order - to correctly match an intent. - - Using contexts, you can control the flow of a - conversation. You can configure contexts for an - intent by setting input and output contexts, which - are identified by string names. When an intent is - matched, any configured output contexts for that - intent become active. While any contexts are active, - Dialogflow is more likely to match intents that are - configured with input contexts that correspond to the - currently active contexts. - - For more information about context, see the [Contexts - guide](\ https://cloud.google.com/dialogflow/docs/contexts-overview). - - """ - # Create or coerce a protobuf request object. - # Quick 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, context]) - 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_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: - request.context = context - - # 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_context, - 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_context(self, - request: Optional[Union[gcd_context.UpdateContextRequest, dict]] = None, - *, - context: Optional[gcd_context.Context] = None, - update_mask: Optional[field_mask_pb2.FieldMask] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gcd_context.Context: - r"""Updates the specified context. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import dialogflow_v2 - - async def sample_update_context(): - # Create a client - client = dialogflow_v2.ContextsAsyncClient() - - # Initialize request argument(s) - context = dialogflow_v2.Context() - context.name = "name_value" - - request = dialogflow_v2.UpdateContextRequest( - context=context, - ) - - # Make the request - response = await client.update_context(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.dialogflow_v2.types.UpdateContextRequest, dict]]): - The request object. The request message for - [Contexts.UpdateContext][google.cloud.dialogflow.v2.Contexts.UpdateContext]. - context (:class:`google.cloud.dialogflow_v2.types.Context`): - Required. The context to update. - This corresponds to the ``context`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - update_mask (:class:`google.protobuf.field_mask_pb2.FieldMask`): - Optional. 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.Context: - Dialogflow contexts are similar to natural language context. If a person says - to you "they are orange", you need context in order - to understand what "they" is referring to. Similarly, - for Dialogflow to handle an end-user expression like - that, it needs to be provided with context in order - to correctly match an intent. - - Using contexts, you can control the flow of a - conversation. You can configure contexts for an - intent by setting input and output contexts, which - are identified by string names. When an intent is - matched, any configured output contexts for that - intent become active. While any contexts are active, - Dialogflow is more likely to match intents that are - configured with input contexts that correspond to the - currently active contexts. - - For more information about context, see the [Contexts - guide](\ https://cloud.google.com/dialogflow/docs/contexts-overview). - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([context, 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_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: - 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_context, - 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(( - ("context.name", request.context.name), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def delete_context(self, - request: Optional[Union[context.DeleteContextRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> None: - r"""Deletes the specified context. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import dialogflow_v2 - - async def sample_delete_context(): - # Create a client - client = dialogflow_v2.ContextsAsyncClient() - - # Initialize request argument(s) - request = dialogflow_v2.DeleteContextRequest( - name="name_value", - ) - - # Make the request - await client.delete_context(request=request) - - Args: - request (Optional[Union[google.cloud.dialogflow_v2.types.DeleteContextRequest, dict]]): - The request object. The request message for - [Contexts.DeleteContext][google.cloud.dialogflow.v2.Contexts.DeleteContext]. - name (:class:`str`): - Required. The name of the context to delete. Format: - ``projects//agent/sessions//contexts/`` - or - ``projects//agent/environments//users//sessions//contexts/``. - If ``Environment ID`` is not specified, we assume - default 'draft' environment. If ``User ID`` is not - specified, we assume default '-' user. - - 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. - # Quick 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 = context.DeleteContextRequest(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_context, - 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 delete_all_contexts(self, - request: Optional[Union[context.DeleteAllContextsRequest, dict]] = None, - *, - parent: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> None: - r"""Deletes all active contexts in the specified session. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import dialogflow_v2 - - async def sample_delete_all_contexts(): - # Create a client - client = dialogflow_v2.ContextsAsyncClient() - - # Initialize request argument(s) - request = dialogflow_v2.DeleteAllContextsRequest( - parent="parent_value", - ) - - # Make the request - await client.delete_all_contexts(request=request) - - Args: - request (Optional[Union[google.cloud.dialogflow_v2.types.DeleteAllContextsRequest, dict]]): - The request object. The request message for - [Contexts.DeleteAllContexts][google.cloud.dialogflow.v2.Contexts.DeleteAllContexts]. - parent (:class:`str`): - Required. The name of the session to delete all contexts - from. Format: - ``projects//agent/sessions/`` or - ``projects//agent/environments//users//sessions/``. - If ``Environment ID`` is not specified we assume default - 'draft' environment. If ``User ID`` is not specified, we - assume default '-' user. - - 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. - """ - # Create or coerce a protobuf request object. - # Quick 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 = context.DeleteAllContextsRequest(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.delete_all_contexts, - 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. - await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - async def list_operations( - self, - request: Optional[operations_pb2.ListOperationsRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operations_pb2.ListOperationsResponse: - r"""Lists operations that match the specified filter in the request. - - Args: - request (:class:`~.operations_pb2.ListOperationsRequest`): - The request object. Request message for - `ListOperations` method. - 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: - ~.operations_pb2.ListOperationsResponse: - Response message for ``ListOperations`` method. - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = operations_pb2.ListOperationsRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._client._transport.list_operations, - 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 get_operation( - self, - request: Optional[operations_pb2.GetOperationRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operations_pb2.Operation: - r"""Gets the latest state of a long-running operation. - - Args: - request (:class:`~.operations_pb2.GetOperationRequest`): - The request object. Request message for - `GetOperation` method. - 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: - ~.operations_pb2.Operation: - An ``Operation`` object. - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = operations_pb2.GetOperationRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._client._transport.get_operation, - 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 cancel_operation( - self, - request: Optional[operations_pb2.CancelOperationRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> None: - r"""Starts asynchronous cancellation on a long-running operation. - - The server makes a best effort to cancel the operation, but success - is not guaranteed. If the server doesn't support this method, it returns - `google.rpc.Code.UNIMPLEMENTED`. - - Args: - request (:class:`~.operations_pb2.CancelOperationRequest`): - The request object. Request message for - `CancelOperation` method. - 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: - None - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = operations_pb2.CancelOperationRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._client._transport.cancel_operation, - 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_location( - self, - request: Optional[locations_pb2.GetLocationRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> locations_pb2.Location: - r"""Gets information about a location. - - Args: - request (:class:`~.location_pb2.GetLocationRequest`): - The request object. Request message for - `GetLocation` method. - 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: - ~.location_pb2.Location: - Location object. - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = locations_pb2.GetLocationRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._client._transport.get_location, - 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 list_locations( - self, - request: Optional[locations_pb2.ListLocationsRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> locations_pb2.ListLocationsResponse: - r"""Lists information about the supported locations for this service. - - Args: - request (:class:`~.location_pb2.ListLocationsRequest`): - The request object. Request message for - `ListLocations` method. - 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: - ~.location_pb2.ListLocationsResponse: - Response message for ``ListLocations`` method. - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = locations_pb2.ListLocationsRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._client._transport.list_locations, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("name", request.name),)), - ) - - # Send the request. - response = await rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - async def __aenter__(self): - return self - - async def __aexit__(self, exc_type, exc, tb): - await self.transport.close() - -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) - - -__all__ = ( - "ContextsAsyncClient", -) diff --git a/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/contexts/client.py b/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/contexts/client.py deleted file mode 100644 index 6cfc98edb..000000000 --- a/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/contexts/client.py +++ /dev/null @@ -1,1351 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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 os -import re -from typing import Dict, Mapping, MutableMapping, MutableSequence, Optional, Sequence, Tuple, Type, Union, cast - -from google.cloud.dialogflow_v2 import gapic_version as package_version - -from google.api_core import client_options as client_options_lib -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import retry as retries -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 - -try: - OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] -except AttributeError: # pragma: NO COVER - OptionalRetry = Union[retries.Retry, object] # 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.cloud.location import locations_pb2 # type: ignore -from google.longrunning import operations_pb2 -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 -from .transports.rest import ContextsRestTransport - - -class ContextsClientMeta(type): - """Metaclass for the Contexts 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[ContextsTransport]] - _transport_registry["grpc"] = ContextsGrpcTransport - _transport_registry["grpc_asyncio"] = ContextsGrpcAsyncIOTransport - _transport_registry["rest"] = ContextsRestTransport - - def get_transport_class(cls, - label: Optional[str] = None, - ) -> Type[ContextsTransport]: - """Returns an appropriate transport class. - - Args: - label: The name of the desired transport. If none is - provided, then the first transport in the registry is used. - - Returns: - The transport class to use. - """ - # If a specific transport is requested, return that one. - if label: - return cls._transport_registry[label] - - # No transport is requested; return the default (that is, the first one - # in the dictionary). - return next(iter(cls._transport_registry.values())) - - -class ContextsClient(metaclass=ContextsClientMeta): - """Service for managing [Contexts][google.cloud.dialogflow.v2.Context].""" - - @staticmethod - def _get_default_mtls_endpoint(api_endpoint): - """Converts api endpoint to mTLS endpoint. - - Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to - "*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively. - Args: - api_endpoint (Optional[str]): the api endpoint to convert. - Returns: - str: converted mTLS api endpoint. - """ - if not api_endpoint: - return api_endpoint - - mtls_endpoint_re = re.compile( - r"(?P[^.]+)(?P\.mtls)?(?P\.sandbox)?(?P\.googleapis\.com)?" - ) - - m = mtls_endpoint_re.match(api_endpoint) - name, mtls, sandbox, googledomain = m.groups() - if mtls or not googledomain: - return api_endpoint - - if sandbox: - return api_endpoint.replace( - "sandbox.googleapis.com", "mtls.sandbox.googleapis.com" - ) - - return api_endpoint.replace(".googleapis.com", ".mtls.googleapis.com") - - DEFAULT_ENDPOINT = "dialogflow.googleapis.com" - DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore - DEFAULT_ENDPOINT - ) - - @classmethod - def from_service_account_info(cls, info: dict, *args, **kwargs): - """Creates an instance of this client using the provided credentials - info. - - Args: - info (dict): The service account private key info. - args: Additional arguments to pass to the constructor. - kwargs: Additional arguments to pass to the constructor. - - Returns: - ContextsClient: 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: - ContextsClient: 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) -> ContextsTransport: - """Returns the transport used by the client instance. - - Returns: - ContextsTransport: The transport used by the client - instance. - """ - return self._transport - - @staticmethod - def context_path(project: str,session: str,context: str,) -> str: - """Returns a fully-qualified context string.""" - return "projects/{project}/agent/sessions/{session}/contexts/{context}".format(project=project, session=session, context=context, ) - - @staticmethod - def parse_context_path(path: str) -> Dict[str,str]: - """Parses a context path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/agent/sessions/(?P.+?)/contexts/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_billing_account_path(billing_account: str, ) -> str: - """Returns a fully-qualified billing_account string.""" - return "billingAccounts/{billing_account}".format(billing_account=billing_account, ) - - @staticmethod - def parse_common_billing_account_path(path: str) -> Dict[str,str]: - """Parse a billing_account path into its component segments.""" - m = re.match(r"^billingAccounts/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_folder_path(folder: str, ) -> str: - """Returns a fully-qualified folder string.""" - return "folders/{folder}".format(folder=folder, ) - - @staticmethod - def parse_common_folder_path(path: str) -> Dict[str,str]: - """Parse a folder path into its component segments.""" - m = re.match(r"^folders/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_organization_path(organization: str, ) -> str: - """Returns a fully-qualified organization string.""" - return "organizations/{organization}".format(organization=organization, ) - - @staticmethod - def parse_common_organization_path(path: str) -> Dict[str,str]: - """Parse a organization path into its component segments.""" - m = re.match(r"^organizations/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_project_path(project: str, ) -> str: - """Returns a fully-qualified project string.""" - return "projects/{project}".format(project=project, ) - - @staticmethod - def parse_common_project_path(path: str) -> Dict[str,str]: - """Parse a project path into its component segments.""" - m = re.match(r"^projects/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_location_path(project: str, location: str, ) -> str: - """Returns a fully-qualified location string.""" - return "projects/{project}/locations/{location}".format(project=project, location=location, ) - - @staticmethod - def parse_common_location_path(path: str) -> Dict[str,str]: - """Parse a location path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)$", path) - return m.groupdict() if m else {} - - @classmethod - def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[client_options_lib.ClientOptions] = None): - """Return the API endpoint and client cert source for mutual TLS. - - The client cert source is determined in the following order: - (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the - client cert source is None. - (2) if `client_options.client_cert_source` is provided, use the provided one; if the - default client cert source exists, use the default one; otherwise the client cert - source is None. - - The API endpoint is determined in the following order: - (1) if `client_options.api_endpoint` if provided, use the provided one. - (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the - default mTLS endpoint; if the environment variable is "never", use the default API - endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise - use the default API endpoint. - - More details can be found at https://google.aip.dev/auth/4114. - - Args: - client_options (google.api_core.client_options.ClientOptions): Custom options for the - client. Only the `api_endpoint` and `client_cert_source` properties may be used - in this method. - - Returns: - Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the - client cert source to use. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If any errors happen. - """ - if client_options is None: - client_options = client_options_lib.ClientOptions() - use_client_cert = os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false") - use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") - if use_client_cert not in ("true", "false"): - raise ValueError("Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`") - if use_mtls_endpoint not in ("auto", "never", "always"): - raise MutualTLSChannelError("Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`") - - # Figure out the client cert source to use. - client_cert_source = None - if use_client_cert == "true": - if client_options.client_cert_source: - client_cert_source = client_options.client_cert_source - elif mtls.has_default_client_cert_source(): - client_cert_source = mtls.default_client_cert_source() - - # Figure out which api endpoint to use. - if client_options.api_endpoint is not None: - api_endpoint = client_options.api_endpoint - elif use_mtls_endpoint == "always" or (use_mtls_endpoint == "auto" and client_cert_source): - api_endpoint = cls.DEFAULT_MTLS_ENDPOINT - else: - api_endpoint = cls.DEFAULT_ENDPOINT - - return api_endpoint, client_cert_source - - def __init__(self, *, - credentials: Optional[ga_credentials.Credentials] = None, - transport: Optional[Union[str, ContextsTransport]] = None, - client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the contexts 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, ContextsTransport]): The - transport to use. If set to None, a transport is chosen - automatically. - client_options (Optional[Union[google.api_core.client_options.ClientOptions, dict]]): 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() - client_options = cast(client_options_lib.ClientOptions, client_options) - - api_endpoint, client_cert_source_func = self.get_mtls_endpoint_and_cert_source(client_options) - - api_key_value = getattr(client_options, "api_key", None) - if api_key_value and credentials: - raise ValueError("client_options.api_key and credentials are mutually exclusive") - - # 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, ContextsTransport): - # transport is a ContextsTransport instance. - if credentials or client_options.credentials_file or api_key_value: - 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: - import google.auth._default # type: ignore - - if api_key_value and hasattr(google.auth._default, "get_api_key_credentials"): - credentials = google.auth._default.get_api_key_credentials(api_key_value) - - Transport = type(self).get_transport_class(transport) - self._transport = Transport( - credentials=credentials, - credentials_file=client_options.credentials_file, - host=api_endpoint, - scopes=client_options.scopes, - client_cert_source_for_mtls=client_cert_source_func, - quota_project_id=client_options.quota_project_id, - client_info=client_info, - always_use_jwt_access=True, - api_audience=client_options.api_audience, - ) - - def list_contexts(self, - request: Optional[Union[context.ListContextsRequest, dict]] = None, - *, - parent: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListContextsPager: - r"""Returns the list of all contexts in the specified - session. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import dialogflow_v2 - - def sample_list_contexts(): - # Create a client - client = dialogflow_v2.ContextsClient() - - # Initialize request argument(s) - request = dialogflow_v2.ListContextsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_contexts(request=request) - - # Handle the response - for response in page_result: - print(response) - - Args: - request (Union[google.cloud.dialogflow_v2.types.ListContextsRequest, dict]): - The request object. The request message for - [Contexts.ListContexts][google.cloud.dialogflow.v2.Contexts.ListContexts]. - parent (str): - Required. The session to list all contexts from. Format: - ``projects//agent/sessions/`` or - ``projects//agent/environments//users//sessions/``. - If ``Environment ID`` is not specified, we assume - default 'draft' environment. If ``User ID`` is not - specified, we assume default '-' user. - - 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.contexts.pagers.ListContextsPager: - The response message for - [Contexts.ListContexts][google.cloud.dialogflow.v2.Contexts.ListContexts]. - - Iterating over this object will yield results and - resolve additional pages automatically. - - """ - # Create or coerce a protobuf request object. - # Quick 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 context.ListContextsRequest. - # There's no risk of modifying the input as we've already verified - # 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 - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.list_contexts] - - # 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.ListContextsPager( - method=rpc, - request=request, - response=response, - metadata=metadata, - ) - - # Done; return the response. - return response - - def get_context(self, - request: Optional[Union[context.GetContextRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> context.Context: - r"""Retrieves the specified context. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import dialogflow_v2 - - def sample_get_context(): - # Create a client - client = dialogflow_v2.ContextsClient() - - # Initialize request argument(s) - request = dialogflow_v2.GetContextRequest( - name="name_value", - ) - - # Make the request - response = client.get_context(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.dialogflow_v2.types.GetContextRequest, dict]): - The request object. The request message for - [Contexts.GetContext][google.cloud.dialogflow.v2.Contexts.GetContext]. - name (str): - Required. The name of the context. Format: - ``projects//agent/sessions//contexts/`` - or - ``projects//agent/environments//users//sessions//contexts/``. - If ``Environment ID`` is not specified, we assume - default 'draft' environment. If ``User ID`` is not - specified, we assume default '-' user. - - 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.Context: - Dialogflow contexts are similar to natural language context. If a person says - to you "they are orange", you need context in order - to understand what "they" is referring to. Similarly, - for Dialogflow to handle an end-user expression like - that, it needs to be provided with context in order - to correctly match an intent. - - Using contexts, you can control the flow of a - conversation. You can configure contexts for an - intent by setting input and output contexts, which - are identified by string names. When an intent is - matched, any configured output contexts for that - intent become active. While any contexts are active, - Dialogflow is more likely to match intents that are - configured with input contexts that correspond to the - currently active contexts. - - For more information about context, see the [Contexts - guide](\ https://cloud.google.com/dialogflow/docs/contexts-overview). - - """ - # Create or coerce a protobuf request object. - # Quick 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 context.GetContextRequest. - # There's no risk of modifying the input as we've already verified - # 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 - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.get_context] - - # 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_context(self, - request: Optional[Union[gcd_context.CreateContextRequest, dict]] = None, - *, - parent: Optional[str] = None, - context: Optional[gcd_context.Context] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gcd_context.Context: - r"""Creates a context. - If the specified context already exists, overrides the - context. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import dialogflow_v2 - - def sample_create_context(): - # Create a client - client = dialogflow_v2.ContextsClient() - - # Initialize request argument(s) - context = dialogflow_v2.Context() - context.name = "name_value" - - request = dialogflow_v2.CreateContextRequest( - parent="parent_value", - context=context, - ) - - # Make the request - response = client.create_context(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.dialogflow_v2.types.CreateContextRequest, dict]): - The request object. The request message for - [Contexts.CreateContext][google.cloud.dialogflow.v2.Contexts.CreateContext]. - parent (str): - Required. The session to create a context for. Format: - ``projects//agent/sessions/`` or - ``projects//agent/environments//users//sessions/``. - If ``Environment ID`` is not specified, we assume - default 'draft' environment. If ``User ID`` is not - specified, we assume default '-' user. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - context (google.cloud.dialogflow_v2.types.Context): - Required. The context to create. - 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. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.dialogflow_v2.types.Context: - Dialogflow contexts are similar to natural language context. If a person says - to you "they are orange", you need context in order - to understand what "they" is referring to. Similarly, - for Dialogflow to handle an end-user expression like - that, it needs to be provided with context in order - to correctly match an intent. - - Using contexts, you can control the flow of a - conversation. You can configure contexts for an - intent by setting input and output contexts, which - are identified by string names. When an intent is - matched, any configured output contexts for that - intent become active. While any contexts are active, - Dialogflow is more likely to match intents that are - configured with input contexts that correspond to the - currently active contexts. - - For more information about context, see the [Contexts - guide](\ https://cloud.google.com/dialogflow/docs/contexts-overview). - - """ - # Create or coerce a protobuf request object. - # Quick 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, context]) - 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_context.CreateContextRequest. - # There's no risk of modifying the input as we've already verified - # 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: - request.context = context - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.create_context] - - # 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_context(self, - request: Optional[Union[gcd_context.UpdateContextRequest, dict]] = None, - *, - context: Optional[gcd_context.Context] = None, - update_mask: Optional[field_mask_pb2.FieldMask] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gcd_context.Context: - r"""Updates the specified context. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import dialogflow_v2 - - def sample_update_context(): - # Create a client - client = dialogflow_v2.ContextsClient() - - # Initialize request argument(s) - context = dialogflow_v2.Context() - context.name = "name_value" - - request = dialogflow_v2.UpdateContextRequest( - context=context, - ) - - # Make the request - response = client.update_context(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.dialogflow_v2.types.UpdateContextRequest, dict]): - The request object. The request message for - [Contexts.UpdateContext][google.cloud.dialogflow.v2.Contexts.UpdateContext]. - context (google.cloud.dialogflow_v2.types.Context): - Required. The context to update. - This corresponds to the ``context`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - update_mask (google.protobuf.field_mask_pb2.FieldMask): - Optional. 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.Context: - Dialogflow contexts are similar to natural language context. If a person says - to you "they are orange", you need context in order - to understand what "they" is referring to. Similarly, - for Dialogflow to handle an end-user expression like - that, it needs to be provided with context in order - to correctly match an intent. - - Using contexts, you can control the flow of a - conversation. You can configure contexts for an - intent by setting input and output contexts, which - are identified by string names. When an intent is - matched, any configured output contexts for that - intent become active. While any contexts are active, - Dialogflow is more likely to match intents that are - configured with input contexts that correspond to the - currently active contexts. - - For more information about context, see the [Contexts - guide](\ https://cloud.google.com/dialogflow/docs/contexts-overview). - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([context, 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_context.UpdateContextRequest. - # There's no risk of modifying the input as we've already verified - # 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: - 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_context] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("context.name", request.context.name), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def delete_context(self, - request: Optional[Union[context.DeleteContextRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> None: - r"""Deletes the specified context. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import dialogflow_v2 - - def sample_delete_context(): - # Create a client - client = dialogflow_v2.ContextsClient() - - # Initialize request argument(s) - request = dialogflow_v2.DeleteContextRequest( - name="name_value", - ) - - # Make the request - client.delete_context(request=request) - - Args: - request (Union[google.cloud.dialogflow_v2.types.DeleteContextRequest, dict]): - The request object. The request message for - [Contexts.DeleteContext][google.cloud.dialogflow.v2.Contexts.DeleteContext]. - name (str): - Required. The name of the context to delete. Format: - ``projects//agent/sessions//contexts/`` - or - ``projects//agent/environments//users//sessions//contexts/``. - If ``Environment ID`` is not specified, we assume - default 'draft' environment. If ``User ID`` is not - specified, we assume default '-' user. - - 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. - # Quick 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 context.DeleteContextRequest. - # There's no risk of modifying the input as we've already verified - # 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 - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.delete_context] - - # 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 delete_all_contexts(self, - request: Optional[Union[context.DeleteAllContextsRequest, dict]] = None, - *, - parent: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> None: - r"""Deletes all active contexts in the specified session. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import dialogflow_v2 - - def sample_delete_all_contexts(): - # Create a client - client = dialogflow_v2.ContextsClient() - - # Initialize request argument(s) - request = dialogflow_v2.DeleteAllContextsRequest( - parent="parent_value", - ) - - # Make the request - client.delete_all_contexts(request=request) - - Args: - request (Union[google.cloud.dialogflow_v2.types.DeleteAllContextsRequest, dict]): - The request object. The request message for - [Contexts.DeleteAllContexts][google.cloud.dialogflow.v2.Contexts.DeleteAllContexts]. - parent (str): - Required. The name of the session to delete all contexts - from. Format: - ``projects//agent/sessions/`` or - ``projects//agent/environments//users//sessions/``. - If ``Environment ID`` is not specified we assume default - 'draft' environment. If ``User ID`` is not specified, we - assume default '-' user. - - 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. - """ - # Create or coerce a protobuf request object. - # Quick 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 context.DeleteAllContextsRequest. - # There's no risk of modifying the input as we've already verified - # 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 - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.delete_all_contexts] - - # 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. - rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - def __enter__(self) -> "ContextsClient": - return self - - def __exit__(self, type, value, traceback): - """Releases underlying transport's resources. - - .. warning:: - ONLY use as a context manager if the transport is NOT shared - with other clients! Exiting the with block will CLOSE the transport - and may cause errors in other clients! - """ - self.transport.close() - - def list_operations( - self, - request: Optional[operations_pb2.ListOperationsRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operations_pb2.ListOperationsResponse: - r"""Lists operations that match the specified filter in the request. - - Args: - request (:class:`~.operations_pb2.ListOperationsRequest`): - The request object. Request message for - `ListOperations` method. - 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: - ~.operations_pb2.ListOperationsResponse: - Response message for ``ListOperations`` method. - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = operations_pb2.ListOperationsRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._transport.list_operations, - 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 = rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - def get_operation( - self, - request: Optional[operations_pb2.GetOperationRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operations_pb2.Operation: - r"""Gets the latest state of a long-running operation. - - Args: - request (:class:`~.operations_pb2.GetOperationRequest`): - The request object. Request message for - `GetOperation` method. - 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: - ~.operations_pb2.Operation: - An ``Operation`` object. - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = operations_pb2.GetOperationRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._transport.get_operation, - 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 = rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - def cancel_operation( - self, - request: Optional[operations_pb2.CancelOperationRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> None: - r"""Starts asynchronous cancellation on a long-running operation. - - The server makes a best effort to cancel the operation, but success - is not guaranteed. If the server doesn't support this method, it returns - `google.rpc.Code.UNIMPLEMENTED`. - - Args: - request (:class:`~.operations_pb2.CancelOperationRequest`): - The request object. Request message for - `CancelOperation` method. - 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: - None - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = operations_pb2.CancelOperationRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._transport.cancel_operation, - 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. - rpc(request, retry=retry, timeout=timeout, metadata=metadata,) - - def get_location( - self, - request: Optional[locations_pb2.GetLocationRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> locations_pb2.Location: - r"""Gets information about a location. - - Args: - request (:class:`~.location_pb2.GetLocationRequest`): - The request object. Request message for - `GetLocation` method. - 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: - ~.location_pb2.Location: - Location object. - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = locations_pb2.GetLocationRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._transport.get_location, - 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 = rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - def list_locations( - self, - request: Optional[locations_pb2.ListLocationsRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> locations_pb2.ListLocationsResponse: - r"""Lists information about the supported locations for this service. - - Args: - request (:class:`~.location_pb2.ListLocationsRequest`): - The request object. Request message for - `ListLocations` method. - 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: - ~.location_pb2.ListLocationsResponse: - Response message for ``ListLocations`` method. - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = locations_pb2.ListLocationsRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._transport.list_locations, - 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 = rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) - - -__all__ = ( - "ContextsClient", -) diff --git a/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/contexts/pagers.py b/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/contexts/pagers.py deleted file mode 100644 index 86275112f..000000000 --- a/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/contexts/pagers.py +++ /dev/null @@ -1,139 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from typing import Any, AsyncIterator, Awaitable, Callable, Sequence, Tuple, Optional, Iterator - -from google.cloud.dialogflow_v2.types import context - - -class ListContextsPager: - """A pager for iterating through ``list_contexts`` requests. - - This class thinly wraps an initial - :class:`google.cloud.dialogflow_v2.types.ListContextsResponse` object, and - provides an ``__iter__`` method to iterate through its - ``contexts`` field. - - If there are more pages, the ``__iter__`` method will make additional - ``ListContexts`` requests and continue to iterate - through the ``contexts`` field on the - corresponding responses. - - All the usual :class:`google.cloud.dialogflow_v2.types.ListContextsResponse` - 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[..., context.ListContextsResponse], - request: context.ListContextsRequest, - response: context.ListContextsResponse, - *, - 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.ListContextsRequest): - The initial request object. - response (google.cloud.dialogflow_v2.types.ListContextsResponse): - 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 = context.ListContextsRequest(request) - self._response = response - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - def pages(self) -> Iterator[context.ListContextsResponse]: - yield self._response - while self._response.next_page_token: - self._request.page_token = self._response.next_page_token - self._response = self._method(self._request, metadata=self._metadata) - yield self._response - - def __iter__(self) -> Iterator[context.Context]: - for page in self.pages: - yield from page.contexts - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListContextsAsyncPager: - """A pager for iterating through ``list_contexts`` requests. - - This class thinly wraps an initial - :class:`google.cloud.dialogflow_v2.types.ListContextsResponse` object, and - provides an ``__aiter__`` method to iterate through its - ``contexts`` field. - - If there are more pages, the ``__aiter__`` method will make additional - ``ListContexts`` requests and continue to iterate - through the ``contexts`` field on the - corresponding responses. - - All the usual :class:`google.cloud.dialogflow_v2.types.ListContextsResponse` - 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[context.ListContextsResponse]], - request: context.ListContextsRequest, - response: context.ListContextsResponse, - *, - metadata: Sequence[Tuple[str, str]] = ()): - """Instantiates the pager. - - Args: - method (Callable): The method that was originally called, and - which instantiated this pager. - request (google.cloud.dialogflow_v2.types.ListContextsRequest): - The initial request object. - response (google.cloud.dialogflow_v2.types.ListContextsResponse): - 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 = context.ListContextsRequest(request) - self._response = response - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - async def pages(self) -> AsyncIterator[context.ListContextsResponse]: - yield self._response - while self._response.next_page_token: - self._request.page_token = self._response.next_page_token - self._response = await self._method(self._request, metadata=self._metadata) - yield self._response - def __aiter__(self) -> AsyncIterator[context.Context]: - async def async_generator(): - async for page in self.pages: - for response in page.contexts: - yield response - - return async_generator() - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) diff --git a/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/contexts/transports/__init__.py b/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/contexts/transports/__init__.py deleted file mode 100644 index f6acdd0a1..000000000 --- a/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/contexts/transports/__init__.py +++ /dev/null @@ -1,38 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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 ContextsTransport -from .grpc import ContextsGrpcTransport -from .grpc_asyncio import ContextsGrpcAsyncIOTransport -from .rest import ContextsRestTransport -from .rest import ContextsRestInterceptor - - -# Compile a registry of transports. -_transport_registry = OrderedDict() # type: Dict[str, Type[ContextsTransport]] -_transport_registry['grpc'] = ContextsGrpcTransport -_transport_registry['grpc_asyncio'] = ContextsGrpcAsyncIOTransport -_transport_registry['rest'] = ContextsRestTransport - -__all__ = ( - 'ContextsTransport', - 'ContextsGrpcTransport', - 'ContextsGrpcAsyncIOTransport', - 'ContextsRestTransport', - 'ContextsRestInterceptor', -) diff --git a/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/contexts/transports/base.py b/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/contexts/transports/base.py deleted file mode 100644 index 2d4784b68..000000000 --- a/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/contexts/transports/base.py +++ /dev/null @@ -1,266 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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 - -from google.cloud.dialogflow_v2 import gapic_version as package_version - -import google.auth # type: ignore -import google.api_core -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import retry as retries -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 context -from google.cloud.dialogflow_v2.types import context as gcd_context -from google.cloud.location import locations_pb2 # type: ignore -from google.longrunning import operations_pb2 -from google.protobuf import empty_pb2 # type: ignore - -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) - - -class ContextsTransport(abc.ABC): - """Abstract transport class for Contexts.""" - - 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: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - api_audience: Optional[str] = None, - **kwargs, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. - scopes (Optional[Sequence[str]]): A list of scopes. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - """ - - scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} - - # Save the scopes. - self._scopes = scopes - - # If no credentials are provided, then determine the appropriate - # defaults. - if credentials and credentials_file: - raise core_exceptions.DuplicateCredentialArgs("'credentials_file' and 'credentials' are mutually exclusive") - - if credentials_file is not None: - credentials, _ = google.auth.load_credentials_from_file( - credentials_file, - **scopes_kwargs, - quota_project_id=quota_project_id - ) - elif credentials is None: - credentials, _ = google.auth.default(**scopes_kwargs, quota_project_id=quota_project_id) - # Don't apply audience if the credentials file passed from user. - if hasattr(credentials, "with_gdch_audience"): - credentials = credentials.with_gdch_audience(api_audience if api_audience else host) - - # If the credentials are service account credentials, then always try to use self signed JWT. - if always_use_jwt_access and isinstance(credentials, service_account.Credentials) and hasattr(service_account.Credentials, "with_always_use_jwt_access"): - credentials = credentials.with_always_use_jwt_access(True) - - # Save the credentials. - self._credentials = credentials - - # Save the hostname. Default to port 443 (HTTPS) if none is specified. - if ':' not in host: - host += ':443' - self._host = host - - def _prep_wrapped_messages(self, client_info): - # Precompute the wrapped methods. - self._wrapped_methods = { - self.list_contexts: gapic_v1.method.wrap_method( - self.list_contexts, - default_timeout=None, - client_info=client_info, - ), - self.get_context: gapic_v1.method.wrap_method( - self.get_context, - default_timeout=None, - client_info=client_info, - ), - self.create_context: gapic_v1.method.wrap_method( - self.create_context, - default_timeout=None, - client_info=client_info, - ), - self.update_context: gapic_v1.method.wrap_method( - self.update_context, - default_timeout=None, - client_info=client_info, - ), - self.delete_context: gapic_v1.method.wrap_method( - self.delete_context, - default_timeout=None, - client_info=client_info, - ), - self.delete_all_contexts: gapic_v1.method.wrap_method( - self.delete_all_contexts, - default_timeout=None, - client_info=client_info, - ), - } - - def close(self): - """Closes resources associated with the transport. - - .. warning:: - Only call this method if the transport is NOT shared - with other clients - this may cause errors in other clients! - """ - raise NotImplementedError() - - @property - def list_contexts(self) -> Callable[ - [context.ListContextsRequest], - Union[ - context.ListContextsResponse, - Awaitable[context.ListContextsResponse] - ]]: - raise NotImplementedError() - - @property - def get_context(self) -> Callable[ - [context.GetContextRequest], - Union[ - context.Context, - Awaitable[context.Context] - ]]: - raise NotImplementedError() - - @property - def create_context(self) -> Callable[ - [gcd_context.CreateContextRequest], - Union[ - gcd_context.Context, - Awaitable[gcd_context.Context] - ]]: - raise NotImplementedError() - - @property - def update_context(self) -> Callable[ - [gcd_context.UpdateContextRequest], - Union[ - gcd_context.Context, - Awaitable[gcd_context.Context] - ]]: - raise NotImplementedError() - - @property - def delete_context(self) -> Callable[ - [context.DeleteContextRequest], - Union[ - empty_pb2.Empty, - Awaitable[empty_pb2.Empty] - ]]: - raise NotImplementedError() - - @property - def delete_all_contexts(self) -> Callable[ - [context.DeleteAllContextsRequest], - Union[ - empty_pb2.Empty, - Awaitable[empty_pb2.Empty] - ]]: - raise NotImplementedError() - - @property - def list_operations( - self, - ) -> Callable[ - [operations_pb2.ListOperationsRequest], - Union[operations_pb2.ListOperationsResponse, Awaitable[operations_pb2.ListOperationsResponse]], - ]: - raise NotImplementedError() - - @property - def get_operation( - self, - ) -> Callable[ - [operations_pb2.GetOperationRequest], - Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], - ]: - raise NotImplementedError() - - @property - def cancel_operation( - self, - ) -> Callable[ - [operations_pb2.CancelOperationRequest], - None, - ]: - raise NotImplementedError() - - @property - def get_location(self, - ) -> Callable[ - [locations_pb2.GetLocationRequest], - Union[locations_pb2.Location, Awaitable[locations_pb2.Location]], - ]: - raise NotImplementedError() - - @property - def list_locations(self, - ) -> Callable[ - [locations_pb2.ListLocationsRequest], - Union[locations_pb2.ListLocationsResponse, Awaitable[locations_pb2.ListLocationsResponse]], - ]: - raise NotImplementedError() - - @property - def kind(self) -> str: - raise NotImplementedError() - - -__all__ = ( - 'ContextsTransport', -) diff --git a/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/contexts/transports/grpc.py b/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/contexts/transports/grpc.py deleted file mode 100644 index 9e9ef9e33..000000000 --- a/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/contexts/transports/grpc.py +++ /dev/null @@ -1,491 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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 -from google.api_core import gapic_v1 -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.cloud.location import locations_pb2 # type: ignore -from google.longrunning import operations_pb2 -from google.protobuf import empty_pb2 # type: ignore -from .base import ContextsTransport, DEFAULT_CLIENT_INFO - - -class ContextsGrpcTransport(ContextsTransport): - """gRPC backend transport for Contexts. - - Service for managing [Contexts][google.cloud.dialogflow.v2.Context]. - - 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: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - channel: Optional[grpc.Channel] = None, - api_mtls_endpoint: Optional[str] = None, - client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, - ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, - client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - api_audience: Optional[str] = None, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - This argument is ignored if ``channel`` is provided. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional(Sequence[str])): A list of scopes. This argument is - ignored if ``channel`` is provided. - channel (Optional[grpc.Channel]): A ``Channel`` instance through - which to make calls. - api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. - If provided, it overrides the ``host`` argument and tries to create - a mutual TLS channel with client SSL credentials from - ``client_cert_source`` or application default SSL credentials. - client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): - Deprecated. A callback to provide client SSL certificate bytes and - private key bytes, both in PEM format. It is ignored if - ``api_mtls_endpoint`` is None. - ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials - for the grpc channel. It is ignored if ``channel`` is provided. - client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): - A callback to provide client certificate bytes and private key bytes, - both in PEM format. It is used to configure a mutual TLS channel. It is - ignored if ``channel`` or ``ssl_channel_credentials`` is provided. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport - creation failed for any reason. - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - self._grpc_channel = None - self._ssl_channel_credentials = ssl_channel_credentials - self._stubs: Dict[str, Callable] = {} - - if api_mtls_endpoint: - warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) - if client_cert_source: - warnings.warn("client_cert_source is deprecated", DeprecationWarning) - - if channel: - # Ignore credentials if a channel was passed. - credentials = False - # If a channel was explicitly provided, set it. - self._grpc_channel = channel - self._ssl_channel_credentials = None - - else: - if api_mtls_endpoint: - host = api_mtls_endpoint - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - self._ssl_channel_credentials = SslCredentials().ssl_credentials - - else: - if client_cert_source_for_mtls and not ssl_channel_credentials: - cert, key = client_cert_source_for_mtls() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - - # The base transport sets the host, credentials and scopes - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes, - quota_project_id=quota_project_id, - client_info=client_info, - always_use_jwt_access=always_use_jwt_access, - api_audience=api_audience, - ) - - if not self._grpc_channel: - self._grpc_channel = type(self).create_channel( - self._host, - # use the credentials which are saved - credentials=self._credentials, - # Set ``credentials_file`` to ``None`` here as - # the credentials that we saved earlier should be used. - credentials_file=None, - 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: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - **kwargs) -> grpc.Channel: - """Create and return a gRPC channel object. - Args: - host (Optional[str]): The host for the channel to use. - credentials (Optional[~.Credentials]): The - authorization credentials to attach to requests. These - credentials identify this application to the service. If - none are specified, the client will attempt to ascertain - the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - kwargs (Optional[dict]): Keyword arguments, which are passed to the - channel creation. - Returns: - grpc.Channel: A gRPC channel object. - - Raises: - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - - return grpc_helpers.create_channel( - host, - credentials=credentials, - credentials_file=credentials_file, - quota_project_id=quota_project_id, - default_scopes=cls.AUTH_SCOPES, - scopes=scopes, - default_host=cls.DEFAULT_HOST, - **kwargs - ) - - @property - def grpc_channel(self) -> grpc.Channel: - """Return the channel designed to connect to this service. - """ - return self._grpc_channel - - @property - def list_contexts(self) -> Callable[ - [context.ListContextsRequest], - context.ListContextsResponse]: - r"""Return a callable for the list contexts method over gRPC. - - Returns the list of all contexts in the specified - session. - - Returns: - Callable[[~.ListContextsRequest], - ~.ListContextsResponse]: - 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_contexts' not in self._stubs: - self._stubs['list_contexts'] = self.grpc_channel.unary_unary( - '/google.cloud.dialogflow.v2.Contexts/ListContexts', - request_serializer=context.ListContextsRequest.serialize, - response_deserializer=context.ListContextsResponse.deserialize, - ) - return self._stubs['list_contexts'] - - @property - def get_context(self) -> Callable[ - [context.GetContextRequest], - context.Context]: - r"""Return a callable for the get context method over gRPC. - - Retrieves the specified context. - - Returns: - Callable[[~.GetContextRequest], - ~.Context]: - 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_context' not in self._stubs: - self._stubs['get_context'] = self.grpc_channel.unary_unary( - '/google.cloud.dialogflow.v2.Contexts/GetContext', - request_serializer=context.GetContextRequest.serialize, - response_deserializer=context.Context.deserialize, - ) - return self._stubs['get_context'] - - @property - def create_context(self) -> Callable[ - [gcd_context.CreateContextRequest], - gcd_context.Context]: - r"""Return a callable for the create context method over gRPC. - - Creates a context. - If the specified context already exists, overrides the - context. - - Returns: - Callable[[~.CreateContextRequest], - ~.Context]: - 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_context' not in self._stubs: - self._stubs['create_context'] = self.grpc_channel.unary_unary( - '/google.cloud.dialogflow.v2.Contexts/CreateContext', - request_serializer=gcd_context.CreateContextRequest.serialize, - response_deserializer=gcd_context.Context.deserialize, - ) - return self._stubs['create_context'] - - @property - def update_context(self) -> Callable[ - [gcd_context.UpdateContextRequest], - gcd_context.Context]: - r"""Return a callable for the update context method over gRPC. - - Updates the specified context. - - Returns: - Callable[[~.UpdateContextRequest], - ~.Context]: - 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_context' not in self._stubs: - self._stubs['update_context'] = self.grpc_channel.unary_unary( - '/google.cloud.dialogflow.v2.Contexts/UpdateContext', - request_serializer=gcd_context.UpdateContextRequest.serialize, - response_deserializer=gcd_context.Context.deserialize, - ) - return self._stubs['update_context'] - - @property - 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. - - Returns: - Callable[[~.DeleteContextRequest], - ~.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_context' not in self._stubs: - self._stubs['delete_context'] = self.grpc_channel.unary_unary( - '/google.cloud.dialogflow.v2.Contexts/DeleteContext', - request_serializer=context.DeleteContextRequest.serialize, - response_deserializer=empty_pb2.Empty.FromString, - ) - return self._stubs['delete_context'] - - @property - def delete_all_contexts(self) -> 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. - - Returns: - Callable[[~.DeleteAllContextsRequest], - ~.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_all_contexts' not in self._stubs: - self._stubs['delete_all_contexts'] = self.grpc_channel.unary_unary( - '/google.cloud.dialogflow.v2.Contexts/DeleteAllContexts', - request_serializer=context.DeleteAllContextsRequest.serialize, - response_deserializer=empty_pb2.Empty.FromString, - ) - return self._stubs['delete_all_contexts'] - - def close(self): - self.grpc_channel.close() - - @property - def cancel_operation( - self, - ) -> Callable[[operations_pb2.CancelOperationRequest], None]: - r"""Return a callable for the cancel_operation method over gRPC. - """ - # 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 "cancel_operation" not in self._stubs: - self._stubs["cancel_operation"] = self.grpc_channel.unary_unary( - "/google.longrunning.Operations/CancelOperation", - request_serializer=operations_pb2.CancelOperationRequest.SerializeToString, - response_deserializer=None, - ) - return self._stubs["cancel_operation"] - - @property - def get_operation( - self, - ) -> Callable[[operations_pb2.GetOperationRequest], operations_pb2.Operation]: - r"""Return a callable for the get_operation method over gRPC. - """ - # 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_operation" not in self._stubs: - self._stubs["get_operation"] = self.grpc_channel.unary_unary( - "/google.longrunning.Operations/GetOperation", - request_serializer=operations_pb2.GetOperationRequest.SerializeToString, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs["get_operation"] - - @property - def list_operations( - self, - ) -> Callable[[operations_pb2.ListOperationsRequest], operations_pb2.ListOperationsResponse]: - r"""Return a callable for the list_operations method over gRPC. - """ - # 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_operations" not in self._stubs: - self._stubs["list_operations"] = self.grpc_channel.unary_unary( - "/google.longrunning.Operations/ListOperations", - request_serializer=operations_pb2.ListOperationsRequest.SerializeToString, - response_deserializer=operations_pb2.ListOperationsResponse.FromString, - ) - return self._stubs["list_operations"] - - @property - def list_locations( - self, - ) -> Callable[[locations_pb2.ListLocationsRequest], locations_pb2.ListLocationsResponse]: - r"""Return a callable for the list locations method over gRPC. - """ - # 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_locations" not in self._stubs: - self._stubs["list_locations"] = self.grpc_channel.unary_unary( - "/google.cloud.location.Locations/ListLocations", - request_serializer=locations_pb2.ListLocationsRequest.SerializeToString, - response_deserializer=locations_pb2.ListLocationsResponse.FromString, - ) - return self._stubs["list_locations"] - - @property - def get_location( - self, - ) -> Callable[[locations_pb2.GetLocationRequest], locations_pb2.Location]: - r"""Return a callable for the list locations method over gRPC. - """ - # 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_location" not in self._stubs: - self._stubs["get_location"] = self.grpc_channel.unary_unary( - "/google.cloud.location.Locations/GetLocation", - request_serializer=locations_pb2.GetLocationRequest.SerializeToString, - response_deserializer=locations_pb2.Location.FromString, - ) - return self._stubs["get_location"] - - @property - def kind(self) -> str: - return "grpc" - - -__all__ = ( - 'ContextsGrpcTransport', -) diff --git a/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/contexts/transports/grpc_asyncio.py b/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/contexts/transports/grpc_asyncio.py deleted file mode 100644 index ec563ef1c..000000000 --- a/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/contexts/transports/grpc_asyncio.py +++ /dev/null @@ -1,490 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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 -from google.api_core import grpc_helpers_async -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore - -import grpc # type: ignore -from grpc.experimental import aio # type: ignore - -from google.cloud.dialogflow_v2.types import context -from google.cloud.dialogflow_v2.types import context as gcd_context -from google.cloud.location import locations_pb2 # type: ignore -from google.longrunning import operations_pb2 -from google.protobuf import empty_pb2 # type: ignore -from .base import ContextsTransport, DEFAULT_CLIENT_INFO -from .grpc import ContextsGrpcTransport - - -class ContextsGrpcAsyncIOTransport(ContextsTransport): - """gRPC AsyncIO backend transport for Contexts. - - Service for managing [Contexts][google.cloud.dialogflow.v2.Context]. - - 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: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - **kwargs) -> aio.Channel: - """Create and return a gRPC AsyncIO channel object. - Args: - host (Optional[str]): The host for the channel to use. - credentials (Optional[~.Credentials]): The - authorization credentials to attach to requests. These - credentials identify this application to the service. If - none are specified, the client will attempt to ascertain - the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - kwargs (Optional[dict]): Keyword arguments, which are passed to the - channel creation. - Returns: - aio.Channel: A gRPC AsyncIO channel object. - """ - - return grpc_helpers_async.create_channel( - host, - credentials=credentials, - credentials_file=credentials_file, - quota_project_id=quota_project_id, - default_scopes=cls.AUTH_SCOPES, - scopes=scopes, - default_host=cls.DEFAULT_HOST, - **kwargs - ) - - def __init__(self, *, - host: str = 'dialogflow.googleapis.com', - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - channel: Optional[aio.Channel] = None, - api_mtls_endpoint: Optional[str] = None, - client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, - ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, - client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - api_audience: Optional[str] = None, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - This argument is ignored if ``channel`` is provided. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - channel (Optional[aio.Channel]): A ``Channel`` instance through - which to make calls. - api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. - If provided, it overrides the ``host`` argument and tries to create - a mutual TLS channel with client SSL credentials from - ``client_cert_source`` or application default SSL credentials. - client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): - Deprecated. A callback to provide client SSL certificate bytes and - private key bytes, both in PEM format. It is ignored if - ``api_mtls_endpoint`` is None. - ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials - for the grpc channel. It is ignored if ``channel`` is provided. - client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): - A callback to provide client certificate bytes and private key bytes, - both in PEM format. It is used to configure a mutual TLS channel. It is - ignored if ``channel`` or ``ssl_channel_credentials`` is provided. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - - Raises: - google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport - creation failed for any reason. - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - self._grpc_channel = None - self._ssl_channel_credentials = ssl_channel_credentials - self._stubs: Dict[str, Callable] = {} - - if api_mtls_endpoint: - warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) - if client_cert_source: - warnings.warn("client_cert_source is deprecated", DeprecationWarning) - - if channel: - # Ignore credentials if a channel was passed. - credentials = False - # If a channel was explicitly provided, set it. - self._grpc_channel = channel - self._ssl_channel_credentials = None - else: - if api_mtls_endpoint: - host = api_mtls_endpoint - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - self._ssl_channel_credentials = SslCredentials().ssl_credentials - - else: - if client_cert_source_for_mtls and not ssl_channel_credentials: - cert, key = client_cert_source_for_mtls() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - - # The base transport sets the host, credentials and scopes - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes, - quota_project_id=quota_project_id, - client_info=client_info, - always_use_jwt_access=always_use_jwt_access, - api_audience=api_audience, - ) - - if not self._grpc_channel: - self._grpc_channel = type(self).create_channel( - self._host, - # use the credentials which are saved - credentials=self._credentials, - # Set ``credentials_file`` to ``None`` here as - # the credentials that we saved earlier should be used. - credentials_file=None, - 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_contexts(self) -> Callable[ - [context.ListContextsRequest], - Awaitable[context.ListContextsResponse]]: - r"""Return a callable for the list contexts method over gRPC. - - Returns the list of all contexts in the specified - session. - - Returns: - Callable[[~.ListContextsRequest], - Awaitable[~.ListContextsResponse]]: - 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_contexts' not in self._stubs: - self._stubs['list_contexts'] = self.grpc_channel.unary_unary( - '/google.cloud.dialogflow.v2.Contexts/ListContexts', - request_serializer=context.ListContextsRequest.serialize, - response_deserializer=context.ListContextsResponse.deserialize, - ) - return self._stubs['list_contexts'] - - @property - def get_context(self) -> Callable[ - [context.GetContextRequest], - Awaitable[context.Context]]: - r"""Return a callable for the get context method over gRPC. - - Retrieves the specified context. - - Returns: - Callable[[~.GetContextRequest], - Awaitable[~.Context]]: - 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_context' not in self._stubs: - self._stubs['get_context'] = self.grpc_channel.unary_unary( - '/google.cloud.dialogflow.v2.Contexts/GetContext', - request_serializer=context.GetContextRequest.serialize, - response_deserializer=context.Context.deserialize, - ) - return self._stubs['get_context'] - - @property - def create_context(self) -> Callable[ - [gcd_context.CreateContextRequest], - Awaitable[gcd_context.Context]]: - r"""Return a callable for the create context method over gRPC. - - Creates a context. - If the specified context already exists, overrides the - context. - - Returns: - Callable[[~.CreateContextRequest], - Awaitable[~.Context]]: - 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_context' not in self._stubs: - self._stubs['create_context'] = self.grpc_channel.unary_unary( - '/google.cloud.dialogflow.v2.Contexts/CreateContext', - request_serializer=gcd_context.CreateContextRequest.serialize, - response_deserializer=gcd_context.Context.deserialize, - ) - return self._stubs['create_context'] - - @property - def update_context(self) -> Callable[ - [gcd_context.UpdateContextRequest], - Awaitable[gcd_context.Context]]: - r"""Return a callable for the update context method over gRPC. - - Updates the specified context. - - Returns: - Callable[[~.UpdateContextRequest], - Awaitable[~.Context]]: - 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_context' not in self._stubs: - self._stubs['update_context'] = self.grpc_channel.unary_unary( - '/google.cloud.dialogflow.v2.Contexts/UpdateContext', - request_serializer=gcd_context.UpdateContextRequest.serialize, - response_deserializer=gcd_context.Context.deserialize, - ) - return self._stubs['update_context'] - - @property - def delete_context(self) -> Callable[ - [context.DeleteContextRequest], - Awaitable[empty_pb2.Empty]]: - r"""Return a callable for the delete context method over gRPC. - - Deletes the specified context. - - Returns: - Callable[[~.DeleteContextRequest], - 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_context' not in self._stubs: - self._stubs['delete_context'] = self.grpc_channel.unary_unary( - '/google.cloud.dialogflow.v2.Contexts/DeleteContext', - request_serializer=context.DeleteContextRequest.serialize, - response_deserializer=empty_pb2.Empty.FromString, - ) - return self._stubs['delete_context'] - - @property - def delete_all_contexts(self) -> 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. - - Returns: - Callable[[~.DeleteAllContextsRequest], - 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_all_contexts' not in self._stubs: - self._stubs['delete_all_contexts'] = self.grpc_channel.unary_unary( - '/google.cloud.dialogflow.v2.Contexts/DeleteAllContexts', - request_serializer=context.DeleteAllContextsRequest.serialize, - response_deserializer=empty_pb2.Empty.FromString, - ) - return self._stubs['delete_all_contexts'] - - def close(self): - return self.grpc_channel.close() - - @property - def cancel_operation( - self, - ) -> Callable[[operations_pb2.CancelOperationRequest], None]: - r"""Return a callable for the cancel_operation method over gRPC. - """ - # 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 "cancel_operation" not in self._stubs: - self._stubs["cancel_operation"] = self.grpc_channel.unary_unary( - "/google.longrunning.Operations/CancelOperation", - request_serializer=operations_pb2.CancelOperationRequest.SerializeToString, - response_deserializer=None, - ) - return self._stubs["cancel_operation"] - - @property - def get_operation( - self, - ) -> Callable[[operations_pb2.GetOperationRequest], operations_pb2.Operation]: - r"""Return a callable for the get_operation method over gRPC. - """ - # 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_operation" not in self._stubs: - self._stubs["get_operation"] = self.grpc_channel.unary_unary( - "/google.longrunning.Operations/GetOperation", - request_serializer=operations_pb2.GetOperationRequest.SerializeToString, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs["get_operation"] - - @property - def list_operations( - self, - ) -> Callable[[operations_pb2.ListOperationsRequest], operations_pb2.ListOperationsResponse]: - r"""Return a callable for the list_operations method over gRPC. - """ - # 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_operations" not in self._stubs: - self._stubs["list_operations"] = self.grpc_channel.unary_unary( - "/google.longrunning.Operations/ListOperations", - request_serializer=operations_pb2.ListOperationsRequest.SerializeToString, - response_deserializer=operations_pb2.ListOperationsResponse.FromString, - ) - return self._stubs["list_operations"] - - @property - def list_locations( - self, - ) -> Callable[[locations_pb2.ListLocationsRequest], locations_pb2.ListLocationsResponse]: - r"""Return a callable for the list locations method over gRPC. - """ - # 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_locations" not in self._stubs: - self._stubs["list_locations"] = self.grpc_channel.unary_unary( - "/google.cloud.location.Locations/ListLocations", - request_serializer=locations_pb2.ListLocationsRequest.SerializeToString, - response_deserializer=locations_pb2.ListLocationsResponse.FromString, - ) - return self._stubs["list_locations"] - - @property - def get_location( - self, - ) -> Callable[[locations_pb2.GetLocationRequest], locations_pb2.Location]: - r"""Return a callable for the list locations method over gRPC. - """ - # 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_location" not in self._stubs: - self._stubs["get_location"] = self.grpc_channel.unary_unary( - "/google.cloud.location.Locations/GetLocation", - request_serializer=locations_pb2.GetLocationRequest.SerializeToString, - response_deserializer=locations_pb2.Location.FromString, - ) - return self._stubs["get_location"] - - -__all__ = ( - 'ContextsGrpcAsyncIOTransport', -) diff --git a/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/contexts/transports/rest.py b/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/contexts/transports/rest.py deleted file mode 100644 index f628494ca..000000000 --- a/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/contexts/transports/rest.py +++ /dev/null @@ -1,1387 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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 google.auth.transport.requests import AuthorizedSession # type: ignore -import json # type: ignore -import grpc # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore -from google.auth import credentials as ga_credentials # type: ignore -from google.api_core import exceptions as core_exceptions -from google.api_core import retry as retries -from google.api_core import rest_helpers -from google.api_core import rest_streaming -from google.api_core import path_template -from google.api_core import gapic_v1 - -from google.protobuf import json_format -from google.cloud.location import locations_pb2 # type: ignore -from google.longrunning import operations_pb2 -from requests import __version__ as requests_version -import dataclasses -import re -from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union -import warnings - -try: - OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] -except AttributeError: # pragma: NO COVER - OptionalRetry = Union[retries.Retry, object] # 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 # type: ignore - -from .base import ContextsTransport, DEFAULT_CLIENT_INFO as BASE_DEFAULT_CLIENT_INFO - - -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=BASE_DEFAULT_CLIENT_INFO.gapic_version, - grpc_version=None, - rest_version=requests_version, -) - - -class ContextsRestInterceptor: - """Interceptor for Contexts. - - Interceptors are used to manipulate requests, request metadata, and responses - in arbitrary ways. - Example use cases include: - * Logging - * Verifying requests according to service or custom semantics - * Stripping extraneous information from responses - - These use cases and more can be enabled by injecting an - instance of a custom subclass when constructing the ContextsRestTransport. - - .. code-block:: python - class MyCustomContextsInterceptor(ContextsRestInterceptor): - def pre_create_context(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_create_context(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_delete_all_contexts(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def pre_delete_context(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def pre_get_context(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_get_context(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_list_contexts(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_list_contexts(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_update_context(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_update_context(self, response): - logging.log(f"Received response: {response}") - return response - - transport = ContextsRestTransport(interceptor=MyCustomContextsInterceptor()) - client = ContextsClient(transport=transport) - - - """ - def pre_create_context(self, request: gcd_context.CreateContextRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[gcd_context.CreateContextRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for create_context - - Override in a subclass to manipulate the request or metadata - before they are sent to the Contexts server. - """ - return request, metadata - - def post_create_context(self, response: gcd_context.Context) -> gcd_context.Context: - """Post-rpc interceptor for create_context - - Override in a subclass to manipulate the response - after it is returned by the Contexts server but before - it is returned to user code. - """ - return response - def pre_delete_all_contexts(self, request: context.DeleteAllContextsRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[context.DeleteAllContextsRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for delete_all_contexts - - Override in a subclass to manipulate the request or metadata - before they are sent to the Contexts server. - """ - return request, metadata - - def pre_delete_context(self, request: context.DeleteContextRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[context.DeleteContextRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for delete_context - - Override in a subclass to manipulate the request or metadata - before they are sent to the Contexts server. - """ - return request, metadata - - def pre_get_context(self, request: context.GetContextRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[context.GetContextRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for get_context - - Override in a subclass to manipulate the request or metadata - before they are sent to the Contexts server. - """ - return request, metadata - - def post_get_context(self, response: context.Context) -> context.Context: - """Post-rpc interceptor for get_context - - Override in a subclass to manipulate the response - after it is returned by the Contexts server but before - it is returned to user code. - """ - return response - def pre_list_contexts(self, request: context.ListContextsRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[context.ListContextsRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for list_contexts - - Override in a subclass to manipulate the request or metadata - before they are sent to the Contexts server. - """ - return request, metadata - - def post_list_contexts(self, response: context.ListContextsResponse) -> context.ListContextsResponse: - """Post-rpc interceptor for list_contexts - - Override in a subclass to manipulate the response - after it is returned by the Contexts server but before - it is returned to user code. - """ - return response - def pre_update_context(self, request: gcd_context.UpdateContextRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[gcd_context.UpdateContextRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for update_context - - Override in a subclass to manipulate the request or metadata - before they are sent to the Contexts server. - """ - return request, metadata - - def post_update_context(self, response: gcd_context.Context) -> gcd_context.Context: - """Post-rpc interceptor for update_context - - Override in a subclass to manipulate the response - after it is returned by the Contexts server but before - it is returned to user code. - """ - return response - - def pre_get_location( - self, request: locations_pb2.GetLocationRequest, metadata: Sequence[Tuple[str, str]] - ) -> Tuple[locations_pb2.GetLocationRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for get_location - - Override in a subclass to manipulate the request or metadata - before they are sent to the Contexts server. - """ - return request, metadata - - def post_get_location( - self, response: locations_pb2.Location - ) -> locations_pb2.Location: - """Post-rpc interceptor for get_location - - Override in a subclass to manipulate the response - after it is returned by the Contexts server but before - it is returned to user code. - """ - return response - def pre_list_locations( - self, request: locations_pb2.ListLocationsRequest, metadata: Sequence[Tuple[str, str]] - ) -> Tuple[locations_pb2.ListLocationsRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for list_locations - - Override in a subclass to manipulate the request or metadata - before they are sent to the Contexts server. - """ - return request, metadata - - def post_list_locations( - self, response: locations_pb2.ListLocationsResponse - ) -> locations_pb2.ListLocationsResponse: - """Post-rpc interceptor for list_locations - - Override in a subclass to manipulate the response - after it is returned by the Contexts server but before - it is returned to user code. - """ - return response - def pre_cancel_operation( - self, request: operations_pb2.CancelOperationRequest, metadata: Sequence[Tuple[str, str]] - ) -> Tuple[operations_pb2.CancelOperationRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for cancel_operation - - Override in a subclass to manipulate the request or metadata - before they are sent to the Contexts server. - """ - return request, metadata - - def post_cancel_operation( - self, response: None - ) -> None: - """Post-rpc interceptor for cancel_operation - - Override in a subclass to manipulate the response - after it is returned by the Contexts server but before - it is returned to user code. - """ - return response - def pre_get_operation( - self, request: operations_pb2.GetOperationRequest, metadata: Sequence[Tuple[str, str]] - ) -> Tuple[operations_pb2.GetOperationRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for get_operation - - Override in a subclass to manipulate the request or metadata - before they are sent to the Contexts server. - """ - return request, metadata - - def post_get_operation( - self, response: operations_pb2.Operation - ) -> operations_pb2.Operation: - """Post-rpc interceptor for get_operation - - Override in a subclass to manipulate the response - after it is returned by the Contexts server but before - it is returned to user code. - """ - return response - def pre_list_operations( - self, request: operations_pb2.ListOperationsRequest, metadata: Sequence[Tuple[str, str]] - ) -> Tuple[operations_pb2.ListOperationsRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for list_operations - - Override in a subclass to manipulate the request or metadata - before they are sent to the Contexts server. - """ - return request, metadata - - def post_list_operations( - self, response: operations_pb2.ListOperationsResponse - ) -> operations_pb2.ListOperationsResponse: - """Post-rpc interceptor for list_operations - - Override in a subclass to manipulate the response - after it is returned by the Contexts server but before - it is returned to user code. - """ - return response - - -@dataclasses.dataclass -class ContextsRestStub: - _session: AuthorizedSession - _host: str - _interceptor: ContextsRestInterceptor - - -class ContextsRestTransport(ContextsTransport): - """REST backend transport for Contexts. - - Service for managing [Contexts][google.cloud.dialogflow.v2.Context]. - - 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 JSON representations of protocol buffers over HTTP/1.1 - - """ - - def __init__(self, *, - host: str = 'dialogflow.googleapis.com', - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - client_cert_source_for_mtls: Optional[Callable[[ - ], Tuple[bytes, bytes]]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - url_scheme: str = 'https', - interceptor: Optional[ContextsRestInterceptor] = None, - api_audience: Optional[str] = None, - ) -> 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 ignored if ``channel`` is provided. - scopes (Optional(Sequence[str])): A list of scopes. This argument is - ignored if ``channel`` is provided. - client_cert_source_for_mtls (Callable[[], Tuple[bytes, bytes]]): Client - certificate to configure mutual TLS HTTP channel. It is ignored - if ``channel`` is provided. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you are developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - url_scheme: the protocol scheme for the API endpoint. Normally - "https", but for testing or local servers, - "http" can be specified. - """ - # Run the base constructor - # TODO(yon-mg): resolve other ctor params i.e. scopes, quota, etc. - # TODO: When custom host (api_endpoint) is set, `scopes` must *also* be set on the - # credentials object - maybe_url_match = re.match("^(?Phttp(?:s)?://)?(?P.*)$", host) - if maybe_url_match is None: - raise ValueError(f"Unexpected hostname structure: {host}") # pragma: NO COVER - - url_match_items = maybe_url_match.groupdict() - - host = f"{url_scheme}://{host}" if not url_match_items["scheme"] else host - - super().__init__( - host=host, - credentials=credentials, - client_info=client_info, - always_use_jwt_access=always_use_jwt_access, - api_audience=api_audience - ) - self._session = AuthorizedSession( - self._credentials, default_host=self.DEFAULT_HOST) - if client_cert_source_for_mtls: - self._session.configure_mtls_channel(client_cert_source_for_mtls) - self._interceptor = interceptor or ContextsRestInterceptor() - self._prep_wrapped_messages(client_info) - - class _CreateContext(ContextsRestStub): - def __hash__(self): - return hash("CreateContext") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: gcd_context.CreateContextRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> gcd_context.Context: - r"""Call the create context method over HTTP. - - Args: - request (~.gcd_context.CreateContextRequest): - The request object. The request message for - [Contexts.CreateContext][google.cloud.dialogflow.v2.Contexts.CreateContext]. - 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: - ~.gcd_context.Context: - Dialogflow contexts are similar to natural language - context. If a person says to you "they are orange", you - need context in order to understand what "they" is - referring to. Similarly, for Dialogflow to handle an - end-user expression like that, it needs to be provided - with context in order to correctly match an intent. - - Using contexts, you can control the flow of a - conversation. You can configure contexts for an intent - by setting input and output contexts, which are - identified by string names. When an intent is matched, - any configured output contexts for that intent become - active. While any contexts are active, Dialogflow is - more likely to match intents that are configured with - input contexts that correspond to the currently active - contexts. - - For more information about context, see the `Contexts - guide `__. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'post', - 'uri': '/v2/{parent=projects/*/agent/sessions/*}/contexts', - 'body': 'context', - }, -{ - 'method': 'post', - 'uri': '/v2/{parent=projects/*/agent/environments/*/users/*/sessions/*}/contexts', - 'body': 'context', - }, -{ - 'method': 'post', - 'uri': '/v2/{parent=projects/*/locations/*/agent/sessions/*}/contexts', - 'body': 'context', - }, -{ - 'method': 'post', - 'uri': '/v2/{parent=projects/*/locations/*/agent/environments/*/users/*/sessions/*}/contexts', - 'body': 'context', - }, - ] - request, metadata = self._interceptor.pre_create_context(request, metadata) - pb_request = gcd_context.CreateContextRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request['body'], - including_default_value_fields=False, - use_integers_for_enums=True - ) - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - including_default_value_fields=False, - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = gcd_context.Context() - pb_resp = gcd_context.Context.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_create_context(resp) - return resp - - class _DeleteAllContexts(ContextsRestStub): - def __hash__(self): - return hash("DeleteAllContexts") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: context.DeleteAllContextsRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ): - r"""Call the delete all contexts method over HTTP. - - Args: - request (~.context.DeleteAllContextsRequest): - The request object. The request message for - [Contexts.DeleteAllContexts][google.cloud.dialogflow.v2.Contexts.DeleteAllContexts]. - 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. - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'delete', - 'uri': '/v2/{parent=projects/*/agent/sessions/*}/contexts', - }, -{ - 'method': 'delete', - 'uri': '/v2/{parent=projects/*/agent/environments/*/users/*/sessions/*}/contexts', - }, -{ - 'method': 'delete', - 'uri': '/v2/{parent=projects/*/locations/*/agent/sessions/*}/contexts', - }, -{ - 'method': 'delete', - 'uri': '/v2/{parent=projects/*/locations/*/agent/environments/*/users/*/sessions/*}/contexts', - }, - ] - request, metadata = self._interceptor.pre_delete_all_contexts(request, metadata) - pb_request = context.DeleteAllContextsRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - including_default_value_fields=False, - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - class _DeleteContext(ContextsRestStub): - def __hash__(self): - return hash("DeleteContext") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: context.DeleteContextRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ): - r"""Call the delete context method over HTTP. - - Args: - request (~.context.DeleteContextRequest): - The request object. The request message for - [Contexts.DeleteContext][google.cloud.dialogflow.v2.Contexts.DeleteContext]. - 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. - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'delete', - 'uri': '/v2/{name=projects/*/agent/sessions/*/contexts/*}', - }, -{ - 'method': 'delete', - 'uri': '/v2/{name=projects/*/agent/environments/*/users/*/sessions/*/contexts/*}', - }, -{ - 'method': 'delete', - 'uri': '/v2/{name=projects/*/locations/*/agent/sessions/*/contexts/*}', - }, -{ - 'method': 'delete', - 'uri': '/v2/{name=projects/*/locations/*/agent/environments/*/users/*/sessions/*/contexts/*}', - }, - ] - request, metadata = self._interceptor.pre_delete_context(request, metadata) - pb_request = context.DeleteContextRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - including_default_value_fields=False, - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - class _GetContext(ContextsRestStub): - def __hash__(self): - return hash("GetContext") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: context.GetContextRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> context.Context: - r"""Call the get context method over HTTP. - - Args: - request (~.context.GetContextRequest): - The request object. The request message for - [Contexts.GetContext][google.cloud.dialogflow.v2.Contexts.GetContext]. - 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: - ~.context.Context: - Dialogflow contexts are similar to natural language - context. If a person says to you "they are orange", you - need context in order to understand what "they" is - referring to. Similarly, for Dialogflow to handle an - end-user expression like that, it needs to be provided - with context in order to correctly match an intent. - - Using contexts, you can control the flow of a - conversation. You can configure contexts for an intent - by setting input and output contexts, which are - identified by string names. When an intent is matched, - any configured output contexts for that intent become - active. While any contexts are active, Dialogflow is - more likely to match intents that are configured with - input contexts that correspond to the currently active - contexts. - - For more information about context, see the `Contexts - guide `__. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v2/{name=projects/*/agent/sessions/*/contexts/*}', - }, -{ - 'method': 'get', - 'uri': '/v2/{name=projects/*/agent/environments/*/users/*/sessions/*/contexts/*}', - }, -{ - 'method': 'get', - 'uri': '/v2/{name=projects/*/locations/*/agent/sessions/*/contexts/*}', - }, -{ - 'method': 'get', - 'uri': '/v2/{name=projects/*/locations/*/agent/environments/*/users/*/sessions/*/contexts/*}', - }, - ] - request, metadata = self._interceptor.pre_get_context(request, metadata) - pb_request = context.GetContextRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - including_default_value_fields=False, - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = context.Context() - pb_resp = context.Context.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_get_context(resp) - return resp - - class _ListContexts(ContextsRestStub): - def __hash__(self): - return hash("ListContexts") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: context.ListContextsRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> context.ListContextsResponse: - r"""Call the list contexts method over HTTP. - - Args: - request (~.context.ListContextsRequest): - The request object. The request message for - [Contexts.ListContexts][google.cloud.dialogflow.v2.Contexts.ListContexts]. - 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: - ~.context.ListContextsResponse: - The response message for - [Contexts.ListContexts][google.cloud.dialogflow.v2.Contexts.ListContexts]. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v2/{parent=projects/*/agent/sessions/*}/contexts', - }, -{ - 'method': 'get', - 'uri': '/v2/{parent=projects/*/agent/environments/*/users/*/sessions/*}/contexts', - }, -{ - 'method': 'get', - 'uri': '/v2/{parent=projects/*/locations/*/agent/sessions/*}/contexts', - }, -{ - 'method': 'get', - 'uri': '/v2/{parent=projects/*/locations/*/agent/environments/*/users/*/sessions/*}/contexts', - }, - ] - request, metadata = self._interceptor.pre_list_contexts(request, metadata) - pb_request = context.ListContextsRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - including_default_value_fields=False, - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = context.ListContextsResponse() - pb_resp = context.ListContextsResponse.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_list_contexts(resp) - return resp - - class _UpdateContext(ContextsRestStub): - def __hash__(self): - return hash("UpdateContext") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: gcd_context.UpdateContextRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> gcd_context.Context: - r"""Call the update context method over HTTP. - - Args: - request (~.gcd_context.UpdateContextRequest): - The request object. The request message for - [Contexts.UpdateContext][google.cloud.dialogflow.v2.Contexts.UpdateContext]. - 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: - ~.gcd_context.Context: - Dialogflow contexts are similar to natural language - context. If a person says to you "they are orange", you - need context in order to understand what "they" is - referring to. Similarly, for Dialogflow to handle an - end-user expression like that, it needs to be provided - with context in order to correctly match an intent. - - Using contexts, you can control the flow of a - conversation. You can configure contexts for an intent - by setting input and output contexts, which are - identified by string names. When an intent is matched, - any configured output contexts for that intent become - active. While any contexts are active, Dialogflow is - more likely to match intents that are configured with - input contexts that correspond to the currently active - contexts. - - For more information about context, see the `Contexts - guide `__. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'patch', - 'uri': '/v2/{context.name=projects/*/agent/sessions/*/contexts/*}', - 'body': 'context', - }, -{ - 'method': 'patch', - 'uri': '/v2/{context.name=projects/*/agent/environments/*/users/*/sessions/*/contexts/*}', - 'body': 'context', - }, -{ - 'method': 'patch', - 'uri': '/v2/{context.name=projects/*/locations/*/agent/sessions/*/contexts/*}', - 'body': 'context', - }, -{ - 'method': 'patch', - 'uri': '/v2/{context.name=projects/*/locations/*/agent/environments/*/users/*/sessions/*/contexts/*}', - 'body': 'context', - }, - ] - request, metadata = self._interceptor.pre_update_context(request, metadata) - pb_request = gcd_context.UpdateContextRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request['body'], - including_default_value_fields=False, - use_integers_for_enums=True - ) - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - including_default_value_fields=False, - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = gcd_context.Context() - pb_resp = gcd_context.Context.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_update_context(resp) - return resp - - @property - def create_context(self) -> Callable[ - [gcd_context.CreateContextRequest], - gcd_context.Context]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._CreateContext(self._session, self._host, self._interceptor) # type: ignore - - @property - def delete_all_contexts(self) -> Callable[ - [context.DeleteAllContextsRequest], - empty_pb2.Empty]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._DeleteAllContexts(self._session, self._host, self._interceptor) # type: ignore - - @property - def delete_context(self) -> Callable[ - [context.DeleteContextRequest], - empty_pb2.Empty]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._DeleteContext(self._session, self._host, self._interceptor) # type: ignore - - @property - def get_context(self) -> Callable[ - [context.GetContextRequest], - context.Context]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._GetContext(self._session, self._host, self._interceptor) # type: ignore - - @property - def list_contexts(self) -> Callable[ - [context.ListContextsRequest], - context.ListContextsResponse]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._ListContexts(self._session, self._host, self._interceptor) # type: ignore - - @property - def update_context(self) -> Callable[ - [gcd_context.UpdateContextRequest], - gcd_context.Context]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._UpdateContext(self._session, self._host, self._interceptor) # type: ignore - - @property - def get_location(self): - return self._GetLocation(self._session, self._host, self._interceptor) # type: ignore - - class _GetLocation(ContextsRestStub): - def __call__(self, - request: locations_pb2.GetLocationRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> locations_pb2.Location: - - r"""Call the get location method over HTTP. - - Args: - request (locations_pb2.GetLocationRequest): - The request object for GetLocation method. - 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: - locations_pb2.Location: Response from GetLocation method. - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v2/{name=projects/*/locations/*}', - }, - ] - - request, metadata = self._interceptor.pre_get_location(request, metadata) - request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode( - http_options, **request_kwargs) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json.dumps(transcoded_request['query_params'])) - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - resp = locations_pb2.Location() - resp = json_format.Parse(response.content.decode("utf-8"), resp) - resp = self._interceptor.post_get_location(resp) - return resp - - @property - def list_locations(self): - return self._ListLocations(self._session, self._host, self._interceptor) # type: ignore - - class _ListLocations(ContextsRestStub): - def __call__(self, - request: locations_pb2.ListLocationsRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> locations_pb2.ListLocationsResponse: - - r"""Call the list locations method over HTTP. - - Args: - request (locations_pb2.ListLocationsRequest): - The request object for ListLocations method. - 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: - locations_pb2.ListLocationsResponse: Response from ListLocations method. - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v2/{name=projects/*}/locations', - }, - ] - - request, metadata = self._interceptor.pre_list_locations(request, metadata) - request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode( - http_options, **request_kwargs) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json.dumps(transcoded_request['query_params'])) - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - resp = locations_pb2.ListLocationsResponse() - resp = json_format.Parse(response.content.decode("utf-8"), resp) - resp = self._interceptor.post_list_locations(resp) - return resp - - @property - def cancel_operation(self): - return self._CancelOperation(self._session, self._host, self._interceptor) # type: ignore - - class _CancelOperation(ContextsRestStub): - def __call__(self, - request: operations_pb2.CancelOperationRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> None: - - r"""Call the cancel operation method over HTTP. - - Args: - request (operations_pb2.CancelOperationRequest): - The request object for CancelOperation method. - 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. - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'post', - 'uri': '/v2/{name=projects/*/operations/*}:cancel', - }, -{ - 'method': 'post', - 'uri': '/v2/{name=projects/*/locations/*/operations/*}:cancel', - }, - ] - - request, metadata = self._interceptor.pre_cancel_operation(request, metadata) - request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode( - http_options, **request_kwargs) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json.dumps(transcoded_request['query_params'])) - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - return self._interceptor.post_cancel_operation(None) - - @property - def get_operation(self): - return self._GetOperation(self._session, self._host, self._interceptor) # type: ignore - - class _GetOperation(ContextsRestStub): - def __call__(self, - request: operations_pb2.GetOperationRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> operations_pb2.Operation: - - r"""Call the get operation method over HTTP. - - Args: - request (operations_pb2.GetOperationRequest): - The request object for GetOperation method. - 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: - operations_pb2.Operation: Response from GetOperation method. - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v2/{name=projects/*/operations/*}', - }, -{ - 'method': 'get', - 'uri': '/v2/{name=projects/*/locations/*/operations/*}', - }, - ] - - request, metadata = self._interceptor.pre_get_operation(request, metadata) - request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode( - http_options, **request_kwargs) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json.dumps(transcoded_request['query_params'])) - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - resp = operations_pb2.Operation() - resp = json_format.Parse(response.content.decode("utf-8"), resp) - resp = self._interceptor.post_get_operation(resp) - return resp - - @property - def list_operations(self): - return self._ListOperations(self._session, self._host, self._interceptor) # type: ignore - - class _ListOperations(ContextsRestStub): - def __call__(self, - request: operations_pb2.ListOperationsRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> operations_pb2.ListOperationsResponse: - - r"""Call the list operations method over HTTP. - - Args: - request (operations_pb2.ListOperationsRequest): - The request object for ListOperations method. - 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: - operations_pb2.ListOperationsResponse: Response from ListOperations method. - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v2/{name=projects/*}/operations', - }, -{ - 'method': 'get', - 'uri': '/v2/{name=projects/*/locations/*}/operations', - }, - ] - - request, metadata = self._interceptor.pre_list_operations(request, metadata) - request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode( - http_options, **request_kwargs) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json.dumps(transcoded_request['query_params'])) - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - resp = operations_pb2.ListOperationsResponse() - resp = json_format.Parse(response.content.decode("utf-8"), resp) - resp = self._interceptor.post_list_operations(resp) - return resp - - @property - def kind(self) -> str: - return "rest" - - def close(self): - self._session.close() - - -__all__=( - 'ContextsRestTransport', -) diff --git a/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/conversation_datasets/__init__.py b/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/conversation_datasets/__init__.py deleted file mode 100644 index 7334c7b46..000000000 --- a/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/conversation_datasets/__init__.py +++ /dev/null @@ -1,22 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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 ConversationDatasetsClient -from .async_client import ConversationDatasetsAsyncClient - -__all__ = ( - 'ConversationDatasetsClient', - 'ConversationDatasetsAsyncClient', -) diff --git a/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/conversation_datasets/async_client.py b/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/conversation_datasets/async_client.py deleted file mode 100644 index 84ba47d58..000000000 --- a/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/conversation_datasets/async_client.py +++ /dev/null @@ -1,1072 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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, Mapping, MutableMapping, MutableSequence, Optional, Sequence, Tuple, Type, Union - -from google.cloud.dialogflow_v2 import gapic_version as package_version - -from google.api_core.client_options import ClientOptions -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import retry as retries -from google.auth import credentials as ga_credentials # type: ignore -from google.oauth2 import service_account # type: ignore - -try: - OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] -except AttributeError: # pragma: NO COVER - OptionalRetry = Union[retries.Retry, object] # type: ignore - -from google.api_core import operation # type: ignore -from google.api_core import operation_async # type: ignore -from google.cloud.dialogflow_v2.services.conversation_datasets import pagers -from google.cloud.dialogflow_v2.types import conversation_dataset -from google.cloud.dialogflow_v2.types import conversation_dataset as gcd_conversation_dataset -from google.cloud.location import locations_pb2 # type: ignore -from google.longrunning import operations_pb2 -from google.protobuf import empty_pb2 # type: ignore -from google.protobuf import timestamp_pb2 # type: ignore -from .transports.base import ConversationDatasetsTransport, DEFAULT_CLIENT_INFO -from .transports.grpc_asyncio import ConversationDatasetsGrpcAsyncIOTransport -from .client import ConversationDatasetsClient - - -class ConversationDatasetsAsyncClient: - """Conversation datasets. - Conversation datasets contain raw conversation files and their - customizable metadata that can be used for model training. - """ - - _client: ConversationDatasetsClient - - DEFAULT_ENDPOINT = ConversationDatasetsClient.DEFAULT_ENDPOINT - DEFAULT_MTLS_ENDPOINT = ConversationDatasetsClient.DEFAULT_MTLS_ENDPOINT - - conversation_dataset_path = staticmethod(ConversationDatasetsClient.conversation_dataset_path) - parse_conversation_dataset_path = staticmethod(ConversationDatasetsClient.parse_conversation_dataset_path) - common_billing_account_path = staticmethod(ConversationDatasetsClient.common_billing_account_path) - parse_common_billing_account_path = staticmethod(ConversationDatasetsClient.parse_common_billing_account_path) - common_folder_path = staticmethod(ConversationDatasetsClient.common_folder_path) - parse_common_folder_path = staticmethod(ConversationDatasetsClient.parse_common_folder_path) - common_organization_path = staticmethod(ConversationDatasetsClient.common_organization_path) - parse_common_organization_path = staticmethod(ConversationDatasetsClient.parse_common_organization_path) - common_project_path = staticmethod(ConversationDatasetsClient.common_project_path) - parse_common_project_path = staticmethod(ConversationDatasetsClient.parse_common_project_path) - common_location_path = staticmethod(ConversationDatasetsClient.common_location_path) - parse_common_location_path = staticmethod(ConversationDatasetsClient.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: - ConversationDatasetsAsyncClient: The constructed client. - """ - return ConversationDatasetsClient.from_service_account_info.__func__(ConversationDatasetsAsyncClient, 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: - ConversationDatasetsAsyncClient: The constructed client. - """ - return ConversationDatasetsClient.from_service_account_file.__func__(ConversationDatasetsAsyncClient, filename, *args, **kwargs) # type: ignore - - from_service_account_json = from_service_account_file - - @classmethod - def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[ClientOptions] = None): - """Return the API endpoint and client cert source for mutual TLS. - - The client cert source is determined in the following order: - (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the - client cert source is None. - (2) if `client_options.client_cert_source` is provided, use the provided one; if the - default client cert source exists, use the default one; otherwise the client cert - source is None. - - The API endpoint is determined in the following order: - (1) if `client_options.api_endpoint` if provided, use the provided one. - (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the - default mTLS endpoint; if the environment variable is "never", use the default API - endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise - use the default API endpoint. - - More details can be found at https://google.aip.dev/auth/4114. - - Args: - client_options (google.api_core.client_options.ClientOptions): Custom options for the - client. Only the `api_endpoint` and `client_cert_source` properties may be used - in this method. - - Returns: - Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the - client cert source to use. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If any errors happen. - """ - return ConversationDatasetsClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore - - @property - def transport(self) -> ConversationDatasetsTransport: - """Returns the transport used by the client instance. - - Returns: - ConversationDatasetsTransport: The transport used by the client instance. - """ - return self._client.transport - - get_transport_class = functools.partial(type(ConversationDatasetsClient).get_transport_class, type(ConversationDatasetsClient)) - - def __init__(self, *, - credentials: Optional[ga_credentials.Credentials] = None, - transport: Union[str, ConversationDatasetsTransport] = "grpc_asyncio", - client_options: Optional[ClientOptions] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the conversation datasets 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, ~.ConversationDatasetsTransport]): 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 = ConversationDatasetsClient( - credentials=credentials, - transport=transport, - client_options=client_options, - client_info=client_info, - - ) - - async def create_conversation_dataset(self, - request: Optional[Union[gcd_conversation_dataset.CreateConversationDatasetRequest, dict]] = None, - *, - parent: Optional[str] = None, - conversation_dataset: Optional[gcd_conversation_dataset.ConversationDataset] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation_async.AsyncOperation: - r"""Creates a new conversation dataset. - - This method is a `long-running - operation `__. - The returned ``Operation`` type has the following - method-specific fields: - - - ``metadata``: - [CreateConversationDatasetOperationMetadata][google.cloud.dialogflow.v2.CreateConversationDatasetOperationMetadata] - - ``response``: - [ConversationDataset][google.cloud.dialogflow.v2.ConversationDataset] - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import dialogflow_v2 - - async def sample_create_conversation_dataset(): - # Create a client - client = dialogflow_v2.ConversationDatasetsAsyncClient() - - # Initialize request argument(s) - conversation_dataset = dialogflow_v2.ConversationDataset() - conversation_dataset.display_name = "display_name_value" - - request = dialogflow_v2.CreateConversationDatasetRequest( - parent="parent_value", - conversation_dataset=conversation_dataset, - ) - - # Make the request - operation = client.create_conversation_dataset(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.dialogflow_v2.types.CreateConversationDatasetRequest, dict]]): - The request object. The request message for - [ConversationDatasets.CreateConversationDataset][google.cloud.dialogflow.v2.ConversationDatasets.CreateConversationDataset]. - parent (:class:`str`): - Required. The project to create conversation dataset - for. Format: - ``projects//locations/`` - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - conversation_dataset (:class:`google.cloud.dialogflow_v2.types.ConversationDataset`): - Required. The conversation dataset to - create. - - This corresponds to the ``conversation_dataset`` field - on the ``request`` instance; if ``request`` is provided, this - should not 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.api_core.operation_async.AsyncOperation: - An object representing a long-running operation. - - The result type for the operation will be :class:`google.cloud.dialogflow_v2.types.ConversationDataset` Represents a conversation dataset that a user imports raw data into. - The data inside ConversationDataset can not be - changed after ImportConversationData finishes (and - calling ImportConversationData on a dataset that - already has data is not allowed). - - """ - # Create or coerce a protobuf request object. - # Quick 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, conversation_dataset]) - 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_conversation_dataset.CreateConversationDatasetRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - if conversation_dataset is not None: - request.conversation_dataset = conversation_dataset - - # 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_conversation_dataset, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Wrap the response in an operation future. - response = operation_async.from_gapic( - response, - self._client._transport.operations_client, - gcd_conversation_dataset.ConversationDataset, - metadata_type=gcd_conversation_dataset.CreateConversationDatasetOperationMetadata, - ) - - # Done; return the response. - return response - - async def get_conversation_dataset(self, - request: Optional[Union[conversation_dataset.GetConversationDatasetRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> conversation_dataset.ConversationDataset: - r"""Retrieves the specified conversation dataset. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import dialogflow_v2 - - async def sample_get_conversation_dataset(): - # Create a client - client = dialogflow_v2.ConversationDatasetsAsyncClient() - - # Initialize request argument(s) - request = dialogflow_v2.GetConversationDatasetRequest( - name="name_value", - ) - - # Make the request - response = await client.get_conversation_dataset(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.dialogflow_v2.types.GetConversationDatasetRequest, dict]]): - The request object. The request message for - [ConversationDatasets.GetConversationDataset][google.cloud.dialogflow.v2.ConversationDatasets.GetConversationDataset]. - name (:class:`str`): - Required. The conversation dataset to retrieve. Format: - ``projects//locations//conversationDatasets/`` - - 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.ConversationDataset: - Represents a conversation dataset - that a user imports raw data into. The - data inside ConversationDataset can not - be changed after ImportConversationData - finishes (and calling - ImportConversationData on a dataset that - already has data is not allowed). - - """ - # Create or coerce a protobuf request object. - # Quick 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 = conversation_dataset.GetConversationDatasetRequest(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_conversation_dataset, - 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 list_conversation_datasets(self, - request: Optional[Union[conversation_dataset.ListConversationDatasetsRequest, dict]] = None, - *, - parent: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListConversationDatasetsAsyncPager: - r"""Returns the list of all conversation datasets in the - specified project and location. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import dialogflow_v2 - - async def sample_list_conversation_datasets(): - # Create a client - client = dialogflow_v2.ConversationDatasetsAsyncClient() - - # Initialize request argument(s) - request = dialogflow_v2.ListConversationDatasetsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_conversation_datasets(request=request) - - # Handle the response - async for response in page_result: - print(response) - - Args: - request (Optional[Union[google.cloud.dialogflow_v2.types.ListConversationDatasetsRequest, dict]]): - The request object. The request message for - [ConversationDatasets.ListConversationDatasets][google.cloud.dialogflow.v2.ConversationDatasets.ListConversationDatasets]. - parent (:class:`str`): - Required. The project and location name to list all - conversation datasets for. Format: - ``projects//locations/`` - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.dialogflow_v2.services.conversation_datasets.pagers.ListConversationDatasetsAsyncPager: - The response message for - [ConversationDatasets.ListConversationDatasets][google.cloud.dialogflow.v2.ConversationDatasets.ListConversationDatasets]. - - Iterating over this object will yield results and - resolve additional pages automatically. - - """ - # Create or coerce a protobuf request object. - # Quick 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 = conversation_dataset.ListConversationDatasetsRequest(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_conversation_datasets, - 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.ListConversationDatasetsAsyncPager( - method=rpc, - request=request, - response=response, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def delete_conversation_dataset(self, - request: Optional[Union[conversation_dataset.DeleteConversationDatasetRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation_async.AsyncOperation: - r"""Deletes the specified conversation dataset. - - This method is a `long-running - operation `__. - The returned ``Operation`` type has the following - method-specific fields: - - - ``metadata``: - [DeleteConversationDatasetOperationMetadata][google.cloud.dialogflow.v2.DeleteConversationDatasetOperationMetadata] - - ``response``: An `Empty - message `__ - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import dialogflow_v2 - - async def sample_delete_conversation_dataset(): - # Create a client - client = dialogflow_v2.ConversationDatasetsAsyncClient() - - # Initialize request argument(s) - request = dialogflow_v2.DeleteConversationDatasetRequest( - name="name_value", - ) - - # Make the request - operation = client.delete_conversation_dataset(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.dialogflow_v2.types.DeleteConversationDatasetRequest, dict]]): - The request object. The request message for - [ConversationDatasets.DeleteConversationDataset][google.cloud.dialogflow.v2.ConversationDatasets.DeleteConversationDataset]. - name (:class:`str`): - Required. The conversation dataset to delete. Format: - ``projects//locations//conversationDatasets/`` - - 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.api_core.operation_async.AsyncOperation: - An object representing a long-running operation. - - The result type for the operation will be :class:`google.protobuf.empty_pb2.Empty` A generic empty message that you can re-use to avoid defining duplicated - empty messages in your APIs. A typical example is to - use it as the request or the response type of an API - method. For instance: - - service Foo { - rpc Bar(google.protobuf.Empty) returns - (google.protobuf.Empty); - - } - - """ - # Create or coerce a protobuf request object. - # Quick 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 = conversation_dataset.DeleteConversationDatasetRequest(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_conversation_dataset, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Wrap the response in an operation future. - response = operation_async.from_gapic( - response, - self._client._transport.operations_client, - empty_pb2.Empty, - metadata_type=conversation_dataset.DeleteConversationDatasetOperationMetadata, - ) - - # Done; return the response. - return response - - async def import_conversation_data(self, - request: Optional[Union[conversation_dataset.ImportConversationDataRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation_async.AsyncOperation: - r"""Import data into the specified conversation dataset. Note that - it is not allowed to import data to a conversation dataset that - already has data in it. - - This method is a `long-running - operation `__. - The returned ``Operation`` type has the following - method-specific fields: - - - ``metadata``: - [ImportConversationDataOperationMetadata][google.cloud.dialogflow.v2.ImportConversationDataOperationMetadata] - - ``response``: - [ImportConversationDataOperationResponse][google.cloud.dialogflow.v2.ImportConversationDataOperationResponse] - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import dialogflow_v2 - - async def sample_import_conversation_data(): - # Create a client - client = dialogflow_v2.ConversationDatasetsAsyncClient() - - # Initialize request argument(s) - input_config = dialogflow_v2.InputConfig() - input_config.gcs_source.uris = ['uris_value1', 'uris_value2'] - - request = dialogflow_v2.ImportConversationDataRequest( - name="name_value", - input_config=input_config, - ) - - # Make the request - operation = client.import_conversation_data(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.dialogflow_v2.types.ImportConversationDataRequest, dict]]): - The request object. The request message for - [ConversationDatasets.ImportConversationData][google.cloud.dialogflow.v2.ConversationDatasets.ImportConversationData]. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.api_core.operation_async.AsyncOperation: - An object representing a long-running operation. - - The result type for the operation will be :class:`google.cloud.dialogflow_v2.types.ImportConversationDataOperationResponse` Response used for - [ConversationDatasets.ImportConversationData][google.cloud.dialogflow.v2.ConversationDatasets.ImportConversationData] - long running operation. - - """ - # Create or coerce a protobuf request object. - request = conversation_dataset.ImportConversationDataRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.import_conversation_data, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Wrap the response in an operation future. - response = operation_async.from_gapic( - response, - self._client._transport.operations_client, - conversation_dataset.ImportConversationDataOperationResponse, - metadata_type=conversation_dataset.ImportConversationDataOperationMetadata, - ) - - # Done; return the response. - return response - - async def list_operations( - self, - request: Optional[operations_pb2.ListOperationsRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operations_pb2.ListOperationsResponse: - r"""Lists operations that match the specified filter in the request. - - Args: - request (:class:`~.operations_pb2.ListOperationsRequest`): - The request object. Request message for - `ListOperations` method. - 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: - ~.operations_pb2.ListOperationsResponse: - Response message for ``ListOperations`` method. - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = operations_pb2.ListOperationsRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._client._transport.list_operations, - 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 get_operation( - self, - request: Optional[operations_pb2.GetOperationRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operations_pb2.Operation: - r"""Gets the latest state of a long-running operation. - - Args: - request (:class:`~.operations_pb2.GetOperationRequest`): - The request object. Request message for - `GetOperation` method. - 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: - ~.operations_pb2.Operation: - An ``Operation`` object. - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = operations_pb2.GetOperationRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._client._transport.get_operation, - 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 cancel_operation( - self, - request: Optional[operations_pb2.CancelOperationRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> None: - r"""Starts asynchronous cancellation on a long-running operation. - - The server makes a best effort to cancel the operation, but success - is not guaranteed. If the server doesn't support this method, it returns - `google.rpc.Code.UNIMPLEMENTED`. - - Args: - request (:class:`~.operations_pb2.CancelOperationRequest`): - The request object. Request message for - `CancelOperation` method. - 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: - None - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = operations_pb2.CancelOperationRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._client._transport.cancel_operation, - 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_location( - self, - request: Optional[locations_pb2.GetLocationRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> locations_pb2.Location: - r"""Gets information about a location. - - Args: - request (:class:`~.location_pb2.GetLocationRequest`): - The request object. Request message for - `GetLocation` method. - 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: - ~.location_pb2.Location: - Location object. - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = locations_pb2.GetLocationRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._client._transport.get_location, - 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 list_locations( - self, - request: Optional[locations_pb2.ListLocationsRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> locations_pb2.ListLocationsResponse: - r"""Lists information about the supported locations for this service. - - Args: - request (:class:`~.location_pb2.ListLocationsRequest`): - The request object. Request message for - `ListLocations` method. - 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: - ~.location_pb2.ListLocationsResponse: - Response message for ``ListLocations`` method. - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = locations_pb2.ListLocationsRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._client._transport.list_locations, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("name", request.name),)), - ) - - # Send the request. - response = await rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - async def __aenter__(self): - return self - - async def __aexit__(self, exc_type, exc, tb): - await self.transport.close() - -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) - - -__all__ = ( - "ConversationDatasetsAsyncClient", -) diff --git a/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/conversation_datasets/client.py b/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/conversation_datasets/client.py deleted file mode 100644 index 4cfe703f0..000000000 --- a/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/conversation_datasets/client.py +++ /dev/null @@ -1,1272 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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 os -import re -from typing import Dict, Mapping, MutableMapping, MutableSequence, Optional, Sequence, Tuple, Type, Union, cast - -from google.cloud.dialogflow_v2 import gapic_version as package_version - -from google.api_core import client_options as client_options_lib -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import retry as retries -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 - -try: - OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] -except AttributeError: # pragma: NO COVER - OptionalRetry = Union[retries.Retry, object] # type: ignore - -from google.api_core import operation # type: ignore -from google.api_core import operation_async # type: ignore -from google.cloud.dialogflow_v2.services.conversation_datasets import pagers -from google.cloud.dialogflow_v2.types import conversation_dataset -from google.cloud.dialogflow_v2.types import conversation_dataset as gcd_conversation_dataset -from google.cloud.location import locations_pb2 # type: ignore -from google.longrunning import operations_pb2 -from google.protobuf import empty_pb2 # type: ignore -from google.protobuf import timestamp_pb2 # type: ignore -from .transports.base import ConversationDatasetsTransport, DEFAULT_CLIENT_INFO -from .transports.grpc import ConversationDatasetsGrpcTransport -from .transports.grpc_asyncio import ConversationDatasetsGrpcAsyncIOTransport -from .transports.rest import ConversationDatasetsRestTransport - - -class ConversationDatasetsClientMeta(type): - """Metaclass for the ConversationDatasets 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[ConversationDatasetsTransport]] - _transport_registry["grpc"] = ConversationDatasetsGrpcTransport - _transport_registry["grpc_asyncio"] = ConversationDatasetsGrpcAsyncIOTransport - _transport_registry["rest"] = ConversationDatasetsRestTransport - - def get_transport_class(cls, - label: Optional[str] = None, - ) -> Type[ConversationDatasetsTransport]: - """Returns an appropriate transport class. - - Args: - label: The name of the desired transport. If none is - provided, then the first transport in the registry is used. - - Returns: - The transport class to use. - """ - # If a specific transport is requested, return that one. - if label: - return cls._transport_registry[label] - - # No transport is requested; return the default (that is, the first one - # in the dictionary). - return next(iter(cls._transport_registry.values())) - - -class ConversationDatasetsClient(metaclass=ConversationDatasetsClientMeta): - """Conversation datasets. - Conversation datasets contain raw conversation files and their - customizable metadata that can be used for model training. - """ - - @staticmethod - def _get_default_mtls_endpoint(api_endpoint): - """Converts api endpoint to mTLS endpoint. - - Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to - "*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively. - Args: - api_endpoint (Optional[str]): the api endpoint to convert. - Returns: - str: converted mTLS api endpoint. - """ - if not api_endpoint: - return api_endpoint - - mtls_endpoint_re = re.compile( - r"(?P[^.]+)(?P\.mtls)?(?P\.sandbox)?(?P\.googleapis\.com)?" - ) - - m = mtls_endpoint_re.match(api_endpoint) - name, mtls, sandbox, googledomain = m.groups() - if mtls or not googledomain: - return api_endpoint - - if sandbox: - return api_endpoint.replace( - "sandbox.googleapis.com", "mtls.sandbox.googleapis.com" - ) - - return api_endpoint.replace(".googleapis.com", ".mtls.googleapis.com") - - DEFAULT_ENDPOINT = "dialogflow.googleapis.com" - DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore - DEFAULT_ENDPOINT - ) - - @classmethod - def from_service_account_info(cls, info: dict, *args, **kwargs): - """Creates an instance of this client using the provided credentials - info. - - Args: - info (dict): The service account private key info. - args: Additional arguments to pass to the constructor. - kwargs: Additional arguments to pass to the constructor. - - Returns: - ConversationDatasetsClient: 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: - ConversationDatasetsClient: 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) -> ConversationDatasetsTransport: - """Returns the transport used by the client instance. - - Returns: - ConversationDatasetsTransport: The transport used by the client - instance. - """ - return self._transport - - @staticmethod - def conversation_dataset_path(project: str,location: str,conversation_dataset: str,) -> str: - """Returns a fully-qualified conversation_dataset string.""" - return "projects/{project}/locations/{location}/conversationDatasets/{conversation_dataset}".format(project=project, location=location, conversation_dataset=conversation_dataset, ) - - @staticmethod - def parse_conversation_dataset_path(path: str) -> Dict[str,str]: - """Parses a conversation_dataset path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/conversationDatasets/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_billing_account_path(billing_account: str, ) -> str: - """Returns a fully-qualified billing_account string.""" - return "billingAccounts/{billing_account}".format(billing_account=billing_account, ) - - @staticmethod - def parse_common_billing_account_path(path: str) -> Dict[str,str]: - """Parse a billing_account path into its component segments.""" - m = re.match(r"^billingAccounts/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_folder_path(folder: str, ) -> str: - """Returns a fully-qualified folder string.""" - return "folders/{folder}".format(folder=folder, ) - - @staticmethod - def parse_common_folder_path(path: str) -> Dict[str,str]: - """Parse a folder path into its component segments.""" - m = re.match(r"^folders/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_organization_path(organization: str, ) -> str: - """Returns a fully-qualified organization string.""" - return "organizations/{organization}".format(organization=organization, ) - - @staticmethod - def parse_common_organization_path(path: str) -> Dict[str,str]: - """Parse a organization path into its component segments.""" - m = re.match(r"^organizations/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_project_path(project: str, ) -> str: - """Returns a fully-qualified project string.""" - return "projects/{project}".format(project=project, ) - - @staticmethod - def parse_common_project_path(path: str) -> Dict[str,str]: - """Parse a project path into its component segments.""" - m = re.match(r"^projects/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_location_path(project: str, location: str, ) -> str: - """Returns a fully-qualified location string.""" - return "projects/{project}/locations/{location}".format(project=project, location=location, ) - - @staticmethod - def parse_common_location_path(path: str) -> Dict[str,str]: - """Parse a location path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)$", path) - return m.groupdict() if m else {} - - @classmethod - def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[client_options_lib.ClientOptions] = None): - """Return the API endpoint and client cert source for mutual TLS. - - The client cert source is determined in the following order: - (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the - client cert source is None. - (2) if `client_options.client_cert_source` is provided, use the provided one; if the - default client cert source exists, use the default one; otherwise the client cert - source is None. - - The API endpoint is determined in the following order: - (1) if `client_options.api_endpoint` if provided, use the provided one. - (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the - default mTLS endpoint; if the environment variable is "never", use the default API - endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise - use the default API endpoint. - - More details can be found at https://google.aip.dev/auth/4114. - - Args: - client_options (google.api_core.client_options.ClientOptions): Custom options for the - client. Only the `api_endpoint` and `client_cert_source` properties may be used - in this method. - - Returns: - Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the - client cert source to use. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If any errors happen. - """ - if client_options is None: - client_options = client_options_lib.ClientOptions() - use_client_cert = os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false") - use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") - if use_client_cert not in ("true", "false"): - raise ValueError("Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`") - if use_mtls_endpoint not in ("auto", "never", "always"): - raise MutualTLSChannelError("Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`") - - # Figure out the client cert source to use. - client_cert_source = None - if use_client_cert == "true": - if client_options.client_cert_source: - client_cert_source = client_options.client_cert_source - elif mtls.has_default_client_cert_source(): - client_cert_source = mtls.default_client_cert_source() - - # Figure out which api endpoint to use. - if client_options.api_endpoint is not None: - api_endpoint = client_options.api_endpoint - elif use_mtls_endpoint == "always" or (use_mtls_endpoint == "auto" and client_cert_source): - api_endpoint = cls.DEFAULT_MTLS_ENDPOINT - else: - api_endpoint = cls.DEFAULT_ENDPOINT - - return api_endpoint, client_cert_source - - def __init__(self, *, - credentials: Optional[ga_credentials.Credentials] = None, - transport: Optional[Union[str, ConversationDatasetsTransport]] = None, - client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the conversation datasets 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, ConversationDatasetsTransport]): The - transport to use. If set to None, a transport is chosen - automatically. - client_options (Optional[Union[google.api_core.client_options.ClientOptions, dict]]): 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() - client_options = cast(client_options_lib.ClientOptions, client_options) - - api_endpoint, client_cert_source_func = self.get_mtls_endpoint_and_cert_source(client_options) - - api_key_value = getattr(client_options, "api_key", None) - if api_key_value and credentials: - raise ValueError("client_options.api_key and credentials are mutually exclusive") - - # 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, ConversationDatasetsTransport): - # transport is a ConversationDatasetsTransport instance. - if credentials or client_options.credentials_file or api_key_value: - 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: - import google.auth._default # type: ignore - - if api_key_value and hasattr(google.auth._default, "get_api_key_credentials"): - credentials = google.auth._default.get_api_key_credentials(api_key_value) - - Transport = type(self).get_transport_class(transport) - self._transport = Transport( - credentials=credentials, - credentials_file=client_options.credentials_file, - host=api_endpoint, - scopes=client_options.scopes, - client_cert_source_for_mtls=client_cert_source_func, - quota_project_id=client_options.quota_project_id, - client_info=client_info, - always_use_jwt_access=True, - api_audience=client_options.api_audience, - ) - - def create_conversation_dataset(self, - request: Optional[Union[gcd_conversation_dataset.CreateConversationDatasetRequest, dict]] = None, - *, - parent: Optional[str] = None, - conversation_dataset: Optional[gcd_conversation_dataset.ConversationDataset] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation.Operation: - r"""Creates a new conversation dataset. - - This method is a `long-running - operation `__. - The returned ``Operation`` type has the following - method-specific fields: - - - ``metadata``: - [CreateConversationDatasetOperationMetadata][google.cloud.dialogflow.v2.CreateConversationDatasetOperationMetadata] - - ``response``: - [ConversationDataset][google.cloud.dialogflow.v2.ConversationDataset] - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import dialogflow_v2 - - def sample_create_conversation_dataset(): - # Create a client - client = dialogflow_v2.ConversationDatasetsClient() - - # Initialize request argument(s) - conversation_dataset = dialogflow_v2.ConversationDataset() - conversation_dataset.display_name = "display_name_value" - - request = dialogflow_v2.CreateConversationDatasetRequest( - parent="parent_value", - conversation_dataset=conversation_dataset, - ) - - # Make the request - operation = client.create_conversation_dataset(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.dialogflow_v2.types.CreateConversationDatasetRequest, dict]): - The request object. The request message for - [ConversationDatasets.CreateConversationDataset][google.cloud.dialogflow.v2.ConversationDatasets.CreateConversationDataset]. - parent (str): - Required. The project to create conversation dataset - for. Format: - ``projects//locations/`` - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - conversation_dataset (google.cloud.dialogflow_v2.types.ConversationDataset): - Required. The conversation dataset to - create. - - This corresponds to the ``conversation_dataset`` field - on the ``request`` instance; if ``request`` is provided, this - should not 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.api_core.operation.Operation: - An object representing a long-running operation. - - The result type for the operation will be :class:`google.cloud.dialogflow_v2.types.ConversationDataset` Represents a conversation dataset that a user imports raw data into. - The data inside ConversationDataset can not be - changed after ImportConversationData finishes (and - calling ImportConversationData on a dataset that - already has data is not allowed). - - """ - # Create or coerce a protobuf request object. - # Quick 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, conversation_dataset]) - 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_conversation_dataset.CreateConversationDatasetRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, gcd_conversation_dataset.CreateConversationDatasetRequest): - request = gcd_conversation_dataset.CreateConversationDatasetRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - if conversation_dataset is not None: - request.conversation_dataset = conversation_dataset - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.create_conversation_dataset] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Wrap the response in an operation future. - response = operation.from_gapic( - response, - self._transport.operations_client, - gcd_conversation_dataset.ConversationDataset, - metadata_type=gcd_conversation_dataset.CreateConversationDatasetOperationMetadata, - ) - - # Done; return the response. - return response - - def get_conversation_dataset(self, - request: Optional[Union[conversation_dataset.GetConversationDatasetRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> conversation_dataset.ConversationDataset: - r"""Retrieves the specified conversation dataset. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import dialogflow_v2 - - def sample_get_conversation_dataset(): - # Create a client - client = dialogflow_v2.ConversationDatasetsClient() - - # Initialize request argument(s) - request = dialogflow_v2.GetConversationDatasetRequest( - name="name_value", - ) - - # Make the request - response = client.get_conversation_dataset(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.dialogflow_v2.types.GetConversationDatasetRequest, dict]): - The request object. The request message for - [ConversationDatasets.GetConversationDataset][google.cloud.dialogflow.v2.ConversationDatasets.GetConversationDataset]. - name (str): - Required. The conversation dataset to retrieve. Format: - ``projects//locations//conversationDatasets/`` - - 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.ConversationDataset: - Represents a conversation dataset - that a user imports raw data into. The - data inside ConversationDataset can not - be changed after ImportConversationData - finishes (and calling - ImportConversationData on a dataset that - already has data is not allowed). - - """ - # Create or coerce a protobuf request object. - # Quick 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 conversation_dataset.GetConversationDatasetRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, conversation_dataset.GetConversationDatasetRequest): - request = conversation_dataset.GetConversationDatasetRequest(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_conversation_dataset] - - # 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 list_conversation_datasets(self, - request: Optional[Union[conversation_dataset.ListConversationDatasetsRequest, dict]] = None, - *, - parent: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListConversationDatasetsPager: - r"""Returns the list of all conversation datasets in the - specified project and location. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import dialogflow_v2 - - def sample_list_conversation_datasets(): - # Create a client - client = dialogflow_v2.ConversationDatasetsClient() - - # Initialize request argument(s) - request = dialogflow_v2.ListConversationDatasetsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_conversation_datasets(request=request) - - # Handle the response - for response in page_result: - print(response) - - Args: - request (Union[google.cloud.dialogflow_v2.types.ListConversationDatasetsRequest, dict]): - The request object. The request message for - [ConversationDatasets.ListConversationDatasets][google.cloud.dialogflow.v2.ConversationDatasets.ListConversationDatasets]. - parent (str): - Required. The project and location name to list all - conversation datasets for. Format: - ``projects//locations/`` - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.dialogflow_v2.services.conversation_datasets.pagers.ListConversationDatasetsPager: - The response message for - [ConversationDatasets.ListConversationDatasets][google.cloud.dialogflow.v2.ConversationDatasets.ListConversationDatasets]. - - Iterating over this object will yield results and - resolve additional pages automatically. - - """ - # Create or coerce a protobuf request object. - # Quick 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 conversation_dataset.ListConversationDatasetsRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, conversation_dataset.ListConversationDatasetsRequest): - request = conversation_dataset.ListConversationDatasetsRequest(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_conversation_datasets] - - # 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.ListConversationDatasetsPager( - method=rpc, - request=request, - response=response, - metadata=metadata, - ) - - # Done; return the response. - return response - - def delete_conversation_dataset(self, - request: Optional[Union[conversation_dataset.DeleteConversationDatasetRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation.Operation: - r"""Deletes the specified conversation dataset. - - This method is a `long-running - operation `__. - The returned ``Operation`` type has the following - method-specific fields: - - - ``metadata``: - [DeleteConversationDatasetOperationMetadata][google.cloud.dialogflow.v2.DeleteConversationDatasetOperationMetadata] - - ``response``: An `Empty - message `__ - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import dialogflow_v2 - - def sample_delete_conversation_dataset(): - # Create a client - client = dialogflow_v2.ConversationDatasetsClient() - - # Initialize request argument(s) - request = dialogflow_v2.DeleteConversationDatasetRequest( - name="name_value", - ) - - # Make the request - operation = client.delete_conversation_dataset(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.dialogflow_v2.types.DeleteConversationDatasetRequest, dict]): - The request object. The request message for - [ConversationDatasets.DeleteConversationDataset][google.cloud.dialogflow.v2.ConversationDatasets.DeleteConversationDataset]. - name (str): - Required. The conversation dataset to delete. Format: - ``projects//locations//conversationDatasets/`` - - 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.api_core.operation.Operation: - An object representing a long-running operation. - - The result type for the operation will be :class:`google.protobuf.empty_pb2.Empty` A generic empty message that you can re-use to avoid defining duplicated - empty messages in your APIs. A typical example is to - use it as the request or the response type of an API - method. For instance: - - service Foo { - rpc Bar(google.protobuf.Empty) returns - (google.protobuf.Empty); - - } - - """ - # Create or coerce a protobuf request object. - # Quick 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 conversation_dataset.DeleteConversationDatasetRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, conversation_dataset.DeleteConversationDatasetRequest): - request = conversation_dataset.DeleteConversationDatasetRequest(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_conversation_dataset] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Wrap the response in an operation future. - response = operation.from_gapic( - response, - self._transport.operations_client, - empty_pb2.Empty, - metadata_type=conversation_dataset.DeleteConversationDatasetOperationMetadata, - ) - - # Done; return the response. - return response - - def import_conversation_data(self, - request: Optional[Union[conversation_dataset.ImportConversationDataRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation.Operation: - r"""Import data into the specified conversation dataset. Note that - it is not allowed to import data to a conversation dataset that - already has data in it. - - This method is a `long-running - operation `__. - The returned ``Operation`` type has the following - method-specific fields: - - - ``metadata``: - [ImportConversationDataOperationMetadata][google.cloud.dialogflow.v2.ImportConversationDataOperationMetadata] - - ``response``: - [ImportConversationDataOperationResponse][google.cloud.dialogflow.v2.ImportConversationDataOperationResponse] - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import dialogflow_v2 - - def sample_import_conversation_data(): - # Create a client - client = dialogflow_v2.ConversationDatasetsClient() - - # Initialize request argument(s) - input_config = dialogflow_v2.InputConfig() - input_config.gcs_source.uris = ['uris_value1', 'uris_value2'] - - request = dialogflow_v2.ImportConversationDataRequest( - name="name_value", - input_config=input_config, - ) - - # Make the request - operation = client.import_conversation_data(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.dialogflow_v2.types.ImportConversationDataRequest, dict]): - The request object. The request message for - [ConversationDatasets.ImportConversationData][google.cloud.dialogflow.v2.ConversationDatasets.ImportConversationData]. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.api_core.operation.Operation: - An object representing a long-running operation. - - The result type for the operation will be :class:`google.cloud.dialogflow_v2.types.ImportConversationDataOperationResponse` Response used for - [ConversationDatasets.ImportConversationData][google.cloud.dialogflow.v2.ConversationDatasets.ImportConversationData] - long running operation. - - """ - # Create or coerce a protobuf request object. - # Minor optimization to avoid making a copy if the user passes - # in a conversation_dataset.ImportConversationDataRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, conversation_dataset.ImportConversationDataRequest): - request = conversation_dataset.ImportConversationDataRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.import_conversation_data] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Wrap the response in an operation future. - response = operation.from_gapic( - response, - self._transport.operations_client, - conversation_dataset.ImportConversationDataOperationResponse, - metadata_type=conversation_dataset.ImportConversationDataOperationMetadata, - ) - - # Done; return the response. - return response - - def __enter__(self) -> "ConversationDatasetsClient": - return self - - def __exit__(self, type, value, traceback): - """Releases underlying transport's resources. - - .. warning:: - ONLY use as a context manager if the transport is NOT shared - with other clients! Exiting the with block will CLOSE the transport - and may cause errors in other clients! - """ - self.transport.close() - - def list_operations( - self, - request: Optional[operations_pb2.ListOperationsRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operations_pb2.ListOperationsResponse: - r"""Lists operations that match the specified filter in the request. - - Args: - request (:class:`~.operations_pb2.ListOperationsRequest`): - The request object. Request message for - `ListOperations` method. - 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: - ~.operations_pb2.ListOperationsResponse: - Response message for ``ListOperations`` method. - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = operations_pb2.ListOperationsRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._transport.list_operations, - 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 = rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - def get_operation( - self, - request: Optional[operations_pb2.GetOperationRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operations_pb2.Operation: - r"""Gets the latest state of a long-running operation. - - Args: - request (:class:`~.operations_pb2.GetOperationRequest`): - The request object. Request message for - `GetOperation` method. - 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: - ~.operations_pb2.Operation: - An ``Operation`` object. - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = operations_pb2.GetOperationRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._transport.get_operation, - 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 = rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - def cancel_operation( - self, - request: Optional[operations_pb2.CancelOperationRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> None: - r"""Starts asynchronous cancellation on a long-running operation. - - The server makes a best effort to cancel the operation, but success - is not guaranteed. If the server doesn't support this method, it returns - `google.rpc.Code.UNIMPLEMENTED`. - - Args: - request (:class:`~.operations_pb2.CancelOperationRequest`): - The request object. Request message for - `CancelOperation` method. - 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: - None - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = operations_pb2.CancelOperationRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._transport.cancel_operation, - 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. - rpc(request, retry=retry, timeout=timeout, metadata=metadata,) - - def get_location( - self, - request: Optional[locations_pb2.GetLocationRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> locations_pb2.Location: - r"""Gets information about a location. - - Args: - request (:class:`~.location_pb2.GetLocationRequest`): - The request object. Request message for - `GetLocation` method. - 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: - ~.location_pb2.Location: - Location object. - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = locations_pb2.GetLocationRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._transport.get_location, - 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 = rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - def list_locations( - self, - request: Optional[locations_pb2.ListLocationsRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> locations_pb2.ListLocationsResponse: - r"""Lists information about the supported locations for this service. - - Args: - request (:class:`~.location_pb2.ListLocationsRequest`): - The request object. Request message for - `ListLocations` method. - 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: - ~.location_pb2.ListLocationsResponse: - Response message for ``ListLocations`` method. - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = locations_pb2.ListLocationsRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._transport.list_locations, - 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 = rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) - - -__all__ = ( - "ConversationDatasetsClient", -) diff --git a/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/conversation_datasets/pagers.py b/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/conversation_datasets/pagers.py deleted file mode 100644 index 23778c56b..000000000 --- a/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/conversation_datasets/pagers.py +++ /dev/null @@ -1,139 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from typing import Any, AsyncIterator, Awaitable, Callable, Sequence, Tuple, Optional, Iterator - -from google.cloud.dialogflow_v2.types import conversation_dataset - - -class ListConversationDatasetsPager: - """A pager for iterating through ``list_conversation_datasets`` requests. - - This class thinly wraps an initial - :class:`google.cloud.dialogflow_v2.types.ListConversationDatasetsResponse` object, and - provides an ``__iter__`` method to iterate through its - ``conversation_datasets`` field. - - If there are more pages, the ``__iter__`` method will make additional - ``ListConversationDatasets`` requests and continue to iterate - through the ``conversation_datasets`` field on the - corresponding responses. - - All the usual :class:`google.cloud.dialogflow_v2.types.ListConversationDatasetsResponse` - 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[..., conversation_dataset.ListConversationDatasetsResponse], - request: conversation_dataset.ListConversationDatasetsRequest, - response: conversation_dataset.ListConversationDatasetsResponse, - *, - 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.ListConversationDatasetsRequest): - The initial request object. - response (google.cloud.dialogflow_v2.types.ListConversationDatasetsResponse): - 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 = conversation_dataset.ListConversationDatasetsRequest(request) - self._response = response - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - def pages(self) -> Iterator[conversation_dataset.ListConversationDatasetsResponse]: - yield self._response - while self._response.next_page_token: - self._request.page_token = self._response.next_page_token - self._response = self._method(self._request, metadata=self._metadata) - yield self._response - - def __iter__(self) -> Iterator[conversation_dataset.ConversationDataset]: - for page in self.pages: - yield from page.conversation_datasets - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListConversationDatasetsAsyncPager: - """A pager for iterating through ``list_conversation_datasets`` requests. - - This class thinly wraps an initial - :class:`google.cloud.dialogflow_v2.types.ListConversationDatasetsResponse` object, and - provides an ``__aiter__`` method to iterate through its - ``conversation_datasets`` field. - - If there are more pages, the ``__aiter__`` method will make additional - ``ListConversationDatasets`` requests and continue to iterate - through the ``conversation_datasets`` field on the - corresponding responses. - - All the usual :class:`google.cloud.dialogflow_v2.types.ListConversationDatasetsResponse` - 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[conversation_dataset.ListConversationDatasetsResponse]], - request: conversation_dataset.ListConversationDatasetsRequest, - response: conversation_dataset.ListConversationDatasetsResponse, - *, - metadata: Sequence[Tuple[str, str]] = ()): - """Instantiates the pager. - - Args: - method (Callable): The method that was originally called, and - which instantiated this pager. - request (google.cloud.dialogflow_v2.types.ListConversationDatasetsRequest): - The initial request object. - response (google.cloud.dialogflow_v2.types.ListConversationDatasetsResponse): - 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 = conversation_dataset.ListConversationDatasetsRequest(request) - self._response = response - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - async def pages(self) -> AsyncIterator[conversation_dataset.ListConversationDatasetsResponse]: - yield self._response - while self._response.next_page_token: - self._request.page_token = self._response.next_page_token - self._response = await self._method(self._request, metadata=self._metadata) - yield self._response - def __aiter__(self) -> AsyncIterator[conversation_dataset.ConversationDataset]: - async def async_generator(): - async for page in self.pages: - for response in page.conversation_datasets: - yield response - - return async_generator() - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) diff --git a/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/conversation_datasets/transports/__init__.py b/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/conversation_datasets/transports/__init__.py deleted file mode 100644 index 477c2abc8..000000000 --- a/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/conversation_datasets/transports/__init__.py +++ /dev/null @@ -1,38 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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 ConversationDatasetsTransport -from .grpc import ConversationDatasetsGrpcTransport -from .grpc_asyncio import ConversationDatasetsGrpcAsyncIOTransport -from .rest import ConversationDatasetsRestTransport -from .rest import ConversationDatasetsRestInterceptor - - -# Compile a registry of transports. -_transport_registry = OrderedDict() # type: Dict[str, Type[ConversationDatasetsTransport]] -_transport_registry['grpc'] = ConversationDatasetsGrpcTransport -_transport_registry['grpc_asyncio'] = ConversationDatasetsGrpcAsyncIOTransport -_transport_registry['rest'] = ConversationDatasetsRestTransport - -__all__ = ( - 'ConversationDatasetsTransport', - 'ConversationDatasetsGrpcTransport', - 'ConversationDatasetsGrpcAsyncIOTransport', - 'ConversationDatasetsRestTransport', - 'ConversationDatasetsRestInterceptor', -) diff --git a/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/conversation_datasets/transports/base.py b/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/conversation_datasets/transports/base.py deleted file mode 100644 index 361de7faa..000000000 --- a/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/conversation_datasets/transports/base.py +++ /dev/null @@ -1,258 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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 - -from google.cloud.dialogflow_v2 import gapic_version as package_version - -import google.auth # type: ignore -import google.api_core -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import retry as retries -from google.api_core import operations_v1 -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 conversation_dataset -from google.cloud.dialogflow_v2.types import conversation_dataset as gcd_conversation_dataset -from google.cloud.location import locations_pb2 # type: ignore -from google.longrunning import operations_pb2 -from google.longrunning import operations_pb2 # type: ignore - -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) - - -class ConversationDatasetsTransport(abc.ABC): - """Abstract transport class for ConversationDatasets.""" - - 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: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - api_audience: Optional[str] = None, - **kwargs, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. - scopes (Optional[Sequence[str]]): A list of scopes. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - """ - - scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} - - # Save the scopes. - self._scopes = scopes - - # If no credentials are provided, then determine the appropriate - # defaults. - if credentials and credentials_file: - raise core_exceptions.DuplicateCredentialArgs("'credentials_file' and 'credentials' are mutually exclusive") - - if credentials_file is not None: - credentials, _ = google.auth.load_credentials_from_file( - credentials_file, - **scopes_kwargs, - quota_project_id=quota_project_id - ) - elif credentials is None: - credentials, _ = google.auth.default(**scopes_kwargs, quota_project_id=quota_project_id) - # Don't apply audience if the credentials file passed from user. - if hasattr(credentials, "with_gdch_audience"): - credentials = credentials.with_gdch_audience(api_audience if api_audience else host) - - # If the credentials are service account credentials, then always try to use self signed JWT. - if always_use_jwt_access and isinstance(credentials, service_account.Credentials) and hasattr(service_account.Credentials, "with_always_use_jwt_access"): - credentials = credentials.with_always_use_jwt_access(True) - - # Save the credentials. - self._credentials = credentials - - # Save the hostname. Default to port 443 (HTTPS) if none is specified. - if ':' not in host: - host += ':443' - self._host = host - - def _prep_wrapped_messages(self, client_info): - # Precompute the wrapped methods. - self._wrapped_methods = { - self.create_conversation_dataset: gapic_v1.method.wrap_method( - self.create_conversation_dataset, - default_timeout=None, - client_info=client_info, - ), - self.get_conversation_dataset: gapic_v1.method.wrap_method( - self.get_conversation_dataset, - default_timeout=None, - client_info=client_info, - ), - self.list_conversation_datasets: gapic_v1.method.wrap_method( - self.list_conversation_datasets, - default_timeout=None, - client_info=client_info, - ), - self.delete_conversation_dataset: gapic_v1.method.wrap_method( - self.delete_conversation_dataset, - default_timeout=None, - client_info=client_info, - ), - self.import_conversation_data: gapic_v1.method.wrap_method( - self.import_conversation_data, - default_timeout=None, - client_info=client_info, - ), - } - - def close(self): - """Closes resources associated with the transport. - - .. warning:: - Only call this method if the transport is NOT shared - with other clients - this may cause errors in other clients! - """ - raise NotImplementedError() - - @property - def operations_client(self): - """Return the client designed to process long-running operations.""" - raise NotImplementedError() - - @property - def create_conversation_dataset(self) -> Callable[ - [gcd_conversation_dataset.CreateConversationDatasetRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: - raise NotImplementedError() - - @property - def get_conversation_dataset(self) -> Callable[ - [conversation_dataset.GetConversationDatasetRequest], - Union[ - conversation_dataset.ConversationDataset, - Awaitable[conversation_dataset.ConversationDataset] - ]]: - raise NotImplementedError() - - @property - def list_conversation_datasets(self) -> Callable[ - [conversation_dataset.ListConversationDatasetsRequest], - Union[ - conversation_dataset.ListConversationDatasetsResponse, - Awaitable[conversation_dataset.ListConversationDatasetsResponse] - ]]: - raise NotImplementedError() - - @property - def delete_conversation_dataset(self) -> Callable[ - [conversation_dataset.DeleteConversationDatasetRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: - raise NotImplementedError() - - @property - def import_conversation_data(self) -> Callable[ - [conversation_dataset.ImportConversationDataRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: - raise NotImplementedError() - - @property - def list_operations( - self, - ) -> Callable[ - [operations_pb2.ListOperationsRequest], - Union[operations_pb2.ListOperationsResponse, Awaitable[operations_pb2.ListOperationsResponse]], - ]: - raise NotImplementedError() - - @property - def get_operation( - self, - ) -> Callable[ - [operations_pb2.GetOperationRequest], - Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], - ]: - raise NotImplementedError() - - @property - def cancel_operation( - self, - ) -> Callable[ - [operations_pb2.CancelOperationRequest], - None, - ]: - raise NotImplementedError() - - @property - def get_location(self, - ) -> Callable[ - [locations_pb2.GetLocationRequest], - Union[locations_pb2.Location, Awaitable[locations_pb2.Location]], - ]: - raise NotImplementedError() - - @property - def list_locations(self, - ) -> Callable[ - [locations_pb2.ListLocationsRequest], - Union[locations_pb2.ListLocationsResponse, Awaitable[locations_pb2.ListLocationsResponse]], - ]: - raise NotImplementedError() - - @property - def kind(self) -> str: - raise NotImplementedError() - - -__all__ = ( - 'ConversationDatasetsTransport', -) diff --git a/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/conversation_datasets/transports/grpc.py b/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/conversation_datasets/transports/grpc.py deleted file mode 100644 index 9ec02c33f..000000000 --- a/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/conversation_datasets/transports/grpc.py +++ /dev/null @@ -1,515 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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 -from google.api_core import operations_v1 -from google.api_core import gapic_v1 -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_dataset -from google.cloud.dialogflow_v2.types import conversation_dataset as gcd_conversation_dataset -from google.cloud.location import locations_pb2 # type: ignore -from google.longrunning import operations_pb2 -from google.longrunning import operations_pb2 # type: ignore -from .base import ConversationDatasetsTransport, DEFAULT_CLIENT_INFO - - -class ConversationDatasetsGrpcTransport(ConversationDatasetsTransport): - """gRPC backend transport for ConversationDatasets. - - Conversation datasets. - Conversation datasets contain raw conversation files and their - customizable metadata that can be used for model training. - - 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: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - channel: Optional[grpc.Channel] = None, - api_mtls_endpoint: Optional[str] = None, - client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, - ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, - client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - api_audience: Optional[str] = None, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - This argument is ignored if ``channel`` is provided. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional(Sequence[str])): A list of scopes. This argument is - ignored if ``channel`` is provided. - channel (Optional[grpc.Channel]): A ``Channel`` instance through - which to make calls. - api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. - If provided, it overrides the ``host`` argument and tries to create - a mutual TLS channel with client SSL credentials from - ``client_cert_source`` or application default SSL credentials. - client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): - Deprecated. A callback to provide client SSL certificate bytes and - private key bytes, both in PEM format. It is ignored if - ``api_mtls_endpoint`` is None. - ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials - for the grpc channel. It is ignored if ``channel`` is provided. - client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): - A callback to provide client certificate bytes and private key bytes, - both in PEM format. It is used to configure a mutual TLS channel. It is - ignored if ``channel`` or ``ssl_channel_credentials`` is provided. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport - creation failed for any reason. - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - self._grpc_channel = None - self._ssl_channel_credentials = ssl_channel_credentials - self._stubs: Dict[str, Callable] = {} - self._operations_client: Optional[operations_v1.OperationsClient] = None - - if api_mtls_endpoint: - warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) - if client_cert_source: - warnings.warn("client_cert_source is deprecated", DeprecationWarning) - - if channel: - # Ignore credentials if a channel was passed. - credentials = False - # If a channel was explicitly provided, set it. - self._grpc_channel = channel - self._ssl_channel_credentials = None - - else: - if api_mtls_endpoint: - host = api_mtls_endpoint - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - self._ssl_channel_credentials = SslCredentials().ssl_credentials - - else: - if client_cert_source_for_mtls and not ssl_channel_credentials: - cert, key = client_cert_source_for_mtls() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - - # The base transport sets the host, credentials and scopes - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes, - quota_project_id=quota_project_id, - client_info=client_info, - always_use_jwt_access=always_use_jwt_access, - api_audience=api_audience, - ) - - if not self._grpc_channel: - self._grpc_channel = type(self).create_channel( - self._host, - # use the credentials which are saved - credentials=self._credentials, - # Set ``credentials_file`` to ``None`` here as - # the credentials that we saved earlier should be used. - credentials_file=None, - 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: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - **kwargs) -> grpc.Channel: - """Create and return a gRPC channel object. - Args: - host (Optional[str]): The host for the channel to use. - credentials (Optional[~.Credentials]): The - authorization credentials to attach to requests. These - credentials identify this application to the service. If - none are specified, the client will attempt to ascertain - the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - kwargs (Optional[dict]): Keyword arguments, which are passed to the - channel creation. - Returns: - grpc.Channel: A gRPC channel object. - - Raises: - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - - return grpc_helpers.create_channel( - host, - credentials=credentials, - credentials_file=credentials_file, - quota_project_id=quota_project_id, - default_scopes=cls.AUTH_SCOPES, - scopes=scopes, - default_host=cls.DEFAULT_HOST, - **kwargs - ) - - @property - def grpc_channel(self) -> grpc.Channel: - """Return the channel designed to connect to this service. - """ - return self._grpc_channel - - @property - def operations_client(self) -> operations_v1.OperationsClient: - """Create the client designed to process long-running operations. - - This property caches on the instance; repeated calls return the same - client. - """ - # Quick check: Only create a new client if we do not already have one. - if self._operations_client is None: - self._operations_client = operations_v1.OperationsClient( - self.grpc_channel - ) - - # Return the client from cache. - return self._operations_client - - @property - def create_conversation_dataset(self) -> Callable[ - [gcd_conversation_dataset.CreateConversationDatasetRequest], - operations_pb2.Operation]: - r"""Return a callable for the create conversation dataset method over gRPC. - - Creates a new conversation dataset. - - This method is a `long-running - operation `__. - The returned ``Operation`` type has the following - method-specific fields: - - - ``metadata``: - [CreateConversationDatasetOperationMetadata][google.cloud.dialogflow.v2.CreateConversationDatasetOperationMetadata] - - ``response``: - [ConversationDataset][google.cloud.dialogflow.v2.ConversationDataset] - - Returns: - Callable[[~.CreateConversationDatasetRequest], - ~.Operation]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'create_conversation_dataset' not in self._stubs: - self._stubs['create_conversation_dataset'] = self.grpc_channel.unary_unary( - '/google.cloud.dialogflow.v2.ConversationDatasets/CreateConversationDataset', - request_serializer=gcd_conversation_dataset.CreateConversationDatasetRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['create_conversation_dataset'] - - @property - def get_conversation_dataset(self) -> Callable[ - [conversation_dataset.GetConversationDatasetRequest], - conversation_dataset.ConversationDataset]: - r"""Return a callable for the get conversation dataset method over gRPC. - - Retrieves the specified conversation dataset. - - Returns: - Callable[[~.GetConversationDatasetRequest], - ~.ConversationDataset]: - 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_conversation_dataset' not in self._stubs: - self._stubs['get_conversation_dataset'] = self.grpc_channel.unary_unary( - '/google.cloud.dialogflow.v2.ConversationDatasets/GetConversationDataset', - request_serializer=conversation_dataset.GetConversationDatasetRequest.serialize, - response_deserializer=conversation_dataset.ConversationDataset.deserialize, - ) - return self._stubs['get_conversation_dataset'] - - @property - def list_conversation_datasets(self) -> Callable[ - [conversation_dataset.ListConversationDatasetsRequest], - conversation_dataset.ListConversationDatasetsResponse]: - r"""Return a callable for the list conversation datasets method over gRPC. - - Returns the list of all conversation datasets in the - specified project and location. - - Returns: - Callable[[~.ListConversationDatasetsRequest], - ~.ListConversationDatasetsResponse]: - 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_conversation_datasets' not in self._stubs: - self._stubs['list_conversation_datasets'] = self.grpc_channel.unary_unary( - '/google.cloud.dialogflow.v2.ConversationDatasets/ListConversationDatasets', - request_serializer=conversation_dataset.ListConversationDatasetsRequest.serialize, - response_deserializer=conversation_dataset.ListConversationDatasetsResponse.deserialize, - ) - return self._stubs['list_conversation_datasets'] - - @property - def delete_conversation_dataset(self) -> Callable[ - [conversation_dataset.DeleteConversationDatasetRequest], - operations_pb2.Operation]: - r"""Return a callable for the delete conversation dataset method over gRPC. - - Deletes the specified conversation dataset. - - This method is a `long-running - operation `__. - The returned ``Operation`` type has the following - method-specific fields: - - - ``metadata``: - [DeleteConversationDatasetOperationMetadata][google.cloud.dialogflow.v2.DeleteConversationDatasetOperationMetadata] - - ``response``: An `Empty - message `__ - - Returns: - Callable[[~.DeleteConversationDatasetRequest], - ~.Operation]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'delete_conversation_dataset' not in self._stubs: - self._stubs['delete_conversation_dataset'] = self.grpc_channel.unary_unary( - '/google.cloud.dialogflow.v2.ConversationDatasets/DeleteConversationDataset', - request_serializer=conversation_dataset.DeleteConversationDatasetRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['delete_conversation_dataset'] - - @property - def import_conversation_data(self) -> Callable[ - [conversation_dataset.ImportConversationDataRequest], - operations_pb2.Operation]: - r"""Return a callable for the import conversation data method over gRPC. - - Import data into the specified conversation dataset. Note that - it is not allowed to import data to a conversation dataset that - already has data in it. - - This method is a `long-running - operation `__. - The returned ``Operation`` type has the following - method-specific fields: - - - ``metadata``: - [ImportConversationDataOperationMetadata][google.cloud.dialogflow.v2.ImportConversationDataOperationMetadata] - - ``response``: - [ImportConversationDataOperationResponse][google.cloud.dialogflow.v2.ImportConversationDataOperationResponse] - - Returns: - Callable[[~.ImportConversationDataRequest], - ~.Operation]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'import_conversation_data' not in self._stubs: - self._stubs['import_conversation_data'] = self.grpc_channel.unary_unary( - '/google.cloud.dialogflow.v2.ConversationDatasets/ImportConversationData', - request_serializer=conversation_dataset.ImportConversationDataRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['import_conversation_data'] - - def close(self): - self.grpc_channel.close() - - @property - def cancel_operation( - self, - ) -> Callable[[operations_pb2.CancelOperationRequest], None]: - r"""Return a callable for the cancel_operation method over gRPC. - """ - # 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 "cancel_operation" not in self._stubs: - self._stubs["cancel_operation"] = self.grpc_channel.unary_unary( - "/google.longrunning.Operations/CancelOperation", - request_serializer=operations_pb2.CancelOperationRequest.SerializeToString, - response_deserializer=None, - ) - return self._stubs["cancel_operation"] - - @property - def get_operation( - self, - ) -> Callable[[operations_pb2.GetOperationRequest], operations_pb2.Operation]: - r"""Return a callable for the get_operation method over gRPC. - """ - # 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_operation" not in self._stubs: - self._stubs["get_operation"] = self.grpc_channel.unary_unary( - "/google.longrunning.Operations/GetOperation", - request_serializer=operations_pb2.GetOperationRequest.SerializeToString, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs["get_operation"] - - @property - def list_operations( - self, - ) -> Callable[[operations_pb2.ListOperationsRequest], operations_pb2.ListOperationsResponse]: - r"""Return a callable for the list_operations method over gRPC. - """ - # 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_operations" not in self._stubs: - self._stubs["list_operations"] = self.grpc_channel.unary_unary( - "/google.longrunning.Operations/ListOperations", - request_serializer=operations_pb2.ListOperationsRequest.SerializeToString, - response_deserializer=operations_pb2.ListOperationsResponse.FromString, - ) - return self._stubs["list_operations"] - - @property - def list_locations( - self, - ) -> Callable[[locations_pb2.ListLocationsRequest], locations_pb2.ListLocationsResponse]: - r"""Return a callable for the list locations method over gRPC. - """ - # 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_locations" not in self._stubs: - self._stubs["list_locations"] = self.grpc_channel.unary_unary( - "/google.cloud.location.Locations/ListLocations", - request_serializer=locations_pb2.ListLocationsRequest.SerializeToString, - response_deserializer=locations_pb2.ListLocationsResponse.FromString, - ) - return self._stubs["list_locations"] - - @property - def get_location( - self, - ) -> Callable[[locations_pb2.GetLocationRequest], locations_pb2.Location]: - r"""Return a callable for the list locations method over gRPC. - """ - # 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_location" not in self._stubs: - self._stubs["get_location"] = self.grpc_channel.unary_unary( - "/google.cloud.location.Locations/GetLocation", - request_serializer=locations_pb2.GetLocationRequest.SerializeToString, - response_deserializer=locations_pb2.Location.FromString, - ) - return self._stubs["get_location"] - - @property - def kind(self) -> str: - return "grpc" - - -__all__ = ( - 'ConversationDatasetsGrpcTransport', -) diff --git a/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/conversation_datasets/transports/grpc_asyncio.py b/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/conversation_datasets/transports/grpc_asyncio.py deleted file mode 100644 index 3a169f6f8..000000000 --- a/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/conversation_datasets/transports/grpc_asyncio.py +++ /dev/null @@ -1,514 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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 -from google.api_core import grpc_helpers_async -from google.api_core import operations_v1 -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore - -import grpc # type: ignore -from grpc.experimental import aio # type: ignore - -from google.cloud.dialogflow_v2.types import conversation_dataset -from google.cloud.dialogflow_v2.types import conversation_dataset as gcd_conversation_dataset -from google.cloud.location import locations_pb2 # type: ignore -from google.longrunning import operations_pb2 -from google.longrunning import operations_pb2 # type: ignore -from .base import ConversationDatasetsTransport, DEFAULT_CLIENT_INFO -from .grpc import ConversationDatasetsGrpcTransport - - -class ConversationDatasetsGrpcAsyncIOTransport(ConversationDatasetsTransport): - """gRPC AsyncIO backend transport for ConversationDatasets. - - Conversation datasets. - Conversation datasets contain raw conversation files and their - customizable metadata that can be used for model training. - - 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: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - **kwargs) -> aio.Channel: - """Create and return a gRPC AsyncIO channel object. - Args: - host (Optional[str]): The host for the channel to use. - credentials (Optional[~.Credentials]): The - authorization credentials to attach to requests. These - credentials identify this application to the service. If - none are specified, the client will attempt to ascertain - the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - kwargs (Optional[dict]): Keyword arguments, which are passed to the - channel creation. - Returns: - aio.Channel: A gRPC AsyncIO channel object. - """ - - return grpc_helpers_async.create_channel( - host, - credentials=credentials, - credentials_file=credentials_file, - quota_project_id=quota_project_id, - default_scopes=cls.AUTH_SCOPES, - scopes=scopes, - default_host=cls.DEFAULT_HOST, - **kwargs - ) - - def __init__(self, *, - host: str = 'dialogflow.googleapis.com', - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - channel: Optional[aio.Channel] = None, - api_mtls_endpoint: Optional[str] = None, - client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, - ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, - client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - api_audience: Optional[str] = None, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - This argument is ignored if ``channel`` is provided. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - channel (Optional[aio.Channel]): A ``Channel`` instance through - which to make calls. - api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. - If provided, it overrides the ``host`` argument and tries to create - a mutual TLS channel with client SSL credentials from - ``client_cert_source`` or application default SSL credentials. - client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): - Deprecated. A callback to provide client SSL certificate bytes and - private key bytes, both in PEM format. It is ignored if - ``api_mtls_endpoint`` is None. - ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials - for the grpc channel. It is ignored if ``channel`` is provided. - client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): - A callback to provide client certificate bytes and private key bytes, - both in PEM format. It is used to configure a mutual TLS channel. It is - ignored if ``channel`` or ``ssl_channel_credentials`` is provided. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - - Raises: - google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport - creation failed for any reason. - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - self._grpc_channel = None - self._ssl_channel_credentials = ssl_channel_credentials - self._stubs: Dict[str, Callable] = {} - self._operations_client: Optional[operations_v1.OperationsAsyncClient] = None - - if api_mtls_endpoint: - warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) - if client_cert_source: - warnings.warn("client_cert_source is deprecated", DeprecationWarning) - - if channel: - # Ignore credentials if a channel was passed. - credentials = False - # If a channel was explicitly provided, set it. - self._grpc_channel = channel - self._ssl_channel_credentials = None - else: - if api_mtls_endpoint: - host = api_mtls_endpoint - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - self._ssl_channel_credentials = SslCredentials().ssl_credentials - - else: - if client_cert_source_for_mtls and not ssl_channel_credentials: - cert, key = client_cert_source_for_mtls() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - - # The base transport sets the host, credentials and scopes - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes, - quota_project_id=quota_project_id, - client_info=client_info, - always_use_jwt_access=always_use_jwt_access, - api_audience=api_audience, - ) - - if not self._grpc_channel: - self._grpc_channel = type(self).create_channel( - self._host, - # use the credentials which are saved - credentials=self._credentials, - # Set ``credentials_file`` to ``None`` here as - # the credentials that we saved earlier should be used. - credentials_file=None, - 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 operations_client(self) -> operations_v1.OperationsAsyncClient: - """Create the client designed to process long-running operations. - - This property caches on the instance; repeated calls return the same - client. - """ - # Quick check: Only create a new client if we do not already have one. - if self._operations_client is None: - self._operations_client = operations_v1.OperationsAsyncClient( - self.grpc_channel - ) - - # Return the client from cache. - return self._operations_client - - @property - def create_conversation_dataset(self) -> Callable[ - [gcd_conversation_dataset.CreateConversationDatasetRequest], - Awaitable[operations_pb2.Operation]]: - r"""Return a callable for the create conversation dataset method over gRPC. - - Creates a new conversation dataset. - - This method is a `long-running - operation `__. - The returned ``Operation`` type has the following - method-specific fields: - - - ``metadata``: - [CreateConversationDatasetOperationMetadata][google.cloud.dialogflow.v2.CreateConversationDatasetOperationMetadata] - - ``response``: - [ConversationDataset][google.cloud.dialogflow.v2.ConversationDataset] - - Returns: - Callable[[~.CreateConversationDatasetRequest], - Awaitable[~.Operation]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'create_conversation_dataset' not in self._stubs: - self._stubs['create_conversation_dataset'] = self.grpc_channel.unary_unary( - '/google.cloud.dialogflow.v2.ConversationDatasets/CreateConversationDataset', - request_serializer=gcd_conversation_dataset.CreateConversationDatasetRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['create_conversation_dataset'] - - @property - def get_conversation_dataset(self) -> Callable[ - [conversation_dataset.GetConversationDatasetRequest], - Awaitable[conversation_dataset.ConversationDataset]]: - r"""Return a callable for the get conversation dataset method over gRPC. - - Retrieves the specified conversation dataset. - - Returns: - Callable[[~.GetConversationDatasetRequest], - Awaitable[~.ConversationDataset]]: - 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_conversation_dataset' not in self._stubs: - self._stubs['get_conversation_dataset'] = self.grpc_channel.unary_unary( - '/google.cloud.dialogflow.v2.ConversationDatasets/GetConversationDataset', - request_serializer=conversation_dataset.GetConversationDatasetRequest.serialize, - response_deserializer=conversation_dataset.ConversationDataset.deserialize, - ) - return self._stubs['get_conversation_dataset'] - - @property - def list_conversation_datasets(self) -> Callable[ - [conversation_dataset.ListConversationDatasetsRequest], - Awaitable[conversation_dataset.ListConversationDatasetsResponse]]: - r"""Return a callable for the list conversation datasets method over gRPC. - - Returns the list of all conversation datasets in the - specified project and location. - - Returns: - Callable[[~.ListConversationDatasetsRequest], - Awaitable[~.ListConversationDatasetsResponse]]: - 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_conversation_datasets' not in self._stubs: - self._stubs['list_conversation_datasets'] = self.grpc_channel.unary_unary( - '/google.cloud.dialogflow.v2.ConversationDatasets/ListConversationDatasets', - request_serializer=conversation_dataset.ListConversationDatasetsRequest.serialize, - response_deserializer=conversation_dataset.ListConversationDatasetsResponse.deserialize, - ) - return self._stubs['list_conversation_datasets'] - - @property - def delete_conversation_dataset(self) -> Callable[ - [conversation_dataset.DeleteConversationDatasetRequest], - Awaitable[operations_pb2.Operation]]: - r"""Return a callable for the delete conversation dataset method over gRPC. - - Deletes the specified conversation dataset. - - This method is a `long-running - operation `__. - The returned ``Operation`` type has the following - method-specific fields: - - - ``metadata``: - [DeleteConversationDatasetOperationMetadata][google.cloud.dialogflow.v2.DeleteConversationDatasetOperationMetadata] - - ``response``: An `Empty - message `__ - - Returns: - Callable[[~.DeleteConversationDatasetRequest], - Awaitable[~.Operation]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'delete_conversation_dataset' not in self._stubs: - self._stubs['delete_conversation_dataset'] = self.grpc_channel.unary_unary( - '/google.cloud.dialogflow.v2.ConversationDatasets/DeleteConversationDataset', - request_serializer=conversation_dataset.DeleteConversationDatasetRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['delete_conversation_dataset'] - - @property - def import_conversation_data(self) -> Callable[ - [conversation_dataset.ImportConversationDataRequest], - Awaitable[operations_pb2.Operation]]: - r"""Return a callable for the import conversation data method over gRPC. - - Import data into the specified conversation dataset. Note that - it is not allowed to import data to a conversation dataset that - already has data in it. - - This method is a `long-running - operation `__. - The returned ``Operation`` type has the following - method-specific fields: - - - ``metadata``: - [ImportConversationDataOperationMetadata][google.cloud.dialogflow.v2.ImportConversationDataOperationMetadata] - - ``response``: - [ImportConversationDataOperationResponse][google.cloud.dialogflow.v2.ImportConversationDataOperationResponse] - - Returns: - Callable[[~.ImportConversationDataRequest], - Awaitable[~.Operation]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'import_conversation_data' not in self._stubs: - self._stubs['import_conversation_data'] = self.grpc_channel.unary_unary( - '/google.cloud.dialogflow.v2.ConversationDatasets/ImportConversationData', - request_serializer=conversation_dataset.ImportConversationDataRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['import_conversation_data'] - - def close(self): - return self.grpc_channel.close() - - @property - def cancel_operation( - self, - ) -> Callable[[operations_pb2.CancelOperationRequest], None]: - r"""Return a callable for the cancel_operation method over gRPC. - """ - # 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 "cancel_operation" not in self._stubs: - self._stubs["cancel_operation"] = self.grpc_channel.unary_unary( - "/google.longrunning.Operations/CancelOperation", - request_serializer=operations_pb2.CancelOperationRequest.SerializeToString, - response_deserializer=None, - ) - return self._stubs["cancel_operation"] - - @property - def get_operation( - self, - ) -> Callable[[operations_pb2.GetOperationRequest], operations_pb2.Operation]: - r"""Return a callable for the get_operation method over gRPC. - """ - # 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_operation" not in self._stubs: - self._stubs["get_operation"] = self.grpc_channel.unary_unary( - "/google.longrunning.Operations/GetOperation", - request_serializer=operations_pb2.GetOperationRequest.SerializeToString, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs["get_operation"] - - @property - def list_operations( - self, - ) -> Callable[[operations_pb2.ListOperationsRequest], operations_pb2.ListOperationsResponse]: - r"""Return a callable for the list_operations method over gRPC. - """ - # 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_operations" not in self._stubs: - self._stubs["list_operations"] = self.grpc_channel.unary_unary( - "/google.longrunning.Operations/ListOperations", - request_serializer=operations_pb2.ListOperationsRequest.SerializeToString, - response_deserializer=operations_pb2.ListOperationsResponse.FromString, - ) - return self._stubs["list_operations"] - - @property - def list_locations( - self, - ) -> Callable[[locations_pb2.ListLocationsRequest], locations_pb2.ListLocationsResponse]: - r"""Return a callable for the list locations method over gRPC. - """ - # 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_locations" not in self._stubs: - self._stubs["list_locations"] = self.grpc_channel.unary_unary( - "/google.cloud.location.Locations/ListLocations", - request_serializer=locations_pb2.ListLocationsRequest.SerializeToString, - response_deserializer=locations_pb2.ListLocationsResponse.FromString, - ) - return self._stubs["list_locations"] - - @property - def get_location( - self, - ) -> Callable[[locations_pb2.GetLocationRequest], locations_pb2.Location]: - r"""Return a callable for the list locations method over gRPC. - """ - # 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_location" not in self._stubs: - self._stubs["get_location"] = self.grpc_channel.unary_unary( - "/google.cloud.location.Locations/GetLocation", - request_serializer=locations_pb2.GetLocationRequest.SerializeToString, - response_deserializer=locations_pb2.Location.FromString, - ) - return self._stubs["get_location"] - - -__all__ = ( - 'ConversationDatasetsGrpcAsyncIOTransport', -) diff --git a/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/conversation_datasets/transports/rest.py b/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/conversation_datasets/transports/rest.py deleted file mode 100644 index ecfef6cf5..000000000 --- a/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/conversation_datasets/transports/rest.py +++ /dev/null @@ -1,1274 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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 google.auth.transport.requests import AuthorizedSession # type: ignore -import json # type: ignore -import grpc # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore -from google.auth import credentials as ga_credentials # type: ignore -from google.api_core import exceptions as core_exceptions -from google.api_core import retry as retries -from google.api_core import rest_helpers -from google.api_core import rest_streaming -from google.api_core import path_template -from google.api_core import gapic_v1 - -from google.protobuf import json_format -from google.api_core import operations_v1 -from google.cloud.location import locations_pb2 # type: ignore -from google.longrunning import operations_pb2 -from requests import __version__ as requests_version -import dataclasses -import re -from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union -import warnings - -try: - OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] -except AttributeError: # pragma: NO COVER - OptionalRetry = Union[retries.Retry, object] # type: ignore - - -from google.cloud.dialogflow_v2.types import conversation_dataset -from google.cloud.dialogflow_v2.types import conversation_dataset as gcd_conversation_dataset -from google.longrunning import operations_pb2 # type: ignore - -from .base import ConversationDatasetsTransport, DEFAULT_CLIENT_INFO as BASE_DEFAULT_CLIENT_INFO - - -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=BASE_DEFAULT_CLIENT_INFO.gapic_version, - grpc_version=None, - rest_version=requests_version, -) - - -class ConversationDatasetsRestInterceptor: - """Interceptor for ConversationDatasets. - - Interceptors are used to manipulate requests, request metadata, and responses - in arbitrary ways. - Example use cases include: - * Logging - * Verifying requests according to service or custom semantics - * Stripping extraneous information from responses - - These use cases and more can be enabled by injecting an - instance of a custom subclass when constructing the ConversationDatasetsRestTransport. - - .. code-block:: python - class MyCustomConversationDatasetsInterceptor(ConversationDatasetsRestInterceptor): - def pre_create_conversation_dataset(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_create_conversation_dataset(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_delete_conversation_dataset(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_delete_conversation_dataset(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_get_conversation_dataset(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_get_conversation_dataset(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_import_conversation_data(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_import_conversation_data(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_list_conversation_datasets(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_list_conversation_datasets(self, response): - logging.log(f"Received response: {response}") - return response - - transport = ConversationDatasetsRestTransport(interceptor=MyCustomConversationDatasetsInterceptor()) - client = ConversationDatasetsClient(transport=transport) - - - """ - def pre_create_conversation_dataset(self, request: gcd_conversation_dataset.CreateConversationDatasetRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[gcd_conversation_dataset.CreateConversationDatasetRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for create_conversation_dataset - - Override in a subclass to manipulate the request or metadata - before they are sent to the ConversationDatasets server. - """ - return request, metadata - - def post_create_conversation_dataset(self, response: operations_pb2.Operation) -> operations_pb2.Operation: - """Post-rpc interceptor for create_conversation_dataset - - Override in a subclass to manipulate the response - after it is returned by the ConversationDatasets server but before - it is returned to user code. - """ - return response - def pre_delete_conversation_dataset(self, request: conversation_dataset.DeleteConversationDatasetRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[conversation_dataset.DeleteConversationDatasetRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for delete_conversation_dataset - - Override in a subclass to manipulate the request or metadata - before they are sent to the ConversationDatasets server. - """ - return request, metadata - - def post_delete_conversation_dataset(self, response: operations_pb2.Operation) -> operations_pb2.Operation: - """Post-rpc interceptor for delete_conversation_dataset - - Override in a subclass to manipulate the response - after it is returned by the ConversationDatasets server but before - it is returned to user code. - """ - return response - def pre_get_conversation_dataset(self, request: conversation_dataset.GetConversationDatasetRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[conversation_dataset.GetConversationDatasetRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for get_conversation_dataset - - Override in a subclass to manipulate the request or metadata - before they are sent to the ConversationDatasets server. - """ - return request, metadata - - def post_get_conversation_dataset(self, response: conversation_dataset.ConversationDataset) -> conversation_dataset.ConversationDataset: - """Post-rpc interceptor for get_conversation_dataset - - Override in a subclass to manipulate the response - after it is returned by the ConversationDatasets server but before - it is returned to user code. - """ - return response - def pre_import_conversation_data(self, request: conversation_dataset.ImportConversationDataRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[conversation_dataset.ImportConversationDataRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for import_conversation_data - - Override in a subclass to manipulate the request or metadata - before they are sent to the ConversationDatasets server. - """ - return request, metadata - - def post_import_conversation_data(self, response: operations_pb2.Operation) -> operations_pb2.Operation: - """Post-rpc interceptor for import_conversation_data - - Override in a subclass to manipulate the response - after it is returned by the ConversationDatasets server but before - it is returned to user code. - """ - return response - def pre_list_conversation_datasets(self, request: conversation_dataset.ListConversationDatasetsRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[conversation_dataset.ListConversationDatasetsRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for list_conversation_datasets - - Override in a subclass to manipulate the request or metadata - before they are sent to the ConversationDatasets server. - """ - return request, metadata - - def post_list_conversation_datasets(self, response: conversation_dataset.ListConversationDatasetsResponse) -> conversation_dataset.ListConversationDatasetsResponse: - """Post-rpc interceptor for list_conversation_datasets - - Override in a subclass to manipulate the response - after it is returned by the ConversationDatasets server but before - it is returned to user code. - """ - return response - - def pre_get_location( - self, request: locations_pb2.GetLocationRequest, metadata: Sequence[Tuple[str, str]] - ) -> Tuple[locations_pb2.GetLocationRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for get_location - - Override in a subclass to manipulate the request or metadata - before they are sent to the ConversationDatasets server. - """ - return request, metadata - - def post_get_location( - self, response: locations_pb2.Location - ) -> locations_pb2.Location: - """Post-rpc interceptor for get_location - - Override in a subclass to manipulate the response - after it is returned by the ConversationDatasets server but before - it is returned to user code. - """ - return response - def pre_list_locations( - self, request: locations_pb2.ListLocationsRequest, metadata: Sequence[Tuple[str, str]] - ) -> Tuple[locations_pb2.ListLocationsRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for list_locations - - Override in a subclass to manipulate the request or metadata - before they are sent to the ConversationDatasets server. - """ - return request, metadata - - def post_list_locations( - self, response: locations_pb2.ListLocationsResponse - ) -> locations_pb2.ListLocationsResponse: - """Post-rpc interceptor for list_locations - - Override in a subclass to manipulate the response - after it is returned by the ConversationDatasets server but before - it is returned to user code. - """ - return response - def pre_cancel_operation( - self, request: operations_pb2.CancelOperationRequest, metadata: Sequence[Tuple[str, str]] - ) -> Tuple[operations_pb2.CancelOperationRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for cancel_operation - - Override in a subclass to manipulate the request or metadata - before they are sent to the ConversationDatasets server. - """ - return request, metadata - - def post_cancel_operation( - self, response: None - ) -> None: - """Post-rpc interceptor for cancel_operation - - Override in a subclass to manipulate the response - after it is returned by the ConversationDatasets server but before - it is returned to user code. - """ - return response - def pre_get_operation( - self, request: operations_pb2.GetOperationRequest, metadata: Sequence[Tuple[str, str]] - ) -> Tuple[operations_pb2.GetOperationRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for get_operation - - Override in a subclass to manipulate the request or metadata - before they are sent to the ConversationDatasets server. - """ - return request, metadata - - def post_get_operation( - self, response: operations_pb2.Operation - ) -> operations_pb2.Operation: - """Post-rpc interceptor for get_operation - - Override in a subclass to manipulate the response - after it is returned by the ConversationDatasets server but before - it is returned to user code. - """ - return response - def pre_list_operations( - self, request: operations_pb2.ListOperationsRequest, metadata: Sequence[Tuple[str, str]] - ) -> Tuple[operations_pb2.ListOperationsRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for list_operations - - Override in a subclass to manipulate the request or metadata - before they are sent to the ConversationDatasets server. - """ - return request, metadata - - def post_list_operations( - self, response: operations_pb2.ListOperationsResponse - ) -> operations_pb2.ListOperationsResponse: - """Post-rpc interceptor for list_operations - - Override in a subclass to manipulate the response - after it is returned by the ConversationDatasets server but before - it is returned to user code. - """ - return response - - -@dataclasses.dataclass -class ConversationDatasetsRestStub: - _session: AuthorizedSession - _host: str - _interceptor: ConversationDatasetsRestInterceptor - - -class ConversationDatasetsRestTransport(ConversationDatasetsTransport): - """REST backend transport for ConversationDatasets. - - Conversation datasets. - Conversation datasets contain raw conversation files and their - customizable metadata that can be used for model training. - - 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 JSON representations of protocol buffers over HTTP/1.1 - - """ - - def __init__(self, *, - host: str = 'dialogflow.googleapis.com', - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - client_cert_source_for_mtls: Optional[Callable[[ - ], Tuple[bytes, bytes]]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - url_scheme: str = 'https', - interceptor: Optional[ConversationDatasetsRestInterceptor] = None, - api_audience: Optional[str] = None, - ) -> 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 ignored if ``channel`` is provided. - scopes (Optional(Sequence[str])): A list of scopes. This argument is - ignored if ``channel`` is provided. - client_cert_source_for_mtls (Callable[[], Tuple[bytes, bytes]]): Client - certificate to configure mutual TLS HTTP channel. It is ignored - if ``channel`` is provided. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you are developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - url_scheme: the protocol scheme for the API endpoint. Normally - "https", but for testing or local servers, - "http" can be specified. - """ - # Run the base constructor - # TODO(yon-mg): resolve other ctor params i.e. scopes, quota, etc. - # TODO: When custom host (api_endpoint) is set, `scopes` must *also* be set on the - # credentials object - maybe_url_match = re.match("^(?Phttp(?:s)?://)?(?P.*)$", host) - if maybe_url_match is None: - raise ValueError(f"Unexpected hostname structure: {host}") # pragma: NO COVER - - url_match_items = maybe_url_match.groupdict() - - host = f"{url_scheme}://{host}" if not url_match_items["scheme"] else host - - super().__init__( - host=host, - credentials=credentials, - client_info=client_info, - always_use_jwt_access=always_use_jwt_access, - api_audience=api_audience - ) - self._session = AuthorizedSession( - self._credentials, default_host=self.DEFAULT_HOST) - self._operations_client: Optional[operations_v1.AbstractOperationsClient] = None - if client_cert_source_for_mtls: - self._session.configure_mtls_channel(client_cert_source_for_mtls) - self._interceptor = interceptor or ConversationDatasetsRestInterceptor() - self._prep_wrapped_messages(client_info) - - @property - def operations_client(self) -> operations_v1.AbstractOperationsClient: - """Create the client designed to process long-running operations. - - This property caches on the instance; repeated calls return the same - client. - """ - # Only create a new client if we do not already have one. - if self._operations_client is None: - http_options: Dict[str, List[Dict[str, str]]] = { - 'google.longrunning.Operations.CancelOperation': [ - { - 'method': 'post', - 'uri': '/v2/{name=projects/*/operations/*}:cancel', - }, - { - 'method': 'post', - 'uri': '/v2/{name=projects/*/locations/*/operations/*}:cancel', - }, - ], - 'google.longrunning.Operations.GetOperation': [ - { - 'method': 'get', - 'uri': '/v2/{name=projects/*/operations/*}', - }, - { - 'method': 'get', - 'uri': '/v2/{name=projects/*/locations/*/operations/*}', - }, - ], - 'google.longrunning.Operations.ListOperations': [ - { - 'method': 'get', - 'uri': '/v2/{name=projects/*}/operations', - }, - { - 'method': 'get', - 'uri': '/v2/{name=projects/*/locations/*}/operations', - }, - ], - } - - rest_transport = operations_v1.OperationsRestTransport( - host=self._host, - # use the credentials which are saved - credentials=self._credentials, - scopes=self._scopes, - http_options=http_options, - path_prefix="v2") - - self._operations_client = operations_v1.AbstractOperationsClient(transport=rest_transport) - - # Return the client from cache. - return self._operations_client - - class _CreateConversationDataset(ConversationDatasetsRestStub): - def __hash__(self): - return hash("CreateConversationDataset") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: gcd_conversation_dataset.CreateConversationDatasetRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> operations_pb2.Operation: - r"""Call the create conversation - dataset method over HTTP. - - Args: - request (~.gcd_conversation_dataset.CreateConversationDatasetRequest): - The request object. The request message for - [ConversationDatasets.CreateConversationDataset][google.cloud.dialogflow.v2.ConversationDatasets.CreateConversationDataset]. - 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: - ~.operations_pb2.Operation: - This resource represents a - long-running operation that is the - result of a network API call. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'post', - 'uri': '/v2/{parent=projects/*/locations/*}/conversationDatasets', - 'body': 'conversation_dataset', - }, - ] - request, metadata = self._interceptor.pre_create_conversation_dataset(request, metadata) - pb_request = gcd_conversation_dataset.CreateConversationDatasetRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request['body'], - including_default_value_fields=False, - use_integers_for_enums=True - ) - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - including_default_value_fields=False, - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = operations_pb2.Operation() - json_format.Parse(response.content, resp, ignore_unknown_fields=True) - resp = self._interceptor.post_create_conversation_dataset(resp) - return resp - - class _DeleteConversationDataset(ConversationDatasetsRestStub): - def __hash__(self): - return hash("DeleteConversationDataset") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: conversation_dataset.DeleteConversationDatasetRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> operations_pb2.Operation: - r"""Call the delete conversation - dataset method over HTTP. - - Args: - request (~.conversation_dataset.DeleteConversationDatasetRequest): - The request object. The request message for - [ConversationDatasets.DeleteConversationDataset][google.cloud.dialogflow.v2.ConversationDatasets.DeleteConversationDataset]. - 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: - ~.operations_pb2.Operation: - This resource represents a - long-running operation that is the - result of a network API call. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'delete', - 'uri': '/v2/{name=projects/*/locations/*/conversationDatasets/*}', - }, - ] - request, metadata = self._interceptor.pre_delete_conversation_dataset(request, metadata) - pb_request = conversation_dataset.DeleteConversationDatasetRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - including_default_value_fields=False, - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = operations_pb2.Operation() - json_format.Parse(response.content, resp, ignore_unknown_fields=True) - resp = self._interceptor.post_delete_conversation_dataset(resp) - return resp - - class _GetConversationDataset(ConversationDatasetsRestStub): - def __hash__(self): - return hash("GetConversationDataset") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: conversation_dataset.GetConversationDatasetRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> conversation_dataset.ConversationDataset: - r"""Call the get conversation dataset method over HTTP. - - Args: - request (~.conversation_dataset.GetConversationDatasetRequest): - The request object. The request message for - [ConversationDatasets.GetConversationDataset][google.cloud.dialogflow.v2.ConversationDatasets.GetConversationDataset]. - 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: - ~.conversation_dataset.ConversationDataset: - Represents a conversation dataset - that a user imports raw data into. The - data inside ConversationDataset can not - be changed after ImportConversationData - finishes (and calling - ImportConversationData on a dataset that - already has data is not allowed). - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v2/{name=projects/*/conversationDatasets/*}', - }, -{ - 'method': 'get', - 'uri': '/v2/{name=projects/*/locations/*/conversationDatasets/*}', - }, - ] - request, metadata = self._interceptor.pre_get_conversation_dataset(request, metadata) - pb_request = conversation_dataset.GetConversationDatasetRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - including_default_value_fields=False, - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = conversation_dataset.ConversationDataset() - pb_resp = conversation_dataset.ConversationDataset.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_get_conversation_dataset(resp) - return resp - - class _ImportConversationData(ConversationDatasetsRestStub): - def __hash__(self): - return hash("ImportConversationData") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: conversation_dataset.ImportConversationDataRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> operations_pb2.Operation: - r"""Call the import conversation data method over HTTP. - - Args: - request (~.conversation_dataset.ImportConversationDataRequest): - The request object. The request message for - [ConversationDatasets.ImportConversationData][google.cloud.dialogflow.v2.ConversationDatasets.ImportConversationData]. - 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: - ~.operations_pb2.Operation: - This resource represents a - long-running operation that is the - result of a network API call. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'post', - 'uri': '/v2/{name=projects/*/conversationDatasets/*}:importConversationData', - 'body': '*', - }, -{ - 'method': 'post', - 'uri': '/v2/{name=projects/*/locations/*/conversationDatasets/*}:importConversationData', - 'body': '*', - }, - ] - request, metadata = self._interceptor.pre_import_conversation_data(request, metadata) - pb_request = conversation_dataset.ImportConversationDataRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request['body'], - including_default_value_fields=False, - use_integers_for_enums=True - ) - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - including_default_value_fields=False, - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = operations_pb2.Operation() - json_format.Parse(response.content, resp, ignore_unknown_fields=True) - resp = self._interceptor.post_import_conversation_data(resp) - return resp - - class _ListConversationDatasets(ConversationDatasetsRestStub): - def __hash__(self): - return hash("ListConversationDatasets") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: conversation_dataset.ListConversationDatasetsRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> conversation_dataset.ListConversationDatasetsResponse: - r"""Call the list conversation - datasets method over HTTP. - - Args: - request (~.conversation_dataset.ListConversationDatasetsRequest): - The request object. The request message for - [ConversationDatasets.ListConversationDatasets][google.cloud.dialogflow.v2.ConversationDatasets.ListConversationDatasets]. - 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: - ~.conversation_dataset.ListConversationDatasetsResponse: - The response message for - [ConversationDatasets.ListConversationDatasets][google.cloud.dialogflow.v2.ConversationDatasets.ListConversationDatasets]. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v2/{parent=projects/*}/conversationDatasets', - }, -{ - 'method': 'get', - 'uri': '/v2/{parent=projects/*/locations/*}/conversationDatasets', - }, - ] - request, metadata = self._interceptor.pre_list_conversation_datasets(request, metadata) - pb_request = conversation_dataset.ListConversationDatasetsRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - including_default_value_fields=False, - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = conversation_dataset.ListConversationDatasetsResponse() - pb_resp = conversation_dataset.ListConversationDatasetsResponse.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_list_conversation_datasets(resp) - return resp - - @property - def create_conversation_dataset(self) -> Callable[ - [gcd_conversation_dataset.CreateConversationDatasetRequest], - operations_pb2.Operation]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._CreateConversationDataset(self._session, self._host, self._interceptor) # type: ignore - - @property - def delete_conversation_dataset(self) -> Callable[ - [conversation_dataset.DeleteConversationDatasetRequest], - operations_pb2.Operation]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._DeleteConversationDataset(self._session, self._host, self._interceptor) # type: ignore - - @property - def get_conversation_dataset(self) -> Callable[ - [conversation_dataset.GetConversationDatasetRequest], - conversation_dataset.ConversationDataset]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._GetConversationDataset(self._session, self._host, self._interceptor) # type: ignore - - @property - def import_conversation_data(self) -> Callable[ - [conversation_dataset.ImportConversationDataRequest], - operations_pb2.Operation]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._ImportConversationData(self._session, self._host, self._interceptor) # type: ignore - - @property - def list_conversation_datasets(self) -> Callable[ - [conversation_dataset.ListConversationDatasetsRequest], - conversation_dataset.ListConversationDatasetsResponse]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._ListConversationDatasets(self._session, self._host, self._interceptor) # type: ignore - - @property - def get_location(self): - return self._GetLocation(self._session, self._host, self._interceptor) # type: ignore - - class _GetLocation(ConversationDatasetsRestStub): - def __call__(self, - request: locations_pb2.GetLocationRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> locations_pb2.Location: - - r"""Call the get location method over HTTP. - - Args: - request (locations_pb2.GetLocationRequest): - The request object for GetLocation method. - 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: - locations_pb2.Location: Response from GetLocation method. - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v2/{name=projects/*/locations/*}', - }, - ] - - request, metadata = self._interceptor.pre_get_location(request, metadata) - request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode( - http_options, **request_kwargs) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json.dumps(transcoded_request['query_params'])) - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - resp = locations_pb2.Location() - resp = json_format.Parse(response.content.decode("utf-8"), resp) - resp = self._interceptor.post_get_location(resp) - return resp - - @property - def list_locations(self): - return self._ListLocations(self._session, self._host, self._interceptor) # type: ignore - - class _ListLocations(ConversationDatasetsRestStub): - def __call__(self, - request: locations_pb2.ListLocationsRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> locations_pb2.ListLocationsResponse: - - r"""Call the list locations method over HTTP. - - Args: - request (locations_pb2.ListLocationsRequest): - The request object for ListLocations method. - 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: - locations_pb2.ListLocationsResponse: Response from ListLocations method. - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v2/{name=projects/*}/locations', - }, - ] - - request, metadata = self._interceptor.pre_list_locations(request, metadata) - request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode( - http_options, **request_kwargs) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json.dumps(transcoded_request['query_params'])) - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - resp = locations_pb2.ListLocationsResponse() - resp = json_format.Parse(response.content.decode("utf-8"), resp) - resp = self._interceptor.post_list_locations(resp) - return resp - - @property - def cancel_operation(self): - return self._CancelOperation(self._session, self._host, self._interceptor) # type: ignore - - class _CancelOperation(ConversationDatasetsRestStub): - def __call__(self, - request: operations_pb2.CancelOperationRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> None: - - r"""Call the cancel operation method over HTTP. - - Args: - request (operations_pb2.CancelOperationRequest): - The request object for CancelOperation method. - 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. - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'post', - 'uri': '/v2/{name=projects/*/operations/*}:cancel', - }, -{ - 'method': 'post', - 'uri': '/v2/{name=projects/*/locations/*/operations/*}:cancel', - }, - ] - - request, metadata = self._interceptor.pre_cancel_operation(request, metadata) - request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode( - http_options, **request_kwargs) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json.dumps(transcoded_request['query_params'])) - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - return self._interceptor.post_cancel_operation(None) - - @property - def get_operation(self): - return self._GetOperation(self._session, self._host, self._interceptor) # type: ignore - - class _GetOperation(ConversationDatasetsRestStub): - def __call__(self, - request: operations_pb2.GetOperationRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> operations_pb2.Operation: - - r"""Call the get operation method over HTTP. - - Args: - request (operations_pb2.GetOperationRequest): - The request object for GetOperation method. - 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: - operations_pb2.Operation: Response from GetOperation method. - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v2/{name=projects/*/operations/*}', - }, -{ - 'method': 'get', - 'uri': '/v2/{name=projects/*/locations/*/operations/*}', - }, - ] - - request, metadata = self._interceptor.pre_get_operation(request, metadata) - request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode( - http_options, **request_kwargs) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json.dumps(transcoded_request['query_params'])) - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - resp = operations_pb2.Operation() - resp = json_format.Parse(response.content.decode("utf-8"), resp) - resp = self._interceptor.post_get_operation(resp) - return resp - - @property - def list_operations(self): - return self._ListOperations(self._session, self._host, self._interceptor) # type: ignore - - class _ListOperations(ConversationDatasetsRestStub): - def __call__(self, - request: operations_pb2.ListOperationsRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> operations_pb2.ListOperationsResponse: - - r"""Call the list operations method over HTTP. - - Args: - request (operations_pb2.ListOperationsRequest): - The request object for ListOperations method. - 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: - operations_pb2.ListOperationsResponse: Response from ListOperations method. - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v2/{name=projects/*}/operations', - }, -{ - 'method': 'get', - 'uri': '/v2/{name=projects/*/locations/*}/operations', - }, - ] - - request, metadata = self._interceptor.pre_list_operations(request, metadata) - request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode( - http_options, **request_kwargs) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json.dumps(transcoded_request['query_params'])) - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - resp = operations_pb2.ListOperationsResponse() - resp = json_format.Parse(response.content.decode("utf-8"), resp) - resp = self._interceptor.post_list_operations(resp) - return resp - - @property - def kind(self) -> str: - return "rest" - - def close(self): - self._session.close() - - -__all__=( - 'ConversationDatasetsRestTransport', -) diff --git a/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/conversation_models/__init__.py b/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/conversation_models/__init__.py deleted file mode 100644 index 5a1641980..000000000 --- a/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/conversation_models/__init__.py +++ /dev/null @@ -1,22 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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 ConversationModelsClient -from .async_client import ConversationModelsAsyncClient - -__all__ = ( - 'ConversationModelsClient', - 'ConversationModelsAsyncClient', -) diff --git a/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/conversation_models/async_client.py b/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/conversation_models/async_client.py deleted file mode 100644 index 523513095..000000000 --- a/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/conversation_models/async_client.py +++ /dev/null @@ -1,1526 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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, Mapping, MutableMapping, MutableSequence, Optional, Sequence, Tuple, Type, Union - -from google.cloud.dialogflow_v2 import gapic_version as package_version - -from google.api_core.client_options import ClientOptions -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import retry as retries -from google.auth import credentials as ga_credentials # type: ignore -from google.oauth2 import service_account # type: ignore - -try: - OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] -except AttributeError: # pragma: NO COVER - OptionalRetry = Union[retries.Retry, object] # type: ignore - -from google.api_core import operation # type: ignore -from google.api_core import operation_async # type: ignore -from google.cloud.dialogflow_v2.services.conversation_models import pagers -from google.cloud.dialogflow_v2.types import conversation_model -from google.cloud.dialogflow_v2.types import conversation_model as gcd_conversation_model -from google.cloud.location import locations_pb2 # type: ignore -from google.longrunning import operations_pb2 -from google.protobuf import empty_pb2 # type: ignore -from google.protobuf import timestamp_pb2 # type: ignore -from .transports.base import ConversationModelsTransport, DEFAULT_CLIENT_INFO -from .transports.grpc_asyncio import ConversationModelsGrpcAsyncIOTransport -from .client import ConversationModelsClient - - -class ConversationModelsAsyncClient: - """Manages a collection of models for human agent assistant.""" - - _client: ConversationModelsClient - - DEFAULT_ENDPOINT = ConversationModelsClient.DEFAULT_ENDPOINT - DEFAULT_MTLS_ENDPOINT = ConversationModelsClient.DEFAULT_MTLS_ENDPOINT - - conversation_dataset_path = staticmethod(ConversationModelsClient.conversation_dataset_path) - parse_conversation_dataset_path = staticmethod(ConversationModelsClient.parse_conversation_dataset_path) - conversation_model_path = staticmethod(ConversationModelsClient.conversation_model_path) - parse_conversation_model_path = staticmethod(ConversationModelsClient.parse_conversation_model_path) - conversation_model_evaluation_path = staticmethod(ConversationModelsClient.conversation_model_evaluation_path) - parse_conversation_model_evaluation_path = staticmethod(ConversationModelsClient.parse_conversation_model_evaluation_path) - document_path = staticmethod(ConversationModelsClient.document_path) - parse_document_path = staticmethod(ConversationModelsClient.parse_document_path) - common_billing_account_path = staticmethod(ConversationModelsClient.common_billing_account_path) - parse_common_billing_account_path = staticmethod(ConversationModelsClient.parse_common_billing_account_path) - common_folder_path = staticmethod(ConversationModelsClient.common_folder_path) - parse_common_folder_path = staticmethod(ConversationModelsClient.parse_common_folder_path) - common_organization_path = staticmethod(ConversationModelsClient.common_organization_path) - parse_common_organization_path = staticmethod(ConversationModelsClient.parse_common_organization_path) - common_project_path = staticmethod(ConversationModelsClient.common_project_path) - parse_common_project_path = staticmethod(ConversationModelsClient.parse_common_project_path) - common_location_path = staticmethod(ConversationModelsClient.common_location_path) - parse_common_location_path = staticmethod(ConversationModelsClient.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: - ConversationModelsAsyncClient: The constructed client. - """ - return ConversationModelsClient.from_service_account_info.__func__(ConversationModelsAsyncClient, 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: - ConversationModelsAsyncClient: The constructed client. - """ - return ConversationModelsClient.from_service_account_file.__func__(ConversationModelsAsyncClient, filename, *args, **kwargs) # type: ignore - - from_service_account_json = from_service_account_file - - @classmethod - def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[ClientOptions] = None): - """Return the API endpoint and client cert source for mutual TLS. - - The client cert source is determined in the following order: - (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the - client cert source is None. - (2) if `client_options.client_cert_source` is provided, use the provided one; if the - default client cert source exists, use the default one; otherwise the client cert - source is None. - - The API endpoint is determined in the following order: - (1) if `client_options.api_endpoint` if provided, use the provided one. - (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the - default mTLS endpoint; if the environment variable is "never", use the default API - endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise - use the default API endpoint. - - More details can be found at https://google.aip.dev/auth/4114. - - Args: - client_options (google.api_core.client_options.ClientOptions): Custom options for the - client. Only the `api_endpoint` and `client_cert_source` properties may be used - in this method. - - Returns: - Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the - client cert source to use. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If any errors happen. - """ - return ConversationModelsClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore - - @property - def transport(self) -> ConversationModelsTransport: - """Returns the transport used by the client instance. - - Returns: - ConversationModelsTransport: The transport used by the client instance. - """ - return self._client.transport - - get_transport_class = functools.partial(type(ConversationModelsClient).get_transport_class, type(ConversationModelsClient)) - - def __init__(self, *, - credentials: Optional[ga_credentials.Credentials] = None, - transport: Union[str, ConversationModelsTransport] = "grpc_asyncio", - client_options: Optional[ClientOptions] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the conversation models 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, ~.ConversationModelsTransport]): 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 = ConversationModelsClient( - credentials=credentials, - transport=transport, - client_options=client_options, - client_info=client_info, - - ) - - async def create_conversation_model(self, - request: Optional[Union[gcd_conversation_model.CreateConversationModelRequest, dict]] = None, - *, - parent: Optional[str] = None, - conversation_model: Optional[gcd_conversation_model.ConversationModel] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation_async.AsyncOperation: - r"""Creates a model. - - This method is a `long-running - operation `__. - The returned ``Operation`` type has the following - method-specific fields: - - - ``metadata``: - [CreateConversationModelOperationMetadata][google.cloud.dialogflow.v2.CreateConversationModelOperationMetadata] - - ``response``: - [ConversationModel][google.cloud.dialogflow.v2.ConversationModel] - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import dialogflow_v2 - - async def sample_create_conversation_model(): - # Create a client - client = dialogflow_v2.ConversationModelsAsyncClient() - - # Initialize request argument(s) - conversation_model = dialogflow_v2.ConversationModel() - conversation_model.display_name = "display_name_value" - conversation_model.datasets.dataset = "dataset_value" - - request = dialogflow_v2.CreateConversationModelRequest( - conversation_model=conversation_model, - ) - - # Make the request - operation = client.create_conversation_model(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.dialogflow_v2.types.CreateConversationModelRequest, dict]]): - The request object. The request message for - [ConversationModels.CreateConversationModel][google.cloud.dialogflow.v2.ConversationModels.CreateConversationModel] - parent (:class:`str`): - The project to create conversation model for. Format: - ``projects/`` - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - conversation_model (:class:`google.cloud.dialogflow_v2.types.ConversationModel`): - Required. The conversation model to - create. - - This corresponds to the ``conversation_model`` field - on the ``request`` instance; if ``request`` is provided, this - should not 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.api_core.operation_async.AsyncOperation: - An object representing a long-running operation. - - The result type for the operation will be - :class:`google.cloud.dialogflow_v2.types.ConversationModel` - Represents a conversation model. - - """ - # Create or coerce a protobuf request object. - # Quick 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, conversation_model]) - 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_conversation_model.CreateConversationModelRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - if conversation_model is not None: - request.conversation_model = conversation_model - - # 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_conversation_model, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Wrap the response in an operation future. - response = operation_async.from_gapic( - response, - self._client._transport.operations_client, - gcd_conversation_model.ConversationModel, - metadata_type=gcd_conversation_model.CreateConversationModelOperationMetadata, - ) - - # Done; return the response. - return response - - async def get_conversation_model(self, - request: Optional[Union[conversation_model.GetConversationModelRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> conversation_model.ConversationModel: - r"""Gets conversation model. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import dialogflow_v2 - - async def sample_get_conversation_model(): - # Create a client - client = dialogflow_v2.ConversationModelsAsyncClient() - - # Initialize request argument(s) - request = dialogflow_v2.GetConversationModelRequest( - name="name_value", - ) - - # Make the request - response = await client.get_conversation_model(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.dialogflow_v2.types.GetConversationModelRequest, dict]]): - The request object. The request message for - [ConversationModels.GetConversationModel][google.cloud.dialogflow.v2.ConversationModels.GetConversationModel] - name (:class:`str`): - Required. The conversation model to retrieve. Format: - ``projects//conversationModels/`` - - 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.ConversationModel: - Represents a conversation model. - """ - # Create or coerce a protobuf request object. - # Quick 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 = conversation_model.GetConversationModelRequest(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_conversation_model, - 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 list_conversation_models(self, - request: Optional[Union[conversation_model.ListConversationModelsRequest, dict]] = None, - *, - parent: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListConversationModelsAsyncPager: - r"""Lists conversation models. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import dialogflow_v2 - - async def sample_list_conversation_models(): - # Create a client - client = dialogflow_v2.ConversationModelsAsyncClient() - - # Initialize request argument(s) - request = dialogflow_v2.ListConversationModelsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_conversation_models(request=request) - - # Handle the response - async for response in page_result: - print(response) - - Args: - request (Optional[Union[google.cloud.dialogflow_v2.types.ListConversationModelsRequest, dict]]): - The request object. The request message for - [ConversationModels.ListConversationModels][google.cloud.dialogflow.v2.ConversationModels.ListConversationModels] - parent (:class:`str`): - Required. The project to list all conversation models - for. Format: ``projects/`` - - 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.conversation_models.pagers.ListConversationModelsAsyncPager: - The response message for - [ConversationModels.ListConversationModels][google.cloud.dialogflow.v2.ConversationModels.ListConversationModels] - - Iterating over this object will yield results and - resolve additional pages automatically. - - """ - # Create or coerce a protobuf request object. - # Quick 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 = conversation_model.ListConversationModelsRequest(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_conversation_models, - 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.ListConversationModelsAsyncPager( - method=rpc, - request=request, - response=response, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def delete_conversation_model(self, - request: Optional[Union[conversation_model.DeleteConversationModelRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation_async.AsyncOperation: - r"""Deletes a model. - - This method is a `long-running - operation `__. - The returned ``Operation`` type has the following - method-specific fields: - - - ``metadata``: - [DeleteConversationModelOperationMetadata][google.cloud.dialogflow.v2.DeleteConversationModelOperationMetadata] - - ``response``: An `Empty - message `__ - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import dialogflow_v2 - - async def sample_delete_conversation_model(): - # Create a client - client = dialogflow_v2.ConversationModelsAsyncClient() - - # Initialize request argument(s) - request = dialogflow_v2.DeleteConversationModelRequest( - name="name_value", - ) - - # Make the request - operation = client.delete_conversation_model(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.dialogflow_v2.types.DeleteConversationModelRequest, dict]]): - The request object. The request message for - [ConversationModels.DeleteConversationModel][google.cloud.dialogflow.v2.ConversationModels.DeleteConversationModel] - name (:class:`str`): - Required. The conversation model to delete. Format: - ``projects//conversationModels/`` - - 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.api_core.operation_async.AsyncOperation: - An object representing a long-running operation. - - The result type for the operation will be :class:`google.protobuf.empty_pb2.Empty` A generic empty message that you can re-use to avoid defining duplicated - empty messages in your APIs. A typical example is to - use it as the request or the response type of an API - method. For instance: - - service Foo { - rpc Bar(google.protobuf.Empty) returns - (google.protobuf.Empty); - - } - - """ - # Create or coerce a protobuf request object. - # Quick 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 = conversation_model.DeleteConversationModelRequest(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_conversation_model, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Wrap the response in an operation future. - response = operation_async.from_gapic( - response, - self._client._transport.operations_client, - empty_pb2.Empty, - metadata_type=conversation_model.DeleteConversationModelOperationMetadata, - ) - - # Done; return the response. - return response - - async def deploy_conversation_model(self, - request: Optional[Union[conversation_model.DeployConversationModelRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation_async.AsyncOperation: - r"""Deploys a model. If a model is already deployed, deploying it - has no effect. A model can only serve prediction requests after - it gets deployed. For article suggestion, custom model will not - be used unless it is deployed. - - This method is a `long-running - operation `__. - The returned ``Operation`` type has the following - method-specific fields: - - - ``metadata``: - [DeployConversationModelOperationMetadata][google.cloud.dialogflow.v2.DeployConversationModelOperationMetadata] - - ``response``: An `Empty - message `__ - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import dialogflow_v2 - - async def sample_deploy_conversation_model(): - # Create a client - client = dialogflow_v2.ConversationModelsAsyncClient() - - # Initialize request argument(s) - request = dialogflow_v2.DeployConversationModelRequest( - name="name_value", - ) - - # Make the request - operation = client.deploy_conversation_model(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.dialogflow_v2.types.DeployConversationModelRequest, dict]]): - The request object. The request message for - [ConversationModels.DeployConversationModel][google.cloud.dialogflow.v2.ConversationModels.DeployConversationModel] - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.api_core.operation_async.AsyncOperation: - An object representing a long-running operation. - - The result type for the operation will be :class:`google.protobuf.empty_pb2.Empty` A generic empty message that you can re-use to avoid defining duplicated - empty messages in your APIs. A typical example is to - use it as the request or the response type of an API - method. For instance: - - service Foo { - rpc Bar(google.protobuf.Empty) returns - (google.protobuf.Empty); - - } - - """ - # Create or coerce a protobuf request object. - request = conversation_model.DeployConversationModelRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.deploy_conversation_model, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Wrap the response in an operation future. - response = operation_async.from_gapic( - response, - self._client._transport.operations_client, - empty_pb2.Empty, - metadata_type=conversation_model.DeployConversationModelOperationMetadata, - ) - - # Done; return the response. - return response - - async def undeploy_conversation_model(self, - request: Optional[Union[conversation_model.UndeployConversationModelRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation_async.AsyncOperation: - r"""Undeploys a model. If the model is not deployed this method has - no effect. If the model is currently being used: - - - For article suggestion, article suggestion will fallback to - the default model if model is undeployed. - - This method is a `long-running - operation `__. - The returned ``Operation`` type has the following - method-specific fields: - - - ``metadata``: - [UndeployConversationModelOperationMetadata][google.cloud.dialogflow.v2.UndeployConversationModelOperationMetadata] - - ``response``: An `Empty - message `__ - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import dialogflow_v2 - - async def sample_undeploy_conversation_model(): - # Create a client - client = dialogflow_v2.ConversationModelsAsyncClient() - - # Initialize request argument(s) - request = dialogflow_v2.UndeployConversationModelRequest( - name="name_value", - ) - - # Make the request - operation = client.undeploy_conversation_model(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.dialogflow_v2.types.UndeployConversationModelRequest, dict]]): - The request object. The request message for - [ConversationModels.UndeployConversationModel][google.cloud.dialogflow.v2.ConversationModels.UndeployConversationModel] - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.api_core.operation_async.AsyncOperation: - An object representing a long-running operation. - - The result type for the operation will be :class:`google.protobuf.empty_pb2.Empty` A generic empty message that you can re-use to avoid defining duplicated - empty messages in your APIs. A typical example is to - use it as the request or the response type of an API - method. For instance: - - service Foo { - rpc Bar(google.protobuf.Empty) returns - (google.protobuf.Empty); - - } - - """ - # Create or coerce a protobuf request object. - request = conversation_model.UndeployConversationModelRequest(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.undeploy_conversation_model, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Wrap the response in an operation future. - response = operation_async.from_gapic( - response, - self._client._transport.operations_client, - empty_pb2.Empty, - metadata_type=conversation_model.UndeployConversationModelOperationMetadata, - ) - - # Done; return the response. - return response - - async def get_conversation_model_evaluation(self, - request: Optional[Union[conversation_model.GetConversationModelEvaluationRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> conversation_model.ConversationModelEvaluation: - r"""Gets an evaluation of conversation model. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import dialogflow_v2 - - async def sample_get_conversation_model_evaluation(): - # Create a client - client = dialogflow_v2.ConversationModelsAsyncClient() - - # Initialize request argument(s) - request = dialogflow_v2.GetConversationModelEvaluationRequest( - name="name_value", - ) - - # Make the request - response = await client.get_conversation_model_evaluation(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.dialogflow_v2.types.GetConversationModelEvaluationRequest, dict]]): - The request object. The request message for - [ConversationModels.GetConversationModelEvaluation][google.cloud.dialogflow.v2.ConversationModels.GetConversationModelEvaluation] - name (:class:`str`): - Required. The conversation model evaluation resource - name. Format: - ``projects//conversationModels//evaluations/`` - - 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.ConversationModelEvaluation: - Represents evaluation result of a - conversation model. - - """ - # Create or coerce a protobuf request object. - # Quick 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 = conversation_model.GetConversationModelEvaluationRequest(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_conversation_model_evaluation, - 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 list_conversation_model_evaluations(self, - request: Optional[Union[conversation_model.ListConversationModelEvaluationsRequest, dict]] = None, - *, - parent: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListConversationModelEvaluationsAsyncPager: - r"""Lists evaluations of a conversation model. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import dialogflow_v2 - - async def sample_list_conversation_model_evaluations(): - # Create a client - client = dialogflow_v2.ConversationModelsAsyncClient() - - # Initialize request argument(s) - request = dialogflow_v2.ListConversationModelEvaluationsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_conversation_model_evaluations(request=request) - - # Handle the response - async for response in page_result: - print(response) - - Args: - request (Optional[Union[google.cloud.dialogflow_v2.types.ListConversationModelEvaluationsRequest, dict]]): - The request object. The request message for - [ConversationModels.ListConversationModelEvaluations][google.cloud.dialogflow.v2.ConversationModels.ListConversationModelEvaluations] - parent (:class:`str`): - Required. The conversation model resource name. Format: - ``projects//conversationModels/`` - - 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.conversation_models.pagers.ListConversationModelEvaluationsAsyncPager: - The response message for - [ConversationModels.ListConversationModelEvaluations][google.cloud.dialogflow.v2.ConversationModels.ListConversationModelEvaluations] - - Iterating over this object will yield results and - resolve additional pages automatically. - - """ - # Create or coerce a protobuf request object. - # Quick 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 = conversation_model.ListConversationModelEvaluationsRequest(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_conversation_model_evaluations, - 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.ListConversationModelEvaluationsAsyncPager( - method=rpc, - request=request, - response=response, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def create_conversation_model_evaluation(self, - request: Optional[Union[conversation_model.CreateConversationModelEvaluationRequest, dict]] = None, - *, - parent: Optional[str] = None, - conversation_model_evaluation: Optional[conversation_model.ConversationModelEvaluation] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation_async.AsyncOperation: - r"""Creates evaluation of a conversation model. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import dialogflow_v2 - - async def sample_create_conversation_model_evaluation(): - # Create a client - client = dialogflow_v2.ConversationModelsAsyncClient() - - # Initialize request argument(s) - request = dialogflow_v2.CreateConversationModelEvaluationRequest( - parent="parent_value", - ) - - # Make the request - operation = client.create_conversation_model_evaluation(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.dialogflow_v2.types.CreateConversationModelEvaluationRequest, dict]]): - The request object. The request message for - [ConversationModels.CreateConversationModelEvaluation][google.cloud.dialogflow.v2.ConversationModels.CreateConversationModelEvaluation] - parent (:class:`str`): - Required. The conversation model resource name. Format: - ``projects//locations//conversationModels/`` - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - conversation_model_evaluation (:class:`google.cloud.dialogflow_v2.types.ConversationModelEvaluation`): - Required. The conversation model - evaluation to be created. - - This corresponds to the ``conversation_model_evaluation`` field - on the ``request`` instance; if ``request`` is provided, this - should not 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.api_core.operation_async.AsyncOperation: - An object representing a long-running operation. - - The result type for the operation will be - :class:`google.cloud.dialogflow_v2.types.ConversationModelEvaluation` - Represents evaluation result of a conversation model. - - """ - # Create or coerce a protobuf request object. - # Quick 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, conversation_model_evaluation]) - 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 = conversation_model.CreateConversationModelEvaluationRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - if conversation_model_evaluation is not None: - request.conversation_model_evaluation = conversation_model_evaluation - - # 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_conversation_model_evaluation, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Wrap the response in an operation future. - response = operation_async.from_gapic( - response, - self._client._transport.operations_client, - conversation_model.ConversationModelEvaluation, - metadata_type=conversation_model.CreateConversationModelEvaluationOperationMetadata, - ) - - # Done; return the response. - return response - - async def list_operations( - self, - request: Optional[operations_pb2.ListOperationsRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operations_pb2.ListOperationsResponse: - r"""Lists operations that match the specified filter in the request. - - Args: - request (:class:`~.operations_pb2.ListOperationsRequest`): - The request object. Request message for - `ListOperations` method. - 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: - ~.operations_pb2.ListOperationsResponse: - Response message for ``ListOperations`` method. - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = operations_pb2.ListOperationsRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._client._transport.list_operations, - 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 get_operation( - self, - request: Optional[operations_pb2.GetOperationRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operations_pb2.Operation: - r"""Gets the latest state of a long-running operation. - - Args: - request (:class:`~.operations_pb2.GetOperationRequest`): - The request object. Request message for - `GetOperation` method. - 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: - ~.operations_pb2.Operation: - An ``Operation`` object. - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = operations_pb2.GetOperationRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._client._transport.get_operation, - 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 cancel_operation( - self, - request: Optional[operations_pb2.CancelOperationRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> None: - r"""Starts asynchronous cancellation on a long-running operation. - - The server makes a best effort to cancel the operation, but success - is not guaranteed. If the server doesn't support this method, it returns - `google.rpc.Code.UNIMPLEMENTED`. - - Args: - request (:class:`~.operations_pb2.CancelOperationRequest`): - The request object. Request message for - `CancelOperation` method. - 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: - None - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = operations_pb2.CancelOperationRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._client._transport.cancel_operation, - 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_location( - self, - request: Optional[locations_pb2.GetLocationRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> locations_pb2.Location: - r"""Gets information about a location. - - Args: - request (:class:`~.location_pb2.GetLocationRequest`): - The request object. Request message for - `GetLocation` method. - 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: - ~.location_pb2.Location: - Location object. - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = locations_pb2.GetLocationRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._client._transport.get_location, - 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 list_locations( - self, - request: Optional[locations_pb2.ListLocationsRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> locations_pb2.ListLocationsResponse: - r"""Lists information about the supported locations for this service. - - Args: - request (:class:`~.location_pb2.ListLocationsRequest`): - The request object. Request message for - `ListLocations` method. - 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: - ~.location_pb2.ListLocationsResponse: - Response message for ``ListLocations`` method. - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = locations_pb2.ListLocationsRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._client._transport.list_locations, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("name", request.name),)), - ) - - # Send the request. - response = await rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - async def __aenter__(self): - return self - - async def __aexit__(self, exc_type, exc, tb): - await self.transport.close() - -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) - - -__all__ = ( - "ConversationModelsAsyncClient", -) diff --git a/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/conversation_models/client.py b/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/conversation_models/client.py deleted file mode 100644 index 527c6346f..000000000 --- a/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/conversation_models/client.py +++ /dev/null @@ -1,1754 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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 os -import re -from typing import Dict, Mapping, MutableMapping, MutableSequence, Optional, Sequence, Tuple, Type, Union, cast - -from google.cloud.dialogflow_v2 import gapic_version as package_version - -from google.api_core import client_options as client_options_lib -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import retry as retries -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 - -try: - OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] -except AttributeError: # pragma: NO COVER - OptionalRetry = Union[retries.Retry, object] # type: ignore - -from google.api_core import operation # type: ignore -from google.api_core import operation_async # type: ignore -from google.cloud.dialogflow_v2.services.conversation_models import pagers -from google.cloud.dialogflow_v2.types import conversation_model -from google.cloud.dialogflow_v2.types import conversation_model as gcd_conversation_model -from google.cloud.location import locations_pb2 # type: ignore -from google.longrunning import operations_pb2 -from google.protobuf import empty_pb2 # type: ignore -from google.protobuf import timestamp_pb2 # type: ignore -from .transports.base import ConversationModelsTransport, DEFAULT_CLIENT_INFO -from .transports.grpc import ConversationModelsGrpcTransport -from .transports.grpc_asyncio import ConversationModelsGrpcAsyncIOTransport -from .transports.rest import ConversationModelsRestTransport - - -class ConversationModelsClientMeta(type): - """Metaclass for the ConversationModels 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[ConversationModelsTransport]] - _transport_registry["grpc"] = ConversationModelsGrpcTransport - _transport_registry["grpc_asyncio"] = ConversationModelsGrpcAsyncIOTransport - _transport_registry["rest"] = ConversationModelsRestTransport - - def get_transport_class(cls, - label: Optional[str] = None, - ) -> Type[ConversationModelsTransport]: - """Returns an appropriate transport class. - - Args: - label: The name of the desired transport. If none is - provided, then the first transport in the registry is used. - - Returns: - The transport class to use. - """ - # If a specific transport is requested, return that one. - if label: - return cls._transport_registry[label] - - # No transport is requested; return the default (that is, the first one - # in the dictionary). - return next(iter(cls._transport_registry.values())) - - -class ConversationModelsClient(metaclass=ConversationModelsClientMeta): - """Manages a collection of models for human agent assistant.""" - - @staticmethod - def _get_default_mtls_endpoint(api_endpoint): - """Converts api endpoint to mTLS endpoint. - - Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to - "*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively. - Args: - api_endpoint (Optional[str]): the api endpoint to convert. - Returns: - str: converted mTLS api endpoint. - """ - if not api_endpoint: - return api_endpoint - - mtls_endpoint_re = re.compile( - r"(?P[^.]+)(?P\.mtls)?(?P\.sandbox)?(?P\.googleapis\.com)?" - ) - - m = mtls_endpoint_re.match(api_endpoint) - name, mtls, sandbox, googledomain = m.groups() - if mtls or not googledomain: - return api_endpoint - - if sandbox: - return api_endpoint.replace( - "sandbox.googleapis.com", "mtls.sandbox.googleapis.com" - ) - - return api_endpoint.replace(".googleapis.com", ".mtls.googleapis.com") - - DEFAULT_ENDPOINT = "dialogflow.googleapis.com" - DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore - DEFAULT_ENDPOINT - ) - - @classmethod - def from_service_account_info(cls, info: dict, *args, **kwargs): - """Creates an instance of this client using the provided credentials - info. - - Args: - info (dict): The service account private key info. - args: Additional arguments to pass to the constructor. - kwargs: Additional arguments to pass to the constructor. - - Returns: - ConversationModelsClient: 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: - ConversationModelsClient: 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) -> ConversationModelsTransport: - """Returns the transport used by the client instance. - - Returns: - ConversationModelsTransport: The transport used by the client - instance. - """ - return self._transport - - @staticmethod - def conversation_dataset_path(project: str,location: str,conversation_dataset: str,) -> str: - """Returns a fully-qualified conversation_dataset string.""" - return "projects/{project}/locations/{location}/conversationDatasets/{conversation_dataset}".format(project=project, location=location, conversation_dataset=conversation_dataset, ) - - @staticmethod - def parse_conversation_dataset_path(path: str) -> Dict[str,str]: - """Parses a conversation_dataset path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/conversationDatasets/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def conversation_model_path(project: str,location: str,conversation_model: str,) -> str: - """Returns 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]: - """Parses 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_model_evaluation_path(project: str,conversation_model: str,evaluation: str,) -> str: - """Returns a fully-qualified conversation_model_evaluation string.""" - return "projects/{project}/conversationModels/{conversation_model}/evaluations/{evaluation}".format(project=project, conversation_model=conversation_model, evaluation=evaluation, ) - - @staticmethod - def parse_conversation_model_evaluation_path(path: str) -> Dict[str,str]: - """Parses a conversation_model_evaluation path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/conversationModels/(?P.+?)/evaluations/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def document_path(project: str,knowledge_base: str,document: str,) -> str: - """Returns a fully-qualified document string.""" - return "projects/{project}/knowledgeBases/{knowledge_base}/documents/{document}".format(project=project, knowledge_base=knowledge_base, document=document, ) - - @staticmethod - def parse_document_path(path: str) -> Dict[str,str]: - """Parses a document path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/knowledgeBases/(?P.+?)/documents/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_billing_account_path(billing_account: str, ) -> str: - """Returns a fully-qualified billing_account string.""" - return "billingAccounts/{billing_account}".format(billing_account=billing_account, ) - - @staticmethod - def parse_common_billing_account_path(path: str) -> Dict[str,str]: - """Parse a billing_account path into its component segments.""" - m = re.match(r"^billingAccounts/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_folder_path(folder: str, ) -> str: - """Returns a fully-qualified folder string.""" - return "folders/{folder}".format(folder=folder, ) - - @staticmethod - def parse_common_folder_path(path: str) -> Dict[str,str]: - """Parse a folder path into its component segments.""" - m = re.match(r"^folders/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_organization_path(organization: str, ) -> str: - """Returns a fully-qualified organization string.""" - return "organizations/{organization}".format(organization=organization, ) - - @staticmethod - def parse_common_organization_path(path: str) -> Dict[str,str]: - """Parse a organization path into its component segments.""" - m = re.match(r"^organizations/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_project_path(project: str, ) -> str: - """Returns a fully-qualified project string.""" - return "projects/{project}".format(project=project, ) - - @staticmethod - def parse_common_project_path(path: str) -> Dict[str,str]: - """Parse a project path into its component segments.""" - m = re.match(r"^projects/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_location_path(project: str, location: str, ) -> str: - """Returns a fully-qualified location string.""" - return "projects/{project}/locations/{location}".format(project=project, location=location, ) - - @staticmethod - def parse_common_location_path(path: str) -> Dict[str,str]: - """Parse a location path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)$", path) - return m.groupdict() if m else {} - - @classmethod - def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[client_options_lib.ClientOptions] = None): - """Return the API endpoint and client cert source for mutual TLS. - - The client cert source is determined in the following order: - (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the - client cert source is None. - (2) if `client_options.client_cert_source` is provided, use the provided one; if the - default client cert source exists, use the default one; otherwise the client cert - source is None. - - The API endpoint is determined in the following order: - (1) if `client_options.api_endpoint` if provided, use the provided one. - (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the - default mTLS endpoint; if the environment variable is "never", use the default API - endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise - use the default API endpoint. - - More details can be found at https://google.aip.dev/auth/4114. - - Args: - client_options (google.api_core.client_options.ClientOptions): Custom options for the - client. Only the `api_endpoint` and `client_cert_source` properties may be used - in this method. - - Returns: - Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the - client cert source to use. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If any errors happen. - """ - if client_options is None: - client_options = client_options_lib.ClientOptions() - use_client_cert = os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false") - use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") - if use_client_cert not in ("true", "false"): - raise ValueError("Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`") - if use_mtls_endpoint not in ("auto", "never", "always"): - raise MutualTLSChannelError("Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`") - - # Figure out the client cert source to use. - client_cert_source = None - if use_client_cert == "true": - if client_options.client_cert_source: - client_cert_source = client_options.client_cert_source - elif mtls.has_default_client_cert_source(): - client_cert_source = mtls.default_client_cert_source() - - # Figure out which api endpoint to use. - if client_options.api_endpoint is not None: - api_endpoint = client_options.api_endpoint - elif use_mtls_endpoint == "always" or (use_mtls_endpoint == "auto" and client_cert_source): - api_endpoint = cls.DEFAULT_MTLS_ENDPOINT - else: - api_endpoint = cls.DEFAULT_ENDPOINT - - return api_endpoint, client_cert_source - - def __init__(self, *, - credentials: Optional[ga_credentials.Credentials] = None, - transport: Optional[Union[str, ConversationModelsTransport]] = None, - client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the conversation models 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, ConversationModelsTransport]): The - transport to use. If set to None, a transport is chosen - automatically. - client_options (Optional[Union[google.api_core.client_options.ClientOptions, dict]]): 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() - client_options = cast(client_options_lib.ClientOptions, client_options) - - api_endpoint, client_cert_source_func = self.get_mtls_endpoint_and_cert_source(client_options) - - api_key_value = getattr(client_options, "api_key", None) - if api_key_value and credentials: - raise ValueError("client_options.api_key and credentials are mutually exclusive") - - # 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, ConversationModelsTransport): - # transport is a ConversationModelsTransport instance. - if credentials or client_options.credentials_file or api_key_value: - 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: - import google.auth._default # type: ignore - - if api_key_value and hasattr(google.auth._default, "get_api_key_credentials"): - credentials = google.auth._default.get_api_key_credentials(api_key_value) - - Transport = type(self).get_transport_class(transport) - self._transport = Transport( - credentials=credentials, - credentials_file=client_options.credentials_file, - host=api_endpoint, - scopes=client_options.scopes, - client_cert_source_for_mtls=client_cert_source_func, - quota_project_id=client_options.quota_project_id, - client_info=client_info, - always_use_jwt_access=True, - api_audience=client_options.api_audience, - ) - - def create_conversation_model(self, - request: Optional[Union[gcd_conversation_model.CreateConversationModelRequest, dict]] = None, - *, - parent: Optional[str] = None, - conversation_model: Optional[gcd_conversation_model.ConversationModel] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation.Operation: - r"""Creates a model. - - This method is a `long-running - operation `__. - The returned ``Operation`` type has the following - method-specific fields: - - - ``metadata``: - [CreateConversationModelOperationMetadata][google.cloud.dialogflow.v2.CreateConversationModelOperationMetadata] - - ``response``: - [ConversationModel][google.cloud.dialogflow.v2.ConversationModel] - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import dialogflow_v2 - - def sample_create_conversation_model(): - # Create a client - client = dialogflow_v2.ConversationModelsClient() - - # Initialize request argument(s) - conversation_model = dialogflow_v2.ConversationModel() - conversation_model.display_name = "display_name_value" - conversation_model.datasets.dataset = "dataset_value" - - request = dialogflow_v2.CreateConversationModelRequest( - conversation_model=conversation_model, - ) - - # Make the request - operation = client.create_conversation_model(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.dialogflow_v2.types.CreateConversationModelRequest, dict]): - The request object. The request message for - [ConversationModels.CreateConversationModel][google.cloud.dialogflow.v2.ConversationModels.CreateConversationModel] - parent (str): - The project to create conversation model for. Format: - ``projects/`` - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - conversation_model (google.cloud.dialogflow_v2.types.ConversationModel): - Required. The conversation model to - create. - - This corresponds to the ``conversation_model`` field - on the ``request`` instance; if ``request`` is provided, this - should not 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.api_core.operation.Operation: - An object representing a long-running operation. - - The result type for the operation will be - :class:`google.cloud.dialogflow_v2.types.ConversationModel` - Represents a conversation model. - - """ - # Create or coerce a protobuf request object. - # Quick 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, conversation_model]) - 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_conversation_model.CreateConversationModelRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, gcd_conversation_model.CreateConversationModelRequest): - request = gcd_conversation_model.CreateConversationModelRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - if conversation_model is not None: - request.conversation_model = conversation_model - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.create_conversation_model] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Wrap the response in an operation future. - response = operation.from_gapic( - response, - self._transport.operations_client, - gcd_conversation_model.ConversationModel, - metadata_type=gcd_conversation_model.CreateConversationModelOperationMetadata, - ) - - # Done; return the response. - return response - - def get_conversation_model(self, - request: Optional[Union[conversation_model.GetConversationModelRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> conversation_model.ConversationModel: - r"""Gets conversation model. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import dialogflow_v2 - - def sample_get_conversation_model(): - # Create a client - client = dialogflow_v2.ConversationModelsClient() - - # Initialize request argument(s) - request = dialogflow_v2.GetConversationModelRequest( - name="name_value", - ) - - # Make the request - response = client.get_conversation_model(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.dialogflow_v2.types.GetConversationModelRequest, dict]): - The request object. The request message for - [ConversationModels.GetConversationModel][google.cloud.dialogflow.v2.ConversationModels.GetConversationModel] - name (str): - Required. The conversation model to retrieve. Format: - ``projects//conversationModels/`` - - 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.ConversationModel: - Represents a conversation model. - """ - # Create or coerce a protobuf request object. - # Quick 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 conversation_model.GetConversationModelRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, conversation_model.GetConversationModelRequest): - request = conversation_model.GetConversationModelRequest(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_conversation_model] - - # 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 list_conversation_models(self, - request: Optional[Union[conversation_model.ListConversationModelsRequest, dict]] = None, - *, - parent: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListConversationModelsPager: - r"""Lists conversation models. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import dialogflow_v2 - - def sample_list_conversation_models(): - # Create a client - client = dialogflow_v2.ConversationModelsClient() - - # Initialize request argument(s) - request = dialogflow_v2.ListConversationModelsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_conversation_models(request=request) - - # Handle the response - for response in page_result: - print(response) - - Args: - request (Union[google.cloud.dialogflow_v2.types.ListConversationModelsRequest, dict]): - The request object. The request message for - [ConversationModels.ListConversationModels][google.cloud.dialogflow.v2.ConversationModels.ListConversationModels] - parent (str): - Required. The project to list all conversation models - for. Format: ``projects/`` - - 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.conversation_models.pagers.ListConversationModelsPager: - The response message for - [ConversationModels.ListConversationModels][google.cloud.dialogflow.v2.ConversationModels.ListConversationModels] - - Iterating over this object will yield results and - resolve additional pages automatically. - - """ - # Create or coerce a protobuf request object. - # Quick 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 conversation_model.ListConversationModelsRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, conversation_model.ListConversationModelsRequest): - request = conversation_model.ListConversationModelsRequest(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_conversation_models] - - # 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.ListConversationModelsPager( - method=rpc, - request=request, - response=response, - metadata=metadata, - ) - - # Done; return the response. - return response - - def delete_conversation_model(self, - request: Optional[Union[conversation_model.DeleteConversationModelRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation.Operation: - r"""Deletes a model. - - This method is a `long-running - operation `__. - The returned ``Operation`` type has the following - method-specific fields: - - - ``metadata``: - [DeleteConversationModelOperationMetadata][google.cloud.dialogflow.v2.DeleteConversationModelOperationMetadata] - - ``response``: An `Empty - message `__ - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import dialogflow_v2 - - def sample_delete_conversation_model(): - # Create a client - client = dialogflow_v2.ConversationModelsClient() - - # Initialize request argument(s) - request = dialogflow_v2.DeleteConversationModelRequest( - name="name_value", - ) - - # Make the request - operation = client.delete_conversation_model(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.dialogflow_v2.types.DeleteConversationModelRequest, dict]): - The request object. The request message for - [ConversationModels.DeleteConversationModel][google.cloud.dialogflow.v2.ConversationModels.DeleteConversationModel] - name (str): - Required. The conversation model to delete. Format: - ``projects//conversationModels/`` - - 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.api_core.operation.Operation: - An object representing a long-running operation. - - The result type for the operation will be :class:`google.protobuf.empty_pb2.Empty` A generic empty message that you can re-use to avoid defining duplicated - empty messages in your APIs. A typical example is to - use it as the request or the response type of an API - method. For instance: - - service Foo { - rpc Bar(google.protobuf.Empty) returns - (google.protobuf.Empty); - - } - - """ - # Create or coerce a protobuf request object. - # Quick 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 conversation_model.DeleteConversationModelRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, conversation_model.DeleteConversationModelRequest): - request = conversation_model.DeleteConversationModelRequest(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_conversation_model] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Wrap the response in an operation future. - response = operation.from_gapic( - response, - self._transport.operations_client, - empty_pb2.Empty, - metadata_type=conversation_model.DeleteConversationModelOperationMetadata, - ) - - # Done; return the response. - return response - - def deploy_conversation_model(self, - request: Optional[Union[conversation_model.DeployConversationModelRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation.Operation: - r"""Deploys a model. If a model is already deployed, deploying it - has no effect. A model can only serve prediction requests after - it gets deployed. For article suggestion, custom model will not - be used unless it is deployed. - - This method is a `long-running - operation `__. - The returned ``Operation`` type has the following - method-specific fields: - - - ``metadata``: - [DeployConversationModelOperationMetadata][google.cloud.dialogflow.v2.DeployConversationModelOperationMetadata] - - ``response``: An `Empty - message `__ - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import dialogflow_v2 - - def sample_deploy_conversation_model(): - # Create a client - client = dialogflow_v2.ConversationModelsClient() - - # Initialize request argument(s) - request = dialogflow_v2.DeployConversationModelRequest( - name="name_value", - ) - - # Make the request - operation = client.deploy_conversation_model(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.dialogflow_v2.types.DeployConversationModelRequest, dict]): - The request object. The request message for - [ConversationModels.DeployConversationModel][google.cloud.dialogflow.v2.ConversationModels.DeployConversationModel] - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.api_core.operation.Operation: - An object representing a long-running operation. - - The result type for the operation will be :class:`google.protobuf.empty_pb2.Empty` A generic empty message that you can re-use to avoid defining duplicated - empty messages in your APIs. A typical example is to - use it as the request or the response type of an API - method. For instance: - - service Foo { - rpc Bar(google.protobuf.Empty) returns - (google.protobuf.Empty); - - } - - """ - # Create or coerce a protobuf request object. - # Minor optimization to avoid making a copy if the user passes - # in a conversation_model.DeployConversationModelRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, conversation_model.DeployConversationModelRequest): - request = conversation_model.DeployConversationModelRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.deploy_conversation_model] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Wrap the response in an operation future. - response = operation.from_gapic( - response, - self._transport.operations_client, - empty_pb2.Empty, - metadata_type=conversation_model.DeployConversationModelOperationMetadata, - ) - - # Done; return the response. - return response - - def undeploy_conversation_model(self, - request: Optional[Union[conversation_model.UndeployConversationModelRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation.Operation: - r"""Undeploys a model. If the model is not deployed this method has - no effect. If the model is currently being used: - - - For article suggestion, article suggestion will fallback to - the default model if model is undeployed. - - This method is a `long-running - operation `__. - The returned ``Operation`` type has the following - method-specific fields: - - - ``metadata``: - [UndeployConversationModelOperationMetadata][google.cloud.dialogflow.v2.UndeployConversationModelOperationMetadata] - - ``response``: An `Empty - message `__ - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import dialogflow_v2 - - def sample_undeploy_conversation_model(): - # Create a client - client = dialogflow_v2.ConversationModelsClient() - - # Initialize request argument(s) - request = dialogflow_v2.UndeployConversationModelRequest( - name="name_value", - ) - - # Make the request - operation = client.undeploy_conversation_model(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.dialogflow_v2.types.UndeployConversationModelRequest, dict]): - The request object. The request message for - [ConversationModels.UndeployConversationModel][google.cloud.dialogflow.v2.ConversationModels.UndeployConversationModel] - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.api_core.operation.Operation: - An object representing a long-running operation. - - The result type for the operation will be :class:`google.protobuf.empty_pb2.Empty` A generic empty message that you can re-use to avoid defining duplicated - empty messages in your APIs. A typical example is to - use it as the request or the response type of an API - method. For instance: - - service Foo { - rpc Bar(google.protobuf.Empty) returns - (google.protobuf.Empty); - - } - - """ - # Create or coerce a protobuf request object. - # Minor optimization to avoid making a copy if the user passes - # in a conversation_model.UndeployConversationModelRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, conversation_model.UndeployConversationModelRequest): - request = conversation_model.UndeployConversationModelRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.undeploy_conversation_model] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Wrap the response in an operation future. - response = operation.from_gapic( - response, - self._transport.operations_client, - empty_pb2.Empty, - metadata_type=conversation_model.UndeployConversationModelOperationMetadata, - ) - - # Done; return the response. - return response - - def get_conversation_model_evaluation(self, - request: Optional[Union[conversation_model.GetConversationModelEvaluationRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> conversation_model.ConversationModelEvaluation: - r"""Gets an evaluation of conversation model. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import dialogflow_v2 - - def sample_get_conversation_model_evaluation(): - # Create a client - client = dialogflow_v2.ConversationModelsClient() - - # Initialize request argument(s) - request = dialogflow_v2.GetConversationModelEvaluationRequest( - name="name_value", - ) - - # Make the request - response = client.get_conversation_model_evaluation(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.dialogflow_v2.types.GetConversationModelEvaluationRequest, dict]): - The request object. The request message for - [ConversationModels.GetConversationModelEvaluation][google.cloud.dialogflow.v2.ConversationModels.GetConversationModelEvaluation] - name (str): - Required. The conversation model evaluation resource - name. Format: - ``projects//conversationModels//evaluations/`` - - 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.ConversationModelEvaluation: - Represents evaluation result of a - conversation model. - - """ - # Create or coerce a protobuf request object. - # Quick 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 conversation_model.GetConversationModelEvaluationRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, conversation_model.GetConversationModelEvaluationRequest): - request = conversation_model.GetConversationModelEvaluationRequest(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_conversation_model_evaluation] - - # 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 list_conversation_model_evaluations(self, - request: Optional[Union[conversation_model.ListConversationModelEvaluationsRequest, dict]] = None, - *, - parent: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListConversationModelEvaluationsPager: - r"""Lists evaluations of a conversation model. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import dialogflow_v2 - - def sample_list_conversation_model_evaluations(): - # Create a client - client = dialogflow_v2.ConversationModelsClient() - - # Initialize request argument(s) - request = dialogflow_v2.ListConversationModelEvaluationsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_conversation_model_evaluations(request=request) - - # Handle the response - for response in page_result: - print(response) - - Args: - request (Union[google.cloud.dialogflow_v2.types.ListConversationModelEvaluationsRequest, dict]): - The request object. The request message for - [ConversationModels.ListConversationModelEvaluations][google.cloud.dialogflow.v2.ConversationModels.ListConversationModelEvaluations] - parent (str): - Required. The conversation model resource name. Format: - ``projects//conversationModels/`` - - 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.conversation_models.pagers.ListConversationModelEvaluationsPager: - The response message for - [ConversationModels.ListConversationModelEvaluations][google.cloud.dialogflow.v2.ConversationModels.ListConversationModelEvaluations] - - Iterating over this object will yield results and - resolve additional pages automatically. - - """ - # Create or coerce a protobuf request object. - # Quick 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 conversation_model.ListConversationModelEvaluationsRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, conversation_model.ListConversationModelEvaluationsRequest): - request = conversation_model.ListConversationModelEvaluationsRequest(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_conversation_model_evaluations] - - # 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.ListConversationModelEvaluationsPager( - method=rpc, - request=request, - response=response, - metadata=metadata, - ) - - # Done; return the response. - return response - - def create_conversation_model_evaluation(self, - request: Optional[Union[conversation_model.CreateConversationModelEvaluationRequest, dict]] = None, - *, - parent: Optional[str] = None, - conversation_model_evaluation: Optional[conversation_model.ConversationModelEvaluation] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation.Operation: - r"""Creates evaluation of a conversation model. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import dialogflow_v2 - - def sample_create_conversation_model_evaluation(): - # Create a client - client = dialogflow_v2.ConversationModelsClient() - - # Initialize request argument(s) - request = dialogflow_v2.CreateConversationModelEvaluationRequest( - parent="parent_value", - ) - - # Make the request - operation = client.create_conversation_model_evaluation(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.dialogflow_v2.types.CreateConversationModelEvaluationRequest, dict]): - The request object. The request message for - [ConversationModels.CreateConversationModelEvaluation][google.cloud.dialogflow.v2.ConversationModels.CreateConversationModelEvaluation] - parent (str): - Required. The conversation model resource name. Format: - ``projects//locations//conversationModels/`` - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - conversation_model_evaluation (google.cloud.dialogflow_v2.types.ConversationModelEvaluation): - Required. The conversation model - evaluation to be created. - - This corresponds to the ``conversation_model_evaluation`` field - on the ``request`` instance; if ``request`` is provided, this - should not 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.api_core.operation.Operation: - An object representing a long-running operation. - - The result type for the operation will be - :class:`google.cloud.dialogflow_v2.types.ConversationModelEvaluation` - Represents evaluation result of a conversation model. - - """ - # Create or coerce a protobuf request object. - # Quick 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, conversation_model_evaluation]) - 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 conversation_model.CreateConversationModelEvaluationRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, conversation_model.CreateConversationModelEvaluationRequest): - request = conversation_model.CreateConversationModelEvaluationRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - if conversation_model_evaluation is not None: - request.conversation_model_evaluation = conversation_model_evaluation - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.create_conversation_model_evaluation] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Wrap the response in an operation future. - response = operation.from_gapic( - response, - self._transport.operations_client, - conversation_model.ConversationModelEvaluation, - metadata_type=conversation_model.CreateConversationModelEvaluationOperationMetadata, - ) - - # Done; return the response. - return response - - def __enter__(self) -> "ConversationModelsClient": - return self - - def __exit__(self, type, value, traceback): - """Releases underlying transport's resources. - - .. warning:: - ONLY use as a context manager if the transport is NOT shared - with other clients! Exiting the with block will CLOSE the transport - and may cause errors in other clients! - """ - self.transport.close() - - def list_operations( - self, - request: Optional[operations_pb2.ListOperationsRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operations_pb2.ListOperationsResponse: - r"""Lists operations that match the specified filter in the request. - - Args: - request (:class:`~.operations_pb2.ListOperationsRequest`): - The request object. Request message for - `ListOperations` method. - 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: - ~.operations_pb2.ListOperationsResponse: - Response message for ``ListOperations`` method. - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = operations_pb2.ListOperationsRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._transport.list_operations, - 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 = rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - def get_operation( - self, - request: Optional[operations_pb2.GetOperationRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operations_pb2.Operation: - r"""Gets the latest state of a long-running operation. - - Args: - request (:class:`~.operations_pb2.GetOperationRequest`): - The request object. Request message for - `GetOperation` method. - 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: - ~.operations_pb2.Operation: - An ``Operation`` object. - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = operations_pb2.GetOperationRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._transport.get_operation, - 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 = rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - def cancel_operation( - self, - request: Optional[operations_pb2.CancelOperationRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> None: - r"""Starts asynchronous cancellation on a long-running operation. - - The server makes a best effort to cancel the operation, but success - is not guaranteed. If the server doesn't support this method, it returns - `google.rpc.Code.UNIMPLEMENTED`. - - Args: - request (:class:`~.operations_pb2.CancelOperationRequest`): - The request object. Request message for - `CancelOperation` method. - 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: - None - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = operations_pb2.CancelOperationRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._transport.cancel_operation, - 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. - rpc(request, retry=retry, timeout=timeout, metadata=metadata,) - - def get_location( - self, - request: Optional[locations_pb2.GetLocationRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> locations_pb2.Location: - r"""Gets information about a location. - - Args: - request (:class:`~.location_pb2.GetLocationRequest`): - The request object. Request message for - `GetLocation` method. - 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: - ~.location_pb2.Location: - Location object. - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = locations_pb2.GetLocationRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._transport.get_location, - 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 = rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - def list_locations( - self, - request: Optional[locations_pb2.ListLocationsRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> locations_pb2.ListLocationsResponse: - r"""Lists information about the supported locations for this service. - - Args: - request (:class:`~.location_pb2.ListLocationsRequest`): - The request object. Request message for - `ListLocations` method. - 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: - ~.location_pb2.ListLocationsResponse: - Response message for ``ListLocations`` method. - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = locations_pb2.ListLocationsRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._transport.list_locations, - 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 = rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) - - -__all__ = ( - "ConversationModelsClient", -) diff --git a/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/conversation_models/pagers.py b/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/conversation_models/pagers.py deleted file mode 100644 index 48927a968..000000000 --- a/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/conversation_models/pagers.py +++ /dev/null @@ -1,260 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from typing import Any, AsyncIterator, Awaitable, Callable, Sequence, Tuple, Optional, Iterator - -from google.cloud.dialogflow_v2.types import conversation_model - - -class ListConversationModelsPager: - """A pager for iterating through ``list_conversation_models`` requests. - - This class thinly wraps an initial - :class:`google.cloud.dialogflow_v2.types.ListConversationModelsResponse` object, and - provides an ``__iter__`` method to iterate through its - ``conversation_models`` field. - - If there are more pages, the ``__iter__`` method will make additional - ``ListConversationModels`` requests and continue to iterate - through the ``conversation_models`` field on the - corresponding responses. - - All the usual :class:`google.cloud.dialogflow_v2.types.ListConversationModelsResponse` - 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[..., conversation_model.ListConversationModelsResponse], - request: conversation_model.ListConversationModelsRequest, - response: conversation_model.ListConversationModelsResponse, - *, - 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.ListConversationModelsRequest): - The initial request object. - response (google.cloud.dialogflow_v2.types.ListConversationModelsResponse): - 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 = conversation_model.ListConversationModelsRequest(request) - self._response = response - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - def pages(self) -> Iterator[conversation_model.ListConversationModelsResponse]: - yield self._response - while self._response.next_page_token: - self._request.page_token = self._response.next_page_token - self._response = self._method(self._request, metadata=self._metadata) - yield self._response - - def __iter__(self) -> Iterator[conversation_model.ConversationModel]: - for page in self.pages: - yield from page.conversation_models - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListConversationModelsAsyncPager: - """A pager for iterating through ``list_conversation_models`` requests. - - This class thinly wraps an initial - :class:`google.cloud.dialogflow_v2.types.ListConversationModelsResponse` object, and - provides an ``__aiter__`` method to iterate through its - ``conversation_models`` field. - - If there are more pages, the ``__aiter__`` method will make additional - ``ListConversationModels`` requests and continue to iterate - through the ``conversation_models`` field on the - corresponding responses. - - All the usual :class:`google.cloud.dialogflow_v2.types.ListConversationModelsResponse` - 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[conversation_model.ListConversationModelsResponse]], - request: conversation_model.ListConversationModelsRequest, - response: conversation_model.ListConversationModelsResponse, - *, - metadata: Sequence[Tuple[str, str]] = ()): - """Instantiates the pager. - - Args: - method (Callable): The method that was originally called, and - which instantiated this pager. - request (google.cloud.dialogflow_v2.types.ListConversationModelsRequest): - The initial request object. - response (google.cloud.dialogflow_v2.types.ListConversationModelsResponse): - 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 = conversation_model.ListConversationModelsRequest(request) - self._response = response - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - async def pages(self) -> AsyncIterator[conversation_model.ListConversationModelsResponse]: - yield self._response - while self._response.next_page_token: - self._request.page_token = self._response.next_page_token - self._response = await self._method(self._request, metadata=self._metadata) - yield self._response - def __aiter__(self) -> AsyncIterator[conversation_model.ConversationModel]: - async def async_generator(): - async for page in self.pages: - for response in page.conversation_models: - yield response - - return async_generator() - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListConversationModelEvaluationsPager: - """A pager for iterating through ``list_conversation_model_evaluations`` requests. - - This class thinly wraps an initial - :class:`google.cloud.dialogflow_v2.types.ListConversationModelEvaluationsResponse` object, and - provides an ``__iter__`` method to iterate through its - ``conversation_model_evaluations`` field. - - If there are more pages, the ``__iter__`` method will make additional - ``ListConversationModelEvaluations`` requests and continue to iterate - through the ``conversation_model_evaluations`` field on the - corresponding responses. - - All the usual :class:`google.cloud.dialogflow_v2.types.ListConversationModelEvaluationsResponse` - 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[..., conversation_model.ListConversationModelEvaluationsResponse], - request: conversation_model.ListConversationModelEvaluationsRequest, - response: conversation_model.ListConversationModelEvaluationsResponse, - *, - 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.ListConversationModelEvaluationsRequest): - The initial request object. - response (google.cloud.dialogflow_v2.types.ListConversationModelEvaluationsResponse): - 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 = conversation_model.ListConversationModelEvaluationsRequest(request) - self._response = response - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - def pages(self) -> Iterator[conversation_model.ListConversationModelEvaluationsResponse]: - yield self._response - while self._response.next_page_token: - self._request.page_token = self._response.next_page_token - self._response = self._method(self._request, metadata=self._metadata) - yield self._response - - def __iter__(self) -> Iterator[conversation_model.ConversationModelEvaluation]: - for page in self.pages: - yield from page.conversation_model_evaluations - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListConversationModelEvaluationsAsyncPager: - """A pager for iterating through ``list_conversation_model_evaluations`` requests. - - This class thinly wraps an initial - :class:`google.cloud.dialogflow_v2.types.ListConversationModelEvaluationsResponse` object, and - provides an ``__aiter__`` method to iterate through its - ``conversation_model_evaluations`` field. - - If there are more pages, the ``__aiter__`` method will make additional - ``ListConversationModelEvaluations`` requests and continue to iterate - through the ``conversation_model_evaluations`` field on the - corresponding responses. - - All the usual :class:`google.cloud.dialogflow_v2.types.ListConversationModelEvaluationsResponse` - 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[conversation_model.ListConversationModelEvaluationsResponse]], - request: conversation_model.ListConversationModelEvaluationsRequest, - response: conversation_model.ListConversationModelEvaluationsResponse, - *, - metadata: Sequence[Tuple[str, str]] = ()): - """Instantiates the pager. - - Args: - method (Callable): The method that was originally called, and - which instantiated this pager. - request (google.cloud.dialogflow_v2.types.ListConversationModelEvaluationsRequest): - The initial request object. - response (google.cloud.dialogflow_v2.types.ListConversationModelEvaluationsResponse): - 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 = conversation_model.ListConversationModelEvaluationsRequest(request) - self._response = response - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - async def pages(self) -> AsyncIterator[conversation_model.ListConversationModelEvaluationsResponse]: - yield self._response - while self._response.next_page_token: - self._request.page_token = self._response.next_page_token - self._response = await self._method(self._request, metadata=self._metadata) - yield self._response - def __aiter__(self) -> AsyncIterator[conversation_model.ConversationModelEvaluation]: - async def async_generator(): - async for page in self.pages: - for response in page.conversation_model_evaluations: - yield response - - return async_generator() - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) diff --git a/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/conversation_models/transports/__init__.py b/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/conversation_models/transports/__init__.py deleted file mode 100644 index 66cda5b72..000000000 --- a/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/conversation_models/transports/__init__.py +++ /dev/null @@ -1,38 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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 ConversationModelsTransport -from .grpc import ConversationModelsGrpcTransport -from .grpc_asyncio import ConversationModelsGrpcAsyncIOTransport -from .rest import ConversationModelsRestTransport -from .rest import ConversationModelsRestInterceptor - - -# Compile a registry of transports. -_transport_registry = OrderedDict() # type: Dict[str, Type[ConversationModelsTransport]] -_transport_registry['grpc'] = ConversationModelsGrpcTransport -_transport_registry['grpc_asyncio'] = ConversationModelsGrpcAsyncIOTransport -_transport_registry['rest'] = ConversationModelsRestTransport - -__all__ = ( - 'ConversationModelsTransport', - 'ConversationModelsGrpcTransport', - 'ConversationModelsGrpcAsyncIOTransport', - 'ConversationModelsRestTransport', - 'ConversationModelsRestInterceptor', -) diff --git a/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/conversation_models/transports/base.py b/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/conversation_models/transports/base.py deleted file mode 100644 index e2d44e86e..000000000 --- a/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/conversation_models/transports/base.py +++ /dev/null @@ -1,314 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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 - -from google.cloud.dialogflow_v2 import gapic_version as package_version - -import google.auth # type: ignore -import google.api_core -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import retry as retries -from google.api_core import operations_v1 -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 conversation_model -from google.cloud.dialogflow_v2.types import conversation_model as gcd_conversation_model -from google.cloud.location import locations_pb2 # type: ignore -from google.longrunning import operations_pb2 -from google.longrunning import operations_pb2 # type: ignore - -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) - - -class ConversationModelsTransport(abc.ABC): - """Abstract transport class for ConversationModels.""" - - 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: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - api_audience: Optional[str] = None, - **kwargs, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. - scopes (Optional[Sequence[str]]): A list of scopes. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - """ - - scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} - - # Save the scopes. - self._scopes = scopes - - # If no credentials are provided, then determine the appropriate - # defaults. - if credentials and credentials_file: - raise core_exceptions.DuplicateCredentialArgs("'credentials_file' and 'credentials' are mutually exclusive") - - if credentials_file is not None: - credentials, _ = google.auth.load_credentials_from_file( - credentials_file, - **scopes_kwargs, - quota_project_id=quota_project_id - ) - elif credentials is None: - credentials, _ = google.auth.default(**scopes_kwargs, quota_project_id=quota_project_id) - # Don't apply audience if the credentials file passed from user. - if hasattr(credentials, "with_gdch_audience"): - credentials = credentials.with_gdch_audience(api_audience if api_audience else host) - - # If the credentials are service account credentials, then always try to use self signed JWT. - if always_use_jwt_access and isinstance(credentials, service_account.Credentials) and hasattr(service_account.Credentials, "with_always_use_jwt_access"): - credentials = credentials.with_always_use_jwt_access(True) - - # Save the credentials. - self._credentials = credentials - - # Save the hostname. Default to port 443 (HTTPS) if none is specified. - if ':' not in host: - host += ':443' - self._host = host - - def _prep_wrapped_messages(self, client_info): - # Precompute the wrapped methods. - self._wrapped_methods = { - self.create_conversation_model: gapic_v1.method.wrap_method( - self.create_conversation_model, - default_timeout=None, - client_info=client_info, - ), - self.get_conversation_model: gapic_v1.method.wrap_method( - self.get_conversation_model, - default_timeout=None, - client_info=client_info, - ), - self.list_conversation_models: gapic_v1.method.wrap_method( - self.list_conversation_models, - default_timeout=None, - client_info=client_info, - ), - self.delete_conversation_model: gapic_v1.method.wrap_method( - self.delete_conversation_model, - default_timeout=None, - client_info=client_info, - ), - self.deploy_conversation_model: gapic_v1.method.wrap_method( - self.deploy_conversation_model, - default_timeout=None, - client_info=client_info, - ), - self.undeploy_conversation_model: gapic_v1.method.wrap_method( - self.undeploy_conversation_model, - default_timeout=None, - client_info=client_info, - ), - self.get_conversation_model_evaluation: gapic_v1.method.wrap_method( - self.get_conversation_model_evaluation, - default_timeout=None, - client_info=client_info, - ), - self.list_conversation_model_evaluations: gapic_v1.method.wrap_method( - self.list_conversation_model_evaluations, - default_timeout=None, - client_info=client_info, - ), - self.create_conversation_model_evaluation: gapic_v1.method.wrap_method( - self.create_conversation_model_evaluation, - default_timeout=None, - client_info=client_info, - ), - } - - def close(self): - """Closes resources associated with the transport. - - .. warning:: - Only call this method if the transport is NOT shared - with other clients - this may cause errors in other clients! - """ - raise NotImplementedError() - - @property - def operations_client(self): - """Return the client designed to process long-running operations.""" - raise NotImplementedError() - - @property - def create_conversation_model(self) -> Callable[ - [gcd_conversation_model.CreateConversationModelRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: - raise NotImplementedError() - - @property - def get_conversation_model(self) -> Callable[ - [conversation_model.GetConversationModelRequest], - Union[ - conversation_model.ConversationModel, - Awaitable[conversation_model.ConversationModel] - ]]: - raise NotImplementedError() - - @property - def list_conversation_models(self) -> Callable[ - [conversation_model.ListConversationModelsRequest], - Union[ - conversation_model.ListConversationModelsResponse, - Awaitable[conversation_model.ListConversationModelsResponse] - ]]: - raise NotImplementedError() - - @property - def delete_conversation_model(self) -> Callable[ - [conversation_model.DeleteConversationModelRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: - raise NotImplementedError() - - @property - def deploy_conversation_model(self) -> Callable[ - [conversation_model.DeployConversationModelRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: - raise NotImplementedError() - - @property - def undeploy_conversation_model(self) -> Callable[ - [conversation_model.UndeployConversationModelRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: - raise NotImplementedError() - - @property - def get_conversation_model_evaluation(self) -> Callable[ - [conversation_model.GetConversationModelEvaluationRequest], - Union[ - conversation_model.ConversationModelEvaluation, - Awaitable[conversation_model.ConversationModelEvaluation] - ]]: - raise NotImplementedError() - - @property - def list_conversation_model_evaluations(self) -> Callable[ - [conversation_model.ListConversationModelEvaluationsRequest], - Union[ - conversation_model.ListConversationModelEvaluationsResponse, - Awaitable[conversation_model.ListConversationModelEvaluationsResponse] - ]]: - raise NotImplementedError() - - @property - def create_conversation_model_evaluation(self) -> Callable[ - [conversation_model.CreateConversationModelEvaluationRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: - raise NotImplementedError() - - @property - def list_operations( - self, - ) -> Callable[ - [operations_pb2.ListOperationsRequest], - Union[operations_pb2.ListOperationsResponse, Awaitable[operations_pb2.ListOperationsResponse]], - ]: - raise NotImplementedError() - - @property - def get_operation( - self, - ) -> Callable[ - [operations_pb2.GetOperationRequest], - Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], - ]: - raise NotImplementedError() - - @property - def cancel_operation( - self, - ) -> Callable[ - [operations_pb2.CancelOperationRequest], - None, - ]: - raise NotImplementedError() - - @property - def get_location(self, - ) -> Callable[ - [locations_pb2.GetLocationRequest], - Union[locations_pb2.Location, Awaitable[locations_pb2.Location]], - ]: - raise NotImplementedError() - - @property - def list_locations(self, - ) -> Callable[ - [locations_pb2.ListLocationsRequest], - Union[locations_pb2.ListLocationsResponse, Awaitable[locations_pb2.ListLocationsResponse]], - ]: - raise NotImplementedError() - - @property - def kind(self) -> str: - raise NotImplementedError() - - -__all__ = ( - 'ConversationModelsTransport', -) diff --git a/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/conversation_models/transports/grpc.py b/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/conversation_models/transports/grpc.py deleted file mode 100644 index 591349f1f..000000000 --- a/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/conversation_models/transports/grpc.py +++ /dev/null @@ -1,634 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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 -from google.api_core import operations_v1 -from google.api_core import gapic_v1 -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_model -from google.cloud.dialogflow_v2.types import conversation_model as gcd_conversation_model -from google.cloud.location import locations_pb2 # type: ignore -from google.longrunning import operations_pb2 -from google.longrunning import operations_pb2 # type: ignore -from .base import ConversationModelsTransport, DEFAULT_CLIENT_INFO - - -class ConversationModelsGrpcTransport(ConversationModelsTransport): - """gRPC backend transport for ConversationModels. - - Manages a collection of models for human agent assistant. - - 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: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - channel: Optional[grpc.Channel] = None, - api_mtls_endpoint: Optional[str] = None, - client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, - ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, - client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - api_audience: Optional[str] = None, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - This argument is ignored if ``channel`` is provided. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional(Sequence[str])): A list of scopes. This argument is - ignored if ``channel`` is provided. - channel (Optional[grpc.Channel]): A ``Channel`` instance through - which to make calls. - api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. - If provided, it overrides the ``host`` argument and tries to create - a mutual TLS channel with client SSL credentials from - ``client_cert_source`` or application default SSL credentials. - client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): - Deprecated. A callback to provide client SSL certificate bytes and - private key bytes, both in PEM format. It is ignored if - ``api_mtls_endpoint`` is None. - ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials - for the grpc channel. It is ignored if ``channel`` is provided. - client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): - A callback to provide client certificate bytes and private key bytes, - both in PEM format. It is used to configure a mutual TLS channel. It is - ignored if ``channel`` or ``ssl_channel_credentials`` is provided. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport - creation failed for any reason. - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - self._grpc_channel = None - self._ssl_channel_credentials = ssl_channel_credentials - self._stubs: Dict[str, Callable] = {} - self._operations_client: Optional[operations_v1.OperationsClient] = None - - if api_mtls_endpoint: - warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) - if client_cert_source: - warnings.warn("client_cert_source is deprecated", DeprecationWarning) - - if channel: - # Ignore credentials if a channel was passed. - credentials = False - # If a channel was explicitly provided, set it. - self._grpc_channel = channel - self._ssl_channel_credentials = None - - else: - if api_mtls_endpoint: - host = api_mtls_endpoint - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - self._ssl_channel_credentials = SslCredentials().ssl_credentials - - else: - if client_cert_source_for_mtls and not ssl_channel_credentials: - cert, key = client_cert_source_for_mtls() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - - # The base transport sets the host, credentials and scopes - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes, - quota_project_id=quota_project_id, - client_info=client_info, - always_use_jwt_access=always_use_jwt_access, - api_audience=api_audience, - ) - - if not self._grpc_channel: - self._grpc_channel = type(self).create_channel( - self._host, - # use the credentials which are saved - credentials=self._credentials, - # Set ``credentials_file`` to ``None`` here as - # the credentials that we saved earlier should be used. - credentials_file=None, - 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: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - **kwargs) -> grpc.Channel: - """Create and return a gRPC channel object. - Args: - host (Optional[str]): The host for the channel to use. - credentials (Optional[~.Credentials]): The - authorization credentials to attach to requests. These - credentials identify this application to the service. If - none are specified, the client will attempt to ascertain - the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - kwargs (Optional[dict]): Keyword arguments, which are passed to the - channel creation. - Returns: - grpc.Channel: A gRPC channel object. - - Raises: - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - - return grpc_helpers.create_channel( - host, - credentials=credentials, - credentials_file=credentials_file, - quota_project_id=quota_project_id, - default_scopes=cls.AUTH_SCOPES, - scopes=scopes, - default_host=cls.DEFAULT_HOST, - **kwargs - ) - - @property - def grpc_channel(self) -> grpc.Channel: - """Return the channel designed to connect to this service. - """ - return self._grpc_channel - - @property - def operations_client(self) -> operations_v1.OperationsClient: - """Create the client designed to process long-running operations. - - This property caches on the instance; repeated calls return the same - client. - """ - # Quick check: Only create a new client if we do not already have one. - if self._operations_client is None: - self._operations_client = operations_v1.OperationsClient( - self.grpc_channel - ) - - # Return the client from cache. - return self._operations_client - - @property - def create_conversation_model(self) -> Callable[ - [gcd_conversation_model.CreateConversationModelRequest], - operations_pb2.Operation]: - r"""Return a callable for the create conversation model method over gRPC. - - Creates a model. - - This method is a `long-running - operation `__. - The returned ``Operation`` type has the following - method-specific fields: - - - ``metadata``: - [CreateConversationModelOperationMetadata][google.cloud.dialogflow.v2.CreateConversationModelOperationMetadata] - - ``response``: - [ConversationModel][google.cloud.dialogflow.v2.ConversationModel] - - Returns: - Callable[[~.CreateConversationModelRequest], - ~.Operation]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'create_conversation_model' not in self._stubs: - self._stubs['create_conversation_model'] = self.grpc_channel.unary_unary( - '/google.cloud.dialogflow.v2.ConversationModels/CreateConversationModel', - request_serializer=gcd_conversation_model.CreateConversationModelRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['create_conversation_model'] - - @property - def get_conversation_model(self) -> Callable[ - [conversation_model.GetConversationModelRequest], - conversation_model.ConversationModel]: - r"""Return a callable for the get conversation model method over gRPC. - - Gets conversation model. - - Returns: - Callable[[~.GetConversationModelRequest], - ~.ConversationModel]: - 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_conversation_model' not in self._stubs: - self._stubs['get_conversation_model'] = self.grpc_channel.unary_unary( - '/google.cloud.dialogflow.v2.ConversationModels/GetConversationModel', - request_serializer=conversation_model.GetConversationModelRequest.serialize, - response_deserializer=conversation_model.ConversationModel.deserialize, - ) - return self._stubs['get_conversation_model'] - - @property - def list_conversation_models(self) -> Callable[ - [conversation_model.ListConversationModelsRequest], - conversation_model.ListConversationModelsResponse]: - r"""Return a callable for the list conversation models method over gRPC. - - Lists conversation models. - - Returns: - Callable[[~.ListConversationModelsRequest], - ~.ListConversationModelsResponse]: - 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_conversation_models' not in self._stubs: - self._stubs['list_conversation_models'] = self.grpc_channel.unary_unary( - '/google.cloud.dialogflow.v2.ConversationModels/ListConversationModels', - request_serializer=conversation_model.ListConversationModelsRequest.serialize, - response_deserializer=conversation_model.ListConversationModelsResponse.deserialize, - ) - return self._stubs['list_conversation_models'] - - @property - def delete_conversation_model(self) -> Callable[ - [conversation_model.DeleteConversationModelRequest], - operations_pb2.Operation]: - r"""Return a callable for the delete conversation model method over gRPC. - - Deletes a model. - - This method is a `long-running - operation `__. - The returned ``Operation`` type has the following - method-specific fields: - - - ``metadata``: - [DeleteConversationModelOperationMetadata][google.cloud.dialogflow.v2.DeleteConversationModelOperationMetadata] - - ``response``: An `Empty - message `__ - - Returns: - Callable[[~.DeleteConversationModelRequest], - ~.Operation]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'delete_conversation_model' not in self._stubs: - self._stubs['delete_conversation_model'] = self.grpc_channel.unary_unary( - '/google.cloud.dialogflow.v2.ConversationModels/DeleteConversationModel', - request_serializer=conversation_model.DeleteConversationModelRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['delete_conversation_model'] - - @property - def deploy_conversation_model(self) -> Callable[ - [conversation_model.DeployConversationModelRequest], - operations_pb2.Operation]: - r"""Return a callable for the deploy conversation model method over gRPC. - - Deploys a model. If a model is already deployed, deploying it - has no effect. A model can only serve prediction requests after - it gets deployed. For article suggestion, custom model will not - be used unless it is deployed. - - This method is a `long-running - operation `__. - The returned ``Operation`` type has the following - method-specific fields: - - - ``metadata``: - [DeployConversationModelOperationMetadata][google.cloud.dialogflow.v2.DeployConversationModelOperationMetadata] - - ``response``: An `Empty - message `__ - - Returns: - Callable[[~.DeployConversationModelRequest], - ~.Operation]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'deploy_conversation_model' not in self._stubs: - self._stubs['deploy_conversation_model'] = self.grpc_channel.unary_unary( - '/google.cloud.dialogflow.v2.ConversationModels/DeployConversationModel', - request_serializer=conversation_model.DeployConversationModelRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['deploy_conversation_model'] - - @property - def undeploy_conversation_model(self) -> Callable[ - [conversation_model.UndeployConversationModelRequest], - operations_pb2.Operation]: - r"""Return a callable for the undeploy conversation model method over gRPC. - - Undeploys a model. If the model is not deployed this method has - no effect. If the model is currently being used: - - - For article suggestion, article suggestion will fallback to - the default model if model is undeployed. - - This method is a `long-running - operation `__. - The returned ``Operation`` type has the following - method-specific fields: - - - ``metadata``: - [UndeployConversationModelOperationMetadata][google.cloud.dialogflow.v2.UndeployConversationModelOperationMetadata] - - ``response``: An `Empty - message `__ - - Returns: - Callable[[~.UndeployConversationModelRequest], - ~.Operation]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'undeploy_conversation_model' not in self._stubs: - self._stubs['undeploy_conversation_model'] = self.grpc_channel.unary_unary( - '/google.cloud.dialogflow.v2.ConversationModels/UndeployConversationModel', - request_serializer=conversation_model.UndeployConversationModelRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['undeploy_conversation_model'] - - @property - def get_conversation_model_evaluation(self) -> Callable[ - [conversation_model.GetConversationModelEvaluationRequest], - conversation_model.ConversationModelEvaluation]: - r"""Return a callable for the get conversation model - evaluation method over gRPC. - - Gets an evaluation of conversation model. - - Returns: - Callable[[~.GetConversationModelEvaluationRequest], - ~.ConversationModelEvaluation]: - 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_conversation_model_evaluation' not in self._stubs: - self._stubs['get_conversation_model_evaluation'] = self.grpc_channel.unary_unary( - '/google.cloud.dialogflow.v2.ConversationModels/GetConversationModelEvaluation', - request_serializer=conversation_model.GetConversationModelEvaluationRequest.serialize, - response_deserializer=conversation_model.ConversationModelEvaluation.deserialize, - ) - return self._stubs['get_conversation_model_evaluation'] - - @property - def list_conversation_model_evaluations(self) -> Callable[ - [conversation_model.ListConversationModelEvaluationsRequest], - conversation_model.ListConversationModelEvaluationsResponse]: - r"""Return a callable for the list conversation model - evaluations method over gRPC. - - Lists evaluations of a conversation model. - - Returns: - Callable[[~.ListConversationModelEvaluationsRequest], - ~.ListConversationModelEvaluationsResponse]: - 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_conversation_model_evaluations' not in self._stubs: - self._stubs['list_conversation_model_evaluations'] = self.grpc_channel.unary_unary( - '/google.cloud.dialogflow.v2.ConversationModels/ListConversationModelEvaluations', - request_serializer=conversation_model.ListConversationModelEvaluationsRequest.serialize, - response_deserializer=conversation_model.ListConversationModelEvaluationsResponse.deserialize, - ) - return self._stubs['list_conversation_model_evaluations'] - - @property - def create_conversation_model_evaluation(self) -> Callable[ - [conversation_model.CreateConversationModelEvaluationRequest], - operations_pb2.Operation]: - r"""Return a callable for the create conversation model - evaluation method over gRPC. - - Creates evaluation of a conversation model. - - Returns: - Callable[[~.CreateConversationModelEvaluationRequest], - ~.Operation]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'create_conversation_model_evaluation' not in self._stubs: - self._stubs['create_conversation_model_evaluation'] = self.grpc_channel.unary_unary( - '/google.cloud.dialogflow.v2.ConversationModels/CreateConversationModelEvaluation', - request_serializer=conversation_model.CreateConversationModelEvaluationRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['create_conversation_model_evaluation'] - - def close(self): - self.grpc_channel.close() - - @property - def cancel_operation( - self, - ) -> Callable[[operations_pb2.CancelOperationRequest], None]: - r"""Return a callable for the cancel_operation method over gRPC. - """ - # 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 "cancel_operation" not in self._stubs: - self._stubs["cancel_operation"] = self.grpc_channel.unary_unary( - "/google.longrunning.Operations/CancelOperation", - request_serializer=operations_pb2.CancelOperationRequest.SerializeToString, - response_deserializer=None, - ) - return self._stubs["cancel_operation"] - - @property - def get_operation( - self, - ) -> Callable[[operations_pb2.GetOperationRequest], operations_pb2.Operation]: - r"""Return a callable for the get_operation method over gRPC. - """ - # 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_operation" not in self._stubs: - self._stubs["get_operation"] = self.grpc_channel.unary_unary( - "/google.longrunning.Operations/GetOperation", - request_serializer=operations_pb2.GetOperationRequest.SerializeToString, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs["get_operation"] - - @property - def list_operations( - self, - ) -> Callable[[operations_pb2.ListOperationsRequest], operations_pb2.ListOperationsResponse]: - r"""Return a callable for the list_operations method over gRPC. - """ - # 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_operations" not in self._stubs: - self._stubs["list_operations"] = self.grpc_channel.unary_unary( - "/google.longrunning.Operations/ListOperations", - request_serializer=operations_pb2.ListOperationsRequest.SerializeToString, - response_deserializer=operations_pb2.ListOperationsResponse.FromString, - ) - return self._stubs["list_operations"] - - @property - def list_locations( - self, - ) -> Callable[[locations_pb2.ListLocationsRequest], locations_pb2.ListLocationsResponse]: - r"""Return a callable for the list locations method over gRPC. - """ - # 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_locations" not in self._stubs: - self._stubs["list_locations"] = self.grpc_channel.unary_unary( - "/google.cloud.location.Locations/ListLocations", - request_serializer=locations_pb2.ListLocationsRequest.SerializeToString, - response_deserializer=locations_pb2.ListLocationsResponse.FromString, - ) - return self._stubs["list_locations"] - - @property - def get_location( - self, - ) -> Callable[[locations_pb2.GetLocationRequest], locations_pb2.Location]: - r"""Return a callable for the list locations method over gRPC. - """ - # 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_location" not in self._stubs: - self._stubs["get_location"] = self.grpc_channel.unary_unary( - "/google.cloud.location.Locations/GetLocation", - request_serializer=locations_pb2.GetLocationRequest.SerializeToString, - response_deserializer=locations_pb2.Location.FromString, - ) - return self._stubs["get_location"] - - @property - def kind(self) -> str: - return "grpc" - - -__all__ = ( - 'ConversationModelsGrpcTransport', -) diff --git a/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/conversation_models/transports/grpc_asyncio.py b/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/conversation_models/transports/grpc_asyncio.py deleted file mode 100644 index 058d71d95..000000000 --- a/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/conversation_models/transports/grpc_asyncio.py +++ /dev/null @@ -1,633 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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 -from google.api_core import grpc_helpers_async -from google.api_core import operations_v1 -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore - -import grpc # type: ignore -from grpc.experimental import aio # type: ignore - -from google.cloud.dialogflow_v2.types import conversation_model -from google.cloud.dialogflow_v2.types import conversation_model as gcd_conversation_model -from google.cloud.location import locations_pb2 # type: ignore -from google.longrunning import operations_pb2 -from google.longrunning import operations_pb2 # type: ignore -from .base import ConversationModelsTransport, DEFAULT_CLIENT_INFO -from .grpc import ConversationModelsGrpcTransport - - -class ConversationModelsGrpcAsyncIOTransport(ConversationModelsTransport): - """gRPC AsyncIO backend transport for ConversationModels. - - Manages a collection of models for human agent assistant. - - 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: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - **kwargs) -> aio.Channel: - """Create and return a gRPC AsyncIO channel object. - Args: - host (Optional[str]): The host for the channel to use. - credentials (Optional[~.Credentials]): The - authorization credentials to attach to requests. These - credentials identify this application to the service. If - none are specified, the client will attempt to ascertain - the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - kwargs (Optional[dict]): Keyword arguments, which are passed to the - channel creation. - Returns: - aio.Channel: A gRPC AsyncIO channel object. - """ - - return grpc_helpers_async.create_channel( - host, - credentials=credentials, - credentials_file=credentials_file, - quota_project_id=quota_project_id, - default_scopes=cls.AUTH_SCOPES, - scopes=scopes, - default_host=cls.DEFAULT_HOST, - **kwargs - ) - - def __init__(self, *, - host: str = 'dialogflow.googleapis.com', - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - channel: Optional[aio.Channel] = None, - api_mtls_endpoint: Optional[str] = None, - client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, - ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, - client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - api_audience: Optional[str] = None, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - This argument is ignored if ``channel`` is provided. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - channel (Optional[aio.Channel]): A ``Channel`` instance through - which to make calls. - api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. - If provided, it overrides the ``host`` argument and tries to create - a mutual TLS channel with client SSL credentials from - ``client_cert_source`` or application default SSL credentials. - client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): - Deprecated. A callback to provide client SSL certificate bytes and - private key bytes, both in PEM format. It is ignored if - ``api_mtls_endpoint`` is None. - ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials - for the grpc channel. It is ignored if ``channel`` is provided. - client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): - A callback to provide client certificate bytes and private key bytes, - both in PEM format. It is used to configure a mutual TLS channel. It is - ignored if ``channel`` or ``ssl_channel_credentials`` is provided. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - - Raises: - google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport - creation failed for any reason. - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - self._grpc_channel = None - self._ssl_channel_credentials = ssl_channel_credentials - self._stubs: Dict[str, Callable] = {} - self._operations_client: Optional[operations_v1.OperationsAsyncClient] = None - - if api_mtls_endpoint: - warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) - if client_cert_source: - warnings.warn("client_cert_source is deprecated", DeprecationWarning) - - if channel: - # Ignore credentials if a channel was passed. - credentials = False - # If a channel was explicitly provided, set it. - self._grpc_channel = channel - self._ssl_channel_credentials = None - else: - if api_mtls_endpoint: - host = api_mtls_endpoint - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - self._ssl_channel_credentials = SslCredentials().ssl_credentials - - else: - if client_cert_source_for_mtls and not ssl_channel_credentials: - cert, key = client_cert_source_for_mtls() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - - # The base transport sets the host, credentials and scopes - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes, - quota_project_id=quota_project_id, - client_info=client_info, - always_use_jwt_access=always_use_jwt_access, - api_audience=api_audience, - ) - - if not self._grpc_channel: - self._grpc_channel = type(self).create_channel( - self._host, - # use the credentials which are saved - credentials=self._credentials, - # Set ``credentials_file`` to ``None`` here as - # the credentials that we saved earlier should be used. - credentials_file=None, - 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 operations_client(self) -> operations_v1.OperationsAsyncClient: - """Create the client designed to process long-running operations. - - This property caches on the instance; repeated calls return the same - client. - """ - # Quick check: Only create a new client if we do not already have one. - if self._operations_client is None: - self._operations_client = operations_v1.OperationsAsyncClient( - self.grpc_channel - ) - - # Return the client from cache. - return self._operations_client - - @property - def create_conversation_model(self) -> Callable[ - [gcd_conversation_model.CreateConversationModelRequest], - Awaitable[operations_pb2.Operation]]: - r"""Return a callable for the create conversation model method over gRPC. - - Creates a model. - - This method is a `long-running - operation `__. - The returned ``Operation`` type has the following - method-specific fields: - - - ``metadata``: - [CreateConversationModelOperationMetadata][google.cloud.dialogflow.v2.CreateConversationModelOperationMetadata] - - ``response``: - [ConversationModel][google.cloud.dialogflow.v2.ConversationModel] - - Returns: - Callable[[~.CreateConversationModelRequest], - Awaitable[~.Operation]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'create_conversation_model' not in self._stubs: - self._stubs['create_conversation_model'] = self.grpc_channel.unary_unary( - '/google.cloud.dialogflow.v2.ConversationModels/CreateConversationModel', - request_serializer=gcd_conversation_model.CreateConversationModelRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['create_conversation_model'] - - @property - def get_conversation_model(self) -> Callable[ - [conversation_model.GetConversationModelRequest], - Awaitable[conversation_model.ConversationModel]]: - r"""Return a callable for the get conversation model method over gRPC. - - Gets conversation model. - - Returns: - Callable[[~.GetConversationModelRequest], - Awaitable[~.ConversationModel]]: - 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_conversation_model' not in self._stubs: - self._stubs['get_conversation_model'] = self.grpc_channel.unary_unary( - '/google.cloud.dialogflow.v2.ConversationModels/GetConversationModel', - request_serializer=conversation_model.GetConversationModelRequest.serialize, - response_deserializer=conversation_model.ConversationModel.deserialize, - ) - return self._stubs['get_conversation_model'] - - @property - def list_conversation_models(self) -> Callable[ - [conversation_model.ListConversationModelsRequest], - Awaitable[conversation_model.ListConversationModelsResponse]]: - r"""Return a callable for the list conversation models method over gRPC. - - Lists conversation models. - - Returns: - Callable[[~.ListConversationModelsRequest], - Awaitable[~.ListConversationModelsResponse]]: - 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_conversation_models' not in self._stubs: - self._stubs['list_conversation_models'] = self.grpc_channel.unary_unary( - '/google.cloud.dialogflow.v2.ConversationModels/ListConversationModels', - request_serializer=conversation_model.ListConversationModelsRequest.serialize, - response_deserializer=conversation_model.ListConversationModelsResponse.deserialize, - ) - return self._stubs['list_conversation_models'] - - @property - def delete_conversation_model(self) -> Callable[ - [conversation_model.DeleteConversationModelRequest], - Awaitable[operations_pb2.Operation]]: - r"""Return a callable for the delete conversation model method over gRPC. - - Deletes a model. - - This method is a `long-running - operation `__. - The returned ``Operation`` type has the following - method-specific fields: - - - ``metadata``: - [DeleteConversationModelOperationMetadata][google.cloud.dialogflow.v2.DeleteConversationModelOperationMetadata] - - ``response``: An `Empty - message `__ - - Returns: - Callable[[~.DeleteConversationModelRequest], - Awaitable[~.Operation]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'delete_conversation_model' not in self._stubs: - self._stubs['delete_conversation_model'] = self.grpc_channel.unary_unary( - '/google.cloud.dialogflow.v2.ConversationModels/DeleteConversationModel', - request_serializer=conversation_model.DeleteConversationModelRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['delete_conversation_model'] - - @property - def deploy_conversation_model(self) -> Callable[ - [conversation_model.DeployConversationModelRequest], - Awaitable[operations_pb2.Operation]]: - r"""Return a callable for the deploy conversation model method over gRPC. - - Deploys a model. If a model is already deployed, deploying it - has no effect. A model can only serve prediction requests after - it gets deployed. For article suggestion, custom model will not - be used unless it is deployed. - - This method is a `long-running - operation `__. - The returned ``Operation`` type has the following - method-specific fields: - - - ``metadata``: - [DeployConversationModelOperationMetadata][google.cloud.dialogflow.v2.DeployConversationModelOperationMetadata] - - ``response``: An `Empty - message `__ - - Returns: - Callable[[~.DeployConversationModelRequest], - Awaitable[~.Operation]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'deploy_conversation_model' not in self._stubs: - self._stubs['deploy_conversation_model'] = self.grpc_channel.unary_unary( - '/google.cloud.dialogflow.v2.ConversationModels/DeployConversationModel', - request_serializer=conversation_model.DeployConversationModelRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['deploy_conversation_model'] - - @property - def undeploy_conversation_model(self) -> Callable[ - [conversation_model.UndeployConversationModelRequest], - Awaitable[operations_pb2.Operation]]: - r"""Return a callable for the undeploy conversation model method over gRPC. - - Undeploys a model. If the model is not deployed this method has - no effect. If the model is currently being used: - - - For article suggestion, article suggestion will fallback to - the default model if model is undeployed. - - This method is a `long-running - operation `__. - The returned ``Operation`` type has the following - method-specific fields: - - - ``metadata``: - [UndeployConversationModelOperationMetadata][google.cloud.dialogflow.v2.UndeployConversationModelOperationMetadata] - - ``response``: An `Empty - message `__ - - Returns: - Callable[[~.UndeployConversationModelRequest], - Awaitable[~.Operation]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'undeploy_conversation_model' not in self._stubs: - self._stubs['undeploy_conversation_model'] = self.grpc_channel.unary_unary( - '/google.cloud.dialogflow.v2.ConversationModels/UndeployConversationModel', - request_serializer=conversation_model.UndeployConversationModelRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['undeploy_conversation_model'] - - @property - def get_conversation_model_evaluation(self) -> Callable[ - [conversation_model.GetConversationModelEvaluationRequest], - Awaitable[conversation_model.ConversationModelEvaluation]]: - r"""Return a callable for the get conversation model - evaluation method over gRPC. - - Gets an evaluation of conversation model. - - Returns: - Callable[[~.GetConversationModelEvaluationRequest], - Awaitable[~.ConversationModelEvaluation]]: - 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_conversation_model_evaluation' not in self._stubs: - self._stubs['get_conversation_model_evaluation'] = self.grpc_channel.unary_unary( - '/google.cloud.dialogflow.v2.ConversationModels/GetConversationModelEvaluation', - request_serializer=conversation_model.GetConversationModelEvaluationRequest.serialize, - response_deserializer=conversation_model.ConversationModelEvaluation.deserialize, - ) - return self._stubs['get_conversation_model_evaluation'] - - @property - def list_conversation_model_evaluations(self) -> Callable[ - [conversation_model.ListConversationModelEvaluationsRequest], - Awaitable[conversation_model.ListConversationModelEvaluationsResponse]]: - r"""Return a callable for the list conversation model - evaluations method over gRPC. - - Lists evaluations of a conversation model. - - Returns: - Callable[[~.ListConversationModelEvaluationsRequest], - Awaitable[~.ListConversationModelEvaluationsResponse]]: - 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_conversation_model_evaluations' not in self._stubs: - self._stubs['list_conversation_model_evaluations'] = self.grpc_channel.unary_unary( - '/google.cloud.dialogflow.v2.ConversationModels/ListConversationModelEvaluations', - request_serializer=conversation_model.ListConversationModelEvaluationsRequest.serialize, - response_deserializer=conversation_model.ListConversationModelEvaluationsResponse.deserialize, - ) - return self._stubs['list_conversation_model_evaluations'] - - @property - def create_conversation_model_evaluation(self) -> Callable[ - [conversation_model.CreateConversationModelEvaluationRequest], - Awaitable[operations_pb2.Operation]]: - r"""Return a callable for the create conversation model - evaluation method over gRPC. - - Creates evaluation of a conversation model. - - Returns: - Callable[[~.CreateConversationModelEvaluationRequest], - Awaitable[~.Operation]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'create_conversation_model_evaluation' not in self._stubs: - self._stubs['create_conversation_model_evaluation'] = self.grpc_channel.unary_unary( - '/google.cloud.dialogflow.v2.ConversationModels/CreateConversationModelEvaluation', - request_serializer=conversation_model.CreateConversationModelEvaluationRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['create_conversation_model_evaluation'] - - def close(self): - return self.grpc_channel.close() - - @property - def cancel_operation( - self, - ) -> Callable[[operations_pb2.CancelOperationRequest], None]: - r"""Return a callable for the cancel_operation method over gRPC. - """ - # 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 "cancel_operation" not in self._stubs: - self._stubs["cancel_operation"] = self.grpc_channel.unary_unary( - "/google.longrunning.Operations/CancelOperation", - request_serializer=operations_pb2.CancelOperationRequest.SerializeToString, - response_deserializer=None, - ) - return self._stubs["cancel_operation"] - - @property - def get_operation( - self, - ) -> Callable[[operations_pb2.GetOperationRequest], operations_pb2.Operation]: - r"""Return a callable for the get_operation method over gRPC. - """ - # 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_operation" not in self._stubs: - self._stubs["get_operation"] = self.grpc_channel.unary_unary( - "/google.longrunning.Operations/GetOperation", - request_serializer=operations_pb2.GetOperationRequest.SerializeToString, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs["get_operation"] - - @property - def list_operations( - self, - ) -> Callable[[operations_pb2.ListOperationsRequest], operations_pb2.ListOperationsResponse]: - r"""Return a callable for the list_operations method over gRPC. - """ - # 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_operations" not in self._stubs: - self._stubs["list_operations"] = self.grpc_channel.unary_unary( - "/google.longrunning.Operations/ListOperations", - request_serializer=operations_pb2.ListOperationsRequest.SerializeToString, - response_deserializer=operations_pb2.ListOperationsResponse.FromString, - ) - return self._stubs["list_operations"] - - @property - def list_locations( - self, - ) -> Callable[[locations_pb2.ListLocationsRequest], locations_pb2.ListLocationsResponse]: - r"""Return a callable for the list locations method over gRPC. - """ - # 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_locations" not in self._stubs: - self._stubs["list_locations"] = self.grpc_channel.unary_unary( - "/google.cloud.location.Locations/ListLocations", - request_serializer=locations_pb2.ListLocationsRequest.SerializeToString, - response_deserializer=locations_pb2.ListLocationsResponse.FromString, - ) - return self._stubs["list_locations"] - - @property - def get_location( - self, - ) -> Callable[[locations_pb2.GetLocationRequest], locations_pb2.Location]: - r"""Return a callable for the list locations method over gRPC. - """ - # 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_location" not in self._stubs: - self._stubs["get_location"] = self.grpc_channel.unary_unary( - "/google.cloud.location.Locations/GetLocation", - request_serializer=locations_pb2.GetLocationRequest.SerializeToString, - response_deserializer=locations_pb2.Location.FromString, - ) - return self._stubs["get_location"] - - -__all__ = ( - 'ConversationModelsGrpcAsyncIOTransport', -) diff --git a/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/conversation_models/transports/rest.py b/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/conversation_models/transports/rest.py deleted file mode 100644 index 8a0d35869..000000000 --- a/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/conversation_models/transports/rest.py +++ /dev/null @@ -1,1756 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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 google.auth.transport.requests import AuthorizedSession # type: ignore -import json # type: ignore -import grpc # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore -from google.auth import credentials as ga_credentials # type: ignore -from google.api_core import exceptions as core_exceptions -from google.api_core import retry as retries -from google.api_core import rest_helpers -from google.api_core import rest_streaming -from google.api_core import path_template -from google.api_core import gapic_v1 - -from google.protobuf import json_format -from google.api_core import operations_v1 -from google.cloud.location import locations_pb2 # type: ignore -from google.longrunning import operations_pb2 -from requests import __version__ as requests_version -import dataclasses -import re -from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union -import warnings - -try: - OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] -except AttributeError: # pragma: NO COVER - OptionalRetry = Union[retries.Retry, object] # type: ignore - - -from google.cloud.dialogflow_v2.types import conversation_model -from google.cloud.dialogflow_v2.types import conversation_model as gcd_conversation_model -from google.longrunning import operations_pb2 # type: ignore - -from .base import ConversationModelsTransport, DEFAULT_CLIENT_INFO as BASE_DEFAULT_CLIENT_INFO - - -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=BASE_DEFAULT_CLIENT_INFO.gapic_version, - grpc_version=None, - rest_version=requests_version, -) - - -class ConversationModelsRestInterceptor: - """Interceptor for ConversationModels. - - Interceptors are used to manipulate requests, request metadata, and responses - in arbitrary ways. - Example use cases include: - * Logging - * Verifying requests according to service or custom semantics - * Stripping extraneous information from responses - - These use cases and more can be enabled by injecting an - instance of a custom subclass when constructing the ConversationModelsRestTransport. - - .. code-block:: python - class MyCustomConversationModelsInterceptor(ConversationModelsRestInterceptor): - def pre_create_conversation_model(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_create_conversation_model(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_create_conversation_model_evaluation(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_create_conversation_model_evaluation(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_delete_conversation_model(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_delete_conversation_model(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_deploy_conversation_model(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_deploy_conversation_model(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_get_conversation_model(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_get_conversation_model(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_get_conversation_model_evaluation(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_get_conversation_model_evaluation(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_list_conversation_model_evaluations(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_list_conversation_model_evaluations(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_list_conversation_models(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_list_conversation_models(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_undeploy_conversation_model(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_undeploy_conversation_model(self, response): - logging.log(f"Received response: {response}") - return response - - transport = ConversationModelsRestTransport(interceptor=MyCustomConversationModelsInterceptor()) - client = ConversationModelsClient(transport=transport) - - - """ - def pre_create_conversation_model(self, request: gcd_conversation_model.CreateConversationModelRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[gcd_conversation_model.CreateConversationModelRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for create_conversation_model - - Override in a subclass to manipulate the request or metadata - before they are sent to the ConversationModels server. - """ - return request, metadata - - def post_create_conversation_model(self, response: operations_pb2.Operation) -> operations_pb2.Operation: - """Post-rpc interceptor for create_conversation_model - - Override in a subclass to manipulate the response - after it is returned by the ConversationModels server but before - it is returned to user code. - """ - return response - def pre_create_conversation_model_evaluation(self, request: conversation_model.CreateConversationModelEvaluationRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[conversation_model.CreateConversationModelEvaluationRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for create_conversation_model_evaluation - - Override in a subclass to manipulate the request or metadata - before they are sent to the ConversationModels server. - """ - return request, metadata - - def post_create_conversation_model_evaluation(self, response: operations_pb2.Operation) -> operations_pb2.Operation: - """Post-rpc interceptor for create_conversation_model_evaluation - - Override in a subclass to manipulate the response - after it is returned by the ConversationModels server but before - it is returned to user code. - """ - return response - def pre_delete_conversation_model(self, request: conversation_model.DeleteConversationModelRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[conversation_model.DeleteConversationModelRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for delete_conversation_model - - Override in a subclass to manipulate the request or metadata - before they are sent to the ConversationModels server. - """ - return request, metadata - - def post_delete_conversation_model(self, response: operations_pb2.Operation) -> operations_pb2.Operation: - """Post-rpc interceptor for delete_conversation_model - - Override in a subclass to manipulate the response - after it is returned by the ConversationModels server but before - it is returned to user code. - """ - return response - def pre_deploy_conversation_model(self, request: conversation_model.DeployConversationModelRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[conversation_model.DeployConversationModelRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for deploy_conversation_model - - Override in a subclass to manipulate the request or metadata - before they are sent to the ConversationModels server. - """ - return request, metadata - - def post_deploy_conversation_model(self, response: operations_pb2.Operation) -> operations_pb2.Operation: - """Post-rpc interceptor for deploy_conversation_model - - Override in a subclass to manipulate the response - after it is returned by the ConversationModels server but before - it is returned to user code. - """ - return response - def pre_get_conversation_model(self, request: conversation_model.GetConversationModelRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[conversation_model.GetConversationModelRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for get_conversation_model - - Override in a subclass to manipulate the request or metadata - before they are sent to the ConversationModels server. - """ - return request, metadata - - def post_get_conversation_model(self, response: conversation_model.ConversationModel) -> conversation_model.ConversationModel: - """Post-rpc interceptor for get_conversation_model - - Override in a subclass to manipulate the response - after it is returned by the ConversationModels server but before - it is returned to user code. - """ - return response - def pre_get_conversation_model_evaluation(self, request: conversation_model.GetConversationModelEvaluationRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[conversation_model.GetConversationModelEvaluationRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for get_conversation_model_evaluation - - Override in a subclass to manipulate the request or metadata - before they are sent to the ConversationModels server. - """ - return request, metadata - - def post_get_conversation_model_evaluation(self, response: conversation_model.ConversationModelEvaluation) -> conversation_model.ConversationModelEvaluation: - """Post-rpc interceptor for get_conversation_model_evaluation - - Override in a subclass to manipulate the response - after it is returned by the ConversationModels server but before - it is returned to user code. - """ - return response - def pre_list_conversation_model_evaluations(self, request: conversation_model.ListConversationModelEvaluationsRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[conversation_model.ListConversationModelEvaluationsRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for list_conversation_model_evaluations - - Override in a subclass to manipulate the request or metadata - before they are sent to the ConversationModels server. - """ - return request, metadata - - def post_list_conversation_model_evaluations(self, response: conversation_model.ListConversationModelEvaluationsResponse) -> conversation_model.ListConversationModelEvaluationsResponse: - """Post-rpc interceptor for list_conversation_model_evaluations - - Override in a subclass to manipulate the response - after it is returned by the ConversationModels server but before - it is returned to user code. - """ - return response - def pre_list_conversation_models(self, request: conversation_model.ListConversationModelsRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[conversation_model.ListConversationModelsRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for list_conversation_models - - Override in a subclass to manipulate the request or metadata - before they are sent to the ConversationModels server. - """ - return request, metadata - - def post_list_conversation_models(self, response: conversation_model.ListConversationModelsResponse) -> conversation_model.ListConversationModelsResponse: - """Post-rpc interceptor for list_conversation_models - - Override in a subclass to manipulate the response - after it is returned by the ConversationModels server but before - it is returned to user code. - """ - return response - def pre_undeploy_conversation_model(self, request: conversation_model.UndeployConversationModelRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[conversation_model.UndeployConversationModelRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for undeploy_conversation_model - - Override in a subclass to manipulate the request or metadata - before they are sent to the ConversationModels server. - """ - return request, metadata - - def post_undeploy_conversation_model(self, response: operations_pb2.Operation) -> operations_pb2.Operation: - """Post-rpc interceptor for undeploy_conversation_model - - Override in a subclass to manipulate the response - after it is returned by the ConversationModels server but before - it is returned to user code. - """ - return response - - def pre_get_location( - self, request: locations_pb2.GetLocationRequest, metadata: Sequence[Tuple[str, str]] - ) -> Tuple[locations_pb2.GetLocationRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for get_location - - Override in a subclass to manipulate the request or metadata - before they are sent to the ConversationModels server. - """ - return request, metadata - - def post_get_location( - self, response: locations_pb2.Location - ) -> locations_pb2.Location: - """Post-rpc interceptor for get_location - - Override in a subclass to manipulate the response - after it is returned by the ConversationModels server but before - it is returned to user code. - """ - return response - def pre_list_locations( - self, request: locations_pb2.ListLocationsRequest, metadata: Sequence[Tuple[str, str]] - ) -> Tuple[locations_pb2.ListLocationsRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for list_locations - - Override in a subclass to manipulate the request or metadata - before they are sent to the ConversationModels server. - """ - return request, metadata - - def post_list_locations( - self, response: locations_pb2.ListLocationsResponse - ) -> locations_pb2.ListLocationsResponse: - """Post-rpc interceptor for list_locations - - Override in a subclass to manipulate the response - after it is returned by the ConversationModels server but before - it is returned to user code. - """ - return response - def pre_cancel_operation( - self, request: operations_pb2.CancelOperationRequest, metadata: Sequence[Tuple[str, str]] - ) -> Tuple[operations_pb2.CancelOperationRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for cancel_operation - - Override in a subclass to manipulate the request or metadata - before they are sent to the ConversationModels server. - """ - return request, metadata - - def post_cancel_operation( - self, response: None - ) -> None: - """Post-rpc interceptor for cancel_operation - - Override in a subclass to manipulate the response - after it is returned by the ConversationModels server but before - it is returned to user code. - """ - return response - def pre_get_operation( - self, request: operations_pb2.GetOperationRequest, metadata: Sequence[Tuple[str, str]] - ) -> Tuple[operations_pb2.GetOperationRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for get_operation - - Override in a subclass to manipulate the request or metadata - before they are sent to the ConversationModels server. - """ - return request, metadata - - def post_get_operation( - self, response: operations_pb2.Operation - ) -> operations_pb2.Operation: - """Post-rpc interceptor for get_operation - - Override in a subclass to manipulate the response - after it is returned by the ConversationModels server but before - it is returned to user code. - """ - return response - def pre_list_operations( - self, request: operations_pb2.ListOperationsRequest, metadata: Sequence[Tuple[str, str]] - ) -> Tuple[operations_pb2.ListOperationsRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for list_operations - - Override in a subclass to manipulate the request or metadata - before they are sent to the ConversationModels server. - """ - return request, metadata - - def post_list_operations( - self, response: operations_pb2.ListOperationsResponse - ) -> operations_pb2.ListOperationsResponse: - """Post-rpc interceptor for list_operations - - Override in a subclass to manipulate the response - after it is returned by the ConversationModels server but before - it is returned to user code. - """ - return response - - -@dataclasses.dataclass -class ConversationModelsRestStub: - _session: AuthorizedSession - _host: str - _interceptor: ConversationModelsRestInterceptor - - -class ConversationModelsRestTransport(ConversationModelsTransport): - """REST backend transport for ConversationModels. - - Manages a collection of models for human agent assistant. - - 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 JSON representations of protocol buffers over HTTP/1.1 - - """ - - def __init__(self, *, - host: str = 'dialogflow.googleapis.com', - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - client_cert_source_for_mtls: Optional[Callable[[ - ], Tuple[bytes, bytes]]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - url_scheme: str = 'https', - interceptor: Optional[ConversationModelsRestInterceptor] = None, - api_audience: Optional[str] = None, - ) -> 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 ignored if ``channel`` is provided. - scopes (Optional(Sequence[str])): A list of scopes. This argument is - ignored if ``channel`` is provided. - client_cert_source_for_mtls (Callable[[], Tuple[bytes, bytes]]): Client - certificate to configure mutual TLS HTTP channel. It is ignored - if ``channel`` is provided. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you are developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - url_scheme: the protocol scheme for the API endpoint. Normally - "https", but for testing or local servers, - "http" can be specified. - """ - # Run the base constructor - # TODO(yon-mg): resolve other ctor params i.e. scopes, quota, etc. - # TODO: When custom host (api_endpoint) is set, `scopes` must *also* be set on the - # credentials object - maybe_url_match = re.match("^(?Phttp(?:s)?://)?(?P.*)$", host) - if maybe_url_match is None: - raise ValueError(f"Unexpected hostname structure: {host}") # pragma: NO COVER - - url_match_items = maybe_url_match.groupdict() - - host = f"{url_scheme}://{host}" if not url_match_items["scheme"] else host - - super().__init__( - host=host, - credentials=credentials, - client_info=client_info, - always_use_jwt_access=always_use_jwt_access, - api_audience=api_audience - ) - self._session = AuthorizedSession( - self._credentials, default_host=self.DEFAULT_HOST) - self._operations_client: Optional[operations_v1.AbstractOperationsClient] = None - if client_cert_source_for_mtls: - self._session.configure_mtls_channel(client_cert_source_for_mtls) - self._interceptor = interceptor or ConversationModelsRestInterceptor() - self._prep_wrapped_messages(client_info) - - @property - def operations_client(self) -> operations_v1.AbstractOperationsClient: - """Create the client designed to process long-running operations. - - This property caches on the instance; repeated calls return the same - client. - """ - # Only create a new client if we do not already have one. - if self._operations_client is None: - http_options: Dict[str, List[Dict[str, str]]] = { - 'google.longrunning.Operations.CancelOperation': [ - { - 'method': 'post', - 'uri': '/v2/{name=projects/*/operations/*}:cancel', - }, - { - 'method': 'post', - 'uri': '/v2/{name=projects/*/locations/*/operations/*}:cancel', - }, - ], - 'google.longrunning.Operations.GetOperation': [ - { - 'method': 'get', - 'uri': '/v2/{name=projects/*/operations/*}', - }, - { - 'method': 'get', - 'uri': '/v2/{name=projects/*/locations/*/operations/*}', - }, - ], - 'google.longrunning.Operations.ListOperations': [ - { - 'method': 'get', - 'uri': '/v2/{name=projects/*}/operations', - }, - { - 'method': 'get', - 'uri': '/v2/{name=projects/*/locations/*}/operations', - }, - ], - } - - rest_transport = operations_v1.OperationsRestTransport( - host=self._host, - # use the credentials which are saved - credentials=self._credentials, - scopes=self._scopes, - http_options=http_options, - path_prefix="v2") - - self._operations_client = operations_v1.AbstractOperationsClient(transport=rest_transport) - - # Return the client from cache. - return self._operations_client - - class _CreateConversationModel(ConversationModelsRestStub): - def __hash__(self): - return hash("CreateConversationModel") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: gcd_conversation_model.CreateConversationModelRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> operations_pb2.Operation: - r"""Call the create conversation model method over HTTP. - - Args: - request (~.gcd_conversation_model.CreateConversationModelRequest): - The request object. The request message for - [ConversationModels.CreateConversationModel][google.cloud.dialogflow.v2.ConversationModels.CreateConversationModel] - 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: - ~.operations_pb2.Operation: - This resource represents a - long-running operation that is the - result of a network API call. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'post', - 'uri': '/v2/{parent=projects/*}/conversationModels', - 'body': 'conversation_model', - }, -{ - 'method': 'post', - 'uri': '/v2/{parent=projects/*/locations/*}/conversationModels', - 'body': 'conversation_model', - }, - ] - request, metadata = self._interceptor.pre_create_conversation_model(request, metadata) - pb_request = gcd_conversation_model.CreateConversationModelRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request['body'], - including_default_value_fields=False, - use_integers_for_enums=True - ) - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - including_default_value_fields=False, - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = operations_pb2.Operation() - json_format.Parse(response.content, resp, ignore_unknown_fields=True) - resp = self._interceptor.post_create_conversation_model(resp) - return resp - - class _CreateConversationModelEvaluation(ConversationModelsRestStub): - def __hash__(self): - return hash("CreateConversationModelEvaluation") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: conversation_model.CreateConversationModelEvaluationRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> operations_pb2.Operation: - r"""Call the create conversation model - evaluation method over HTTP. - - Args: - request (~.conversation_model.CreateConversationModelEvaluationRequest): - The request object. The request message for - [ConversationModels.CreateConversationModelEvaluation][google.cloud.dialogflow.v2.ConversationModels.CreateConversationModelEvaluation] - 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: - ~.operations_pb2.Operation: - This resource represents a - long-running operation that is the - result of a network API call. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'post', - 'uri': '/v2/{parent=projects/*/locations/*/conversationModels/*}/evaluations', - 'body': '*', - }, - ] - request, metadata = self._interceptor.pre_create_conversation_model_evaluation(request, metadata) - pb_request = conversation_model.CreateConversationModelEvaluationRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request['body'], - including_default_value_fields=False, - use_integers_for_enums=True - ) - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - including_default_value_fields=False, - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = operations_pb2.Operation() - json_format.Parse(response.content, resp, ignore_unknown_fields=True) - resp = self._interceptor.post_create_conversation_model_evaluation(resp) - return resp - - class _DeleteConversationModel(ConversationModelsRestStub): - def __hash__(self): - return hash("DeleteConversationModel") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: conversation_model.DeleteConversationModelRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> operations_pb2.Operation: - r"""Call the delete conversation model method over HTTP. - - Args: - request (~.conversation_model.DeleteConversationModelRequest): - The request object. The request message for - [ConversationModels.DeleteConversationModel][google.cloud.dialogflow.v2.ConversationModels.DeleteConversationModel] - 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: - ~.operations_pb2.Operation: - This resource represents a - long-running operation that is the - result of a network API call. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'delete', - 'uri': '/v2/{name=projects/*/conversationModels/*}', - }, -{ - 'method': 'delete', - 'uri': '/v2/{name=projects/*/locations/*/conversationModels/*}', - }, - ] - request, metadata = self._interceptor.pre_delete_conversation_model(request, metadata) - pb_request = conversation_model.DeleteConversationModelRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - including_default_value_fields=False, - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = operations_pb2.Operation() - json_format.Parse(response.content, resp, ignore_unknown_fields=True) - resp = self._interceptor.post_delete_conversation_model(resp) - return resp - - class _DeployConversationModel(ConversationModelsRestStub): - def __hash__(self): - return hash("DeployConversationModel") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: conversation_model.DeployConversationModelRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> operations_pb2.Operation: - r"""Call the deploy conversation model method over HTTP. - - Args: - request (~.conversation_model.DeployConversationModelRequest): - The request object. The request message for - [ConversationModels.DeployConversationModel][google.cloud.dialogflow.v2.ConversationModels.DeployConversationModel] - 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: - ~.operations_pb2.Operation: - This resource represents a - long-running operation that is the - result of a network API call. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'post', - 'uri': '/v2/{name=projects/*/conversationModels/*}:deploy', - 'body': '*', - }, -{ - 'method': 'post', - 'uri': '/v2/{name=projects/*/locations/*/conversationModels/*}:deploy', - 'body': '*', - }, - ] - request, metadata = self._interceptor.pre_deploy_conversation_model(request, metadata) - pb_request = conversation_model.DeployConversationModelRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request['body'], - including_default_value_fields=False, - use_integers_for_enums=True - ) - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - including_default_value_fields=False, - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = operations_pb2.Operation() - json_format.Parse(response.content, resp, ignore_unknown_fields=True) - resp = self._interceptor.post_deploy_conversation_model(resp) - return resp - - class _GetConversationModel(ConversationModelsRestStub): - def __hash__(self): - return hash("GetConversationModel") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: conversation_model.GetConversationModelRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> conversation_model.ConversationModel: - r"""Call the get conversation model method over HTTP. - - Args: - request (~.conversation_model.GetConversationModelRequest): - The request object. The request message for - [ConversationModels.GetConversationModel][google.cloud.dialogflow.v2.ConversationModels.GetConversationModel] - 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: - ~.conversation_model.ConversationModel: - Represents a conversation model. - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v2/{name=projects/*/conversationModels/*}', - }, -{ - 'method': 'get', - 'uri': '/v2/{name=projects/*/locations/*/conversationModels/*}', - }, - ] - request, metadata = self._interceptor.pre_get_conversation_model(request, metadata) - pb_request = conversation_model.GetConversationModelRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - including_default_value_fields=False, - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = conversation_model.ConversationModel() - pb_resp = conversation_model.ConversationModel.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_get_conversation_model(resp) - return resp - - class _GetConversationModelEvaluation(ConversationModelsRestStub): - def __hash__(self): - return hash("GetConversationModelEvaluation") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: conversation_model.GetConversationModelEvaluationRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> conversation_model.ConversationModelEvaluation: - r"""Call the get conversation model - evaluation method over HTTP. - - Args: - request (~.conversation_model.GetConversationModelEvaluationRequest): - The request object. The request message for - [ConversationModels.GetConversationModelEvaluation][google.cloud.dialogflow.v2.ConversationModels.GetConversationModelEvaluation] - 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: - ~.conversation_model.ConversationModelEvaluation: - Represents evaluation result of a - conversation model. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v2/{name=projects/*/conversationModels/*/evaluations/*}', - }, -{ - 'method': 'get', - 'uri': '/v2/{name=projects/*/locations/*/conversationModels/*/evaluations/*}', - }, - ] - request, metadata = self._interceptor.pre_get_conversation_model_evaluation(request, metadata) - pb_request = conversation_model.GetConversationModelEvaluationRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - including_default_value_fields=False, - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = conversation_model.ConversationModelEvaluation() - pb_resp = conversation_model.ConversationModelEvaluation.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_get_conversation_model_evaluation(resp) - return resp - - class _ListConversationModelEvaluations(ConversationModelsRestStub): - def __hash__(self): - return hash("ListConversationModelEvaluations") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: conversation_model.ListConversationModelEvaluationsRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> conversation_model.ListConversationModelEvaluationsResponse: - r"""Call the list conversation model - evaluations method over HTTP. - - Args: - request (~.conversation_model.ListConversationModelEvaluationsRequest): - The request object. The request message for - [ConversationModels.ListConversationModelEvaluations][google.cloud.dialogflow.v2.ConversationModels.ListConversationModelEvaluations] - 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: - ~.conversation_model.ListConversationModelEvaluationsResponse: - The response message for - [ConversationModels.ListConversationModelEvaluations][google.cloud.dialogflow.v2.ConversationModels.ListConversationModelEvaluations] - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v2/{parent=projects/*/conversationModels/*}/evaluations', - }, -{ - 'method': 'get', - 'uri': '/v2/{parent=projects/*/locations/*/conversationModels/*}/evaluations', - }, - ] - request, metadata = self._interceptor.pre_list_conversation_model_evaluations(request, metadata) - pb_request = conversation_model.ListConversationModelEvaluationsRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - including_default_value_fields=False, - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = conversation_model.ListConversationModelEvaluationsResponse() - pb_resp = conversation_model.ListConversationModelEvaluationsResponse.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_list_conversation_model_evaluations(resp) - return resp - - class _ListConversationModels(ConversationModelsRestStub): - def __hash__(self): - return hash("ListConversationModels") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: conversation_model.ListConversationModelsRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> conversation_model.ListConversationModelsResponse: - r"""Call the list conversation models method over HTTP. - - Args: - request (~.conversation_model.ListConversationModelsRequest): - The request object. The request message for - [ConversationModels.ListConversationModels][google.cloud.dialogflow.v2.ConversationModels.ListConversationModels] - 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: - ~.conversation_model.ListConversationModelsResponse: - The response message for - [ConversationModels.ListConversationModels][google.cloud.dialogflow.v2.ConversationModels.ListConversationModels] - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v2/{parent=projects/*}/conversationModels', - }, -{ - 'method': 'get', - 'uri': '/v2/{parent=projects/*/locations/*}/conversationModels', - }, - ] - request, metadata = self._interceptor.pre_list_conversation_models(request, metadata) - pb_request = conversation_model.ListConversationModelsRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - including_default_value_fields=False, - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = conversation_model.ListConversationModelsResponse() - pb_resp = conversation_model.ListConversationModelsResponse.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_list_conversation_models(resp) - return resp - - class _UndeployConversationModel(ConversationModelsRestStub): - def __hash__(self): - return hash("UndeployConversationModel") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: conversation_model.UndeployConversationModelRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> operations_pb2.Operation: - r"""Call the undeploy conversation - model method over HTTP. - - Args: - request (~.conversation_model.UndeployConversationModelRequest): - The request object. The request message for - [ConversationModels.UndeployConversationModel][google.cloud.dialogflow.v2.ConversationModels.UndeployConversationModel] - 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: - ~.operations_pb2.Operation: - This resource represents a - long-running operation that is the - result of a network API call. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'post', - 'uri': '/v2/{name=projects/*/conversationModels/*}:undeploy', - 'body': '*', - }, -{ - 'method': 'post', - 'uri': '/v2/{name=projects/*/locations/*/conversationModels/*}:undeploy', - 'body': '*', - }, - ] - request, metadata = self._interceptor.pre_undeploy_conversation_model(request, metadata) - pb_request = conversation_model.UndeployConversationModelRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request['body'], - including_default_value_fields=False, - use_integers_for_enums=True - ) - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - including_default_value_fields=False, - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = operations_pb2.Operation() - json_format.Parse(response.content, resp, ignore_unknown_fields=True) - resp = self._interceptor.post_undeploy_conversation_model(resp) - return resp - - @property - def create_conversation_model(self) -> Callable[ - [gcd_conversation_model.CreateConversationModelRequest], - operations_pb2.Operation]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._CreateConversationModel(self._session, self._host, self._interceptor) # type: ignore - - @property - def create_conversation_model_evaluation(self) -> Callable[ - [conversation_model.CreateConversationModelEvaluationRequest], - operations_pb2.Operation]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._CreateConversationModelEvaluation(self._session, self._host, self._interceptor) # type: ignore - - @property - def delete_conversation_model(self) -> Callable[ - [conversation_model.DeleteConversationModelRequest], - operations_pb2.Operation]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._DeleteConversationModel(self._session, self._host, self._interceptor) # type: ignore - - @property - def deploy_conversation_model(self) -> Callable[ - [conversation_model.DeployConversationModelRequest], - operations_pb2.Operation]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._DeployConversationModel(self._session, self._host, self._interceptor) # type: ignore - - @property - def get_conversation_model(self) -> Callable[ - [conversation_model.GetConversationModelRequest], - conversation_model.ConversationModel]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._GetConversationModel(self._session, self._host, self._interceptor) # type: ignore - - @property - def get_conversation_model_evaluation(self) -> Callable[ - [conversation_model.GetConversationModelEvaluationRequest], - conversation_model.ConversationModelEvaluation]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._GetConversationModelEvaluation(self._session, self._host, self._interceptor) # type: ignore - - @property - def list_conversation_model_evaluations(self) -> Callable[ - [conversation_model.ListConversationModelEvaluationsRequest], - conversation_model.ListConversationModelEvaluationsResponse]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._ListConversationModelEvaluations(self._session, self._host, self._interceptor) # type: ignore - - @property - def list_conversation_models(self) -> Callable[ - [conversation_model.ListConversationModelsRequest], - conversation_model.ListConversationModelsResponse]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._ListConversationModels(self._session, self._host, self._interceptor) # type: ignore - - @property - def undeploy_conversation_model(self) -> Callable[ - [conversation_model.UndeployConversationModelRequest], - operations_pb2.Operation]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._UndeployConversationModel(self._session, self._host, self._interceptor) # type: ignore - - @property - def get_location(self): - return self._GetLocation(self._session, self._host, self._interceptor) # type: ignore - - class _GetLocation(ConversationModelsRestStub): - def __call__(self, - request: locations_pb2.GetLocationRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> locations_pb2.Location: - - r"""Call the get location method over HTTP. - - Args: - request (locations_pb2.GetLocationRequest): - The request object for GetLocation method. - 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: - locations_pb2.Location: Response from GetLocation method. - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v2/{name=projects/*/locations/*}', - }, - ] - - request, metadata = self._interceptor.pre_get_location(request, metadata) - request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode( - http_options, **request_kwargs) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json.dumps(transcoded_request['query_params'])) - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - resp = locations_pb2.Location() - resp = json_format.Parse(response.content.decode("utf-8"), resp) - resp = self._interceptor.post_get_location(resp) - return resp - - @property - def list_locations(self): - return self._ListLocations(self._session, self._host, self._interceptor) # type: ignore - - class _ListLocations(ConversationModelsRestStub): - def __call__(self, - request: locations_pb2.ListLocationsRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> locations_pb2.ListLocationsResponse: - - r"""Call the list locations method over HTTP. - - Args: - request (locations_pb2.ListLocationsRequest): - The request object for ListLocations method. - 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: - locations_pb2.ListLocationsResponse: Response from ListLocations method. - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v2/{name=projects/*}/locations', - }, - ] - - request, metadata = self._interceptor.pre_list_locations(request, metadata) - request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode( - http_options, **request_kwargs) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json.dumps(transcoded_request['query_params'])) - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - resp = locations_pb2.ListLocationsResponse() - resp = json_format.Parse(response.content.decode("utf-8"), resp) - resp = self._interceptor.post_list_locations(resp) - return resp - - @property - def cancel_operation(self): - return self._CancelOperation(self._session, self._host, self._interceptor) # type: ignore - - class _CancelOperation(ConversationModelsRestStub): - def __call__(self, - request: operations_pb2.CancelOperationRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> None: - - r"""Call the cancel operation method over HTTP. - - Args: - request (operations_pb2.CancelOperationRequest): - The request object for CancelOperation method. - 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. - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'post', - 'uri': '/v2/{name=projects/*/operations/*}:cancel', - }, -{ - 'method': 'post', - 'uri': '/v2/{name=projects/*/locations/*/operations/*}:cancel', - }, - ] - - request, metadata = self._interceptor.pre_cancel_operation(request, metadata) - request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode( - http_options, **request_kwargs) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json.dumps(transcoded_request['query_params'])) - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - return self._interceptor.post_cancel_operation(None) - - @property - def get_operation(self): - return self._GetOperation(self._session, self._host, self._interceptor) # type: ignore - - class _GetOperation(ConversationModelsRestStub): - def __call__(self, - request: operations_pb2.GetOperationRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> operations_pb2.Operation: - - r"""Call the get operation method over HTTP. - - Args: - request (operations_pb2.GetOperationRequest): - The request object for GetOperation method. - 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: - operations_pb2.Operation: Response from GetOperation method. - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v2/{name=projects/*/operations/*}', - }, -{ - 'method': 'get', - 'uri': '/v2/{name=projects/*/locations/*/operations/*}', - }, - ] - - request, metadata = self._interceptor.pre_get_operation(request, metadata) - request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode( - http_options, **request_kwargs) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json.dumps(transcoded_request['query_params'])) - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - resp = operations_pb2.Operation() - resp = json_format.Parse(response.content.decode("utf-8"), resp) - resp = self._interceptor.post_get_operation(resp) - return resp - - @property - def list_operations(self): - return self._ListOperations(self._session, self._host, self._interceptor) # type: ignore - - class _ListOperations(ConversationModelsRestStub): - def __call__(self, - request: operations_pb2.ListOperationsRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> operations_pb2.ListOperationsResponse: - - r"""Call the list operations method over HTTP. - - Args: - request (operations_pb2.ListOperationsRequest): - The request object for ListOperations method. - 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: - operations_pb2.ListOperationsResponse: Response from ListOperations method. - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v2/{name=projects/*}/operations', - }, -{ - 'method': 'get', - 'uri': '/v2/{name=projects/*/locations/*}/operations', - }, - ] - - request, metadata = self._interceptor.pre_list_operations(request, metadata) - request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode( - http_options, **request_kwargs) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json.dumps(transcoded_request['query_params'])) - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - resp = operations_pb2.ListOperationsResponse() - resp = json_format.Parse(response.content.decode("utf-8"), resp) - resp = self._interceptor.post_list_operations(resp) - return resp - - @property - def kind(self) -> str: - return "rest" - - def close(self): - self._session.close() - - -__all__=( - 'ConversationModelsRestTransport', -) diff --git a/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/conversation_profiles/__init__.py b/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/conversation_profiles/__init__.py deleted file mode 100644 index 2418fe346..000000000 --- a/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/conversation_profiles/__init__.py +++ /dev/null @@ -1,22 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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 ConversationProfilesClient -from .async_client import ConversationProfilesAsyncClient - -__all__ = ( - 'ConversationProfilesClient', - 'ConversationProfilesAsyncClient', -) diff --git a/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/conversation_profiles/async_client.py b/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/conversation_profiles/async_client.py deleted file mode 100644 index 4f36a3d17..000000000 --- a/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/conversation_profiles/async_client.py +++ /dev/null @@ -1,1337 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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, Mapping, MutableMapping, MutableSequence, Optional, Sequence, Tuple, Type, Union - -from google.cloud.dialogflow_v2 import gapic_version as package_version - -from google.api_core.client_options import ClientOptions -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import retry as retries -from google.auth import credentials as ga_credentials # type: ignore -from google.oauth2 import service_account # type: ignore - -try: - OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] -except AttributeError: # pragma: NO COVER - OptionalRetry = Union[retries.Retry, object] # type: ignore - -from google.api_core import operation # type: ignore -from google.api_core import operation_async # type: ignore -from google.cloud.dialogflow_v2.services.conversation_profiles import pagers -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.cloud.dialogflow_v2.types import participant -from google.cloud.location import locations_pb2 # type: ignore -from google.longrunning import operations_pb2 -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 - - -class ConversationProfilesAsyncClient: - """Service for managing - [ConversationProfiles][google.cloud.dialogflow.v2.ConversationProfile]. - """ - - _client: ConversationProfilesClient - - DEFAULT_ENDPOINT = ConversationProfilesClient.DEFAULT_ENDPOINT - DEFAULT_MTLS_ENDPOINT = ConversationProfilesClient.DEFAULT_MTLS_ENDPOINT - - 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) - parse_conversation_profile_path = staticmethod(ConversationProfilesClient.parse_conversation_profile_path) - cx_security_settings_path = staticmethod(ConversationProfilesClient.cx_security_settings_path) - parse_cx_security_settings_path = staticmethod(ConversationProfilesClient.parse_cx_security_settings_path) - document_path = staticmethod(ConversationProfilesClient.document_path) - parse_document_path = staticmethod(ConversationProfilesClient.parse_document_path) - knowledge_base_path = staticmethod(ConversationProfilesClient.knowledge_base_path) - 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) - - @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: - ConversationProfilesAsyncClient: The constructed client. - """ - return ConversationProfilesClient.from_service_account_info.__func__(ConversationProfilesAsyncClient, 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: - ConversationProfilesAsyncClient: The constructed client. - """ - return ConversationProfilesClient.from_service_account_file.__func__(ConversationProfilesAsyncClient, filename, *args, **kwargs) # type: ignore - - from_service_account_json = from_service_account_file - - @classmethod - def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[ClientOptions] = None): - """Return the API endpoint and client cert source for mutual TLS. - - The client cert source is determined in the following order: - (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the - client cert source is None. - (2) if `client_options.client_cert_source` is provided, use the provided one; if the - default client cert source exists, use the default one; otherwise the client cert - source is None. - - The API endpoint is determined in the following order: - (1) if `client_options.api_endpoint` if provided, use the provided one. - (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the - default mTLS endpoint; if the environment variable is "never", use the default API - endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise - use the default API endpoint. - - More details can be found at https://google.aip.dev/auth/4114. - - Args: - client_options (google.api_core.client_options.ClientOptions): Custom options for the - client. Only the `api_endpoint` and `client_cert_source` properties may be used - in this method. - - Returns: - Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the - client cert source to use. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If any errors happen. - """ - return ConversationProfilesClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore - - @property - def transport(self) -> ConversationProfilesTransport: - """Returns the transport used by the client instance. - - Returns: - ConversationProfilesTransport: The transport used by the client instance. - """ - return self._client.transport - - get_transport_class = functools.partial(type(ConversationProfilesClient).get_transport_class, type(ConversationProfilesClient)) - - def __init__(self, *, - credentials: Optional[ga_credentials.Credentials] = None, - transport: Union[str, ConversationProfilesTransport] = "grpc_asyncio", - client_options: Optional[ClientOptions] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the conversation profiles 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, ~.ConversationProfilesTransport]): 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 = ConversationProfilesClient( - credentials=credentials, - transport=transport, - client_options=client_options, - client_info=client_info, - - ) - - async def list_conversation_profiles(self, - request: Optional[Union[conversation_profile.ListConversationProfilesRequest, dict]] = None, - *, - parent: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListConversationProfilesAsyncPager: - r"""Returns the list of all conversation profiles in the - specified project. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import dialogflow_v2 - - async def sample_list_conversation_profiles(): - # Create a client - client = dialogflow_v2.ConversationProfilesAsyncClient() - - # Initialize request argument(s) - request = dialogflow_v2.ListConversationProfilesRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_conversation_profiles(request=request) - - # Handle the response - async for response in page_result: - print(response) - - Args: - request (Optional[Union[google.cloud.dialogflow_v2.types.ListConversationProfilesRequest, dict]]): - The request object. The request message for - [ConversationProfiles.ListConversationProfiles][google.cloud.dialogflow.v2.ConversationProfiles.ListConversationProfiles]. - parent (:class:`str`): - Required. The project to list all conversation profiles - from. Format: - ``projects//locations/``. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.dialogflow_v2.services.conversation_profiles.pagers.ListConversationProfilesAsyncPager: - The response message for - [ConversationProfiles.ListConversationProfiles][google.cloud.dialogflow.v2.ConversationProfiles.ListConversationProfiles]. - - Iterating over this object will yield results and - resolve additional pages automatically. - - """ - # Create or coerce a protobuf request object. - # Quick 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 = 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 - - # 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_conversation_profiles, - 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.ListConversationProfilesAsyncPager( - method=rpc, - request=request, - response=response, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def get_conversation_profile(self, - request: Optional[Union[conversation_profile.GetConversationProfileRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> conversation_profile.ConversationProfile: - r"""Retrieves the specified conversation profile. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import dialogflow_v2 - - async def sample_get_conversation_profile(): - # Create a client - client = dialogflow_v2.ConversationProfilesAsyncClient() - - # Initialize request argument(s) - request = dialogflow_v2.GetConversationProfileRequest( - name="name_value", - ) - - # Make the request - response = await client.get_conversation_profile(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.dialogflow_v2.types.GetConversationProfileRequest, dict]]): - The request object. The request message for - [ConversationProfiles.GetConversationProfile][google.cloud.dialogflow.v2.ConversationProfiles.GetConversationProfile]. - name (:class:`str`): - Required. The resource name of the conversation profile. - Format: - ``projects//locations//conversationProfiles/``. - - 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.ConversationProfile: - Defines the services to connect to - incoming Dialogflow conversations. - - """ - # Create or coerce a protobuf request object. - # Quick 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 = 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 - - # 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_conversation_profile, - 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_conversation_profile(self, - request: Optional[Union[gcd_conversation_profile.CreateConversationProfileRequest, dict]] = None, - *, - parent: Optional[str] = None, - conversation_profile: Optional[gcd_conversation_profile.ConversationProfile] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gcd_conversation_profile.ConversationProfile: - r"""Creates a conversation profile in the specified project. - - [ConversationProfile.CreateTime][] and - [ConversationProfile.UpdateTime][] aren't populated in the - response. You can retrieve them via - [GetConversationProfile][google.cloud.dialogflow.v2.ConversationProfiles.GetConversationProfile] - API. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import dialogflow_v2 - - async def sample_create_conversation_profile(): - # Create a client - client = dialogflow_v2.ConversationProfilesAsyncClient() - - # Initialize request argument(s) - conversation_profile = dialogflow_v2.ConversationProfile() - conversation_profile.display_name = "display_name_value" - - request = dialogflow_v2.CreateConversationProfileRequest( - parent="parent_value", - conversation_profile=conversation_profile, - ) - - # Make the request - response = await client.create_conversation_profile(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.dialogflow_v2.types.CreateConversationProfileRequest, dict]]): - The request object. The request message for - [ConversationProfiles.CreateConversationProfile][google.cloud.dialogflow.v2.ConversationProfiles.CreateConversationProfile]. - parent (:class:`str`): - Required. The project to create a conversation profile - for. Format: - ``projects//locations/``. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - conversation_profile (:class:`google.cloud.dialogflow_v2.types.ConversationProfile`): - Required. The conversation profile to - create. - - 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. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.dialogflow_v2.types.ConversationProfile: - Defines the services to connect to - incoming Dialogflow conversations. - - """ - # Create or coerce a protobuf request object. - # Quick 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, conversation_profile]) - 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_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: - request.conversation_profile = conversation_profile - - # 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_conversation_profile, - 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_conversation_profile(self, - request: Optional[Union[gcd_conversation_profile.UpdateConversationProfileRequest, dict]] = None, - *, - conversation_profile: Optional[gcd_conversation_profile.ConversationProfile] = None, - update_mask: Optional[field_mask_pb2.FieldMask] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gcd_conversation_profile.ConversationProfile: - r"""Updates the specified conversation profile. - - [ConversationProfile.CreateTime][] and - [ConversationProfile.UpdateTime][] aren't populated in the - response. You can retrieve them via - [GetConversationProfile][google.cloud.dialogflow.v2.ConversationProfiles.GetConversationProfile] - API. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import dialogflow_v2 - - async def sample_update_conversation_profile(): - # Create a client - client = dialogflow_v2.ConversationProfilesAsyncClient() - - # Initialize request argument(s) - conversation_profile = dialogflow_v2.ConversationProfile() - conversation_profile.display_name = "display_name_value" - - request = dialogflow_v2.UpdateConversationProfileRequest( - conversation_profile=conversation_profile, - ) - - # Make the request - response = await client.update_conversation_profile(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.dialogflow_v2.types.UpdateConversationProfileRequest, dict]]): - The request object. The request message for - [ConversationProfiles.UpdateConversationProfile][google.cloud.dialogflow.v2.ConversationProfiles.UpdateConversationProfile]. - conversation_profile (:class:`google.cloud.dialogflow_v2.types.ConversationProfile`): - Required. The conversation profile to - update. - - This corresponds to the ``conversation_profile`` 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 to update. - - 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.ConversationProfile: - Defines the services to connect to - incoming Dialogflow conversations. - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([conversation_profile, 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_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: - 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_conversation_profile, - 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(( - ("conversation_profile.name", request.conversation_profile.name), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def delete_conversation_profile(self, - request: Optional[Union[conversation_profile.DeleteConversationProfileRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> None: - r"""Deletes the specified conversation profile. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import dialogflow_v2 - - async def sample_delete_conversation_profile(): - # Create a client - client = dialogflow_v2.ConversationProfilesAsyncClient() - - # Initialize request argument(s) - request = dialogflow_v2.DeleteConversationProfileRequest( - name="name_value", - ) - - # Make the request - await client.delete_conversation_profile(request=request) - - Args: - request (Optional[Union[google.cloud.dialogflow_v2.types.DeleteConversationProfileRequest, dict]]): - The request object. The request message for - [ConversationProfiles.DeleteConversationProfile][google.cloud.dialogflow.v2.ConversationProfiles.DeleteConversationProfile]. - - This operation fails if the conversation profile is - still referenced from a phone number. - name (:class:`str`): - Required. The name of the conversation profile to - delete. Format: - ``projects//locations//conversationProfiles/``. - - 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. - # Quick 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 = 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 - - # 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_conversation_profile, - 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 set_suggestion_feature_config(self, - request: Optional[Union[gcd_conversation_profile.SetSuggestionFeatureConfigRequest, dict]] = None, - *, - conversation_profile: Optional[str] = None, - participant_role: Optional[participant.Participant.Role] = None, - suggestion_feature_config: Optional[gcd_conversation_profile.HumanAgentAssistantConfig.SuggestionFeatureConfig] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation_async.AsyncOperation: - r"""Adds or updates a suggestion feature in a conversation profile. - If the conversation profile contains the type of suggestion - feature for the participant role, it will update it. Otherwise - it will insert the suggestion feature. - - This method is a `long-running - operation `__. - The returned ``Operation`` type has the following - method-specific fields: - - - ``metadata``: - [SetSuggestionFeatureConfigOperationMetadata][google.cloud.dialogflow.v2.SetSuggestionFeatureConfigOperationMetadata] - - ``response``: - [ConversationProfile][google.cloud.dialogflow.v2.ConversationProfile] - - If a long running operation to add or update suggestion feature - config for the same conversation profile, participant role and - suggestion feature type exists, please cancel the existing long - running operation before sending such request, otherwise the - request will be rejected. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import dialogflow_v2 - - async def sample_set_suggestion_feature_config(): - # Create a client - client = dialogflow_v2.ConversationProfilesAsyncClient() - - # Initialize request argument(s) - request = dialogflow_v2.SetSuggestionFeatureConfigRequest( - conversation_profile="conversation_profile_value", - participant_role="END_USER", - ) - - # Make the request - operation = client.set_suggestion_feature_config(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.dialogflow_v2.types.SetSuggestionFeatureConfigRequest, dict]]): - The request object. The request message for - [ConversationProfiles.SetSuggestionFeature][]. - conversation_profile (:class:`str`): - Required. The Conversation Profile to add or update the - suggestion feature config. Format: - ``projects//locations//conversationProfiles/``. - - This corresponds to the ``conversation_profile`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - participant_role (:class:`google.cloud.dialogflow_v2.types.Participant.Role`): - Required. The participant role to add or update the - suggestion feature config. Only HUMAN_AGENT or END_USER - can be used. - - This corresponds to the ``participant_role`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - suggestion_feature_config (:class:`google.cloud.dialogflow_v2.types.HumanAgentAssistantConfig.SuggestionFeatureConfig`): - Required. The suggestion feature - config to add or update. - - This corresponds to the ``suggestion_feature_config`` field - on the ``request`` instance; if ``request`` is provided, this - should not 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.api_core.operation_async.AsyncOperation: - An object representing a long-running operation. - - The result type for the operation will be - :class:`google.cloud.dialogflow_v2.types.ConversationProfile` - Defines the services to connect to incoming Dialogflow - conversations. - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([conversation_profile, participant_role, suggestion_feature_config]) - 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_conversation_profile.SetSuggestionFeatureConfigRequest(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 participant_role is not None: - request.participant_role = participant_role - if suggestion_feature_config is not None: - request.suggestion_feature_config = suggestion_feature_config - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.set_suggestion_feature_config, - 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(( - ("conversation_profile", request.conversation_profile), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Wrap the response in an operation future. - response = operation_async.from_gapic( - response, - self._client._transport.operations_client, - gcd_conversation_profile.ConversationProfile, - metadata_type=gcd_conversation_profile.SetSuggestionFeatureConfigOperationMetadata, - ) - - # Done; return the response. - return response - - async def clear_suggestion_feature_config(self, - request: Optional[Union[gcd_conversation_profile.ClearSuggestionFeatureConfigRequest, dict]] = None, - *, - conversation_profile: Optional[str] = None, - participant_role: Optional[participant.Participant.Role] = None, - suggestion_feature_type: Optional[gcd_conversation_profile.SuggestionFeature.Type] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation_async.AsyncOperation: - r"""Clears a suggestion feature from a conversation profile for the - given participant role. - - This method is a `long-running - operation `__. - The returned ``Operation`` type has the following - method-specific fields: - - - ``metadata``: - [ClearSuggestionFeatureConfigOperationMetadata][google.cloud.dialogflow.v2.ClearSuggestionFeatureConfigOperationMetadata] - - ``response``: - [ConversationProfile][google.cloud.dialogflow.v2.ConversationProfile] - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import dialogflow_v2 - - async def sample_clear_suggestion_feature_config(): - # Create a client - client = dialogflow_v2.ConversationProfilesAsyncClient() - - # Initialize request argument(s) - request = dialogflow_v2.ClearSuggestionFeatureConfigRequest( - conversation_profile="conversation_profile_value", - participant_role="END_USER", - suggestion_feature_type="SMART_REPLY", - ) - - # Make the request - operation = client.clear_suggestion_feature_config(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.dialogflow_v2.types.ClearSuggestionFeatureConfigRequest, dict]]): - The request object. The request message for - [ConversationProfiles.ClearFeature][]. - conversation_profile (:class:`str`): - Required. The Conversation Profile to add or update the - suggestion feature config. Format: - ``projects//locations//conversationProfiles/``. - - This corresponds to the ``conversation_profile`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - participant_role (:class:`google.cloud.dialogflow_v2.types.Participant.Role`): - Required. The participant role to remove the suggestion - feature config. Only HUMAN_AGENT or END_USER can be - used. - - This corresponds to the ``participant_role`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - suggestion_feature_type (:class:`google.cloud.dialogflow_v2.types.SuggestionFeature.Type`): - Required. The type of the suggestion - feature to remove. - - This corresponds to the ``suggestion_feature_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. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.api_core.operation_async.AsyncOperation: - An object representing a long-running operation. - - The result type for the operation will be - :class:`google.cloud.dialogflow_v2.types.ConversationProfile` - Defines the services to connect to incoming Dialogflow - conversations. - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([conversation_profile, participant_role, suggestion_feature_type]) - 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_conversation_profile.ClearSuggestionFeatureConfigRequest(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 participant_role is not None: - request.participant_role = participant_role - if suggestion_feature_type is not None: - request.suggestion_feature_type = suggestion_feature_type - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.clear_suggestion_feature_config, - 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(( - ("conversation_profile", request.conversation_profile), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Wrap the response in an operation future. - response = operation_async.from_gapic( - response, - self._client._transport.operations_client, - gcd_conversation_profile.ConversationProfile, - metadata_type=gcd_conversation_profile.ClearSuggestionFeatureConfigOperationMetadata, - ) - - # Done; return the response. - return response - - async def list_operations( - self, - request: Optional[operations_pb2.ListOperationsRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operations_pb2.ListOperationsResponse: - r"""Lists operations that match the specified filter in the request. - - Args: - request (:class:`~.operations_pb2.ListOperationsRequest`): - The request object. Request message for - `ListOperations` method. - 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: - ~.operations_pb2.ListOperationsResponse: - Response message for ``ListOperations`` method. - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = operations_pb2.ListOperationsRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._client._transport.list_operations, - 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 get_operation( - self, - request: Optional[operations_pb2.GetOperationRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operations_pb2.Operation: - r"""Gets the latest state of a long-running operation. - - Args: - request (:class:`~.operations_pb2.GetOperationRequest`): - The request object. Request message for - `GetOperation` method. - 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: - ~.operations_pb2.Operation: - An ``Operation`` object. - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = operations_pb2.GetOperationRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._client._transport.get_operation, - 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 cancel_operation( - self, - request: Optional[operations_pb2.CancelOperationRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> None: - r"""Starts asynchronous cancellation on a long-running operation. - - The server makes a best effort to cancel the operation, but success - is not guaranteed. If the server doesn't support this method, it returns - `google.rpc.Code.UNIMPLEMENTED`. - - Args: - request (:class:`~.operations_pb2.CancelOperationRequest`): - The request object. Request message for - `CancelOperation` method. - 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: - None - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = operations_pb2.CancelOperationRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._client._transport.cancel_operation, - 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_location( - self, - request: Optional[locations_pb2.GetLocationRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> locations_pb2.Location: - r"""Gets information about a location. - - Args: - request (:class:`~.location_pb2.GetLocationRequest`): - The request object. Request message for - `GetLocation` method. - 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: - ~.location_pb2.Location: - Location object. - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = locations_pb2.GetLocationRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._client._transport.get_location, - 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 list_locations( - self, - request: Optional[locations_pb2.ListLocationsRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> locations_pb2.ListLocationsResponse: - r"""Lists information about the supported locations for this service. - - Args: - request (:class:`~.location_pb2.ListLocationsRequest`): - The request object. Request message for - `ListLocations` method. - 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: - ~.location_pb2.ListLocationsResponse: - Response message for ``ListLocations`` method. - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = locations_pb2.ListLocationsRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._client._transport.list_locations, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("name", request.name),)), - ) - - # Send the request. - response = await rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - async def __aenter__(self): - return self - - async def __aexit__(self, exc_type, exc, tb): - await self.transport.close() - -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) - - -__all__ = ( - "ConversationProfilesAsyncClient", -) diff --git a/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/conversation_profiles/client.py b/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/conversation_profiles/client.py deleted file mode 100644 index 537af5178..000000000 --- a/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/conversation_profiles/client.py +++ /dev/null @@ -1,1581 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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 os -import re -from typing import Dict, Mapping, MutableMapping, MutableSequence, Optional, Sequence, Tuple, Type, Union, cast - -from google.cloud.dialogflow_v2 import gapic_version as package_version - -from google.api_core import client_options as client_options_lib -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import retry as retries -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 - -try: - OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] -except AttributeError: # pragma: NO COVER - OptionalRetry = Union[retries.Retry, object] # type: ignore - -from google.api_core import operation # type: ignore -from google.api_core import operation_async # type: ignore -from google.cloud.dialogflow_v2.services.conversation_profiles import pagers -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.cloud.dialogflow_v2.types import participant -from google.cloud.location import locations_pb2 # type: ignore -from google.longrunning import operations_pb2 -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 -from .transports.rest import ConversationProfilesRestTransport - - -class ConversationProfilesClientMeta(type): - """Metaclass for the ConversationProfiles 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[ConversationProfilesTransport]] - _transport_registry["grpc"] = ConversationProfilesGrpcTransport - _transport_registry["grpc_asyncio"] = ConversationProfilesGrpcAsyncIOTransport - _transport_registry["rest"] = ConversationProfilesRestTransport - - def get_transport_class(cls, - label: Optional[str] = None, - ) -> Type[ConversationProfilesTransport]: - """Returns an appropriate transport class. - - Args: - label: The name of the desired transport. If none is - provided, then the first transport in the registry is used. - - Returns: - The transport class to use. - """ - # If a specific transport is requested, return that one. - if label: - return cls._transport_registry[label] - - # No transport is requested; return the default (that is, the first one - # in the dictionary). - return next(iter(cls._transport_registry.values())) - - -class ConversationProfilesClient(metaclass=ConversationProfilesClientMeta): - """Service for managing - [ConversationProfiles][google.cloud.dialogflow.v2.ConversationProfile]. - """ - - @staticmethod - def _get_default_mtls_endpoint(api_endpoint): - """Converts api endpoint to mTLS endpoint. - - Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to - "*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively. - Args: - api_endpoint (Optional[str]): the api endpoint to convert. - Returns: - str: converted mTLS api endpoint. - """ - if not api_endpoint: - return api_endpoint - - mtls_endpoint_re = re.compile( - r"(?P[^.]+)(?P\.mtls)?(?P\.sandbox)?(?P\.googleapis\.com)?" - ) - - m = mtls_endpoint_re.match(api_endpoint) - name, mtls, sandbox, googledomain = m.groups() - if mtls or not googledomain: - return api_endpoint - - if sandbox: - return api_endpoint.replace( - "sandbox.googleapis.com", "mtls.sandbox.googleapis.com" - ) - - return api_endpoint.replace(".googleapis.com", ".mtls.googleapis.com") - - DEFAULT_ENDPOINT = "dialogflow.googleapis.com" - DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore - DEFAULT_ENDPOINT - ) - - @classmethod - def from_service_account_info(cls, info: dict, *args, **kwargs): - """Creates an instance of this client using the provided credentials - info. - - Args: - info (dict): The service account private key info. - args: Additional arguments to pass to the constructor. - kwargs: Additional arguments to pass to the constructor. - - Returns: - ConversationProfilesClient: 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: - ConversationProfilesClient: 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) -> ConversationProfilesTransport: - """Returns the transport used by the client instance. - - Returns: - ConversationProfilesTransport: The transport used by the client - instance. - """ - return self._transport - - @staticmethod - def agent_path(project: str,) -> str: - """Returns a fully-qualified agent string.""" - return "projects/{project}/agent".format(project=project, ) - - @staticmethod - def parse_agent_path(path: str) -> Dict[str,str]: - """Parses a agent path into its component segments.""" - 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: - """Returns 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]: - """Parses 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: - """Returns a fully-qualified conversation_profile string.""" - return "projects/{project}/conversationProfiles/{conversation_profile}".format(project=project, conversation_profile=conversation_profile, ) - - @staticmethod - def parse_conversation_profile_path(path: str) -> Dict[str,str]: - """Parses a conversation_profile path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/conversationProfiles/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def cx_security_settings_path(project: str,location: str,security_settings: str,) -> str: - """Returns a fully-qualified cx_security_settings string.""" - return "projects/{project}/locations/{location}/securitySettings/{security_settings}".format(project=project, location=location, security_settings=security_settings, ) - - @staticmethod - def parse_cx_security_settings_path(path: str) -> Dict[str,str]: - """Parses a cx_security_settings path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/securitySettings/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def document_path(project: str,knowledge_base: str,document: str,) -> str: - """Returns a fully-qualified document string.""" - return "projects/{project}/knowledgeBases/{knowledge_base}/documents/{document}".format(project=project, knowledge_base=knowledge_base, document=document, ) - - @staticmethod - def parse_document_path(path: str) -> Dict[str,str]: - """Parses a document path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/knowledgeBases/(?P.+?)/documents/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def knowledge_base_path(project: str,knowledge_base: str,) -> str: - """Returns a fully-qualified knowledge_base string.""" - return "projects/{project}/knowledgeBases/{knowledge_base}".format(project=project, knowledge_base=knowledge_base, ) - - @staticmethod - def parse_knowledge_base_path(path: str) -> Dict[str,str]: - """Parses a knowledge_base path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/knowledgeBases/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_billing_account_path(billing_account: str, ) -> str: - """Returns a fully-qualified billing_account string.""" - return "billingAccounts/{billing_account}".format(billing_account=billing_account, ) - - @staticmethod - def parse_common_billing_account_path(path: str) -> Dict[str,str]: - """Parse a billing_account path into its component segments.""" - m = re.match(r"^billingAccounts/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_folder_path(folder: str, ) -> str: - """Returns a fully-qualified folder string.""" - return "folders/{folder}".format(folder=folder, ) - - @staticmethod - def parse_common_folder_path(path: str) -> Dict[str,str]: - """Parse a folder path into its component segments.""" - m = re.match(r"^folders/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_organization_path(organization: str, ) -> str: - """Returns a fully-qualified organization string.""" - return "organizations/{organization}".format(organization=organization, ) - - @staticmethod - def parse_common_organization_path(path: str) -> Dict[str,str]: - """Parse a organization path into its component segments.""" - m = re.match(r"^organizations/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_project_path(project: str, ) -> str: - """Returns a fully-qualified project string.""" - return "projects/{project}".format(project=project, ) - - @staticmethod - def parse_common_project_path(path: str) -> Dict[str,str]: - """Parse a project path into its component segments.""" - m = re.match(r"^projects/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_location_path(project: str, location: str, ) -> str: - """Returns a fully-qualified location string.""" - return "projects/{project}/locations/{location}".format(project=project, location=location, ) - - @staticmethod - def parse_common_location_path(path: str) -> Dict[str,str]: - """Parse a location path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)$", path) - return m.groupdict() if m else {} - - @classmethod - def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[client_options_lib.ClientOptions] = None): - """Return the API endpoint and client cert source for mutual TLS. - - The client cert source is determined in the following order: - (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the - client cert source is None. - (2) if `client_options.client_cert_source` is provided, use the provided one; if the - default client cert source exists, use the default one; otherwise the client cert - source is None. - - The API endpoint is determined in the following order: - (1) if `client_options.api_endpoint` if provided, use the provided one. - (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the - default mTLS endpoint; if the environment variable is "never", use the default API - endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise - use the default API endpoint. - - More details can be found at https://google.aip.dev/auth/4114. - - Args: - client_options (google.api_core.client_options.ClientOptions): Custom options for the - client. Only the `api_endpoint` and `client_cert_source` properties may be used - in this method. - - Returns: - Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the - client cert source to use. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If any errors happen. - """ - if client_options is None: - client_options = client_options_lib.ClientOptions() - use_client_cert = os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false") - use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") - if use_client_cert not in ("true", "false"): - raise ValueError("Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`") - if use_mtls_endpoint not in ("auto", "never", "always"): - raise MutualTLSChannelError("Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`") - - # Figure out the client cert source to use. - client_cert_source = None - if use_client_cert == "true": - if client_options.client_cert_source: - client_cert_source = client_options.client_cert_source - elif mtls.has_default_client_cert_source(): - client_cert_source = mtls.default_client_cert_source() - - # Figure out which api endpoint to use. - if client_options.api_endpoint is not None: - api_endpoint = client_options.api_endpoint - elif use_mtls_endpoint == "always" or (use_mtls_endpoint == "auto" and client_cert_source): - api_endpoint = cls.DEFAULT_MTLS_ENDPOINT - else: - api_endpoint = cls.DEFAULT_ENDPOINT - - return api_endpoint, client_cert_source - - def __init__(self, *, - credentials: Optional[ga_credentials.Credentials] = None, - transport: Optional[Union[str, ConversationProfilesTransport]] = None, - client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the conversation profiles 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, ConversationProfilesTransport]): The - transport to use. If set to None, a transport is chosen - automatically. - client_options (Optional[Union[google.api_core.client_options.ClientOptions, dict]]): 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() - client_options = cast(client_options_lib.ClientOptions, client_options) - - api_endpoint, client_cert_source_func = self.get_mtls_endpoint_and_cert_source(client_options) - - api_key_value = getattr(client_options, "api_key", None) - if api_key_value and credentials: - raise ValueError("client_options.api_key and credentials are mutually exclusive") - - # 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, ConversationProfilesTransport): - # transport is a ConversationProfilesTransport instance. - if credentials or client_options.credentials_file or api_key_value: - 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: - import google.auth._default # type: ignore - - if api_key_value and hasattr(google.auth._default, "get_api_key_credentials"): - credentials = google.auth._default.get_api_key_credentials(api_key_value) - - Transport = type(self).get_transport_class(transport) - self._transport = Transport( - credentials=credentials, - credentials_file=client_options.credentials_file, - host=api_endpoint, - scopes=client_options.scopes, - client_cert_source_for_mtls=client_cert_source_func, - quota_project_id=client_options.quota_project_id, - client_info=client_info, - always_use_jwt_access=True, - api_audience=client_options.api_audience, - ) - - def list_conversation_profiles(self, - request: Optional[Union[conversation_profile.ListConversationProfilesRequest, dict]] = None, - *, - parent: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListConversationProfilesPager: - r"""Returns the list of all conversation profiles in the - specified project. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import dialogflow_v2 - - def sample_list_conversation_profiles(): - # Create a client - client = dialogflow_v2.ConversationProfilesClient() - - # Initialize request argument(s) - request = dialogflow_v2.ListConversationProfilesRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_conversation_profiles(request=request) - - # Handle the response - for response in page_result: - print(response) - - Args: - request (Union[google.cloud.dialogflow_v2.types.ListConversationProfilesRequest, dict]): - The request object. The request message for - [ConversationProfiles.ListConversationProfiles][google.cloud.dialogflow.v2.ConversationProfiles.ListConversationProfiles]. - parent (str): - Required. The project to list all conversation profiles - from. Format: - ``projects//locations/``. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.dialogflow_v2.services.conversation_profiles.pagers.ListConversationProfilesPager: - The response message for - [ConversationProfiles.ListConversationProfiles][google.cloud.dialogflow.v2.ConversationProfiles.ListConversationProfiles]. - - Iterating over this object will yield results and - resolve additional pages automatically. - - """ - # Create or coerce a protobuf request object. - # Quick 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 conversation_profile.ListConversationProfilesRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(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 - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.list_conversation_profiles] - - # 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.ListConversationProfilesPager( - method=rpc, - request=request, - response=response, - metadata=metadata, - ) - - # Done; return the response. - return response - - def get_conversation_profile(self, - request: Optional[Union[conversation_profile.GetConversationProfileRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> conversation_profile.ConversationProfile: - r"""Retrieves the specified conversation profile. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import dialogflow_v2 - - def sample_get_conversation_profile(): - # Create a client - client = dialogflow_v2.ConversationProfilesClient() - - # Initialize request argument(s) - request = dialogflow_v2.GetConversationProfileRequest( - name="name_value", - ) - - # Make the request - response = client.get_conversation_profile(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.dialogflow_v2.types.GetConversationProfileRequest, dict]): - The request object. The request message for - [ConversationProfiles.GetConversationProfile][google.cloud.dialogflow.v2.ConversationProfiles.GetConversationProfile]. - name (str): - Required. The resource name of the conversation profile. - Format: - ``projects//locations//conversationProfiles/``. - - 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.ConversationProfile: - Defines the services to connect to - incoming Dialogflow conversations. - - """ - # Create or coerce a protobuf request object. - # Quick 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 conversation_profile.GetConversationProfileRequest. - # There's no risk of modifying the input as we've already verified - # 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 - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.get_conversation_profile] - - # 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_conversation_profile(self, - request: Optional[Union[gcd_conversation_profile.CreateConversationProfileRequest, dict]] = None, - *, - parent: Optional[str] = None, - conversation_profile: Optional[gcd_conversation_profile.ConversationProfile] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gcd_conversation_profile.ConversationProfile: - r"""Creates a conversation profile in the specified project. - - [ConversationProfile.CreateTime][] and - [ConversationProfile.UpdateTime][] aren't populated in the - response. You can retrieve them via - [GetConversationProfile][google.cloud.dialogflow.v2.ConversationProfiles.GetConversationProfile] - API. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import dialogflow_v2 - - def sample_create_conversation_profile(): - # Create a client - client = dialogflow_v2.ConversationProfilesClient() - - # Initialize request argument(s) - conversation_profile = dialogflow_v2.ConversationProfile() - conversation_profile.display_name = "display_name_value" - - request = dialogflow_v2.CreateConversationProfileRequest( - parent="parent_value", - conversation_profile=conversation_profile, - ) - - # Make the request - response = client.create_conversation_profile(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.dialogflow_v2.types.CreateConversationProfileRequest, dict]): - The request object. The request message for - [ConversationProfiles.CreateConversationProfile][google.cloud.dialogflow.v2.ConversationProfiles.CreateConversationProfile]. - parent (str): - Required. The project to create a conversation profile - for. Format: - ``projects//locations/``. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - conversation_profile (google.cloud.dialogflow_v2.types.ConversationProfile): - Required. The conversation profile to - create. - - 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. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.dialogflow_v2.types.ConversationProfile: - Defines the services to connect to - incoming Dialogflow conversations. - - """ - # Create or coerce a protobuf request object. - # Quick 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, conversation_profile]) - 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_conversation_profile.CreateConversationProfileRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(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: - request.conversation_profile = conversation_profile - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.create_conversation_profile] - - # 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_conversation_profile(self, - request: Optional[Union[gcd_conversation_profile.UpdateConversationProfileRequest, dict]] = None, - *, - conversation_profile: Optional[gcd_conversation_profile.ConversationProfile] = None, - update_mask: Optional[field_mask_pb2.FieldMask] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gcd_conversation_profile.ConversationProfile: - r"""Updates the specified conversation profile. - - [ConversationProfile.CreateTime][] and - [ConversationProfile.UpdateTime][] aren't populated in the - response. You can retrieve them via - [GetConversationProfile][google.cloud.dialogflow.v2.ConversationProfiles.GetConversationProfile] - API. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import dialogflow_v2 - - def sample_update_conversation_profile(): - # Create a client - client = dialogflow_v2.ConversationProfilesClient() - - # Initialize request argument(s) - conversation_profile = dialogflow_v2.ConversationProfile() - conversation_profile.display_name = "display_name_value" - - request = dialogflow_v2.UpdateConversationProfileRequest( - conversation_profile=conversation_profile, - ) - - # Make the request - response = client.update_conversation_profile(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.dialogflow_v2.types.UpdateConversationProfileRequest, dict]): - The request object. The request message for - [ConversationProfiles.UpdateConversationProfile][google.cloud.dialogflow.v2.ConversationProfiles.UpdateConversationProfile]. - conversation_profile (google.cloud.dialogflow_v2.types.ConversationProfile): - Required. The conversation profile to - update. - - This corresponds to the ``conversation_profile`` 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 to update. - - 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.ConversationProfile: - Defines the services to connect to - incoming Dialogflow conversations. - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([conversation_profile, 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_conversation_profile.UpdateConversationProfileRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(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: - 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_conversation_profile] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("conversation_profile.name", request.conversation_profile.name), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def delete_conversation_profile(self, - request: Optional[Union[conversation_profile.DeleteConversationProfileRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> None: - r"""Deletes the specified conversation profile. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import dialogflow_v2 - - def sample_delete_conversation_profile(): - # Create a client - client = dialogflow_v2.ConversationProfilesClient() - - # Initialize request argument(s) - request = dialogflow_v2.DeleteConversationProfileRequest( - name="name_value", - ) - - # Make the request - client.delete_conversation_profile(request=request) - - Args: - request (Union[google.cloud.dialogflow_v2.types.DeleteConversationProfileRequest, dict]): - The request object. The request message for - [ConversationProfiles.DeleteConversationProfile][google.cloud.dialogflow.v2.ConversationProfiles.DeleteConversationProfile]. - - This operation fails if the conversation profile is - still referenced from a phone number. - name (str): - Required. The name of the conversation profile to - delete. Format: - ``projects//locations//conversationProfiles/``. - - 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. - # Quick 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 conversation_profile.DeleteConversationProfileRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(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 - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.delete_conversation_profile] - - # 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 set_suggestion_feature_config(self, - request: Optional[Union[gcd_conversation_profile.SetSuggestionFeatureConfigRequest, dict]] = None, - *, - conversation_profile: Optional[str] = None, - participant_role: Optional[participant.Participant.Role] = None, - suggestion_feature_config: Optional[gcd_conversation_profile.HumanAgentAssistantConfig.SuggestionFeatureConfig] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation.Operation: - r"""Adds or updates a suggestion feature in a conversation profile. - If the conversation profile contains the type of suggestion - feature for the participant role, it will update it. Otherwise - it will insert the suggestion feature. - - This method is a `long-running - operation `__. - The returned ``Operation`` type has the following - method-specific fields: - - - ``metadata``: - [SetSuggestionFeatureConfigOperationMetadata][google.cloud.dialogflow.v2.SetSuggestionFeatureConfigOperationMetadata] - - ``response``: - [ConversationProfile][google.cloud.dialogflow.v2.ConversationProfile] - - If a long running operation to add or update suggestion feature - config for the same conversation profile, participant role and - suggestion feature type exists, please cancel the existing long - running operation before sending such request, otherwise the - request will be rejected. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import dialogflow_v2 - - def sample_set_suggestion_feature_config(): - # Create a client - client = dialogflow_v2.ConversationProfilesClient() - - # Initialize request argument(s) - request = dialogflow_v2.SetSuggestionFeatureConfigRequest( - conversation_profile="conversation_profile_value", - participant_role="END_USER", - ) - - # Make the request - operation = client.set_suggestion_feature_config(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.dialogflow_v2.types.SetSuggestionFeatureConfigRequest, dict]): - The request object. The request message for - [ConversationProfiles.SetSuggestionFeature][]. - conversation_profile (str): - Required. The Conversation Profile to add or update the - suggestion feature config. Format: - ``projects//locations//conversationProfiles/``. - - This corresponds to the ``conversation_profile`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - participant_role (google.cloud.dialogflow_v2.types.Participant.Role): - Required. The participant role to add or update the - suggestion feature config. Only HUMAN_AGENT or END_USER - can be used. - - This corresponds to the ``participant_role`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - suggestion_feature_config (google.cloud.dialogflow_v2.types.HumanAgentAssistantConfig.SuggestionFeatureConfig): - Required. The suggestion feature - config to add or update. - - This corresponds to the ``suggestion_feature_config`` field - on the ``request`` instance; if ``request`` is provided, this - should not 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.api_core.operation.Operation: - An object representing a long-running operation. - - The result type for the operation will be - :class:`google.cloud.dialogflow_v2.types.ConversationProfile` - Defines the services to connect to incoming Dialogflow - conversations. - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([conversation_profile, participant_role, suggestion_feature_config]) - 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_conversation_profile.SetSuggestionFeatureConfigRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, gcd_conversation_profile.SetSuggestionFeatureConfigRequest): - request = gcd_conversation_profile.SetSuggestionFeatureConfigRequest(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 participant_role is not None: - request.participant_role = participant_role - if suggestion_feature_config is not None: - request.suggestion_feature_config = suggestion_feature_config - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.set_suggestion_feature_config] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("conversation_profile", request.conversation_profile), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Wrap the response in an operation future. - response = operation.from_gapic( - response, - self._transport.operations_client, - gcd_conversation_profile.ConversationProfile, - metadata_type=gcd_conversation_profile.SetSuggestionFeatureConfigOperationMetadata, - ) - - # Done; return the response. - return response - - def clear_suggestion_feature_config(self, - request: Optional[Union[gcd_conversation_profile.ClearSuggestionFeatureConfigRequest, dict]] = None, - *, - conversation_profile: Optional[str] = None, - participant_role: Optional[participant.Participant.Role] = None, - suggestion_feature_type: Optional[gcd_conversation_profile.SuggestionFeature.Type] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation.Operation: - r"""Clears a suggestion feature from a conversation profile for the - given participant role. - - This method is a `long-running - operation `__. - The returned ``Operation`` type has the following - method-specific fields: - - - ``metadata``: - [ClearSuggestionFeatureConfigOperationMetadata][google.cloud.dialogflow.v2.ClearSuggestionFeatureConfigOperationMetadata] - - ``response``: - [ConversationProfile][google.cloud.dialogflow.v2.ConversationProfile] - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import dialogflow_v2 - - def sample_clear_suggestion_feature_config(): - # Create a client - client = dialogflow_v2.ConversationProfilesClient() - - # Initialize request argument(s) - request = dialogflow_v2.ClearSuggestionFeatureConfigRequest( - conversation_profile="conversation_profile_value", - participant_role="END_USER", - suggestion_feature_type="SMART_REPLY", - ) - - # Make the request - operation = client.clear_suggestion_feature_config(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.dialogflow_v2.types.ClearSuggestionFeatureConfigRequest, dict]): - The request object. The request message for - [ConversationProfiles.ClearFeature][]. - conversation_profile (str): - Required. The Conversation Profile to add or update the - suggestion feature config. Format: - ``projects//locations//conversationProfiles/``. - - This corresponds to the ``conversation_profile`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - participant_role (google.cloud.dialogflow_v2.types.Participant.Role): - Required. The participant role to remove the suggestion - feature config. Only HUMAN_AGENT or END_USER can be - used. - - This corresponds to the ``participant_role`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - suggestion_feature_type (google.cloud.dialogflow_v2.types.SuggestionFeature.Type): - Required. The type of the suggestion - feature to remove. - - This corresponds to the ``suggestion_feature_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. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.api_core.operation.Operation: - An object representing a long-running operation. - - The result type for the operation will be - :class:`google.cloud.dialogflow_v2.types.ConversationProfile` - Defines the services to connect to incoming Dialogflow - conversations. - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([conversation_profile, participant_role, suggestion_feature_type]) - 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_conversation_profile.ClearSuggestionFeatureConfigRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, gcd_conversation_profile.ClearSuggestionFeatureConfigRequest): - request = gcd_conversation_profile.ClearSuggestionFeatureConfigRequest(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 participant_role is not None: - request.participant_role = participant_role - if suggestion_feature_type is not None: - request.suggestion_feature_type = suggestion_feature_type - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.clear_suggestion_feature_config] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("conversation_profile", request.conversation_profile), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Wrap the response in an operation future. - response = operation.from_gapic( - response, - self._transport.operations_client, - gcd_conversation_profile.ConversationProfile, - metadata_type=gcd_conversation_profile.ClearSuggestionFeatureConfigOperationMetadata, - ) - - # Done; return the response. - return response - - def __enter__(self) -> "ConversationProfilesClient": - return self - - def __exit__(self, type, value, traceback): - """Releases underlying transport's resources. - - .. warning:: - ONLY use as a context manager if the transport is NOT shared - with other clients! Exiting the with block will CLOSE the transport - and may cause errors in other clients! - """ - self.transport.close() - - def list_operations( - self, - request: Optional[operations_pb2.ListOperationsRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operations_pb2.ListOperationsResponse: - r"""Lists operations that match the specified filter in the request. - - Args: - request (:class:`~.operations_pb2.ListOperationsRequest`): - The request object. Request message for - `ListOperations` method. - 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: - ~.operations_pb2.ListOperationsResponse: - Response message for ``ListOperations`` method. - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = operations_pb2.ListOperationsRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._transport.list_operations, - 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 = rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - def get_operation( - self, - request: Optional[operations_pb2.GetOperationRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operations_pb2.Operation: - r"""Gets the latest state of a long-running operation. - - Args: - request (:class:`~.operations_pb2.GetOperationRequest`): - The request object. Request message for - `GetOperation` method. - 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: - ~.operations_pb2.Operation: - An ``Operation`` object. - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = operations_pb2.GetOperationRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._transport.get_operation, - 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 = rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - def cancel_operation( - self, - request: Optional[operations_pb2.CancelOperationRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> None: - r"""Starts asynchronous cancellation on a long-running operation. - - The server makes a best effort to cancel the operation, but success - is not guaranteed. If the server doesn't support this method, it returns - `google.rpc.Code.UNIMPLEMENTED`. - - Args: - request (:class:`~.operations_pb2.CancelOperationRequest`): - The request object. Request message for - `CancelOperation` method. - 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: - None - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = operations_pb2.CancelOperationRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._transport.cancel_operation, - 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. - rpc(request, retry=retry, timeout=timeout, metadata=metadata,) - - def get_location( - self, - request: Optional[locations_pb2.GetLocationRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> locations_pb2.Location: - r"""Gets information about a location. - - Args: - request (:class:`~.location_pb2.GetLocationRequest`): - The request object. Request message for - `GetLocation` method. - 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: - ~.location_pb2.Location: - Location object. - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = locations_pb2.GetLocationRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._transport.get_location, - 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 = rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - def list_locations( - self, - request: Optional[locations_pb2.ListLocationsRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> locations_pb2.ListLocationsResponse: - r"""Lists information about the supported locations for this service. - - Args: - request (:class:`~.location_pb2.ListLocationsRequest`): - The request object. Request message for - `ListLocations` method. - 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: - ~.location_pb2.ListLocationsResponse: - Response message for ``ListLocations`` method. - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = locations_pb2.ListLocationsRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._transport.list_locations, - 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 = rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) - - -__all__ = ( - "ConversationProfilesClient", -) diff --git a/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/conversation_profiles/pagers.py b/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/conversation_profiles/pagers.py deleted file mode 100644 index 49bf285da..000000000 --- a/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/conversation_profiles/pagers.py +++ /dev/null @@ -1,139 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from typing import Any, AsyncIterator, Awaitable, Callable, Sequence, Tuple, Optional, Iterator - -from google.cloud.dialogflow_v2.types import conversation_profile - - -class ListConversationProfilesPager: - """A pager for iterating through ``list_conversation_profiles`` requests. - - This class thinly wraps an initial - :class:`google.cloud.dialogflow_v2.types.ListConversationProfilesResponse` object, and - provides an ``__iter__`` method to iterate through its - ``conversation_profiles`` field. - - If there are more pages, the ``__iter__`` method will make additional - ``ListConversationProfiles`` requests and continue to iterate - through the ``conversation_profiles`` field on the - corresponding responses. - - All the usual :class:`google.cloud.dialogflow_v2.types.ListConversationProfilesResponse` - 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[..., conversation_profile.ListConversationProfilesResponse], - request: conversation_profile.ListConversationProfilesRequest, - response: conversation_profile.ListConversationProfilesResponse, - *, - 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.ListConversationProfilesRequest): - The initial request object. - response (google.cloud.dialogflow_v2.types.ListConversationProfilesResponse): - 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 = conversation_profile.ListConversationProfilesRequest(request) - self._response = response - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - def pages(self) -> Iterator[conversation_profile.ListConversationProfilesResponse]: - yield self._response - while self._response.next_page_token: - self._request.page_token = self._response.next_page_token - self._response = self._method(self._request, metadata=self._metadata) - yield self._response - - def __iter__(self) -> Iterator[conversation_profile.ConversationProfile]: - for page in self.pages: - yield from page.conversation_profiles - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListConversationProfilesAsyncPager: - """A pager for iterating through ``list_conversation_profiles`` requests. - - This class thinly wraps an initial - :class:`google.cloud.dialogflow_v2.types.ListConversationProfilesResponse` object, and - provides an ``__aiter__`` method to iterate through its - ``conversation_profiles`` field. - - If there are more pages, the ``__aiter__`` method will make additional - ``ListConversationProfiles`` requests and continue to iterate - through the ``conversation_profiles`` field on the - corresponding responses. - - All the usual :class:`google.cloud.dialogflow_v2.types.ListConversationProfilesResponse` - 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[conversation_profile.ListConversationProfilesResponse]], - request: conversation_profile.ListConversationProfilesRequest, - response: conversation_profile.ListConversationProfilesResponse, - *, - metadata: Sequence[Tuple[str, str]] = ()): - """Instantiates the pager. - - Args: - method (Callable): The method that was originally called, and - which instantiated this pager. - request (google.cloud.dialogflow_v2.types.ListConversationProfilesRequest): - The initial request object. - response (google.cloud.dialogflow_v2.types.ListConversationProfilesResponse): - 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 = conversation_profile.ListConversationProfilesRequest(request) - self._response = response - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - async def pages(self) -> AsyncIterator[conversation_profile.ListConversationProfilesResponse]: - yield self._response - while self._response.next_page_token: - self._request.page_token = self._response.next_page_token - self._response = await self._method(self._request, metadata=self._metadata) - yield self._response - def __aiter__(self) -> AsyncIterator[conversation_profile.ConversationProfile]: - async def async_generator(): - async for page in self.pages: - for response in page.conversation_profiles: - yield response - - return async_generator() - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) diff --git a/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/conversation_profiles/transports/__init__.py b/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/conversation_profiles/transports/__init__.py deleted file mode 100644 index f328b6c64..000000000 --- a/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/conversation_profiles/transports/__init__.py +++ /dev/null @@ -1,38 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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 ConversationProfilesTransport -from .grpc import ConversationProfilesGrpcTransport -from .grpc_asyncio import ConversationProfilesGrpcAsyncIOTransport -from .rest import ConversationProfilesRestTransport -from .rest import ConversationProfilesRestInterceptor - - -# Compile a registry of transports. -_transport_registry = OrderedDict() # type: Dict[str, Type[ConversationProfilesTransport]] -_transport_registry['grpc'] = ConversationProfilesGrpcTransport -_transport_registry['grpc_asyncio'] = ConversationProfilesGrpcAsyncIOTransport -_transport_registry['rest'] = ConversationProfilesRestTransport - -__all__ = ( - 'ConversationProfilesTransport', - 'ConversationProfilesGrpcTransport', - 'ConversationProfilesGrpcAsyncIOTransport', - 'ConversationProfilesRestTransport', - 'ConversationProfilesRestInterceptor', -) diff --git a/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/conversation_profiles/transports/base.py b/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/conversation_profiles/transports/base.py deleted file mode 100644 index 611e0b479..000000000 --- a/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/conversation_profiles/transports/base.py +++ /dev/null @@ -1,287 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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 - -from google.cloud.dialogflow_v2 import gapic_version as package_version - -import google.auth # type: ignore -import google.api_core -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import retry as retries -from google.api_core import operations_v1 -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 conversation_profile -from google.cloud.dialogflow_v2.types import conversation_profile as gcd_conversation_profile -from google.cloud.location import locations_pb2 # type: ignore -from google.longrunning import operations_pb2 -from google.longrunning import operations_pb2 # type: ignore -from google.protobuf import empty_pb2 # type: ignore - -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) - - -class ConversationProfilesTransport(abc.ABC): - """Abstract transport class for ConversationProfiles.""" - - 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: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - api_audience: Optional[str] = None, - **kwargs, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. - scopes (Optional[Sequence[str]]): A list of scopes. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - """ - - scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} - - # Save the scopes. - self._scopes = scopes - - # If no credentials are provided, then determine the appropriate - # defaults. - if credentials and credentials_file: - raise core_exceptions.DuplicateCredentialArgs("'credentials_file' and 'credentials' are mutually exclusive") - - if credentials_file is not None: - credentials, _ = google.auth.load_credentials_from_file( - credentials_file, - **scopes_kwargs, - quota_project_id=quota_project_id - ) - elif credentials is None: - credentials, _ = google.auth.default(**scopes_kwargs, quota_project_id=quota_project_id) - # Don't apply audience if the credentials file passed from user. - if hasattr(credentials, "with_gdch_audience"): - credentials = credentials.with_gdch_audience(api_audience if api_audience else host) - - # If the credentials are service account credentials, then always try to use self signed JWT. - if always_use_jwt_access and isinstance(credentials, service_account.Credentials) and hasattr(service_account.Credentials, "with_always_use_jwt_access"): - credentials = credentials.with_always_use_jwt_access(True) - - # Save the credentials. - self._credentials = credentials - - # Save the hostname. Default to port 443 (HTTPS) if none is specified. - if ':' not in host: - host += ':443' - self._host = host - - def _prep_wrapped_messages(self, client_info): - # Precompute the wrapped methods. - self._wrapped_methods = { - self.list_conversation_profiles: gapic_v1.method.wrap_method( - self.list_conversation_profiles, - default_timeout=None, - client_info=client_info, - ), - self.get_conversation_profile: gapic_v1.method.wrap_method( - self.get_conversation_profile, - default_timeout=None, - client_info=client_info, - ), - self.create_conversation_profile: gapic_v1.method.wrap_method( - self.create_conversation_profile, - default_timeout=None, - client_info=client_info, - ), - self.update_conversation_profile: gapic_v1.method.wrap_method( - self.update_conversation_profile, - default_timeout=None, - client_info=client_info, - ), - self.delete_conversation_profile: gapic_v1.method.wrap_method( - self.delete_conversation_profile, - default_timeout=None, - client_info=client_info, - ), - self.set_suggestion_feature_config: gapic_v1.method.wrap_method( - self.set_suggestion_feature_config, - default_timeout=None, - client_info=client_info, - ), - self.clear_suggestion_feature_config: gapic_v1.method.wrap_method( - self.clear_suggestion_feature_config, - default_timeout=None, - client_info=client_info, - ), - } - - def close(self): - """Closes resources associated with the transport. - - .. warning:: - Only call this method if the transport is NOT shared - with other clients - this may cause errors in other clients! - """ - raise NotImplementedError() - - @property - def operations_client(self): - """Return the client designed to process long-running operations.""" - raise NotImplementedError() - - @property - def list_conversation_profiles(self) -> Callable[ - [conversation_profile.ListConversationProfilesRequest], - Union[ - conversation_profile.ListConversationProfilesResponse, - Awaitable[conversation_profile.ListConversationProfilesResponse] - ]]: - raise NotImplementedError() - - @property - def get_conversation_profile(self) -> Callable[ - [conversation_profile.GetConversationProfileRequest], - Union[ - conversation_profile.ConversationProfile, - Awaitable[conversation_profile.ConversationProfile] - ]]: - raise NotImplementedError() - - @property - def create_conversation_profile(self) -> Callable[ - [gcd_conversation_profile.CreateConversationProfileRequest], - Union[ - gcd_conversation_profile.ConversationProfile, - Awaitable[gcd_conversation_profile.ConversationProfile] - ]]: - raise NotImplementedError() - - @property - def update_conversation_profile(self) -> Callable[ - [gcd_conversation_profile.UpdateConversationProfileRequest], - Union[ - gcd_conversation_profile.ConversationProfile, - Awaitable[gcd_conversation_profile.ConversationProfile] - ]]: - raise NotImplementedError() - - @property - def delete_conversation_profile(self) -> Callable[ - [conversation_profile.DeleteConversationProfileRequest], - Union[ - empty_pb2.Empty, - Awaitable[empty_pb2.Empty] - ]]: - raise NotImplementedError() - - @property - def set_suggestion_feature_config(self) -> Callable[ - [gcd_conversation_profile.SetSuggestionFeatureConfigRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: - raise NotImplementedError() - - @property - def clear_suggestion_feature_config(self) -> Callable[ - [gcd_conversation_profile.ClearSuggestionFeatureConfigRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: - raise NotImplementedError() - - @property - def list_operations( - self, - ) -> Callable[ - [operations_pb2.ListOperationsRequest], - Union[operations_pb2.ListOperationsResponse, Awaitable[operations_pb2.ListOperationsResponse]], - ]: - raise NotImplementedError() - - @property - def get_operation( - self, - ) -> Callable[ - [operations_pb2.GetOperationRequest], - Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], - ]: - raise NotImplementedError() - - @property - def cancel_operation( - self, - ) -> Callable[ - [operations_pb2.CancelOperationRequest], - None, - ]: - raise NotImplementedError() - - @property - def get_location(self, - ) -> Callable[ - [locations_pb2.GetLocationRequest], - Union[locations_pb2.Location, Awaitable[locations_pb2.Location]], - ]: - raise NotImplementedError() - - @property - def list_locations(self, - ) -> Callable[ - [locations_pb2.ListLocationsRequest], - Union[locations_pb2.ListLocationsResponse, Awaitable[locations_pb2.ListLocationsResponse]], - ]: - raise NotImplementedError() - - @property - def kind(self) -> str: - raise NotImplementedError() - - -__all__ = ( - 'ConversationProfilesTransport', -) diff --git a/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/conversation_profiles/transports/grpc.py b/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/conversation_profiles/transports/grpc.py deleted file mode 100644 index 5b9d4d4a0..000000000 --- a/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/conversation_profiles/transports/grpc.py +++ /dev/null @@ -1,578 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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 -from google.api_core import operations_v1 -from google.api_core import gapic_v1 -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_profile -from google.cloud.dialogflow_v2.types import conversation_profile as gcd_conversation_profile -from google.cloud.location import locations_pb2 # type: ignore -from google.longrunning import operations_pb2 -from google.longrunning import operations_pb2 # type: ignore -from google.protobuf import empty_pb2 # type: ignore -from .base import ConversationProfilesTransport, DEFAULT_CLIENT_INFO - - -class ConversationProfilesGrpcTransport(ConversationProfilesTransport): - """gRPC backend transport for ConversationProfiles. - - Service for managing - [ConversationProfiles][google.cloud.dialogflow.v2.ConversationProfile]. - - 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: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - channel: Optional[grpc.Channel] = None, - api_mtls_endpoint: Optional[str] = None, - client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, - ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, - client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - api_audience: Optional[str] = None, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - This argument is ignored if ``channel`` is provided. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional(Sequence[str])): A list of scopes. This argument is - ignored if ``channel`` is provided. - channel (Optional[grpc.Channel]): A ``Channel`` instance through - which to make calls. - api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. - If provided, it overrides the ``host`` argument and tries to create - a mutual TLS channel with client SSL credentials from - ``client_cert_source`` or application default SSL credentials. - client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): - Deprecated. A callback to provide client SSL certificate bytes and - private key bytes, both in PEM format. It is ignored if - ``api_mtls_endpoint`` is None. - ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials - for the grpc channel. It is ignored if ``channel`` is provided. - client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): - A callback to provide client certificate bytes and private key bytes, - both in PEM format. It is used to configure a mutual TLS channel. It is - ignored if ``channel`` or ``ssl_channel_credentials`` is provided. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport - creation failed for any reason. - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - self._grpc_channel = None - self._ssl_channel_credentials = ssl_channel_credentials - self._stubs: Dict[str, Callable] = {} - self._operations_client: Optional[operations_v1.OperationsClient] = None - - if api_mtls_endpoint: - warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) - if client_cert_source: - warnings.warn("client_cert_source is deprecated", DeprecationWarning) - - if channel: - # Ignore credentials if a channel was passed. - credentials = False - # If a channel was explicitly provided, set it. - self._grpc_channel = channel - self._ssl_channel_credentials = None - - else: - if api_mtls_endpoint: - host = api_mtls_endpoint - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - self._ssl_channel_credentials = SslCredentials().ssl_credentials - - else: - if client_cert_source_for_mtls and not ssl_channel_credentials: - cert, key = client_cert_source_for_mtls() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - - # The base transport sets the host, credentials and scopes - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes, - quota_project_id=quota_project_id, - client_info=client_info, - always_use_jwt_access=always_use_jwt_access, - api_audience=api_audience, - ) - - if not self._grpc_channel: - self._grpc_channel = type(self).create_channel( - self._host, - # use the credentials which are saved - credentials=self._credentials, - # Set ``credentials_file`` to ``None`` here as - # the credentials that we saved earlier should be used. - credentials_file=None, - 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: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - **kwargs) -> grpc.Channel: - """Create and return a gRPC channel object. - Args: - host (Optional[str]): The host for the channel to use. - credentials (Optional[~.Credentials]): The - authorization credentials to attach to requests. These - credentials identify this application to the service. If - none are specified, the client will attempt to ascertain - the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - kwargs (Optional[dict]): Keyword arguments, which are passed to the - channel creation. - Returns: - grpc.Channel: A gRPC channel object. - - Raises: - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - - return grpc_helpers.create_channel( - host, - credentials=credentials, - credentials_file=credentials_file, - quota_project_id=quota_project_id, - default_scopes=cls.AUTH_SCOPES, - scopes=scopes, - default_host=cls.DEFAULT_HOST, - **kwargs - ) - - @property - def grpc_channel(self) -> grpc.Channel: - """Return the channel designed to connect to this service. - """ - return self._grpc_channel - - @property - def operations_client(self) -> operations_v1.OperationsClient: - """Create the client designed to process long-running operations. - - This property caches on the instance; repeated calls return the same - client. - """ - # Quick check: Only create a new client if we do not already have one. - if self._operations_client is None: - self._operations_client = operations_v1.OperationsClient( - self.grpc_channel - ) - - # Return the client from cache. - return self._operations_client - - @property - def list_conversation_profiles(self) -> Callable[ - [conversation_profile.ListConversationProfilesRequest], - conversation_profile.ListConversationProfilesResponse]: - r"""Return a callable for the list conversation profiles method over gRPC. - - Returns the list of all conversation profiles in the - specified project. - - Returns: - Callable[[~.ListConversationProfilesRequest], - ~.ListConversationProfilesResponse]: - 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_conversation_profiles' not in self._stubs: - self._stubs['list_conversation_profiles'] = self.grpc_channel.unary_unary( - '/google.cloud.dialogflow.v2.ConversationProfiles/ListConversationProfiles', - request_serializer=conversation_profile.ListConversationProfilesRequest.serialize, - response_deserializer=conversation_profile.ListConversationProfilesResponse.deserialize, - ) - return self._stubs['list_conversation_profiles'] - - @property - def get_conversation_profile(self) -> Callable[ - [conversation_profile.GetConversationProfileRequest], - conversation_profile.ConversationProfile]: - r"""Return a callable for the get conversation profile method over gRPC. - - Retrieves the specified conversation profile. - - Returns: - Callable[[~.GetConversationProfileRequest], - ~.ConversationProfile]: - 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_conversation_profile' not in self._stubs: - self._stubs['get_conversation_profile'] = self.grpc_channel.unary_unary( - '/google.cloud.dialogflow.v2.ConversationProfiles/GetConversationProfile', - request_serializer=conversation_profile.GetConversationProfileRequest.serialize, - response_deserializer=conversation_profile.ConversationProfile.deserialize, - ) - return self._stubs['get_conversation_profile'] - - @property - def create_conversation_profile(self) -> Callable[ - [gcd_conversation_profile.CreateConversationProfileRequest], - gcd_conversation_profile.ConversationProfile]: - r"""Return a callable for the create conversation profile method over gRPC. - - Creates a conversation profile in the specified project. - - [ConversationProfile.CreateTime][] and - [ConversationProfile.UpdateTime][] aren't populated in the - response. You can retrieve them via - [GetConversationProfile][google.cloud.dialogflow.v2.ConversationProfiles.GetConversationProfile] - API. - - Returns: - Callable[[~.CreateConversationProfileRequest], - ~.ConversationProfile]: - 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_conversation_profile' not in self._stubs: - self._stubs['create_conversation_profile'] = self.grpc_channel.unary_unary( - '/google.cloud.dialogflow.v2.ConversationProfiles/CreateConversationProfile', - request_serializer=gcd_conversation_profile.CreateConversationProfileRequest.serialize, - response_deserializer=gcd_conversation_profile.ConversationProfile.deserialize, - ) - return self._stubs['create_conversation_profile'] - - @property - def update_conversation_profile(self) -> Callable[ - [gcd_conversation_profile.UpdateConversationProfileRequest], - gcd_conversation_profile.ConversationProfile]: - r"""Return a callable for the update conversation profile method over gRPC. - - Updates the specified conversation profile. - - [ConversationProfile.CreateTime][] and - [ConversationProfile.UpdateTime][] aren't populated in the - response. You can retrieve them via - [GetConversationProfile][google.cloud.dialogflow.v2.ConversationProfiles.GetConversationProfile] - API. - - Returns: - Callable[[~.UpdateConversationProfileRequest], - ~.ConversationProfile]: - 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_conversation_profile' not in self._stubs: - self._stubs['update_conversation_profile'] = self.grpc_channel.unary_unary( - '/google.cloud.dialogflow.v2.ConversationProfiles/UpdateConversationProfile', - request_serializer=gcd_conversation_profile.UpdateConversationProfileRequest.serialize, - response_deserializer=gcd_conversation_profile.ConversationProfile.deserialize, - ) - return self._stubs['update_conversation_profile'] - - @property - def delete_conversation_profile(self) -> Callable[ - [conversation_profile.DeleteConversationProfileRequest], - empty_pb2.Empty]: - r"""Return a callable for the delete conversation profile method over gRPC. - - Deletes the specified conversation profile. - - Returns: - Callable[[~.DeleteConversationProfileRequest], - ~.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_conversation_profile' not in self._stubs: - 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_pb2.Empty.FromString, - ) - return self._stubs['delete_conversation_profile'] - - @property - def set_suggestion_feature_config(self) -> Callable[ - [gcd_conversation_profile.SetSuggestionFeatureConfigRequest], - operations_pb2.Operation]: - r"""Return a callable for the set suggestion feature config method over gRPC. - - Adds or updates a suggestion feature in a conversation profile. - If the conversation profile contains the type of suggestion - feature for the participant role, it will update it. Otherwise - it will insert the suggestion feature. - - This method is a `long-running - operation `__. - The returned ``Operation`` type has the following - method-specific fields: - - - ``metadata``: - [SetSuggestionFeatureConfigOperationMetadata][google.cloud.dialogflow.v2.SetSuggestionFeatureConfigOperationMetadata] - - ``response``: - [ConversationProfile][google.cloud.dialogflow.v2.ConversationProfile] - - If a long running operation to add or update suggestion feature - config for the same conversation profile, participant role and - suggestion feature type exists, please cancel the existing long - running operation before sending such request, otherwise the - request will be rejected. - - Returns: - Callable[[~.SetSuggestionFeatureConfigRequest], - ~.Operation]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'set_suggestion_feature_config' not in self._stubs: - self._stubs['set_suggestion_feature_config'] = self.grpc_channel.unary_unary( - '/google.cloud.dialogflow.v2.ConversationProfiles/SetSuggestionFeatureConfig', - request_serializer=gcd_conversation_profile.SetSuggestionFeatureConfigRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['set_suggestion_feature_config'] - - @property - def clear_suggestion_feature_config(self) -> Callable[ - [gcd_conversation_profile.ClearSuggestionFeatureConfigRequest], - operations_pb2.Operation]: - r"""Return a callable for the clear suggestion feature - config method over gRPC. - - Clears a suggestion feature from a conversation profile for the - given participant role. - - This method is a `long-running - operation `__. - The returned ``Operation`` type has the following - method-specific fields: - - - ``metadata``: - [ClearSuggestionFeatureConfigOperationMetadata][google.cloud.dialogflow.v2.ClearSuggestionFeatureConfigOperationMetadata] - - ``response``: - [ConversationProfile][google.cloud.dialogflow.v2.ConversationProfile] - - Returns: - Callable[[~.ClearSuggestionFeatureConfigRequest], - ~.Operation]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'clear_suggestion_feature_config' not in self._stubs: - self._stubs['clear_suggestion_feature_config'] = self.grpc_channel.unary_unary( - '/google.cloud.dialogflow.v2.ConversationProfiles/ClearSuggestionFeatureConfig', - request_serializer=gcd_conversation_profile.ClearSuggestionFeatureConfigRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['clear_suggestion_feature_config'] - - def close(self): - self.grpc_channel.close() - - @property - def cancel_operation( - self, - ) -> Callable[[operations_pb2.CancelOperationRequest], None]: - r"""Return a callable for the cancel_operation method over gRPC. - """ - # 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 "cancel_operation" not in self._stubs: - self._stubs["cancel_operation"] = self.grpc_channel.unary_unary( - "/google.longrunning.Operations/CancelOperation", - request_serializer=operations_pb2.CancelOperationRequest.SerializeToString, - response_deserializer=None, - ) - return self._stubs["cancel_operation"] - - @property - def get_operation( - self, - ) -> Callable[[operations_pb2.GetOperationRequest], operations_pb2.Operation]: - r"""Return a callable for the get_operation method over gRPC. - """ - # 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_operation" not in self._stubs: - self._stubs["get_operation"] = self.grpc_channel.unary_unary( - "/google.longrunning.Operations/GetOperation", - request_serializer=operations_pb2.GetOperationRequest.SerializeToString, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs["get_operation"] - - @property - def list_operations( - self, - ) -> Callable[[operations_pb2.ListOperationsRequest], operations_pb2.ListOperationsResponse]: - r"""Return a callable for the list_operations method over gRPC. - """ - # 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_operations" not in self._stubs: - self._stubs["list_operations"] = self.grpc_channel.unary_unary( - "/google.longrunning.Operations/ListOperations", - request_serializer=operations_pb2.ListOperationsRequest.SerializeToString, - response_deserializer=operations_pb2.ListOperationsResponse.FromString, - ) - return self._stubs["list_operations"] - - @property - def list_locations( - self, - ) -> Callable[[locations_pb2.ListLocationsRequest], locations_pb2.ListLocationsResponse]: - r"""Return a callable for the list locations method over gRPC. - """ - # 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_locations" not in self._stubs: - self._stubs["list_locations"] = self.grpc_channel.unary_unary( - "/google.cloud.location.Locations/ListLocations", - request_serializer=locations_pb2.ListLocationsRequest.SerializeToString, - response_deserializer=locations_pb2.ListLocationsResponse.FromString, - ) - return self._stubs["list_locations"] - - @property - def get_location( - self, - ) -> Callable[[locations_pb2.GetLocationRequest], locations_pb2.Location]: - r"""Return a callable for the list locations method over gRPC. - """ - # 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_location" not in self._stubs: - self._stubs["get_location"] = self.grpc_channel.unary_unary( - "/google.cloud.location.Locations/GetLocation", - request_serializer=locations_pb2.GetLocationRequest.SerializeToString, - response_deserializer=locations_pb2.Location.FromString, - ) - return self._stubs["get_location"] - - @property - def kind(self) -> str: - return "grpc" - - -__all__ = ( - 'ConversationProfilesGrpcTransport', -) diff --git a/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/conversation_profiles/transports/grpc_asyncio.py b/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/conversation_profiles/transports/grpc_asyncio.py deleted file mode 100644 index a0c4c819e..000000000 --- a/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/conversation_profiles/transports/grpc_asyncio.py +++ /dev/null @@ -1,577 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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 -from google.api_core import grpc_helpers_async -from google.api_core import operations_v1 -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore - -import grpc # type: ignore -from grpc.experimental import aio # type: ignore - -from google.cloud.dialogflow_v2.types import conversation_profile -from google.cloud.dialogflow_v2.types import conversation_profile as gcd_conversation_profile -from google.cloud.location import locations_pb2 # type: ignore -from google.longrunning import operations_pb2 -from google.longrunning import operations_pb2 # type: ignore -from google.protobuf import empty_pb2 # type: ignore -from .base import ConversationProfilesTransport, DEFAULT_CLIENT_INFO -from .grpc import ConversationProfilesGrpcTransport - - -class ConversationProfilesGrpcAsyncIOTransport(ConversationProfilesTransport): - """gRPC AsyncIO backend transport for ConversationProfiles. - - Service for managing - [ConversationProfiles][google.cloud.dialogflow.v2.ConversationProfile]. - - 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: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - **kwargs) -> aio.Channel: - """Create and return a gRPC AsyncIO channel object. - Args: - host (Optional[str]): The host for the channel to use. - credentials (Optional[~.Credentials]): The - authorization credentials to attach to requests. These - credentials identify this application to the service. If - none are specified, the client will attempt to ascertain - the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - kwargs (Optional[dict]): Keyword arguments, which are passed to the - channel creation. - Returns: - aio.Channel: A gRPC AsyncIO channel object. - """ - - return grpc_helpers_async.create_channel( - host, - credentials=credentials, - credentials_file=credentials_file, - quota_project_id=quota_project_id, - default_scopes=cls.AUTH_SCOPES, - scopes=scopes, - default_host=cls.DEFAULT_HOST, - **kwargs - ) - - def __init__(self, *, - host: str = 'dialogflow.googleapis.com', - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - channel: Optional[aio.Channel] = None, - api_mtls_endpoint: Optional[str] = None, - client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, - ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, - client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - api_audience: Optional[str] = None, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - This argument is ignored if ``channel`` is provided. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - channel (Optional[aio.Channel]): A ``Channel`` instance through - which to make calls. - api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. - If provided, it overrides the ``host`` argument and tries to create - a mutual TLS channel with client SSL credentials from - ``client_cert_source`` or application default SSL credentials. - client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): - Deprecated. A callback to provide client SSL certificate bytes and - private key bytes, both in PEM format. It is ignored if - ``api_mtls_endpoint`` is None. - ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials - for the grpc channel. It is ignored if ``channel`` is provided. - client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): - A callback to provide client certificate bytes and private key bytes, - both in PEM format. It is used to configure a mutual TLS channel. It is - ignored if ``channel`` or ``ssl_channel_credentials`` is provided. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - - Raises: - google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport - creation failed for any reason. - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - self._grpc_channel = None - self._ssl_channel_credentials = ssl_channel_credentials - self._stubs: Dict[str, Callable] = {} - self._operations_client: Optional[operations_v1.OperationsAsyncClient] = None - - if api_mtls_endpoint: - warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) - if client_cert_source: - warnings.warn("client_cert_source is deprecated", DeprecationWarning) - - if channel: - # Ignore credentials if a channel was passed. - credentials = False - # If a channel was explicitly provided, set it. - self._grpc_channel = channel - self._ssl_channel_credentials = None - else: - if api_mtls_endpoint: - host = api_mtls_endpoint - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - self._ssl_channel_credentials = SslCredentials().ssl_credentials - - else: - if client_cert_source_for_mtls and not ssl_channel_credentials: - cert, key = client_cert_source_for_mtls() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - - # The base transport sets the host, credentials and scopes - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes, - quota_project_id=quota_project_id, - client_info=client_info, - always_use_jwt_access=always_use_jwt_access, - api_audience=api_audience, - ) - - if not self._grpc_channel: - self._grpc_channel = type(self).create_channel( - self._host, - # use the credentials which are saved - credentials=self._credentials, - # Set ``credentials_file`` to ``None`` here as - # the credentials that we saved earlier should be used. - credentials_file=None, - 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 operations_client(self) -> operations_v1.OperationsAsyncClient: - """Create the client designed to process long-running operations. - - This property caches on the instance; repeated calls return the same - client. - """ - # Quick check: Only create a new client if we do not already have one. - if self._operations_client is None: - self._operations_client = operations_v1.OperationsAsyncClient( - self.grpc_channel - ) - - # Return the client from cache. - return self._operations_client - - @property - def list_conversation_profiles(self) -> Callable[ - [conversation_profile.ListConversationProfilesRequest], - Awaitable[conversation_profile.ListConversationProfilesResponse]]: - r"""Return a callable for the list conversation profiles method over gRPC. - - Returns the list of all conversation profiles in the - specified project. - - Returns: - Callable[[~.ListConversationProfilesRequest], - Awaitable[~.ListConversationProfilesResponse]]: - 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_conversation_profiles' not in self._stubs: - self._stubs['list_conversation_profiles'] = self.grpc_channel.unary_unary( - '/google.cloud.dialogflow.v2.ConversationProfiles/ListConversationProfiles', - request_serializer=conversation_profile.ListConversationProfilesRequest.serialize, - response_deserializer=conversation_profile.ListConversationProfilesResponse.deserialize, - ) - return self._stubs['list_conversation_profiles'] - - @property - def get_conversation_profile(self) -> Callable[ - [conversation_profile.GetConversationProfileRequest], - Awaitable[conversation_profile.ConversationProfile]]: - r"""Return a callable for the get conversation profile method over gRPC. - - Retrieves the specified conversation profile. - - Returns: - Callable[[~.GetConversationProfileRequest], - Awaitable[~.ConversationProfile]]: - 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_conversation_profile' not in self._stubs: - self._stubs['get_conversation_profile'] = self.grpc_channel.unary_unary( - '/google.cloud.dialogflow.v2.ConversationProfiles/GetConversationProfile', - request_serializer=conversation_profile.GetConversationProfileRequest.serialize, - response_deserializer=conversation_profile.ConversationProfile.deserialize, - ) - return self._stubs['get_conversation_profile'] - - @property - def create_conversation_profile(self) -> Callable[ - [gcd_conversation_profile.CreateConversationProfileRequest], - Awaitable[gcd_conversation_profile.ConversationProfile]]: - r"""Return a callable for the create conversation profile method over gRPC. - - Creates a conversation profile in the specified project. - - [ConversationProfile.CreateTime][] and - [ConversationProfile.UpdateTime][] aren't populated in the - response. You can retrieve them via - [GetConversationProfile][google.cloud.dialogflow.v2.ConversationProfiles.GetConversationProfile] - API. - - Returns: - Callable[[~.CreateConversationProfileRequest], - Awaitable[~.ConversationProfile]]: - 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_conversation_profile' not in self._stubs: - self._stubs['create_conversation_profile'] = self.grpc_channel.unary_unary( - '/google.cloud.dialogflow.v2.ConversationProfiles/CreateConversationProfile', - request_serializer=gcd_conversation_profile.CreateConversationProfileRequest.serialize, - response_deserializer=gcd_conversation_profile.ConversationProfile.deserialize, - ) - return self._stubs['create_conversation_profile'] - - @property - def update_conversation_profile(self) -> Callable[ - [gcd_conversation_profile.UpdateConversationProfileRequest], - Awaitable[gcd_conversation_profile.ConversationProfile]]: - r"""Return a callable for the update conversation profile method over gRPC. - - Updates the specified conversation profile. - - [ConversationProfile.CreateTime][] and - [ConversationProfile.UpdateTime][] aren't populated in the - response. You can retrieve them via - [GetConversationProfile][google.cloud.dialogflow.v2.ConversationProfiles.GetConversationProfile] - API. - - Returns: - Callable[[~.UpdateConversationProfileRequest], - Awaitable[~.ConversationProfile]]: - 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_conversation_profile' not in self._stubs: - self._stubs['update_conversation_profile'] = self.grpc_channel.unary_unary( - '/google.cloud.dialogflow.v2.ConversationProfiles/UpdateConversationProfile', - request_serializer=gcd_conversation_profile.UpdateConversationProfileRequest.serialize, - response_deserializer=gcd_conversation_profile.ConversationProfile.deserialize, - ) - return self._stubs['update_conversation_profile'] - - @property - def delete_conversation_profile(self) -> Callable[ - [conversation_profile.DeleteConversationProfileRequest], - Awaitable[empty_pb2.Empty]]: - r"""Return a callable for the delete conversation profile method over gRPC. - - Deletes the specified conversation profile. - - Returns: - Callable[[~.DeleteConversationProfileRequest], - 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_conversation_profile' not in self._stubs: - 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_pb2.Empty.FromString, - ) - return self._stubs['delete_conversation_profile'] - - @property - def set_suggestion_feature_config(self) -> Callable[ - [gcd_conversation_profile.SetSuggestionFeatureConfigRequest], - Awaitable[operations_pb2.Operation]]: - r"""Return a callable for the set suggestion feature config method over gRPC. - - Adds or updates a suggestion feature in a conversation profile. - If the conversation profile contains the type of suggestion - feature for the participant role, it will update it. Otherwise - it will insert the suggestion feature. - - This method is a `long-running - operation `__. - The returned ``Operation`` type has the following - method-specific fields: - - - ``metadata``: - [SetSuggestionFeatureConfigOperationMetadata][google.cloud.dialogflow.v2.SetSuggestionFeatureConfigOperationMetadata] - - ``response``: - [ConversationProfile][google.cloud.dialogflow.v2.ConversationProfile] - - If a long running operation to add or update suggestion feature - config for the same conversation profile, participant role and - suggestion feature type exists, please cancel the existing long - running operation before sending such request, otherwise the - request will be rejected. - - Returns: - Callable[[~.SetSuggestionFeatureConfigRequest], - Awaitable[~.Operation]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'set_suggestion_feature_config' not in self._stubs: - self._stubs['set_suggestion_feature_config'] = self.grpc_channel.unary_unary( - '/google.cloud.dialogflow.v2.ConversationProfiles/SetSuggestionFeatureConfig', - request_serializer=gcd_conversation_profile.SetSuggestionFeatureConfigRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['set_suggestion_feature_config'] - - @property - def clear_suggestion_feature_config(self) -> Callable[ - [gcd_conversation_profile.ClearSuggestionFeatureConfigRequest], - Awaitable[operations_pb2.Operation]]: - r"""Return a callable for the clear suggestion feature - config method over gRPC. - - Clears a suggestion feature from a conversation profile for the - given participant role. - - This method is a `long-running - operation `__. - The returned ``Operation`` type has the following - method-specific fields: - - - ``metadata``: - [ClearSuggestionFeatureConfigOperationMetadata][google.cloud.dialogflow.v2.ClearSuggestionFeatureConfigOperationMetadata] - - ``response``: - [ConversationProfile][google.cloud.dialogflow.v2.ConversationProfile] - - Returns: - Callable[[~.ClearSuggestionFeatureConfigRequest], - Awaitable[~.Operation]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'clear_suggestion_feature_config' not in self._stubs: - self._stubs['clear_suggestion_feature_config'] = self.grpc_channel.unary_unary( - '/google.cloud.dialogflow.v2.ConversationProfiles/ClearSuggestionFeatureConfig', - request_serializer=gcd_conversation_profile.ClearSuggestionFeatureConfigRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['clear_suggestion_feature_config'] - - def close(self): - return self.grpc_channel.close() - - @property - def cancel_operation( - self, - ) -> Callable[[operations_pb2.CancelOperationRequest], None]: - r"""Return a callable for the cancel_operation method over gRPC. - """ - # 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 "cancel_operation" not in self._stubs: - self._stubs["cancel_operation"] = self.grpc_channel.unary_unary( - "/google.longrunning.Operations/CancelOperation", - request_serializer=operations_pb2.CancelOperationRequest.SerializeToString, - response_deserializer=None, - ) - return self._stubs["cancel_operation"] - - @property - def get_operation( - self, - ) -> Callable[[operations_pb2.GetOperationRequest], operations_pb2.Operation]: - r"""Return a callable for the get_operation method over gRPC. - """ - # 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_operation" not in self._stubs: - self._stubs["get_operation"] = self.grpc_channel.unary_unary( - "/google.longrunning.Operations/GetOperation", - request_serializer=operations_pb2.GetOperationRequest.SerializeToString, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs["get_operation"] - - @property - def list_operations( - self, - ) -> Callable[[operations_pb2.ListOperationsRequest], operations_pb2.ListOperationsResponse]: - r"""Return a callable for the list_operations method over gRPC. - """ - # 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_operations" not in self._stubs: - self._stubs["list_operations"] = self.grpc_channel.unary_unary( - "/google.longrunning.Operations/ListOperations", - request_serializer=operations_pb2.ListOperationsRequest.SerializeToString, - response_deserializer=operations_pb2.ListOperationsResponse.FromString, - ) - return self._stubs["list_operations"] - - @property - def list_locations( - self, - ) -> Callable[[locations_pb2.ListLocationsRequest], locations_pb2.ListLocationsResponse]: - r"""Return a callable for the list locations method over gRPC. - """ - # 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_locations" not in self._stubs: - self._stubs["list_locations"] = self.grpc_channel.unary_unary( - "/google.cloud.location.Locations/ListLocations", - request_serializer=locations_pb2.ListLocationsRequest.SerializeToString, - response_deserializer=locations_pb2.ListLocationsResponse.FromString, - ) - return self._stubs["list_locations"] - - @property - def get_location( - self, - ) -> Callable[[locations_pb2.GetLocationRequest], locations_pb2.Location]: - r"""Return a callable for the list locations method over gRPC. - """ - # 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_location" not in self._stubs: - self._stubs["get_location"] = self.grpc_channel.unary_unary( - "/google.cloud.location.Locations/GetLocation", - request_serializer=locations_pb2.GetLocationRequest.SerializeToString, - response_deserializer=locations_pb2.Location.FromString, - ) - return self._stubs["get_location"] - - -__all__ = ( - 'ConversationProfilesGrpcAsyncIOTransport', -) diff --git a/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/conversation_profiles/transports/rest.py b/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/conversation_profiles/transports/rest.py deleted file mode 100644 index 483ea08fc..000000000 --- a/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/conversation_profiles/transports/rest.py +++ /dev/null @@ -1,1513 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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 google.auth.transport.requests import AuthorizedSession # type: ignore -import json # type: ignore -import grpc # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore -from google.auth import credentials as ga_credentials # type: ignore -from google.api_core import exceptions as core_exceptions -from google.api_core import retry as retries -from google.api_core import rest_helpers -from google.api_core import rest_streaming -from google.api_core import path_template -from google.api_core import gapic_v1 - -from google.protobuf import json_format -from google.api_core import operations_v1 -from google.cloud.location import locations_pb2 # type: ignore -from google.longrunning import operations_pb2 -from requests import __version__ as requests_version -import dataclasses -import re -from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union -import warnings - -try: - OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] -except AttributeError: # pragma: NO COVER - OptionalRetry = Union[retries.Retry, object] # 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.longrunning import operations_pb2 # type: ignore -from google.protobuf import empty_pb2 # type: ignore - -from .base import ConversationProfilesTransport, DEFAULT_CLIENT_INFO as BASE_DEFAULT_CLIENT_INFO - - -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=BASE_DEFAULT_CLIENT_INFO.gapic_version, - grpc_version=None, - rest_version=requests_version, -) - - -class ConversationProfilesRestInterceptor: - """Interceptor for ConversationProfiles. - - Interceptors are used to manipulate requests, request metadata, and responses - in arbitrary ways. - Example use cases include: - * Logging - * Verifying requests according to service or custom semantics - * Stripping extraneous information from responses - - These use cases and more can be enabled by injecting an - instance of a custom subclass when constructing the ConversationProfilesRestTransport. - - .. code-block:: python - class MyCustomConversationProfilesInterceptor(ConversationProfilesRestInterceptor): - def pre_clear_suggestion_feature_config(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_clear_suggestion_feature_config(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_create_conversation_profile(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_create_conversation_profile(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_delete_conversation_profile(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def pre_get_conversation_profile(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_get_conversation_profile(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_list_conversation_profiles(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_list_conversation_profiles(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_set_suggestion_feature_config(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_set_suggestion_feature_config(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_update_conversation_profile(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_update_conversation_profile(self, response): - logging.log(f"Received response: {response}") - return response - - transport = ConversationProfilesRestTransport(interceptor=MyCustomConversationProfilesInterceptor()) - client = ConversationProfilesClient(transport=transport) - - - """ - def pre_clear_suggestion_feature_config(self, request: gcd_conversation_profile.ClearSuggestionFeatureConfigRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[gcd_conversation_profile.ClearSuggestionFeatureConfigRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for clear_suggestion_feature_config - - Override in a subclass to manipulate the request or metadata - before they are sent to the ConversationProfiles server. - """ - return request, metadata - - def post_clear_suggestion_feature_config(self, response: operations_pb2.Operation) -> operations_pb2.Operation: - """Post-rpc interceptor for clear_suggestion_feature_config - - Override in a subclass to manipulate the response - after it is returned by the ConversationProfiles server but before - it is returned to user code. - """ - return response - def pre_create_conversation_profile(self, request: gcd_conversation_profile.CreateConversationProfileRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[gcd_conversation_profile.CreateConversationProfileRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for create_conversation_profile - - Override in a subclass to manipulate the request or metadata - before they are sent to the ConversationProfiles server. - """ - return request, metadata - - def post_create_conversation_profile(self, response: gcd_conversation_profile.ConversationProfile) -> gcd_conversation_profile.ConversationProfile: - """Post-rpc interceptor for create_conversation_profile - - Override in a subclass to manipulate the response - after it is returned by the ConversationProfiles server but before - it is returned to user code. - """ - return response - def pre_delete_conversation_profile(self, request: conversation_profile.DeleteConversationProfileRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[conversation_profile.DeleteConversationProfileRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for delete_conversation_profile - - Override in a subclass to manipulate the request or metadata - before they are sent to the ConversationProfiles server. - """ - return request, metadata - - def pre_get_conversation_profile(self, request: conversation_profile.GetConversationProfileRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[conversation_profile.GetConversationProfileRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for get_conversation_profile - - Override in a subclass to manipulate the request or metadata - before they are sent to the ConversationProfiles server. - """ - return request, metadata - - def post_get_conversation_profile(self, response: conversation_profile.ConversationProfile) -> conversation_profile.ConversationProfile: - """Post-rpc interceptor for get_conversation_profile - - Override in a subclass to manipulate the response - after it is returned by the ConversationProfiles server but before - it is returned to user code. - """ - return response - def pre_list_conversation_profiles(self, request: conversation_profile.ListConversationProfilesRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[conversation_profile.ListConversationProfilesRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for list_conversation_profiles - - Override in a subclass to manipulate the request or metadata - before they are sent to the ConversationProfiles server. - """ - return request, metadata - - def post_list_conversation_profiles(self, response: conversation_profile.ListConversationProfilesResponse) -> conversation_profile.ListConversationProfilesResponse: - """Post-rpc interceptor for list_conversation_profiles - - Override in a subclass to manipulate the response - after it is returned by the ConversationProfiles server but before - it is returned to user code. - """ - return response - def pre_set_suggestion_feature_config(self, request: gcd_conversation_profile.SetSuggestionFeatureConfigRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[gcd_conversation_profile.SetSuggestionFeatureConfigRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for set_suggestion_feature_config - - Override in a subclass to manipulate the request or metadata - before they are sent to the ConversationProfiles server. - """ - return request, metadata - - def post_set_suggestion_feature_config(self, response: operations_pb2.Operation) -> operations_pb2.Operation: - """Post-rpc interceptor for set_suggestion_feature_config - - Override in a subclass to manipulate the response - after it is returned by the ConversationProfiles server but before - it is returned to user code. - """ - return response - def pre_update_conversation_profile(self, request: gcd_conversation_profile.UpdateConversationProfileRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[gcd_conversation_profile.UpdateConversationProfileRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for update_conversation_profile - - Override in a subclass to manipulate the request or metadata - before they are sent to the ConversationProfiles server. - """ - return request, metadata - - def post_update_conversation_profile(self, response: gcd_conversation_profile.ConversationProfile) -> gcd_conversation_profile.ConversationProfile: - """Post-rpc interceptor for update_conversation_profile - - Override in a subclass to manipulate the response - after it is returned by the ConversationProfiles server but before - it is returned to user code. - """ - return response - - def pre_get_location( - self, request: locations_pb2.GetLocationRequest, metadata: Sequence[Tuple[str, str]] - ) -> Tuple[locations_pb2.GetLocationRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for get_location - - Override in a subclass to manipulate the request or metadata - before they are sent to the ConversationProfiles server. - """ - return request, metadata - - def post_get_location( - self, response: locations_pb2.Location - ) -> locations_pb2.Location: - """Post-rpc interceptor for get_location - - Override in a subclass to manipulate the response - after it is returned by the ConversationProfiles server but before - it is returned to user code. - """ - return response - def pre_list_locations( - self, request: locations_pb2.ListLocationsRequest, metadata: Sequence[Tuple[str, str]] - ) -> Tuple[locations_pb2.ListLocationsRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for list_locations - - Override in a subclass to manipulate the request or metadata - before they are sent to the ConversationProfiles server. - """ - return request, metadata - - def post_list_locations( - self, response: locations_pb2.ListLocationsResponse - ) -> locations_pb2.ListLocationsResponse: - """Post-rpc interceptor for list_locations - - Override in a subclass to manipulate the response - after it is returned by the ConversationProfiles server but before - it is returned to user code. - """ - return response - def pre_cancel_operation( - self, request: operations_pb2.CancelOperationRequest, metadata: Sequence[Tuple[str, str]] - ) -> Tuple[operations_pb2.CancelOperationRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for cancel_operation - - Override in a subclass to manipulate the request or metadata - before they are sent to the ConversationProfiles server. - """ - return request, metadata - - def post_cancel_operation( - self, response: None - ) -> None: - """Post-rpc interceptor for cancel_operation - - Override in a subclass to manipulate the response - after it is returned by the ConversationProfiles server but before - it is returned to user code. - """ - return response - def pre_get_operation( - self, request: operations_pb2.GetOperationRequest, metadata: Sequence[Tuple[str, str]] - ) -> Tuple[operations_pb2.GetOperationRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for get_operation - - Override in a subclass to manipulate the request or metadata - before they are sent to the ConversationProfiles server. - """ - return request, metadata - - def post_get_operation( - self, response: operations_pb2.Operation - ) -> operations_pb2.Operation: - """Post-rpc interceptor for get_operation - - Override in a subclass to manipulate the response - after it is returned by the ConversationProfiles server but before - it is returned to user code. - """ - return response - def pre_list_operations( - self, request: operations_pb2.ListOperationsRequest, metadata: Sequence[Tuple[str, str]] - ) -> Tuple[operations_pb2.ListOperationsRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for list_operations - - Override in a subclass to manipulate the request or metadata - before they are sent to the ConversationProfiles server. - """ - return request, metadata - - def post_list_operations( - self, response: operations_pb2.ListOperationsResponse - ) -> operations_pb2.ListOperationsResponse: - """Post-rpc interceptor for list_operations - - Override in a subclass to manipulate the response - after it is returned by the ConversationProfiles server but before - it is returned to user code. - """ - return response - - -@dataclasses.dataclass -class ConversationProfilesRestStub: - _session: AuthorizedSession - _host: str - _interceptor: ConversationProfilesRestInterceptor - - -class ConversationProfilesRestTransport(ConversationProfilesTransport): - """REST backend transport for ConversationProfiles. - - Service for managing - [ConversationProfiles][google.cloud.dialogflow.v2.ConversationProfile]. - - 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 JSON representations of protocol buffers over HTTP/1.1 - - """ - - def __init__(self, *, - host: str = 'dialogflow.googleapis.com', - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - client_cert_source_for_mtls: Optional[Callable[[ - ], Tuple[bytes, bytes]]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - url_scheme: str = 'https', - interceptor: Optional[ConversationProfilesRestInterceptor] = None, - api_audience: Optional[str] = None, - ) -> 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 ignored if ``channel`` is provided. - scopes (Optional(Sequence[str])): A list of scopes. This argument is - ignored if ``channel`` is provided. - client_cert_source_for_mtls (Callable[[], Tuple[bytes, bytes]]): Client - certificate to configure mutual TLS HTTP channel. It is ignored - if ``channel`` is provided. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you are developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - url_scheme: the protocol scheme for the API endpoint. Normally - "https", but for testing or local servers, - "http" can be specified. - """ - # Run the base constructor - # TODO(yon-mg): resolve other ctor params i.e. scopes, quota, etc. - # TODO: When custom host (api_endpoint) is set, `scopes` must *also* be set on the - # credentials object - maybe_url_match = re.match("^(?Phttp(?:s)?://)?(?P.*)$", host) - if maybe_url_match is None: - raise ValueError(f"Unexpected hostname structure: {host}") # pragma: NO COVER - - url_match_items = maybe_url_match.groupdict() - - host = f"{url_scheme}://{host}" if not url_match_items["scheme"] else host - - super().__init__( - host=host, - credentials=credentials, - client_info=client_info, - always_use_jwt_access=always_use_jwt_access, - api_audience=api_audience - ) - self._session = AuthorizedSession( - self._credentials, default_host=self.DEFAULT_HOST) - self._operations_client: Optional[operations_v1.AbstractOperationsClient] = None - if client_cert_source_for_mtls: - self._session.configure_mtls_channel(client_cert_source_for_mtls) - self._interceptor = interceptor or ConversationProfilesRestInterceptor() - self._prep_wrapped_messages(client_info) - - @property - def operations_client(self) -> operations_v1.AbstractOperationsClient: - """Create the client designed to process long-running operations. - - This property caches on the instance; repeated calls return the same - client. - """ - # Only create a new client if we do not already have one. - if self._operations_client is None: - http_options: Dict[str, List[Dict[str, str]]] = { - 'google.longrunning.Operations.CancelOperation': [ - { - 'method': 'post', - 'uri': '/v2/{name=projects/*/operations/*}:cancel', - }, - { - 'method': 'post', - 'uri': '/v2/{name=projects/*/locations/*/operations/*}:cancel', - }, - ], - 'google.longrunning.Operations.GetOperation': [ - { - 'method': 'get', - 'uri': '/v2/{name=projects/*/operations/*}', - }, - { - 'method': 'get', - 'uri': '/v2/{name=projects/*/locations/*/operations/*}', - }, - ], - 'google.longrunning.Operations.ListOperations': [ - { - 'method': 'get', - 'uri': '/v2/{name=projects/*}/operations', - }, - { - 'method': 'get', - 'uri': '/v2/{name=projects/*/locations/*}/operations', - }, - ], - } - - rest_transport = operations_v1.OperationsRestTransport( - host=self._host, - # use the credentials which are saved - credentials=self._credentials, - scopes=self._scopes, - http_options=http_options, - path_prefix="v2") - - self._operations_client = operations_v1.AbstractOperationsClient(transport=rest_transport) - - # Return the client from cache. - return self._operations_client - - class _ClearSuggestionFeatureConfig(ConversationProfilesRestStub): - def __hash__(self): - return hash("ClearSuggestionFeatureConfig") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: gcd_conversation_profile.ClearSuggestionFeatureConfigRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> operations_pb2.Operation: - r"""Call the clear suggestion feature - config method over HTTP. - - Args: - request (~.gcd_conversation_profile.ClearSuggestionFeatureConfigRequest): - The request object. The request message for - [ConversationProfiles.ClearFeature][]. - 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: - ~.operations_pb2.Operation: - This resource represents a - long-running operation that is the - result of a network API call. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'post', - 'uri': '/v2/{conversation_profile=projects/*/conversationProfiles/*}:clearSuggestionFeatureConfig', - 'body': '*', - }, -{ - 'method': 'post', - 'uri': '/v2/{conversation_profile=projects/*/locations/*/conversationProfiles/*}:clearSuggestionFeatureConfig', - 'body': '*', - }, - ] - request, metadata = self._interceptor.pre_clear_suggestion_feature_config(request, metadata) - pb_request = gcd_conversation_profile.ClearSuggestionFeatureConfigRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request['body'], - including_default_value_fields=False, - use_integers_for_enums=True - ) - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - including_default_value_fields=False, - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = operations_pb2.Operation() - json_format.Parse(response.content, resp, ignore_unknown_fields=True) - resp = self._interceptor.post_clear_suggestion_feature_config(resp) - return resp - - class _CreateConversationProfile(ConversationProfilesRestStub): - def __hash__(self): - return hash("CreateConversationProfile") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: gcd_conversation_profile.CreateConversationProfileRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> gcd_conversation_profile.ConversationProfile: - r"""Call the create conversation - profile method over HTTP. - - Args: - request (~.gcd_conversation_profile.CreateConversationProfileRequest): - The request object. The request message for - [ConversationProfiles.CreateConversationProfile][google.cloud.dialogflow.v2.ConversationProfiles.CreateConversationProfile]. - 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: - ~.gcd_conversation_profile.ConversationProfile: - Defines the services to connect to - incoming Dialogflow conversations. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'post', - 'uri': '/v2/{parent=projects/*}/conversationProfiles', - 'body': 'conversation_profile', - }, -{ - 'method': 'post', - 'uri': '/v2/{parent=projects/*/locations/*}/conversationProfiles', - 'body': 'conversation_profile', - }, - ] - request, metadata = self._interceptor.pre_create_conversation_profile(request, metadata) - pb_request = gcd_conversation_profile.CreateConversationProfileRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request['body'], - including_default_value_fields=False, - use_integers_for_enums=True - ) - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - including_default_value_fields=False, - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = gcd_conversation_profile.ConversationProfile() - pb_resp = gcd_conversation_profile.ConversationProfile.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_create_conversation_profile(resp) - return resp - - class _DeleteConversationProfile(ConversationProfilesRestStub): - def __hash__(self): - return hash("DeleteConversationProfile") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: conversation_profile.DeleteConversationProfileRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ): - r"""Call the delete conversation - profile method over HTTP. - - Args: - request (~.conversation_profile.DeleteConversationProfileRequest): - The request object. The request message for - [ConversationProfiles.DeleteConversationProfile][google.cloud.dialogflow.v2.ConversationProfiles.DeleteConversationProfile]. - - This operation fails if the conversation profile is - still referenced from a phone number. - 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. - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'delete', - 'uri': '/v2/{name=projects/*/conversationProfiles/*}', - }, -{ - 'method': 'delete', - 'uri': '/v2/{name=projects/*/locations/*/conversationProfiles/*}', - }, - ] - request, metadata = self._interceptor.pre_delete_conversation_profile(request, metadata) - pb_request = conversation_profile.DeleteConversationProfileRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - including_default_value_fields=False, - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - class _GetConversationProfile(ConversationProfilesRestStub): - def __hash__(self): - return hash("GetConversationProfile") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: conversation_profile.GetConversationProfileRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> conversation_profile.ConversationProfile: - r"""Call the get conversation profile method over HTTP. - - Args: - request (~.conversation_profile.GetConversationProfileRequest): - The request object. The request message for - [ConversationProfiles.GetConversationProfile][google.cloud.dialogflow.v2.ConversationProfiles.GetConversationProfile]. - 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: - ~.conversation_profile.ConversationProfile: - Defines the services to connect to - incoming Dialogflow conversations. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v2/{name=projects/*/conversationProfiles/*}', - }, -{ - 'method': 'get', - 'uri': '/v2/{name=projects/*/locations/*/conversationProfiles/*}', - }, - ] - request, metadata = self._interceptor.pre_get_conversation_profile(request, metadata) - pb_request = conversation_profile.GetConversationProfileRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - including_default_value_fields=False, - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = conversation_profile.ConversationProfile() - pb_resp = conversation_profile.ConversationProfile.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_get_conversation_profile(resp) - return resp - - class _ListConversationProfiles(ConversationProfilesRestStub): - def __hash__(self): - return hash("ListConversationProfiles") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: conversation_profile.ListConversationProfilesRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> conversation_profile.ListConversationProfilesResponse: - r"""Call the list conversation - profiles method over HTTP. - - Args: - request (~.conversation_profile.ListConversationProfilesRequest): - The request object. The request message for - [ConversationProfiles.ListConversationProfiles][google.cloud.dialogflow.v2.ConversationProfiles.ListConversationProfiles]. - 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: - ~.conversation_profile.ListConversationProfilesResponse: - The response message for - [ConversationProfiles.ListConversationProfiles][google.cloud.dialogflow.v2.ConversationProfiles.ListConversationProfiles]. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v2/{parent=projects/*}/conversationProfiles', - }, -{ - 'method': 'get', - 'uri': '/v2/{parent=projects/*/locations/*}/conversationProfiles', - }, - ] - request, metadata = self._interceptor.pre_list_conversation_profiles(request, metadata) - pb_request = conversation_profile.ListConversationProfilesRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - including_default_value_fields=False, - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = conversation_profile.ListConversationProfilesResponse() - pb_resp = conversation_profile.ListConversationProfilesResponse.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_list_conversation_profiles(resp) - return resp - - class _SetSuggestionFeatureConfig(ConversationProfilesRestStub): - def __hash__(self): - return hash("SetSuggestionFeatureConfig") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: gcd_conversation_profile.SetSuggestionFeatureConfigRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> operations_pb2.Operation: - r"""Call the set suggestion feature - config method over HTTP. - - Args: - request (~.gcd_conversation_profile.SetSuggestionFeatureConfigRequest): - The request object. The request message for - [ConversationProfiles.SetSuggestionFeature][]. - 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: - ~.operations_pb2.Operation: - This resource represents a - long-running operation that is the - result of a network API call. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'post', - 'uri': '/v2/{conversation_profile=projects/*/conversationProfiles/*}:setSuggestionFeatureConfig', - 'body': '*', - }, -{ - 'method': 'post', - 'uri': '/v2/{conversation_profile=projects/*/locations/*/conversationProfiles/*}:setSuggestionFeatureConfig', - 'body': '*', - }, - ] - request, metadata = self._interceptor.pre_set_suggestion_feature_config(request, metadata) - pb_request = gcd_conversation_profile.SetSuggestionFeatureConfigRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request['body'], - including_default_value_fields=False, - use_integers_for_enums=True - ) - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - including_default_value_fields=False, - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = operations_pb2.Operation() - json_format.Parse(response.content, resp, ignore_unknown_fields=True) - resp = self._interceptor.post_set_suggestion_feature_config(resp) - return resp - - class _UpdateConversationProfile(ConversationProfilesRestStub): - def __hash__(self): - return hash("UpdateConversationProfile") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - "updateMask" : {}, } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: gcd_conversation_profile.UpdateConversationProfileRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> gcd_conversation_profile.ConversationProfile: - r"""Call the update conversation - profile method over HTTP. - - Args: - request (~.gcd_conversation_profile.UpdateConversationProfileRequest): - The request object. The request message for - [ConversationProfiles.UpdateConversationProfile][google.cloud.dialogflow.v2.ConversationProfiles.UpdateConversationProfile]. - 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: - ~.gcd_conversation_profile.ConversationProfile: - Defines the services to connect to - incoming Dialogflow conversations. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'patch', - 'uri': '/v2/{conversation_profile.name=projects/*/conversationProfiles/*}', - 'body': 'conversation_profile', - }, -{ - 'method': 'patch', - 'uri': '/v2/{conversation_profile.name=projects/*/locations/*/conversationProfiles/*}', - 'body': 'conversation_profile', - }, - ] - request, metadata = self._interceptor.pre_update_conversation_profile(request, metadata) - pb_request = gcd_conversation_profile.UpdateConversationProfileRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request['body'], - including_default_value_fields=False, - use_integers_for_enums=True - ) - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - including_default_value_fields=False, - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = gcd_conversation_profile.ConversationProfile() - pb_resp = gcd_conversation_profile.ConversationProfile.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_update_conversation_profile(resp) - return resp - - @property - def clear_suggestion_feature_config(self) -> Callable[ - [gcd_conversation_profile.ClearSuggestionFeatureConfigRequest], - operations_pb2.Operation]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._ClearSuggestionFeatureConfig(self._session, self._host, self._interceptor) # type: ignore - - @property - def create_conversation_profile(self) -> Callable[ - [gcd_conversation_profile.CreateConversationProfileRequest], - gcd_conversation_profile.ConversationProfile]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._CreateConversationProfile(self._session, self._host, self._interceptor) # type: ignore - - @property - def delete_conversation_profile(self) -> Callable[ - [conversation_profile.DeleteConversationProfileRequest], - empty_pb2.Empty]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._DeleteConversationProfile(self._session, self._host, self._interceptor) # type: ignore - - @property - def get_conversation_profile(self) -> Callable[ - [conversation_profile.GetConversationProfileRequest], - conversation_profile.ConversationProfile]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._GetConversationProfile(self._session, self._host, self._interceptor) # type: ignore - - @property - def list_conversation_profiles(self) -> Callable[ - [conversation_profile.ListConversationProfilesRequest], - conversation_profile.ListConversationProfilesResponse]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._ListConversationProfiles(self._session, self._host, self._interceptor) # type: ignore - - @property - def set_suggestion_feature_config(self) -> Callable[ - [gcd_conversation_profile.SetSuggestionFeatureConfigRequest], - operations_pb2.Operation]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._SetSuggestionFeatureConfig(self._session, self._host, self._interceptor) # type: ignore - - @property - def update_conversation_profile(self) -> Callable[ - [gcd_conversation_profile.UpdateConversationProfileRequest], - gcd_conversation_profile.ConversationProfile]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._UpdateConversationProfile(self._session, self._host, self._interceptor) # type: ignore - - @property - def get_location(self): - return self._GetLocation(self._session, self._host, self._interceptor) # type: ignore - - class _GetLocation(ConversationProfilesRestStub): - def __call__(self, - request: locations_pb2.GetLocationRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> locations_pb2.Location: - - r"""Call the get location method over HTTP. - - Args: - request (locations_pb2.GetLocationRequest): - The request object for GetLocation method. - 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: - locations_pb2.Location: Response from GetLocation method. - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v2/{name=projects/*/locations/*}', - }, - ] - - request, metadata = self._interceptor.pre_get_location(request, metadata) - request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode( - http_options, **request_kwargs) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json.dumps(transcoded_request['query_params'])) - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - resp = locations_pb2.Location() - resp = json_format.Parse(response.content.decode("utf-8"), resp) - resp = self._interceptor.post_get_location(resp) - return resp - - @property - def list_locations(self): - return self._ListLocations(self._session, self._host, self._interceptor) # type: ignore - - class _ListLocations(ConversationProfilesRestStub): - def __call__(self, - request: locations_pb2.ListLocationsRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> locations_pb2.ListLocationsResponse: - - r"""Call the list locations method over HTTP. - - Args: - request (locations_pb2.ListLocationsRequest): - The request object for ListLocations method. - 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: - locations_pb2.ListLocationsResponse: Response from ListLocations method. - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v2/{name=projects/*}/locations', - }, - ] - - request, metadata = self._interceptor.pre_list_locations(request, metadata) - request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode( - http_options, **request_kwargs) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json.dumps(transcoded_request['query_params'])) - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - resp = locations_pb2.ListLocationsResponse() - resp = json_format.Parse(response.content.decode("utf-8"), resp) - resp = self._interceptor.post_list_locations(resp) - return resp - - @property - def cancel_operation(self): - return self._CancelOperation(self._session, self._host, self._interceptor) # type: ignore - - class _CancelOperation(ConversationProfilesRestStub): - def __call__(self, - request: operations_pb2.CancelOperationRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> None: - - r"""Call the cancel operation method over HTTP. - - Args: - request (operations_pb2.CancelOperationRequest): - The request object for CancelOperation method. - 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. - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'post', - 'uri': '/v2/{name=projects/*/operations/*}:cancel', - }, -{ - 'method': 'post', - 'uri': '/v2/{name=projects/*/locations/*/operations/*}:cancel', - }, - ] - - request, metadata = self._interceptor.pre_cancel_operation(request, metadata) - request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode( - http_options, **request_kwargs) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json.dumps(transcoded_request['query_params'])) - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - return self._interceptor.post_cancel_operation(None) - - @property - def get_operation(self): - return self._GetOperation(self._session, self._host, self._interceptor) # type: ignore - - class _GetOperation(ConversationProfilesRestStub): - def __call__(self, - request: operations_pb2.GetOperationRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> operations_pb2.Operation: - - r"""Call the get operation method over HTTP. - - Args: - request (operations_pb2.GetOperationRequest): - The request object for GetOperation method. - 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: - operations_pb2.Operation: Response from GetOperation method. - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v2/{name=projects/*/operations/*}', - }, -{ - 'method': 'get', - 'uri': '/v2/{name=projects/*/locations/*/operations/*}', - }, - ] - - request, metadata = self._interceptor.pre_get_operation(request, metadata) - request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode( - http_options, **request_kwargs) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json.dumps(transcoded_request['query_params'])) - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - resp = operations_pb2.Operation() - resp = json_format.Parse(response.content.decode("utf-8"), resp) - resp = self._interceptor.post_get_operation(resp) - return resp - - @property - def list_operations(self): - return self._ListOperations(self._session, self._host, self._interceptor) # type: ignore - - class _ListOperations(ConversationProfilesRestStub): - def __call__(self, - request: operations_pb2.ListOperationsRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> operations_pb2.ListOperationsResponse: - - r"""Call the list operations method over HTTP. - - Args: - request (operations_pb2.ListOperationsRequest): - The request object for ListOperations method. - 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: - operations_pb2.ListOperationsResponse: Response from ListOperations method. - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v2/{name=projects/*}/operations', - }, -{ - 'method': 'get', - 'uri': '/v2/{name=projects/*/locations/*}/operations', - }, - ] - - request, metadata = self._interceptor.pre_list_operations(request, metadata) - request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode( - http_options, **request_kwargs) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json.dumps(transcoded_request['query_params'])) - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - resp = operations_pb2.ListOperationsResponse() - resp = json_format.Parse(response.content.decode("utf-8"), resp) - resp = self._interceptor.post_list_operations(resp) - return resp - - @property - def kind(self) -> str: - return "rest" - - def close(self): - self._session.close() - - -__all__=( - 'ConversationProfilesRestTransport', -) diff --git a/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/conversations/__init__.py b/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/conversations/__init__.py deleted file mode 100644 index 162e3f820..000000000 --- a/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/conversations/__init__.py +++ /dev/null @@ -1,22 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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 ConversationsClient -from .async_client import ConversationsAsyncClient - -__all__ = ( - 'ConversationsClient', - 'ConversationsAsyncClient', -) diff --git a/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/conversations/async_client.py b/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/conversations/async_client.py deleted file mode 100644 index 21013d8e5..000000000 --- a/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/conversations/async_client.py +++ /dev/null @@ -1,1158 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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, Mapping, MutableMapping, MutableSequence, Optional, Sequence, Tuple, Type, Union - -from google.cloud.dialogflow_v2 import gapic_version as package_version - -from google.api_core.client_options import ClientOptions -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import retry as retries -from google.auth import credentials as ga_credentials # type: ignore -from google.oauth2 import service_account # type: ignore - -try: - OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] -except AttributeError: # pragma: NO COVER - OptionalRetry = Union[retries.Retry, object] # 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.cloud.location import locations_pb2 # type: ignore -from google.longrunning import operations_pb2 -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 - - -class ConversationsAsyncClient: - """Service for managing - [Conversations][google.cloud.dialogflow.v2.Conversation]. - """ - - _client: ConversationsClient - - DEFAULT_ENDPOINT = ConversationsClient.DEFAULT_ENDPOINT - DEFAULT_MTLS_ENDPOINT = ConversationsClient.DEFAULT_MTLS_ENDPOINT - - answer_record_path = staticmethod(ConversationsClient.answer_record_path) - parse_answer_record_path = staticmethod(ConversationsClient.parse_answer_record_path) - conversation_path = staticmethod(ConversationsClient.conversation_path) - parse_conversation_path = staticmethod(ConversationsClient.parse_conversation_path) - conversation_profile_path = staticmethod(ConversationsClient.conversation_profile_path) - parse_conversation_profile_path = staticmethod(ConversationsClient.parse_conversation_profile_path) - 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) - - @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: - ConversationsAsyncClient: The constructed client. - """ - return ConversationsClient.from_service_account_info.__func__(ConversationsAsyncClient, 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: - ConversationsAsyncClient: The constructed client. - """ - return ConversationsClient.from_service_account_file.__func__(ConversationsAsyncClient, filename, *args, **kwargs) # type: ignore - - from_service_account_json = from_service_account_file - - @classmethod - def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[ClientOptions] = None): - """Return the API endpoint and client cert source for mutual TLS. - - The client cert source is determined in the following order: - (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the - client cert source is None. - (2) if `client_options.client_cert_source` is provided, use the provided one; if the - default client cert source exists, use the default one; otherwise the client cert - source is None. - - The API endpoint is determined in the following order: - (1) if `client_options.api_endpoint` if provided, use the provided one. - (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the - default mTLS endpoint; if the environment variable is "never", use the default API - endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise - use the default API endpoint. - - More details can be found at https://google.aip.dev/auth/4114. - - Args: - client_options (google.api_core.client_options.ClientOptions): Custom options for the - client. Only the `api_endpoint` and `client_cert_source` properties may be used - in this method. - - Returns: - Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the - client cert source to use. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If any errors happen. - """ - return ConversationsClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore - - @property - def transport(self) -> ConversationsTransport: - """Returns the transport used by the client instance. - - Returns: - ConversationsTransport: The transport used by the client instance. - """ - return self._client.transport - - get_transport_class = functools.partial(type(ConversationsClient).get_transport_class, type(ConversationsClient)) - - def __init__(self, *, - credentials: Optional[ga_credentials.Credentials] = None, - transport: Union[str, ConversationsTransport] = "grpc_asyncio", - client_options: Optional[ClientOptions] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the conversations 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, ~.ConversationsTransport]): 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 = ConversationsClient( - credentials=credentials, - transport=transport, - client_options=client_options, - client_info=client_info, - - ) - - async def create_conversation(self, - request: Optional[Union[gcd_conversation.CreateConversationRequest, dict]] = None, - *, - parent: Optional[str] = None, - conversation: Optional[gcd_conversation.Conversation] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gcd_conversation.Conversation: - r"""Creates a new conversation. Conversations are auto-completed - after 24 hours. - - Conversation Lifecycle: There are two stages during a - conversation: Automated Agent Stage and Assist Stage. - - For Automated Agent Stage, there will be a dialogflow agent - responding to user queries. - - For Assist Stage, there's no dialogflow agent responding to user - queries. But we will provide suggestions which are generated - from conversation. - - If - [Conversation.conversation_profile][google.cloud.dialogflow.v2.Conversation.conversation_profile] - is configured for a dialogflow agent, conversation will start - from ``Automated Agent Stage``, otherwise, it will start from - ``Assist Stage``. And during ``Automated Agent Stage``, once an - [Intent][google.cloud.dialogflow.v2.Intent] with - [Intent.live_agent_handoff][google.cloud.dialogflow.v2.Intent.live_agent_handoff] - is triggered, conversation will transfer to Assist Stage. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import dialogflow_v2 - - async def sample_create_conversation(): - # Create a client - client = dialogflow_v2.ConversationsAsyncClient() - - # Initialize request argument(s) - conversation = dialogflow_v2.Conversation() - conversation.conversation_profile = "conversation_profile_value" - - request = dialogflow_v2.CreateConversationRequest( - parent="parent_value", - conversation=conversation, - ) - - # Make the request - response = await client.create_conversation(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.dialogflow_v2.types.CreateConversationRequest, dict]]): - The request object. The request message for - [Conversations.CreateConversation][google.cloud.dialogflow.v2.Conversations.CreateConversation]. - parent (:class:`str`): - Required. Resource identifier of the project creating - the conversation. Format: - ``projects//locations/``. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - conversation (:class:`google.cloud.dialogflow_v2.types.Conversation`): - Required. The conversation to create. - 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. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.dialogflow_v2.types.Conversation: - Represents a conversation. - A conversation is an interaction between - an agent, including live agents and - Dialogflow agents, and a support - customer. Conversations can include - phone calls and text-based chat - sessions. - - """ - # Create or coerce a protobuf request object. - # Quick 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, conversation]) - 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_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: - request.conversation = conversation - - # 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_conversation, - 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 list_conversations(self, - request: Optional[Union[conversation.ListConversationsRequest, dict]] = None, - *, - parent: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListConversationsAsyncPager: - r"""Returns the list of all conversations in the - specified project. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import dialogflow_v2 - - async def sample_list_conversations(): - # Create a client - client = dialogflow_v2.ConversationsAsyncClient() - - # Initialize request argument(s) - request = dialogflow_v2.ListConversationsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_conversations(request=request) - - # Handle the response - async for response in page_result: - print(response) - - Args: - request (Optional[Union[google.cloud.dialogflow_v2.types.ListConversationsRequest, dict]]): - The request object. The request message for - [Conversations.ListConversations][google.cloud.dialogflow.v2.Conversations.ListConversations]. - parent (:class:`str`): - Required. The project from which to list all - conversation. Format: - ``projects//locations/``. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.dialogflow_v2.services.conversations.pagers.ListConversationsAsyncPager: - The response message for - [Conversations.ListConversations][google.cloud.dialogflow.v2.Conversations.ListConversations]. - - Iterating over this object will yield results and - resolve additional pages automatically. - - """ - # Create or coerce a protobuf request object. - # Quick 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 = conversation.ListConversationsRequest(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_conversations, - 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.ListConversationsAsyncPager( - method=rpc, - request=request, - response=response, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def get_conversation(self, - request: Optional[Union[conversation.GetConversationRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> conversation.Conversation: - r"""Retrieves the specific conversation. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import dialogflow_v2 - - async def sample_get_conversation(): - # Create a client - client = dialogflow_v2.ConversationsAsyncClient() - - # Initialize request argument(s) - request = dialogflow_v2.GetConversationRequest( - name="name_value", - ) - - # Make the request - response = await client.get_conversation(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.dialogflow_v2.types.GetConversationRequest, dict]]): - The request object. The request message for - [Conversations.GetConversation][google.cloud.dialogflow.v2.Conversations.GetConversation]. - name (:class:`str`): - Required. The name of the conversation. Format: - ``projects//locations//conversations/``. - - 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.Conversation: - Represents a conversation. - A conversation is an interaction between - an agent, including live agents and - Dialogflow agents, and a support - customer. Conversations can include - phone calls and text-based chat - sessions. - - """ - # Create or coerce a protobuf request object. - # Quick 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 = conversation.GetConversationRequest(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_conversation, - 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 complete_conversation(self, - request: Optional[Union[conversation.CompleteConversationRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> conversation.Conversation: - r"""Completes the specified conversation. Finished - conversations are purged from the database after 30 - days. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import dialogflow_v2 - - async def sample_complete_conversation(): - # Create a client - client = dialogflow_v2.ConversationsAsyncClient() - - # Initialize request argument(s) - request = dialogflow_v2.CompleteConversationRequest( - name="name_value", - ) - - # Make the request - response = await client.complete_conversation(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.dialogflow_v2.types.CompleteConversationRequest, dict]]): - The request object. The request message for - [Conversations.CompleteConversation][google.cloud.dialogflow.v2.Conversations.CompleteConversation]. - name (:class:`str`): - Required. Resource identifier of the conversation to - close. Format: - ``projects//locations//conversations/``. - - 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.Conversation: - Represents a conversation. - A conversation is an interaction between - an agent, including live agents and - Dialogflow agents, and a support - customer. Conversations can include - phone calls and text-based chat - sessions. - - """ - # Create or coerce a protobuf request object. - # Quick 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 = conversation.CompleteConversationRequest(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.complete_conversation, - 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 list_messages(self, - request: Optional[Union[conversation.ListMessagesRequest, dict]] = None, - *, - parent: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListMessagesAsyncPager: - r"""Lists messages that belong to a given conversation. ``messages`` - are ordered by ``create_time`` in descending order. To fetch - updates without duplication, send request with filter - ``create_time_epoch_microseconds > [first item's create_time of previous request]`` - and empty page_token. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import dialogflow_v2 - - async def sample_list_messages(): - # Create a client - client = dialogflow_v2.ConversationsAsyncClient() - - # Initialize request argument(s) - request = dialogflow_v2.ListMessagesRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_messages(request=request) - - # Handle the response - async for response in page_result: - print(response) - - Args: - request (Optional[Union[google.cloud.dialogflow_v2.types.ListMessagesRequest, dict]]): - The request object. The request message for - [Conversations.ListMessages][google.cloud.dialogflow.v2.Conversations.ListMessages]. - parent (:class:`str`): - Required. The name of the conversation to list messages - for. Format: - ``projects//locations//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. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.dialogflow_v2.services.conversations.pagers.ListMessagesAsyncPager: - The response message for - [Conversations.ListMessages][google.cloud.dialogflow.v2.Conversations.ListMessages]. - - Iterating over this object will yield results and - resolve additional pages automatically. - - """ - # Create or coerce a protobuf request object. - # Quick 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 = conversation.ListMessagesRequest(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_messages, - 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.ListMessagesAsyncPager( - method=rpc, - request=request, - response=response, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def suggest_conversation_summary(self, - request: Optional[Union[gcd_conversation.SuggestConversationSummaryRequest, dict]] = None, - *, - conversation: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gcd_conversation.SuggestConversationSummaryResponse: - r"""Suggests summary for a conversation based on specific - historical messages. The range of the messages to be - used for summary can be specified in the request. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import dialogflow_v2 - - async def sample_suggest_conversation_summary(): - # Create a client - client = dialogflow_v2.ConversationsAsyncClient() - - # Initialize request argument(s) - request = dialogflow_v2.SuggestConversationSummaryRequest( - conversation="conversation_value", - ) - - # Make the request - response = await client.suggest_conversation_summary(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.dialogflow_v2.types.SuggestConversationSummaryRequest, dict]]): - The request object. The request message for - [Conversations.SuggestConversationSummary][google.cloud.dialogflow.v2.Conversations.SuggestConversationSummary]. - conversation (:class:`str`): - Required. The conversation to fetch suggestion for. - Format: - ``projects//locations//conversations/``. - - 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. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.dialogflow_v2.types.SuggestConversationSummaryResponse: - The response message for - [Conversations.SuggestConversationSummary][google.cloud.dialogflow.v2.Conversations.SuggestConversationSummary]. - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([conversation]) - 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_conversation.SuggestConversationSummaryRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if conversation is not None: - request.conversation = conversation - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.suggest_conversation_summary, - 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(( - ("conversation", request.conversation), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def list_operations( - self, - request: Optional[operations_pb2.ListOperationsRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operations_pb2.ListOperationsResponse: - r"""Lists operations that match the specified filter in the request. - - Args: - request (:class:`~.operations_pb2.ListOperationsRequest`): - The request object. Request message for - `ListOperations` method. - 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: - ~.operations_pb2.ListOperationsResponse: - Response message for ``ListOperations`` method. - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = operations_pb2.ListOperationsRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._client._transport.list_operations, - 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 get_operation( - self, - request: Optional[operations_pb2.GetOperationRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operations_pb2.Operation: - r"""Gets the latest state of a long-running operation. - - Args: - request (:class:`~.operations_pb2.GetOperationRequest`): - The request object. Request message for - `GetOperation` method. - 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: - ~.operations_pb2.Operation: - An ``Operation`` object. - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = operations_pb2.GetOperationRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._client._transport.get_operation, - 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 cancel_operation( - self, - request: Optional[operations_pb2.CancelOperationRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> None: - r"""Starts asynchronous cancellation on a long-running operation. - - The server makes a best effort to cancel the operation, but success - is not guaranteed. If the server doesn't support this method, it returns - `google.rpc.Code.UNIMPLEMENTED`. - - Args: - request (:class:`~.operations_pb2.CancelOperationRequest`): - The request object. Request message for - `CancelOperation` method. - 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: - None - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = operations_pb2.CancelOperationRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._client._transport.cancel_operation, - 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_location( - self, - request: Optional[locations_pb2.GetLocationRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> locations_pb2.Location: - r"""Gets information about a location. - - Args: - request (:class:`~.location_pb2.GetLocationRequest`): - The request object. Request message for - `GetLocation` method. - 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: - ~.location_pb2.Location: - Location object. - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = locations_pb2.GetLocationRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._client._transport.get_location, - 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 list_locations( - self, - request: Optional[locations_pb2.ListLocationsRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> locations_pb2.ListLocationsResponse: - r"""Lists information about the supported locations for this service. - - Args: - request (:class:`~.location_pb2.ListLocationsRequest`): - The request object. Request message for - `ListLocations` method. - 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: - ~.location_pb2.ListLocationsResponse: - Response message for ``ListLocations`` method. - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = locations_pb2.ListLocationsRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._client._transport.list_locations, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("name", request.name),)), - ) - - # Send the request. - response = await rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - async def __aenter__(self): - return self - - async def __aexit__(self, exc_type, exc, tb): - await self.transport.close() - -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) - - -__all__ = ( - "ConversationsAsyncClient", -) diff --git a/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/conversations/client.py b/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/conversations/client.py deleted file mode 100644 index 2633f7215..000000000 --- a/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/conversations/client.py +++ /dev/null @@ -1,1384 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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 os -import re -from typing import Dict, Mapping, MutableMapping, MutableSequence, Optional, Sequence, Tuple, Type, Union, cast - -from google.cloud.dialogflow_v2 import gapic_version as package_version - -from google.api_core import client_options as client_options_lib -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import retry as retries -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 - -try: - OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] -except AttributeError: # pragma: NO COVER - OptionalRetry = Union[retries.Retry, object] # 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.cloud.location import locations_pb2 # type: ignore -from google.longrunning import operations_pb2 -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 -from .transports.rest import ConversationsRestTransport - - -class ConversationsClientMeta(type): - """Metaclass for the Conversations 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[ConversationsTransport]] - _transport_registry["grpc"] = ConversationsGrpcTransport - _transport_registry["grpc_asyncio"] = ConversationsGrpcAsyncIOTransport - _transport_registry["rest"] = ConversationsRestTransport - - def get_transport_class(cls, - label: Optional[str] = None, - ) -> Type[ConversationsTransport]: - """Returns an appropriate transport class. - - Args: - label: The name of the desired transport. If none is - provided, then the first transport in the registry is used. - - Returns: - The transport class to use. - """ - # If a specific transport is requested, return that one. - if label: - return cls._transport_registry[label] - - # No transport is requested; return the default (that is, the first one - # in the dictionary). - return next(iter(cls._transport_registry.values())) - - -class ConversationsClient(metaclass=ConversationsClientMeta): - """Service for managing - [Conversations][google.cloud.dialogflow.v2.Conversation]. - """ - - @staticmethod - def _get_default_mtls_endpoint(api_endpoint): - """Converts api endpoint to mTLS endpoint. - - Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to - "*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively. - Args: - api_endpoint (Optional[str]): the api endpoint to convert. - Returns: - str: converted mTLS api endpoint. - """ - if not api_endpoint: - return api_endpoint - - mtls_endpoint_re = re.compile( - r"(?P[^.]+)(?P\.mtls)?(?P\.sandbox)?(?P\.googleapis\.com)?" - ) - - m = mtls_endpoint_re.match(api_endpoint) - name, mtls, sandbox, googledomain = m.groups() - if mtls or not googledomain: - return api_endpoint - - if sandbox: - return api_endpoint.replace( - "sandbox.googleapis.com", "mtls.sandbox.googleapis.com" - ) - - return api_endpoint.replace(".googleapis.com", ".mtls.googleapis.com") - - DEFAULT_ENDPOINT = "dialogflow.googleapis.com" - DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore - DEFAULT_ENDPOINT - ) - - @classmethod - def from_service_account_info(cls, info: dict, *args, **kwargs): - """Creates an instance of this client using the provided credentials - info. - - Args: - info (dict): The service account private key info. - args: Additional arguments to pass to the constructor. - kwargs: Additional arguments to pass to the constructor. - - Returns: - ConversationsClient: 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: - ConversationsClient: 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) -> ConversationsTransport: - """Returns the transport used by the client instance. - - Returns: - ConversationsTransport: The transport used by the client - instance. - """ - return self._transport - - @staticmethod - def answer_record_path(project: str,answer_record: str,) -> str: - """Returns a fully-qualified answer_record string.""" - return "projects/{project}/answerRecords/{answer_record}".format(project=project, answer_record=answer_record, ) - - @staticmethod - def parse_answer_record_path(path: str) -> Dict[str,str]: - """Parses a answer_record path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/answerRecords/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def conversation_path(project: str,conversation: str,) -> str: - """Returns a fully-qualified conversation string.""" - return "projects/{project}/conversations/{conversation}".format(project=project, conversation=conversation, ) - - @staticmethod - def parse_conversation_path(path: str) -> Dict[str,str]: - """Parses a conversation path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/conversations/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def conversation_profile_path(project: str,conversation_profile: str,) -> str: - """Returns a fully-qualified conversation_profile string.""" - return "projects/{project}/conversationProfiles/{conversation_profile}".format(project=project, conversation_profile=conversation_profile, ) - - @staticmethod - def parse_conversation_profile_path(path: str) -> Dict[str,str]: - """Parses a conversation_profile path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/conversationProfiles/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def message_path(project: str,conversation: str,message: str,) -> str: - """Returns a fully-qualified message string.""" - return "projects/{project}/conversations/{conversation}/messages/{message}".format(project=project, conversation=conversation, message=message, ) - - @staticmethod - def parse_message_path(path: str) -> Dict[str,str]: - """Parses a message path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/conversations/(?P.+?)/messages/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_billing_account_path(billing_account: str, ) -> str: - """Returns a fully-qualified billing_account string.""" - return "billingAccounts/{billing_account}".format(billing_account=billing_account, ) - - @staticmethod - def parse_common_billing_account_path(path: str) -> Dict[str,str]: - """Parse a billing_account path into its component segments.""" - m = re.match(r"^billingAccounts/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_folder_path(folder: str, ) -> str: - """Returns a fully-qualified folder string.""" - return "folders/{folder}".format(folder=folder, ) - - @staticmethod - def parse_common_folder_path(path: str) -> Dict[str,str]: - """Parse a folder path into its component segments.""" - m = re.match(r"^folders/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_organization_path(organization: str, ) -> str: - """Returns a fully-qualified organization string.""" - return "organizations/{organization}".format(organization=organization, ) - - @staticmethod - def parse_common_organization_path(path: str) -> Dict[str,str]: - """Parse a organization path into its component segments.""" - m = re.match(r"^organizations/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_project_path(project: str, ) -> str: - """Returns a fully-qualified project string.""" - return "projects/{project}".format(project=project, ) - - @staticmethod - def parse_common_project_path(path: str) -> Dict[str,str]: - """Parse a project path into its component segments.""" - m = re.match(r"^projects/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_location_path(project: str, location: str, ) -> str: - """Returns a fully-qualified location string.""" - return "projects/{project}/locations/{location}".format(project=project, location=location, ) - - @staticmethod - def parse_common_location_path(path: str) -> Dict[str,str]: - """Parse a location path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)$", path) - return m.groupdict() if m else {} - - @classmethod - def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[client_options_lib.ClientOptions] = None): - """Return the API endpoint and client cert source for mutual TLS. - - The client cert source is determined in the following order: - (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the - client cert source is None. - (2) if `client_options.client_cert_source` is provided, use the provided one; if the - default client cert source exists, use the default one; otherwise the client cert - source is None. - - The API endpoint is determined in the following order: - (1) if `client_options.api_endpoint` if provided, use the provided one. - (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the - default mTLS endpoint; if the environment variable is "never", use the default API - endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise - use the default API endpoint. - - More details can be found at https://google.aip.dev/auth/4114. - - Args: - client_options (google.api_core.client_options.ClientOptions): Custom options for the - client. Only the `api_endpoint` and `client_cert_source` properties may be used - in this method. - - Returns: - Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the - client cert source to use. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If any errors happen. - """ - if client_options is None: - client_options = client_options_lib.ClientOptions() - use_client_cert = os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false") - use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") - if use_client_cert not in ("true", "false"): - raise ValueError("Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`") - if use_mtls_endpoint not in ("auto", "never", "always"): - raise MutualTLSChannelError("Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`") - - # Figure out the client cert source to use. - client_cert_source = None - if use_client_cert == "true": - if client_options.client_cert_source: - client_cert_source = client_options.client_cert_source - elif mtls.has_default_client_cert_source(): - client_cert_source = mtls.default_client_cert_source() - - # Figure out which api endpoint to use. - if client_options.api_endpoint is not None: - api_endpoint = client_options.api_endpoint - elif use_mtls_endpoint == "always" or (use_mtls_endpoint == "auto" and client_cert_source): - api_endpoint = cls.DEFAULT_MTLS_ENDPOINT - else: - api_endpoint = cls.DEFAULT_ENDPOINT - - return api_endpoint, client_cert_source - - def __init__(self, *, - credentials: Optional[ga_credentials.Credentials] = None, - transport: Optional[Union[str, ConversationsTransport]] = None, - client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the conversations 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, ConversationsTransport]): The - transport to use. If set to None, a transport is chosen - automatically. - client_options (Optional[Union[google.api_core.client_options.ClientOptions, dict]]): 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() - client_options = cast(client_options_lib.ClientOptions, client_options) - - api_endpoint, client_cert_source_func = self.get_mtls_endpoint_and_cert_source(client_options) - - api_key_value = getattr(client_options, "api_key", None) - if api_key_value and credentials: - raise ValueError("client_options.api_key and credentials are mutually exclusive") - - # 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, ConversationsTransport): - # transport is a ConversationsTransport instance. - if credentials or client_options.credentials_file or api_key_value: - 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: - import google.auth._default # type: ignore - - if api_key_value and hasattr(google.auth._default, "get_api_key_credentials"): - credentials = google.auth._default.get_api_key_credentials(api_key_value) - - Transport = type(self).get_transport_class(transport) - self._transport = Transport( - credentials=credentials, - credentials_file=client_options.credentials_file, - host=api_endpoint, - scopes=client_options.scopes, - client_cert_source_for_mtls=client_cert_source_func, - quota_project_id=client_options.quota_project_id, - client_info=client_info, - always_use_jwt_access=True, - api_audience=client_options.api_audience, - ) - - def create_conversation(self, - request: Optional[Union[gcd_conversation.CreateConversationRequest, dict]] = None, - *, - parent: Optional[str] = None, - conversation: Optional[gcd_conversation.Conversation] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gcd_conversation.Conversation: - r"""Creates a new conversation. Conversations are auto-completed - after 24 hours. - - Conversation Lifecycle: There are two stages during a - conversation: Automated Agent Stage and Assist Stage. - - For Automated Agent Stage, there will be a dialogflow agent - responding to user queries. - - For Assist Stage, there's no dialogflow agent responding to user - queries. But we will provide suggestions which are generated - from conversation. - - If - [Conversation.conversation_profile][google.cloud.dialogflow.v2.Conversation.conversation_profile] - is configured for a dialogflow agent, conversation will start - from ``Automated Agent Stage``, otherwise, it will start from - ``Assist Stage``. And during ``Automated Agent Stage``, once an - [Intent][google.cloud.dialogflow.v2.Intent] with - [Intent.live_agent_handoff][google.cloud.dialogflow.v2.Intent.live_agent_handoff] - is triggered, conversation will transfer to Assist Stage. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import dialogflow_v2 - - def sample_create_conversation(): - # Create a client - client = dialogflow_v2.ConversationsClient() - - # Initialize request argument(s) - conversation = dialogflow_v2.Conversation() - conversation.conversation_profile = "conversation_profile_value" - - request = dialogflow_v2.CreateConversationRequest( - parent="parent_value", - conversation=conversation, - ) - - # Make the request - response = client.create_conversation(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.dialogflow_v2.types.CreateConversationRequest, dict]): - The request object. The request message for - [Conversations.CreateConversation][google.cloud.dialogflow.v2.Conversations.CreateConversation]. - parent (str): - Required. Resource identifier of the project creating - the conversation. Format: - ``projects//locations/``. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - conversation (google.cloud.dialogflow_v2.types.Conversation): - Required. The conversation to create. - 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. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.dialogflow_v2.types.Conversation: - Represents a conversation. - A conversation is an interaction between - an agent, including live agents and - Dialogflow agents, and a support - customer. Conversations can include - phone calls and text-based chat - sessions. - - """ - # Create or coerce a protobuf request object. - # Quick 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, conversation]) - 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_conversation.CreateConversationRequest. - # There's no risk of modifying the input as we've already verified - # 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: - request.conversation = conversation - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.create_conversation] - - # 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 list_conversations(self, - request: Optional[Union[conversation.ListConversationsRequest, dict]] = None, - *, - parent: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListConversationsPager: - r"""Returns the list of all conversations in the - specified project. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import dialogflow_v2 - - def sample_list_conversations(): - # Create a client - client = dialogflow_v2.ConversationsClient() - - # Initialize request argument(s) - request = dialogflow_v2.ListConversationsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_conversations(request=request) - - # Handle the response - for response in page_result: - print(response) - - Args: - request (Union[google.cloud.dialogflow_v2.types.ListConversationsRequest, dict]): - The request object. The request message for - [Conversations.ListConversations][google.cloud.dialogflow.v2.Conversations.ListConversations]. - parent (str): - Required. The project from which to list all - conversation. Format: - ``projects//locations/``. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.dialogflow_v2.services.conversations.pagers.ListConversationsPager: - The response message for - [Conversations.ListConversations][google.cloud.dialogflow.v2.Conversations.ListConversations]. - - Iterating over this object will yield results and - resolve additional pages automatically. - - """ - # Create or coerce a protobuf request object. - # Quick 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 conversation.ListConversationsRequest. - # There's no risk of modifying the input as we've already verified - # 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 - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.list_conversations] - - # 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.ListConversationsPager( - method=rpc, - request=request, - response=response, - metadata=metadata, - ) - - # Done; return the response. - return response - - def get_conversation(self, - request: Optional[Union[conversation.GetConversationRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> conversation.Conversation: - r"""Retrieves the specific conversation. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import dialogflow_v2 - - def sample_get_conversation(): - # Create a client - client = dialogflow_v2.ConversationsClient() - - # Initialize request argument(s) - request = dialogflow_v2.GetConversationRequest( - name="name_value", - ) - - # Make the request - response = client.get_conversation(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.dialogflow_v2.types.GetConversationRequest, dict]): - The request object. The request message for - [Conversations.GetConversation][google.cloud.dialogflow.v2.Conversations.GetConversation]. - name (str): - Required. The name of the conversation. Format: - ``projects//locations//conversations/``. - - 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.Conversation: - Represents a conversation. - A conversation is an interaction between - an agent, including live agents and - Dialogflow agents, and a support - customer. Conversations can include - phone calls and text-based chat - sessions. - - """ - # Create or coerce a protobuf request object. - # Quick 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 conversation.GetConversationRequest. - # There's no risk of modifying the input as we've already verified - # 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 - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.get_conversation] - - # 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 complete_conversation(self, - request: Optional[Union[conversation.CompleteConversationRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> conversation.Conversation: - r"""Completes the specified conversation. Finished - conversations are purged from the database after 30 - days. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import dialogflow_v2 - - def sample_complete_conversation(): - # Create a client - client = dialogflow_v2.ConversationsClient() - - # Initialize request argument(s) - request = dialogflow_v2.CompleteConversationRequest( - name="name_value", - ) - - # Make the request - response = client.complete_conversation(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.dialogflow_v2.types.CompleteConversationRequest, dict]): - The request object. The request message for - [Conversations.CompleteConversation][google.cloud.dialogflow.v2.Conversations.CompleteConversation]. - name (str): - Required. Resource identifier of the conversation to - close. Format: - ``projects//locations//conversations/``. - - 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.Conversation: - Represents a conversation. - A conversation is an interaction between - an agent, including live agents and - Dialogflow agents, and a support - customer. Conversations can include - phone calls and text-based chat - sessions. - - """ - # Create or coerce a protobuf request object. - # Quick 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 conversation.CompleteConversationRequest. - # There's no risk of modifying the input as we've already verified - # 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 - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.complete_conversation] - - # 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 list_messages(self, - request: Optional[Union[conversation.ListMessagesRequest, dict]] = None, - *, - parent: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListMessagesPager: - r"""Lists messages that belong to a given conversation. ``messages`` - are ordered by ``create_time`` in descending order. To fetch - updates without duplication, send request with filter - ``create_time_epoch_microseconds > [first item's create_time of previous request]`` - and empty page_token. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import dialogflow_v2 - - def sample_list_messages(): - # Create a client - client = dialogflow_v2.ConversationsClient() - - # Initialize request argument(s) - request = dialogflow_v2.ListMessagesRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_messages(request=request) - - # Handle the response - for response in page_result: - print(response) - - Args: - request (Union[google.cloud.dialogflow_v2.types.ListMessagesRequest, dict]): - The request object. The request message for - [Conversations.ListMessages][google.cloud.dialogflow.v2.Conversations.ListMessages]. - parent (str): - Required. The name of the conversation to list messages - for. Format: - ``projects//locations//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. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.dialogflow_v2.services.conversations.pagers.ListMessagesPager: - The response message for - [Conversations.ListMessages][google.cloud.dialogflow.v2.Conversations.ListMessages]. - - Iterating over this object will yield results and - resolve additional pages automatically. - - """ - # Create or coerce a protobuf request object. - # Quick 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 conversation.ListMessagesRequest. - # There's no risk of modifying the input as we've already verified - # 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 - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.list_messages] - - # 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.ListMessagesPager( - method=rpc, - request=request, - response=response, - metadata=metadata, - ) - - # Done; return the response. - return response - - def suggest_conversation_summary(self, - request: Optional[Union[gcd_conversation.SuggestConversationSummaryRequest, dict]] = None, - *, - conversation: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gcd_conversation.SuggestConversationSummaryResponse: - r"""Suggests summary for a conversation based on specific - historical messages. The range of the messages to be - used for summary can be specified in the request. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import dialogflow_v2 - - def sample_suggest_conversation_summary(): - # Create a client - client = dialogflow_v2.ConversationsClient() - - # Initialize request argument(s) - request = dialogflow_v2.SuggestConversationSummaryRequest( - conversation="conversation_value", - ) - - # Make the request - response = client.suggest_conversation_summary(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.dialogflow_v2.types.SuggestConversationSummaryRequest, dict]): - The request object. The request message for - [Conversations.SuggestConversationSummary][google.cloud.dialogflow.v2.Conversations.SuggestConversationSummary]. - conversation (str): - Required. The conversation to fetch suggestion for. - Format: - ``projects//locations//conversations/``. - - 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. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.dialogflow_v2.types.SuggestConversationSummaryResponse: - The response message for - [Conversations.SuggestConversationSummary][google.cloud.dialogflow.v2.Conversations.SuggestConversationSummary]. - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([conversation]) - 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_conversation.SuggestConversationSummaryRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, gcd_conversation.SuggestConversationSummaryRequest): - request = gcd_conversation.SuggestConversationSummaryRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if conversation is not None: - request.conversation = conversation - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.suggest_conversation_summary] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("conversation", request.conversation), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def __enter__(self) -> "ConversationsClient": - return self - - def __exit__(self, type, value, traceback): - """Releases underlying transport's resources. - - .. warning:: - ONLY use as a context manager if the transport is NOT shared - with other clients! Exiting the with block will CLOSE the transport - and may cause errors in other clients! - """ - self.transport.close() - - def list_operations( - self, - request: Optional[operations_pb2.ListOperationsRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operations_pb2.ListOperationsResponse: - r"""Lists operations that match the specified filter in the request. - - Args: - request (:class:`~.operations_pb2.ListOperationsRequest`): - The request object. Request message for - `ListOperations` method. - 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: - ~.operations_pb2.ListOperationsResponse: - Response message for ``ListOperations`` method. - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = operations_pb2.ListOperationsRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._transport.list_operations, - 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 = rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - def get_operation( - self, - request: Optional[operations_pb2.GetOperationRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operations_pb2.Operation: - r"""Gets the latest state of a long-running operation. - - Args: - request (:class:`~.operations_pb2.GetOperationRequest`): - The request object. Request message for - `GetOperation` method. - 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: - ~.operations_pb2.Operation: - An ``Operation`` object. - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = operations_pb2.GetOperationRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._transport.get_operation, - 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 = rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - def cancel_operation( - self, - request: Optional[operations_pb2.CancelOperationRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> None: - r"""Starts asynchronous cancellation on a long-running operation. - - The server makes a best effort to cancel the operation, but success - is not guaranteed. If the server doesn't support this method, it returns - `google.rpc.Code.UNIMPLEMENTED`. - - Args: - request (:class:`~.operations_pb2.CancelOperationRequest`): - The request object. Request message for - `CancelOperation` method. - 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: - None - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = operations_pb2.CancelOperationRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._transport.cancel_operation, - 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. - rpc(request, retry=retry, timeout=timeout, metadata=metadata,) - - def get_location( - self, - request: Optional[locations_pb2.GetLocationRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> locations_pb2.Location: - r"""Gets information about a location. - - Args: - request (:class:`~.location_pb2.GetLocationRequest`): - The request object. Request message for - `GetLocation` method. - 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: - ~.location_pb2.Location: - Location object. - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = locations_pb2.GetLocationRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._transport.get_location, - 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 = rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - def list_locations( - self, - request: Optional[locations_pb2.ListLocationsRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> locations_pb2.ListLocationsResponse: - r"""Lists information about the supported locations for this service. - - Args: - request (:class:`~.location_pb2.ListLocationsRequest`): - The request object. Request message for - `ListLocations` method. - 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: - ~.location_pb2.ListLocationsResponse: - Response message for ``ListLocations`` method. - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = locations_pb2.ListLocationsRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._transport.list_locations, - 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 = rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) - - -__all__ = ( - "ConversationsClient", -) diff --git a/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/conversations/pagers.py b/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/conversations/pagers.py deleted file mode 100644 index cf3d6c3d9..000000000 --- a/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/conversations/pagers.py +++ /dev/null @@ -1,261 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from typing import Any, AsyncIterator, Awaitable, Callable, Sequence, Tuple, Optional, Iterator - -from google.cloud.dialogflow_v2.types import conversation -from google.cloud.dialogflow_v2.types import participant - - -class ListConversationsPager: - """A pager for iterating through ``list_conversations`` requests. - - This class thinly wraps an initial - :class:`google.cloud.dialogflow_v2.types.ListConversationsResponse` object, and - provides an ``__iter__`` method to iterate through its - ``conversations`` field. - - If there are more pages, the ``__iter__`` method will make additional - ``ListConversations`` requests and continue to iterate - through the ``conversations`` field on the - corresponding responses. - - All the usual :class:`google.cloud.dialogflow_v2.types.ListConversationsResponse` - 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[..., conversation.ListConversationsResponse], - request: conversation.ListConversationsRequest, - response: conversation.ListConversationsResponse, - *, - 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.ListConversationsRequest): - The initial request object. - response (google.cloud.dialogflow_v2.types.ListConversationsResponse): - 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 = conversation.ListConversationsRequest(request) - self._response = response - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - def pages(self) -> Iterator[conversation.ListConversationsResponse]: - yield self._response - while self._response.next_page_token: - self._request.page_token = self._response.next_page_token - self._response = self._method(self._request, metadata=self._metadata) - yield self._response - - def __iter__(self) -> Iterator[conversation.Conversation]: - for page in self.pages: - yield from page.conversations - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListConversationsAsyncPager: - """A pager for iterating through ``list_conversations`` requests. - - This class thinly wraps an initial - :class:`google.cloud.dialogflow_v2.types.ListConversationsResponse` object, and - provides an ``__aiter__`` method to iterate through its - ``conversations`` field. - - If there are more pages, the ``__aiter__`` method will make additional - ``ListConversations`` requests and continue to iterate - through the ``conversations`` field on the - corresponding responses. - - All the usual :class:`google.cloud.dialogflow_v2.types.ListConversationsResponse` - 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[conversation.ListConversationsResponse]], - request: conversation.ListConversationsRequest, - response: conversation.ListConversationsResponse, - *, - metadata: Sequence[Tuple[str, str]] = ()): - """Instantiates the pager. - - Args: - method (Callable): The method that was originally called, and - which instantiated this pager. - request (google.cloud.dialogflow_v2.types.ListConversationsRequest): - The initial request object. - response (google.cloud.dialogflow_v2.types.ListConversationsResponse): - 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 = conversation.ListConversationsRequest(request) - self._response = response - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - async def pages(self) -> AsyncIterator[conversation.ListConversationsResponse]: - yield self._response - while self._response.next_page_token: - self._request.page_token = self._response.next_page_token - self._response = await self._method(self._request, metadata=self._metadata) - yield self._response - def __aiter__(self) -> AsyncIterator[conversation.Conversation]: - async def async_generator(): - async for page in self.pages: - for response in page.conversations: - yield response - - return async_generator() - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListMessagesPager: - """A pager for iterating through ``list_messages`` requests. - - This class thinly wraps an initial - :class:`google.cloud.dialogflow_v2.types.ListMessagesResponse` object, and - provides an ``__iter__`` method to iterate through its - ``messages`` field. - - If there are more pages, the ``__iter__`` method will make additional - ``ListMessages`` requests and continue to iterate - through the ``messages`` field on the - corresponding responses. - - All the usual :class:`google.cloud.dialogflow_v2.types.ListMessagesResponse` - 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[..., conversation.ListMessagesResponse], - request: conversation.ListMessagesRequest, - response: conversation.ListMessagesResponse, - *, - 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.ListMessagesRequest): - The initial request object. - response (google.cloud.dialogflow_v2.types.ListMessagesResponse): - 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 = conversation.ListMessagesRequest(request) - self._response = response - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - def pages(self) -> Iterator[conversation.ListMessagesResponse]: - yield self._response - while self._response.next_page_token: - self._request.page_token = self._response.next_page_token - self._response = self._method(self._request, metadata=self._metadata) - yield self._response - - def __iter__(self) -> Iterator[participant.Message]: - for page in self.pages: - yield from page.messages - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListMessagesAsyncPager: - """A pager for iterating through ``list_messages`` requests. - - This class thinly wraps an initial - :class:`google.cloud.dialogflow_v2.types.ListMessagesResponse` object, and - provides an ``__aiter__`` method to iterate through its - ``messages`` field. - - If there are more pages, the ``__aiter__`` method will make additional - ``ListMessages`` requests and continue to iterate - through the ``messages`` field on the - corresponding responses. - - All the usual :class:`google.cloud.dialogflow_v2.types.ListMessagesResponse` - 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[conversation.ListMessagesResponse]], - request: conversation.ListMessagesRequest, - response: conversation.ListMessagesResponse, - *, - metadata: Sequence[Tuple[str, str]] = ()): - """Instantiates the pager. - - Args: - method (Callable): The method that was originally called, and - which instantiated this pager. - request (google.cloud.dialogflow_v2.types.ListMessagesRequest): - The initial request object. - response (google.cloud.dialogflow_v2.types.ListMessagesResponse): - 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 = conversation.ListMessagesRequest(request) - self._response = response - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - async def pages(self) -> AsyncIterator[conversation.ListMessagesResponse]: - yield self._response - while self._response.next_page_token: - self._request.page_token = self._response.next_page_token - self._response = await self._method(self._request, metadata=self._metadata) - yield self._response - def __aiter__(self) -> AsyncIterator[participant.Message]: - async def async_generator(): - async for page in self.pages: - for response in page.messages: - yield response - - return async_generator() - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) diff --git a/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/conversations/transports/__init__.py b/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/conversations/transports/__init__.py deleted file mode 100644 index c16106880..000000000 --- a/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/conversations/transports/__init__.py +++ /dev/null @@ -1,38 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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 ConversationsTransport -from .grpc import ConversationsGrpcTransport -from .grpc_asyncio import ConversationsGrpcAsyncIOTransport -from .rest import ConversationsRestTransport -from .rest import ConversationsRestInterceptor - - -# Compile a registry of transports. -_transport_registry = OrderedDict() # type: Dict[str, Type[ConversationsTransport]] -_transport_registry['grpc'] = ConversationsGrpcTransport -_transport_registry['grpc_asyncio'] = ConversationsGrpcAsyncIOTransport -_transport_registry['rest'] = ConversationsRestTransport - -__all__ = ( - 'ConversationsTransport', - 'ConversationsGrpcTransport', - 'ConversationsGrpcAsyncIOTransport', - 'ConversationsRestTransport', - 'ConversationsRestInterceptor', -) diff --git a/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/conversations/transports/base.py b/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/conversations/transports/base.py deleted file mode 100644 index 219763844..000000000 --- a/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/conversations/transports/base.py +++ /dev/null @@ -1,265 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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 - -from google.cloud.dialogflow_v2 import gapic_version as package_version - -import google.auth # type: ignore -import google.api_core -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import retry as retries -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 conversation -from google.cloud.dialogflow_v2.types import conversation as gcd_conversation -from google.cloud.location import locations_pb2 # type: ignore -from google.longrunning import operations_pb2 - -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) - - -class ConversationsTransport(abc.ABC): - """Abstract transport class for Conversations.""" - - 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: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - api_audience: Optional[str] = None, - **kwargs, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. - scopes (Optional[Sequence[str]]): A list of scopes. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - """ - - scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} - - # Save the scopes. - self._scopes = scopes - - # If no credentials are provided, then determine the appropriate - # defaults. - if credentials and credentials_file: - raise core_exceptions.DuplicateCredentialArgs("'credentials_file' and 'credentials' are mutually exclusive") - - if credentials_file is not None: - credentials, _ = google.auth.load_credentials_from_file( - credentials_file, - **scopes_kwargs, - quota_project_id=quota_project_id - ) - elif credentials is None: - credentials, _ = google.auth.default(**scopes_kwargs, quota_project_id=quota_project_id) - # Don't apply audience if the credentials file passed from user. - if hasattr(credentials, "with_gdch_audience"): - credentials = credentials.with_gdch_audience(api_audience if api_audience else host) - - # If the credentials are service account credentials, then always try to use self signed JWT. - if always_use_jwt_access and isinstance(credentials, service_account.Credentials) and hasattr(service_account.Credentials, "with_always_use_jwt_access"): - credentials = credentials.with_always_use_jwt_access(True) - - # Save the credentials. - self._credentials = credentials - - # Save the hostname. Default to port 443 (HTTPS) if none is specified. - if ':' not in host: - host += ':443' - self._host = host - - def _prep_wrapped_messages(self, client_info): - # Precompute the wrapped methods. - self._wrapped_methods = { - self.create_conversation: gapic_v1.method.wrap_method( - self.create_conversation, - default_timeout=None, - client_info=client_info, - ), - self.list_conversations: gapic_v1.method.wrap_method( - self.list_conversations, - default_timeout=None, - client_info=client_info, - ), - self.get_conversation: gapic_v1.method.wrap_method( - self.get_conversation, - default_timeout=None, - client_info=client_info, - ), - self.complete_conversation: gapic_v1.method.wrap_method( - self.complete_conversation, - default_timeout=None, - client_info=client_info, - ), - self.list_messages: gapic_v1.method.wrap_method( - self.list_messages, - default_timeout=None, - client_info=client_info, - ), - self.suggest_conversation_summary: gapic_v1.method.wrap_method( - self.suggest_conversation_summary, - default_timeout=None, - client_info=client_info, - ), - } - - def close(self): - """Closes resources associated with the transport. - - .. warning:: - Only call this method if the transport is NOT shared - with other clients - this may cause errors in other clients! - """ - raise NotImplementedError() - - @property - def create_conversation(self) -> Callable[ - [gcd_conversation.CreateConversationRequest], - Union[ - gcd_conversation.Conversation, - Awaitable[gcd_conversation.Conversation] - ]]: - raise NotImplementedError() - - @property - def list_conversations(self) -> Callable[ - [conversation.ListConversationsRequest], - Union[ - conversation.ListConversationsResponse, - Awaitable[conversation.ListConversationsResponse] - ]]: - raise NotImplementedError() - - @property - def get_conversation(self) -> Callable[ - [conversation.GetConversationRequest], - Union[ - conversation.Conversation, - Awaitable[conversation.Conversation] - ]]: - raise NotImplementedError() - - @property - def complete_conversation(self) -> Callable[ - [conversation.CompleteConversationRequest], - Union[ - conversation.Conversation, - Awaitable[conversation.Conversation] - ]]: - raise NotImplementedError() - - @property - def list_messages(self) -> Callable[ - [conversation.ListMessagesRequest], - Union[ - conversation.ListMessagesResponse, - Awaitable[conversation.ListMessagesResponse] - ]]: - raise NotImplementedError() - - @property - def suggest_conversation_summary(self) -> Callable[ - [gcd_conversation.SuggestConversationSummaryRequest], - Union[ - gcd_conversation.SuggestConversationSummaryResponse, - Awaitable[gcd_conversation.SuggestConversationSummaryResponse] - ]]: - raise NotImplementedError() - - @property - def list_operations( - self, - ) -> Callable[ - [operations_pb2.ListOperationsRequest], - Union[operations_pb2.ListOperationsResponse, Awaitable[operations_pb2.ListOperationsResponse]], - ]: - raise NotImplementedError() - - @property - def get_operation( - self, - ) -> Callable[ - [operations_pb2.GetOperationRequest], - Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], - ]: - raise NotImplementedError() - - @property - def cancel_operation( - self, - ) -> Callable[ - [operations_pb2.CancelOperationRequest], - None, - ]: - raise NotImplementedError() - - @property - def get_location(self, - ) -> Callable[ - [locations_pb2.GetLocationRequest], - Union[locations_pb2.Location, Awaitable[locations_pb2.Location]], - ]: - raise NotImplementedError() - - @property - def list_locations(self, - ) -> Callable[ - [locations_pb2.ListLocationsRequest], - Union[locations_pb2.ListLocationsResponse, Awaitable[locations_pb2.ListLocationsResponse]], - ]: - raise NotImplementedError() - - @property - def kind(self) -> str: - raise NotImplementedError() - - -__all__ = ( - 'ConversationsTransport', -) diff --git a/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/conversations/transports/grpc.py b/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/conversations/transports/grpc.py deleted file mode 100644 index 0fbc091eb..000000000 --- a/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/conversations/transports/grpc.py +++ /dev/null @@ -1,517 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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 -from google.api_core import gapic_v1 -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 google.cloud.location import locations_pb2 # type: ignore -from google.longrunning import operations_pb2 -from .base import ConversationsTransport, DEFAULT_CLIENT_INFO - - -class ConversationsGrpcTransport(ConversationsTransport): - """gRPC backend transport for Conversations. - - Service for managing - [Conversations][google.cloud.dialogflow.v2.Conversation]. - - 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: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - channel: Optional[grpc.Channel] = None, - api_mtls_endpoint: Optional[str] = None, - client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, - ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, - client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - api_audience: Optional[str] = None, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - This argument is ignored if ``channel`` is provided. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional(Sequence[str])): A list of scopes. This argument is - ignored if ``channel`` is provided. - channel (Optional[grpc.Channel]): A ``Channel`` instance through - which to make calls. - api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. - If provided, it overrides the ``host`` argument and tries to create - a mutual TLS channel with client SSL credentials from - ``client_cert_source`` or application default SSL credentials. - client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): - Deprecated. A callback to provide client SSL certificate bytes and - private key bytes, both in PEM format. It is ignored if - ``api_mtls_endpoint`` is None. - ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials - for the grpc channel. It is ignored if ``channel`` is provided. - client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): - A callback to provide client certificate bytes and private key bytes, - both in PEM format. It is used to configure a mutual TLS channel. It is - ignored if ``channel`` or ``ssl_channel_credentials`` is provided. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport - creation failed for any reason. - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - self._grpc_channel = None - self._ssl_channel_credentials = ssl_channel_credentials - self._stubs: Dict[str, Callable] = {} - - if api_mtls_endpoint: - warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) - if client_cert_source: - warnings.warn("client_cert_source is deprecated", DeprecationWarning) - - if channel: - # Ignore credentials if a channel was passed. - credentials = False - # If a channel was explicitly provided, set it. - self._grpc_channel = channel - self._ssl_channel_credentials = None - - else: - if api_mtls_endpoint: - host = api_mtls_endpoint - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - self._ssl_channel_credentials = SslCredentials().ssl_credentials - - else: - if client_cert_source_for_mtls and not ssl_channel_credentials: - cert, key = client_cert_source_for_mtls() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - - # The base transport sets the host, credentials and scopes - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes, - quota_project_id=quota_project_id, - client_info=client_info, - always_use_jwt_access=always_use_jwt_access, - api_audience=api_audience, - ) - - if not self._grpc_channel: - self._grpc_channel = type(self).create_channel( - self._host, - # use the credentials which are saved - credentials=self._credentials, - # Set ``credentials_file`` to ``None`` here as - # the credentials that we saved earlier should be used. - credentials_file=None, - 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: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - **kwargs) -> grpc.Channel: - """Create and return a gRPC channel object. - Args: - host (Optional[str]): The host for the channel to use. - credentials (Optional[~.Credentials]): The - authorization credentials to attach to requests. These - credentials identify this application to the service. If - none are specified, the client will attempt to ascertain - the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - kwargs (Optional[dict]): Keyword arguments, which are passed to the - channel creation. - Returns: - grpc.Channel: A gRPC channel object. - - Raises: - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - - return grpc_helpers.create_channel( - host, - credentials=credentials, - credentials_file=credentials_file, - quota_project_id=quota_project_id, - default_scopes=cls.AUTH_SCOPES, - scopes=scopes, - default_host=cls.DEFAULT_HOST, - **kwargs - ) - - @property - def grpc_channel(self) -> grpc.Channel: - """Return the channel designed to connect to this service. - """ - return self._grpc_channel - - @property - def create_conversation(self) -> Callable[ - [gcd_conversation.CreateConversationRequest], - gcd_conversation.Conversation]: - r"""Return a callable for the create conversation method over gRPC. - - Creates a new conversation. Conversations are auto-completed - after 24 hours. - - Conversation Lifecycle: There are two stages during a - conversation: Automated Agent Stage and Assist Stage. - - For Automated Agent Stage, there will be a dialogflow agent - responding to user queries. - - For Assist Stage, there's no dialogflow agent responding to user - queries. But we will provide suggestions which are generated - from conversation. - - If - [Conversation.conversation_profile][google.cloud.dialogflow.v2.Conversation.conversation_profile] - is configured for a dialogflow agent, conversation will start - from ``Automated Agent Stage``, otherwise, it will start from - ``Assist Stage``. And during ``Automated Agent Stage``, once an - [Intent][google.cloud.dialogflow.v2.Intent] with - [Intent.live_agent_handoff][google.cloud.dialogflow.v2.Intent.live_agent_handoff] - is triggered, conversation will transfer to Assist Stage. - - Returns: - Callable[[~.CreateConversationRequest], - ~.Conversation]: - 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_conversation' not in self._stubs: - self._stubs['create_conversation'] = self.grpc_channel.unary_unary( - '/google.cloud.dialogflow.v2.Conversations/CreateConversation', - request_serializer=gcd_conversation.CreateConversationRequest.serialize, - response_deserializer=gcd_conversation.Conversation.deserialize, - ) - return self._stubs['create_conversation'] - - @property - def list_conversations(self) -> Callable[ - [conversation.ListConversationsRequest], - conversation.ListConversationsResponse]: - r"""Return a callable for the list conversations method over gRPC. - - Returns the list of all conversations in the - specified project. - - Returns: - Callable[[~.ListConversationsRequest], - ~.ListConversationsResponse]: - 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_conversations' not in self._stubs: - self._stubs['list_conversations'] = self.grpc_channel.unary_unary( - '/google.cloud.dialogflow.v2.Conversations/ListConversations', - request_serializer=conversation.ListConversationsRequest.serialize, - response_deserializer=conversation.ListConversationsResponse.deserialize, - ) - return self._stubs['list_conversations'] - - @property - def get_conversation(self) -> Callable[ - [conversation.GetConversationRequest], - conversation.Conversation]: - r"""Return a callable for the get conversation method over gRPC. - - Retrieves the specific conversation. - - Returns: - Callable[[~.GetConversationRequest], - ~.Conversation]: - 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_conversation' not in self._stubs: - self._stubs['get_conversation'] = self.grpc_channel.unary_unary( - '/google.cloud.dialogflow.v2.Conversations/GetConversation', - request_serializer=conversation.GetConversationRequest.serialize, - response_deserializer=conversation.Conversation.deserialize, - ) - return self._stubs['get_conversation'] - - @property - def complete_conversation(self) -> Callable[ - [conversation.CompleteConversationRequest], - conversation.Conversation]: - r"""Return a callable for the complete conversation method over gRPC. - - Completes the specified conversation. Finished - conversations are purged from the database after 30 - days. - - Returns: - Callable[[~.CompleteConversationRequest], - ~.Conversation]: - 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 'complete_conversation' not in self._stubs: - self._stubs['complete_conversation'] = self.grpc_channel.unary_unary( - '/google.cloud.dialogflow.v2.Conversations/CompleteConversation', - request_serializer=conversation.CompleteConversationRequest.serialize, - response_deserializer=conversation.Conversation.deserialize, - ) - return self._stubs['complete_conversation'] - - @property - def list_messages(self) -> Callable[ - [conversation.ListMessagesRequest], - conversation.ListMessagesResponse]: - r"""Return a callable for the list messages method over gRPC. - - Lists messages that belong to a given conversation. ``messages`` - are ordered by ``create_time`` in descending order. To fetch - updates without duplication, send request with filter - ``create_time_epoch_microseconds > [first item's create_time of previous request]`` - and empty page_token. - - Returns: - Callable[[~.ListMessagesRequest], - ~.ListMessagesResponse]: - 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_messages' not in self._stubs: - self._stubs['list_messages'] = self.grpc_channel.unary_unary( - '/google.cloud.dialogflow.v2.Conversations/ListMessages', - request_serializer=conversation.ListMessagesRequest.serialize, - response_deserializer=conversation.ListMessagesResponse.deserialize, - ) - return self._stubs['list_messages'] - - @property - def suggest_conversation_summary(self) -> Callable[ - [gcd_conversation.SuggestConversationSummaryRequest], - gcd_conversation.SuggestConversationSummaryResponse]: - r"""Return a callable for the suggest conversation summary method over gRPC. - - Suggests summary for a conversation based on specific - historical messages. The range of the messages to be - used for summary can be specified in the request. - - Returns: - Callable[[~.SuggestConversationSummaryRequest], - ~.SuggestConversationSummaryResponse]: - 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 'suggest_conversation_summary' not in self._stubs: - self._stubs['suggest_conversation_summary'] = self.grpc_channel.unary_unary( - '/google.cloud.dialogflow.v2.Conversations/SuggestConversationSummary', - request_serializer=gcd_conversation.SuggestConversationSummaryRequest.serialize, - response_deserializer=gcd_conversation.SuggestConversationSummaryResponse.deserialize, - ) - return self._stubs['suggest_conversation_summary'] - - def close(self): - self.grpc_channel.close() - - @property - def cancel_operation( - self, - ) -> Callable[[operations_pb2.CancelOperationRequest], None]: - r"""Return a callable for the cancel_operation method over gRPC. - """ - # 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 "cancel_operation" not in self._stubs: - self._stubs["cancel_operation"] = self.grpc_channel.unary_unary( - "/google.longrunning.Operations/CancelOperation", - request_serializer=operations_pb2.CancelOperationRequest.SerializeToString, - response_deserializer=None, - ) - return self._stubs["cancel_operation"] - - @property - def get_operation( - self, - ) -> Callable[[operations_pb2.GetOperationRequest], operations_pb2.Operation]: - r"""Return a callable for the get_operation method over gRPC. - """ - # 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_operation" not in self._stubs: - self._stubs["get_operation"] = self.grpc_channel.unary_unary( - "/google.longrunning.Operations/GetOperation", - request_serializer=operations_pb2.GetOperationRequest.SerializeToString, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs["get_operation"] - - @property - def list_operations( - self, - ) -> Callable[[operations_pb2.ListOperationsRequest], operations_pb2.ListOperationsResponse]: - r"""Return a callable for the list_operations method over gRPC. - """ - # 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_operations" not in self._stubs: - self._stubs["list_operations"] = self.grpc_channel.unary_unary( - "/google.longrunning.Operations/ListOperations", - request_serializer=operations_pb2.ListOperationsRequest.SerializeToString, - response_deserializer=operations_pb2.ListOperationsResponse.FromString, - ) - return self._stubs["list_operations"] - - @property - def list_locations( - self, - ) -> Callable[[locations_pb2.ListLocationsRequest], locations_pb2.ListLocationsResponse]: - r"""Return a callable for the list locations method over gRPC. - """ - # 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_locations" not in self._stubs: - self._stubs["list_locations"] = self.grpc_channel.unary_unary( - "/google.cloud.location.Locations/ListLocations", - request_serializer=locations_pb2.ListLocationsRequest.SerializeToString, - response_deserializer=locations_pb2.ListLocationsResponse.FromString, - ) - return self._stubs["list_locations"] - - @property - def get_location( - self, - ) -> Callable[[locations_pb2.GetLocationRequest], locations_pb2.Location]: - r"""Return a callable for the list locations method over gRPC. - """ - # 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_location" not in self._stubs: - self._stubs["get_location"] = self.grpc_channel.unary_unary( - "/google.cloud.location.Locations/GetLocation", - request_serializer=locations_pb2.GetLocationRequest.SerializeToString, - response_deserializer=locations_pb2.Location.FromString, - ) - return self._stubs["get_location"] - - @property - def kind(self) -> str: - return "grpc" - - -__all__ = ( - 'ConversationsGrpcTransport', -) diff --git a/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/conversations/transports/grpc_asyncio.py b/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/conversations/transports/grpc_asyncio.py deleted file mode 100644 index 62d7e798b..000000000 --- a/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/conversations/transports/grpc_asyncio.py +++ /dev/null @@ -1,516 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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 -from google.api_core import grpc_helpers_async -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore - -import grpc # type: ignore -from grpc.experimental import aio # type: ignore - -from google.cloud.dialogflow_v2.types import conversation -from google.cloud.dialogflow_v2.types import conversation as gcd_conversation -from google.cloud.location import locations_pb2 # type: ignore -from google.longrunning import operations_pb2 -from .base import ConversationsTransport, DEFAULT_CLIENT_INFO -from .grpc import ConversationsGrpcTransport - - -class ConversationsGrpcAsyncIOTransport(ConversationsTransport): - """gRPC AsyncIO backend transport for Conversations. - - Service for managing - [Conversations][google.cloud.dialogflow.v2.Conversation]. - - 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: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - **kwargs) -> aio.Channel: - """Create and return a gRPC AsyncIO channel object. - Args: - host (Optional[str]): The host for the channel to use. - credentials (Optional[~.Credentials]): The - authorization credentials to attach to requests. These - credentials identify this application to the service. If - none are specified, the client will attempt to ascertain - the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - kwargs (Optional[dict]): Keyword arguments, which are passed to the - channel creation. - Returns: - aio.Channel: A gRPC AsyncIO channel object. - """ - - return grpc_helpers_async.create_channel( - host, - credentials=credentials, - credentials_file=credentials_file, - quota_project_id=quota_project_id, - default_scopes=cls.AUTH_SCOPES, - scopes=scopes, - default_host=cls.DEFAULT_HOST, - **kwargs - ) - - def __init__(self, *, - host: str = 'dialogflow.googleapis.com', - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - channel: Optional[aio.Channel] = None, - api_mtls_endpoint: Optional[str] = None, - client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, - ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, - client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - api_audience: Optional[str] = None, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - This argument is ignored if ``channel`` is provided. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - channel (Optional[aio.Channel]): A ``Channel`` instance through - which to make calls. - api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. - If provided, it overrides the ``host`` argument and tries to create - a mutual TLS channel with client SSL credentials from - ``client_cert_source`` or application default SSL credentials. - client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): - Deprecated. A callback to provide client SSL certificate bytes and - private key bytes, both in PEM format. It is ignored if - ``api_mtls_endpoint`` is None. - ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials - for the grpc channel. It is ignored if ``channel`` is provided. - client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): - A callback to provide client certificate bytes and private key bytes, - both in PEM format. It is used to configure a mutual TLS channel. It is - ignored if ``channel`` or ``ssl_channel_credentials`` is provided. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - - Raises: - google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport - creation failed for any reason. - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - self._grpc_channel = None - self._ssl_channel_credentials = ssl_channel_credentials - self._stubs: Dict[str, Callable] = {} - - if api_mtls_endpoint: - warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) - if client_cert_source: - warnings.warn("client_cert_source is deprecated", DeprecationWarning) - - if channel: - # Ignore credentials if a channel was passed. - credentials = False - # If a channel was explicitly provided, set it. - self._grpc_channel = channel - self._ssl_channel_credentials = None - else: - if api_mtls_endpoint: - host = api_mtls_endpoint - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - self._ssl_channel_credentials = SslCredentials().ssl_credentials - - else: - if client_cert_source_for_mtls and not ssl_channel_credentials: - cert, key = client_cert_source_for_mtls() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - - # The base transport sets the host, credentials and scopes - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes, - quota_project_id=quota_project_id, - client_info=client_info, - always_use_jwt_access=always_use_jwt_access, - api_audience=api_audience, - ) - - if not self._grpc_channel: - self._grpc_channel = type(self).create_channel( - self._host, - # use the credentials which are saved - credentials=self._credentials, - # Set ``credentials_file`` to ``None`` here as - # the credentials that we saved earlier should be used. - credentials_file=None, - 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 create_conversation(self) -> Callable[ - [gcd_conversation.CreateConversationRequest], - Awaitable[gcd_conversation.Conversation]]: - r"""Return a callable for the create conversation method over gRPC. - - Creates a new conversation. Conversations are auto-completed - after 24 hours. - - Conversation Lifecycle: There are two stages during a - conversation: Automated Agent Stage and Assist Stage. - - For Automated Agent Stage, there will be a dialogflow agent - responding to user queries. - - For Assist Stage, there's no dialogflow agent responding to user - queries. But we will provide suggestions which are generated - from conversation. - - If - [Conversation.conversation_profile][google.cloud.dialogflow.v2.Conversation.conversation_profile] - is configured for a dialogflow agent, conversation will start - from ``Automated Agent Stage``, otherwise, it will start from - ``Assist Stage``. And during ``Automated Agent Stage``, once an - [Intent][google.cloud.dialogflow.v2.Intent] with - [Intent.live_agent_handoff][google.cloud.dialogflow.v2.Intent.live_agent_handoff] - is triggered, conversation will transfer to Assist Stage. - - Returns: - Callable[[~.CreateConversationRequest], - Awaitable[~.Conversation]]: - 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_conversation' not in self._stubs: - self._stubs['create_conversation'] = self.grpc_channel.unary_unary( - '/google.cloud.dialogflow.v2.Conversations/CreateConversation', - request_serializer=gcd_conversation.CreateConversationRequest.serialize, - response_deserializer=gcd_conversation.Conversation.deserialize, - ) - return self._stubs['create_conversation'] - - @property - def list_conversations(self) -> Callable[ - [conversation.ListConversationsRequest], - Awaitable[conversation.ListConversationsResponse]]: - r"""Return a callable for the list conversations method over gRPC. - - Returns the list of all conversations in the - specified project. - - Returns: - Callable[[~.ListConversationsRequest], - Awaitable[~.ListConversationsResponse]]: - 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_conversations' not in self._stubs: - self._stubs['list_conversations'] = self.grpc_channel.unary_unary( - '/google.cloud.dialogflow.v2.Conversations/ListConversations', - request_serializer=conversation.ListConversationsRequest.serialize, - response_deserializer=conversation.ListConversationsResponse.deserialize, - ) - return self._stubs['list_conversations'] - - @property - def get_conversation(self) -> Callable[ - [conversation.GetConversationRequest], - Awaitable[conversation.Conversation]]: - r"""Return a callable for the get conversation method over gRPC. - - Retrieves the specific conversation. - - Returns: - Callable[[~.GetConversationRequest], - Awaitable[~.Conversation]]: - 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_conversation' not in self._stubs: - self._stubs['get_conversation'] = self.grpc_channel.unary_unary( - '/google.cloud.dialogflow.v2.Conversations/GetConversation', - request_serializer=conversation.GetConversationRequest.serialize, - response_deserializer=conversation.Conversation.deserialize, - ) - return self._stubs['get_conversation'] - - @property - def complete_conversation(self) -> Callable[ - [conversation.CompleteConversationRequest], - Awaitable[conversation.Conversation]]: - r"""Return a callable for the complete conversation method over gRPC. - - Completes the specified conversation. Finished - conversations are purged from the database after 30 - days. - - Returns: - Callable[[~.CompleteConversationRequest], - Awaitable[~.Conversation]]: - 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 'complete_conversation' not in self._stubs: - self._stubs['complete_conversation'] = self.grpc_channel.unary_unary( - '/google.cloud.dialogflow.v2.Conversations/CompleteConversation', - request_serializer=conversation.CompleteConversationRequest.serialize, - response_deserializer=conversation.Conversation.deserialize, - ) - return self._stubs['complete_conversation'] - - @property - def list_messages(self) -> Callable[ - [conversation.ListMessagesRequest], - Awaitable[conversation.ListMessagesResponse]]: - r"""Return a callable for the list messages method over gRPC. - - Lists messages that belong to a given conversation. ``messages`` - are ordered by ``create_time`` in descending order. To fetch - updates without duplication, send request with filter - ``create_time_epoch_microseconds > [first item's create_time of previous request]`` - and empty page_token. - - Returns: - Callable[[~.ListMessagesRequest], - Awaitable[~.ListMessagesResponse]]: - 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_messages' not in self._stubs: - self._stubs['list_messages'] = self.grpc_channel.unary_unary( - '/google.cloud.dialogflow.v2.Conversations/ListMessages', - request_serializer=conversation.ListMessagesRequest.serialize, - response_deserializer=conversation.ListMessagesResponse.deserialize, - ) - return self._stubs['list_messages'] - - @property - def suggest_conversation_summary(self) -> Callable[ - [gcd_conversation.SuggestConversationSummaryRequest], - Awaitable[gcd_conversation.SuggestConversationSummaryResponse]]: - r"""Return a callable for the suggest conversation summary method over gRPC. - - Suggests summary for a conversation based on specific - historical messages. The range of the messages to be - used for summary can be specified in the request. - - Returns: - Callable[[~.SuggestConversationSummaryRequest], - Awaitable[~.SuggestConversationSummaryResponse]]: - 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 'suggest_conversation_summary' not in self._stubs: - self._stubs['suggest_conversation_summary'] = self.grpc_channel.unary_unary( - '/google.cloud.dialogflow.v2.Conversations/SuggestConversationSummary', - request_serializer=gcd_conversation.SuggestConversationSummaryRequest.serialize, - response_deserializer=gcd_conversation.SuggestConversationSummaryResponse.deserialize, - ) - return self._stubs['suggest_conversation_summary'] - - def close(self): - return self.grpc_channel.close() - - @property - def cancel_operation( - self, - ) -> Callable[[operations_pb2.CancelOperationRequest], None]: - r"""Return a callable for the cancel_operation method over gRPC. - """ - # 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 "cancel_operation" not in self._stubs: - self._stubs["cancel_operation"] = self.grpc_channel.unary_unary( - "/google.longrunning.Operations/CancelOperation", - request_serializer=operations_pb2.CancelOperationRequest.SerializeToString, - response_deserializer=None, - ) - return self._stubs["cancel_operation"] - - @property - def get_operation( - self, - ) -> Callable[[operations_pb2.GetOperationRequest], operations_pb2.Operation]: - r"""Return a callable for the get_operation method over gRPC. - """ - # 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_operation" not in self._stubs: - self._stubs["get_operation"] = self.grpc_channel.unary_unary( - "/google.longrunning.Operations/GetOperation", - request_serializer=operations_pb2.GetOperationRequest.SerializeToString, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs["get_operation"] - - @property - def list_operations( - self, - ) -> Callable[[operations_pb2.ListOperationsRequest], operations_pb2.ListOperationsResponse]: - r"""Return a callable for the list_operations method over gRPC. - """ - # 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_operations" not in self._stubs: - self._stubs["list_operations"] = self.grpc_channel.unary_unary( - "/google.longrunning.Operations/ListOperations", - request_serializer=operations_pb2.ListOperationsRequest.SerializeToString, - response_deserializer=operations_pb2.ListOperationsResponse.FromString, - ) - return self._stubs["list_operations"] - - @property - def list_locations( - self, - ) -> Callable[[locations_pb2.ListLocationsRequest], locations_pb2.ListLocationsResponse]: - r"""Return a callable for the list locations method over gRPC. - """ - # 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_locations" not in self._stubs: - self._stubs["list_locations"] = self.grpc_channel.unary_unary( - "/google.cloud.location.Locations/ListLocations", - request_serializer=locations_pb2.ListLocationsRequest.SerializeToString, - response_deserializer=locations_pb2.ListLocationsResponse.FromString, - ) - return self._stubs["list_locations"] - - @property - def get_location( - self, - ) -> Callable[[locations_pb2.GetLocationRequest], locations_pb2.Location]: - r"""Return a callable for the list locations method over gRPC. - """ - # 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_location" not in self._stubs: - self._stubs["get_location"] = self.grpc_channel.unary_unary( - "/google.cloud.location.Locations/GetLocation", - request_serializer=locations_pb2.GetLocationRequest.SerializeToString, - response_deserializer=locations_pb2.Location.FromString, - ) - return self._stubs["get_location"] - - -__all__ = ( - 'ConversationsGrpcAsyncIOTransport', -) diff --git a/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/conversations/transports/rest.py b/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/conversations/transports/rest.py deleted file mode 100644 index 76ac32adf..000000000 --- a/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/conversations/transports/rest.py +++ /dev/null @@ -1,1362 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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 google.auth.transport.requests import AuthorizedSession # type: ignore -import json # type: ignore -import grpc # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore -from google.auth import credentials as ga_credentials # type: ignore -from google.api_core import exceptions as core_exceptions -from google.api_core import retry as retries -from google.api_core import rest_helpers -from google.api_core import rest_streaming -from google.api_core import path_template -from google.api_core import gapic_v1 - -from google.protobuf import json_format -from google.cloud.location import locations_pb2 # type: ignore -from google.longrunning import operations_pb2 -from requests import __version__ as requests_version -import dataclasses -import re -from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union -import warnings - -try: - OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] -except AttributeError: # pragma: NO COVER - OptionalRetry = Union[retries.Retry, object] # 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 as BASE_DEFAULT_CLIENT_INFO - - -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=BASE_DEFAULT_CLIENT_INFO.gapic_version, - grpc_version=None, - rest_version=requests_version, -) - - -class ConversationsRestInterceptor: - """Interceptor for Conversations. - - Interceptors are used to manipulate requests, request metadata, and responses - in arbitrary ways. - Example use cases include: - * Logging - * Verifying requests according to service or custom semantics - * Stripping extraneous information from responses - - These use cases and more can be enabled by injecting an - instance of a custom subclass when constructing the ConversationsRestTransport. - - .. code-block:: python - class MyCustomConversationsInterceptor(ConversationsRestInterceptor): - def pre_complete_conversation(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_complete_conversation(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_create_conversation(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_create_conversation(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_get_conversation(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_get_conversation(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_list_conversations(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_list_conversations(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_list_messages(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_list_messages(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_suggest_conversation_summary(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_suggest_conversation_summary(self, response): - logging.log(f"Received response: {response}") - return response - - transport = ConversationsRestTransport(interceptor=MyCustomConversationsInterceptor()) - client = ConversationsClient(transport=transport) - - - """ - def pre_complete_conversation(self, request: conversation.CompleteConversationRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[conversation.CompleteConversationRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for complete_conversation - - Override in a subclass to manipulate the request or metadata - before they are sent to the Conversations server. - """ - return request, metadata - - def post_complete_conversation(self, response: conversation.Conversation) -> conversation.Conversation: - """Post-rpc interceptor for complete_conversation - - Override in a subclass to manipulate the response - after it is returned by the Conversations server but before - it is returned to user code. - """ - return response - def pre_create_conversation(self, request: gcd_conversation.CreateConversationRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[gcd_conversation.CreateConversationRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for create_conversation - - Override in a subclass to manipulate the request or metadata - before they are sent to the Conversations server. - """ - return request, metadata - - def post_create_conversation(self, response: gcd_conversation.Conversation) -> gcd_conversation.Conversation: - """Post-rpc interceptor for create_conversation - - Override in a subclass to manipulate the response - after it is returned by the Conversations server but before - it is returned to user code. - """ - return response - def pre_get_conversation(self, request: conversation.GetConversationRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[conversation.GetConversationRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for get_conversation - - Override in a subclass to manipulate the request or metadata - before they are sent to the Conversations server. - """ - return request, metadata - - def post_get_conversation(self, response: conversation.Conversation) -> conversation.Conversation: - """Post-rpc interceptor for get_conversation - - Override in a subclass to manipulate the response - after it is returned by the Conversations server but before - it is returned to user code. - """ - return response - def pre_list_conversations(self, request: conversation.ListConversationsRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[conversation.ListConversationsRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for list_conversations - - Override in a subclass to manipulate the request or metadata - before they are sent to the Conversations server. - """ - return request, metadata - - def post_list_conversations(self, response: conversation.ListConversationsResponse) -> conversation.ListConversationsResponse: - """Post-rpc interceptor for list_conversations - - Override in a subclass to manipulate the response - after it is returned by the Conversations server but before - it is returned to user code. - """ - return response - def pre_list_messages(self, request: conversation.ListMessagesRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[conversation.ListMessagesRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for list_messages - - Override in a subclass to manipulate the request or metadata - before they are sent to the Conversations server. - """ - return request, metadata - - def post_list_messages(self, response: conversation.ListMessagesResponse) -> conversation.ListMessagesResponse: - """Post-rpc interceptor for list_messages - - Override in a subclass to manipulate the response - after it is returned by the Conversations server but before - it is returned to user code. - """ - return response - def pre_suggest_conversation_summary(self, request: gcd_conversation.SuggestConversationSummaryRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[gcd_conversation.SuggestConversationSummaryRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for suggest_conversation_summary - - Override in a subclass to manipulate the request or metadata - before they are sent to the Conversations server. - """ - return request, metadata - - def post_suggest_conversation_summary(self, response: gcd_conversation.SuggestConversationSummaryResponse) -> gcd_conversation.SuggestConversationSummaryResponse: - """Post-rpc interceptor for suggest_conversation_summary - - Override in a subclass to manipulate the response - after it is returned by the Conversations server but before - it is returned to user code. - """ - return response - - def pre_get_location( - self, request: locations_pb2.GetLocationRequest, metadata: Sequence[Tuple[str, str]] - ) -> Tuple[locations_pb2.GetLocationRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for get_location - - Override in a subclass to manipulate the request or metadata - before they are sent to the Conversations server. - """ - return request, metadata - - def post_get_location( - self, response: locations_pb2.Location - ) -> locations_pb2.Location: - """Post-rpc interceptor for get_location - - Override in a subclass to manipulate the response - after it is returned by the Conversations server but before - it is returned to user code. - """ - return response - def pre_list_locations( - self, request: locations_pb2.ListLocationsRequest, metadata: Sequence[Tuple[str, str]] - ) -> Tuple[locations_pb2.ListLocationsRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for list_locations - - Override in a subclass to manipulate the request or metadata - before they are sent to the Conversations server. - """ - return request, metadata - - def post_list_locations( - self, response: locations_pb2.ListLocationsResponse - ) -> locations_pb2.ListLocationsResponse: - """Post-rpc interceptor for list_locations - - Override in a subclass to manipulate the response - after it is returned by the Conversations server but before - it is returned to user code. - """ - return response - def pre_cancel_operation( - self, request: operations_pb2.CancelOperationRequest, metadata: Sequence[Tuple[str, str]] - ) -> Tuple[operations_pb2.CancelOperationRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for cancel_operation - - Override in a subclass to manipulate the request or metadata - before they are sent to the Conversations server. - """ - return request, metadata - - def post_cancel_operation( - self, response: None - ) -> None: - """Post-rpc interceptor for cancel_operation - - Override in a subclass to manipulate the response - after it is returned by the Conversations server but before - it is returned to user code. - """ - return response - def pre_get_operation( - self, request: operations_pb2.GetOperationRequest, metadata: Sequence[Tuple[str, str]] - ) -> Tuple[operations_pb2.GetOperationRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for get_operation - - Override in a subclass to manipulate the request or metadata - before they are sent to the Conversations server. - """ - return request, metadata - - def post_get_operation( - self, response: operations_pb2.Operation - ) -> operations_pb2.Operation: - """Post-rpc interceptor for get_operation - - Override in a subclass to manipulate the response - after it is returned by the Conversations server but before - it is returned to user code. - """ - return response - def pre_list_operations( - self, request: operations_pb2.ListOperationsRequest, metadata: Sequence[Tuple[str, str]] - ) -> Tuple[operations_pb2.ListOperationsRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for list_operations - - Override in a subclass to manipulate the request or metadata - before they are sent to the Conversations server. - """ - return request, metadata - - def post_list_operations( - self, response: operations_pb2.ListOperationsResponse - ) -> operations_pb2.ListOperationsResponse: - """Post-rpc interceptor for list_operations - - Override in a subclass to manipulate the response - after it is returned by the Conversations server but before - it is returned to user code. - """ - return response - - -@dataclasses.dataclass -class ConversationsRestStub: - _session: AuthorizedSession - _host: str - _interceptor: ConversationsRestInterceptor - - -class ConversationsRestTransport(ConversationsTransport): - """REST backend transport for Conversations. - - Service for managing - [Conversations][google.cloud.dialogflow.v2.Conversation]. - - 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 JSON representations of protocol buffers over HTTP/1.1 - - """ - - def __init__(self, *, - host: str = 'dialogflow.googleapis.com', - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - client_cert_source_for_mtls: Optional[Callable[[ - ], Tuple[bytes, bytes]]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - url_scheme: str = 'https', - interceptor: Optional[ConversationsRestInterceptor] = None, - api_audience: Optional[str] = None, - ) -> 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 ignored if ``channel`` is provided. - scopes (Optional(Sequence[str])): A list of scopes. This argument is - ignored if ``channel`` is provided. - client_cert_source_for_mtls (Callable[[], Tuple[bytes, bytes]]): Client - certificate to configure mutual TLS HTTP channel. It is ignored - if ``channel`` is provided. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you are developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - url_scheme: the protocol scheme for the API endpoint. Normally - "https", but for testing or local servers, - "http" can be specified. - """ - # Run the base constructor - # TODO(yon-mg): resolve other ctor params i.e. scopes, quota, etc. - # TODO: When custom host (api_endpoint) is set, `scopes` must *also* be set on the - # credentials object - maybe_url_match = re.match("^(?Phttp(?:s)?://)?(?P.*)$", host) - if maybe_url_match is None: - raise ValueError(f"Unexpected hostname structure: {host}") # pragma: NO COVER - - url_match_items = maybe_url_match.groupdict() - - host = f"{url_scheme}://{host}" if not url_match_items["scheme"] else host - - super().__init__( - host=host, - credentials=credentials, - client_info=client_info, - always_use_jwt_access=always_use_jwt_access, - api_audience=api_audience - ) - self._session = AuthorizedSession( - self._credentials, default_host=self.DEFAULT_HOST) - if client_cert_source_for_mtls: - self._session.configure_mtls_channel(client_cert_source_for_mtls) - self._interceptor = interceptor or ConversationsRestInterceptor() - self._prep_wrapped_messages(client_info) - - class _CompleteConversation(ConversationsRestStub): - def __hash__(self): - return hash("CompleteConversation") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: conversation.CompleteConversationRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> conversation.Conversation: - r"""Call the complete conversation method over HTTP. - - Args: - request (~.conversation.CompleteConversationRequest): - The request object. The request message for - [Conversations.CompleteConversation][google.cloud.dialogflow.v2.Conversations.CompleteConversation]. - 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: - ~.conversation.Conversation: - Represents a conversation. - A conversation is an interaction between - an agent, including live agents and - Dialogflow agents, and a support - customer. Conversations can include - phone calls and text-based chat - sessions. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'post', - 'uri': '/v2/{name=projects/*/conversations/*}:complete', - 'body': '*', - }, -{ - 'method': 'post', - 'uri': '/v2/{name=projects/*/locations/*/conversations/*}:complete', - 'body': '*', - }, - ] - request, metadata = self._interceptor.pre_complete_conversation(request, metadata) - pb_request = conversation.CompleteConversationRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request['body'], - including_default_value_fields=False, - use_integers_for_enums=True - ) - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - including_default_value_fields=False, - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = conversation.Conversation() - pb_resp = conversation.Conversation.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_complete_conversation(resp) - return resp - - class _CreateConversation(ConversationsRestStub): - def __hash__(self): - return hash("CreateConversation") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: gcd_conversation.CreateConversationRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> gcd_conversation.Conversation: - r"""Call the create conversation method over HTTP. - - Args: - request (~.gcd_conversation.CreateConversationRequest): - The request object. The request message for - [Conversations.CreateConversation][google.cloud.dialogflow.v2.Conversations.CreateConversation]. - 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: - ~.gcd_conversation.Conversation: - Represents a conversation. - A conversation is an interaction between - an agent, including live agents and - Dialogflow agents, and a support - customer. Conversations can include - phone calls and text-based chat - sessions. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'post', - 'uri': '/v2/{parent=projects/*}/conversations', - 'body': 'conversation', - }, -{ - 'method': 'post', - 'uri': '/v2/{parent=projects/*/locations/*}/conversations', - 'body': 'conversation', - }, - ] - request, metadata = self._interceptor.pre_create_conversation(request, metadata) - pb_request = gcd_conversation.CreateConversationRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request['body'], - including_default_value_fields=False, - use_integers_for_enums=True - ) - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - including_default_value_fields=False, - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = gcd_conversation.Conversation() - pb_resp = gcd_conversation.Conversation.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_create_conversation(resp) - return resp - - class _GetConversation(ConversationsRestStub): - def __hash__(self): - return hash("GetConversation") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: conversation.GetConversationRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> conversation.Conversation: - r"""Call the get conversation method over HTTP. - - Args: - request (~.conversation.GetConversationRequest): - The request object. The request message for - [Conversations.GetConversation][google.cloud.dialogflow.v2.Conversations.GetConversation]. - 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: - ~.conversation.Conversation: - Represents a conversation. - A conversation is an interaction between - an agent, including live agents and - Dialogflow agents, and a support - customer. Conversations can include - phone calls and text-based chat - sessions. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v2/{name=projects/*/conversations/*}', - }, -{ - 'method': 'get', - 'uri': '/v2/{name=projects/*/locations/*/conversations/*}', - }, - ] - request, metadata = self._interceptor.pre_get_conversation(request, metadata) - pb_request = conversation.GetConversationRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - including_default_value_fields=False, - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = conversation.Conversation() - pb_resp = conversation.Conversation.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_get_conversation(resp) - return resp - - class _ListConversations(ConversationsRestStub): - def __hash__(self): - return hash("ListConversations") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: conversation.ListConversationsRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> conversation.ListConversationsResponse: - r"""Call the list conversations method over HTTP. - - Args: - request (~.conversation.ListConversationsRequest): - The request object. The request message for - [Conversations.ListConversations][google.cloud.dialogflow.v2.Conversations.ListConversations]. - 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: - ~.conversation.ListConversationsResponse: - The response message for - [Conversations.ListConversations][google.cloud.dialogflow.v2.Conversations.ListConversations]. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v2/{parent=projects/*}/conversations', - }, -{ - 'method': 'get', - 'uri': '/v2/{parent=projects/*/locations/*}/conversations', - }, - ] - request, metadata = self._interceptor.pre_list_conversations(request, metadata) - pb_request = conversation.ListConversationsRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - including_default_value_fields=False, - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = conversation.ListConversationsResponse() - pb_resp = conversation.ListConversationsResponse.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_list_conversations(resp) - return resp - - class _ListMessages(ConversationsRestStub): - def __hash__(self): - return hash("ListMessages") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: conversation.ListMessagesRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> conversation.ListMessagesResponse: - r"""Call the list messages method over HTTP. - - Args: - request (~.conversation.ListMessagesRequest): - The request object. The request message for - [Conversations.ListMessages][google.cloud.dialogflow.v2.Conversations.ListMessages]. - 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: - ~.conversation.ListMessagesResponse: - The response message for - [Conversations.ListMessages][google.cloud.dialogflow.v2.Conversations.ListMessages]. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v2/{parent=projects/*/conversations/*}/messages', - }, -{ - 'method': 'get', - 'uri': '/v2/{parent=projects/*/locations/*/conversations/*}/messages', - }, - ] - request, metadata = self._interceptor.pre_list_messages(request, metadata) - pb_request = conversation.ListMessagesRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - including_default_value_fields=False, - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = conversation.ListMessagesResponse() - pb_resp = conversation.ListMessagesResponse.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_list_messages(resp) - return resp - - class _SuggestConversationSummary(ConversationsRestStub): - def __hash__(self): - return hash("SuggestConversationSummary") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: gcd_conversation.SuggestConversationSummaryRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> gcd_conversation.SuggestConversationSummaryResponse: - r"""Call the suggest conversation - summary method over HTTP. - - Args: - request (~.gcd_conversation.SuggestConversationSummaryRequest): - The request object. The request message for - [Conversations.SuggestConversationSummary][google.cloud.dialogflow.v2.Conversations.SuggestConversationSummary]. - 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: - ~.gcd_conversation.SuggestConversationSummaryResponse: - The response message for - [Conversations.SuggestConversationSummary][google.cloud.dialogflow.v2.Conversations.SuggestConversationSummary]. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'post', - 'uri': '/v2/{conversation=projects/*/conversations/*}/suggestions:suggestConversationSummary', - 'body': '*', - }, -{ - 'method': 'post', - 'uri': '/v2/{conversation=projects/*/locations/*/conversations/*}/suggestions:suggestConversationSummary', - 'body': '*', - }, - ] - request, metadata = self._interceptor.pre_suggest_conversation_summary(request, metadata) - pb_request = gcd_conversation.SuggestConversationSummaryRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request['body'], - including_default_value_fields=False, - use_integers_for_enums=True - ) - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - including_default_value_fields=False, - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = gcd_conversation.SuggestConversationSummaryResponse() - pb_resp = gcd_conversation.SuggestConversationSummaryResponse.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_suggest_conversation_summary(resp) - return resp - - @property - def complete_conversation(self) -> Callable[ - [conversation.CompleteConversationRequest], - conversation.Conversation]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._CompleteConversation(self._session, self._host, self._interceptor) # type: ignore - - @property - def create_conversation(self) -> Callable[ - [gcd_conversation.CreateConversationRequest], - gcd_conversation.Conversation]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._CreateConversation(self._session, self._host, self._interceptor) # type: ignore - - @property - def get_conversation(self) -> Callable[ - [conversation.GetConversationRequest], - conversation.Conversation]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._GetConversation(self._session, self._host, self._interceptor) # type: ignore - - @property - def list_conversations(self) -> Callable[ - [conversation.ListConversationsRequest], - conversation.ListConversationsResponse]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._ListConversations(self._session, self._host, self._interceptor) # type: ignore - - @property - def list_messages(self) -> Callable[ - [conversation.ListMessagesRequest], - conversation.ListMessagesResponse]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._ListMessages(self._session, self._host, self._interceptor) # type: ignore - - @property - def suggest_conversation_summary(self) -> Callable[ - [gcd_conversation.SuggestConversationSummaryRequest], - gcd_conversation.SuggestConversationSummaryResponse]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._SuggestConversationSummary(self._session, self._host, self._interceptor) # type: ignore - - @property - def get_location(self): - return self._GetLocation(self._session, self._host, self._interceptor) # type: ignore - - class _GetLocation(ConversationsRestStub): - def __call__(self, - request: locations_pb2.GetLocationRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> locations_pb2.Location: - - r"""Call the get location method over HTTP. - - Args: - request (locations_pb2.GetLocationRequest): - The request object for GetLocation method. - 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: - locations_pb2.Location: Response from GetLocation method. - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v2/{name=projects/*/locations/*}', - }, - ] - - request, metadata = self._interceptor.pre_get_location(request, metadata) - request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode( - http_options, **request_kwargs) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json.dumps(transcoded_request['query_params'])) - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - resp = locations_pb2.Location() - resp = json_format.Parse(response.content.decode("utf-8"), resp) - resp = self._interceptor.post_get_location(resp) - return resp - - @property - def list_locations(self): - return self._ListLocations(self._session, self._host, self._interceptor) # type: ignore - - class _ListLocations(ConversationsRestStub): - def __call__(self, - request: locations_pb2.ListLocationsRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> locations_pb2.ListLocationsResponse: - - r"""Call the list locations method over HTTP. - - Args: - request (locations_pb2.ListLocationsRequest): - The request object for ListLocations method. - 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: - locations_pb2.ListLocationsResponse: Response from ListLocations method. - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v2/{name=projects/*}/locations', - }, - ] - - request, metadata = self._interceptor.pre_list_locations(request, metadata) - request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode( - http_options, **request_kwargs) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json.dumps(transcoded_request['query_params'])) - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - resp = locations_pb2.ListLocationsResponse() - resp = json_format.Parse(response.content.decode("utf-8"), resp) - resp = self._interceptor.post_list_locations(resp) - return resp - - @property - def cancel_operation(self): - return self._CancelOperation(self._session, self._host, self._interceptor) # type: ignore - - class _CancelOperation(ConversationsRestStub): - def __call__(self, - request: operations_pb2.CancelOperationRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> None: - - r"""Call the cancel operation method over HTTP. - - Args: - request (operations_pb2.CancelOperationRequest): - The request object for CancelOperation method. - 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. - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'post', - 'uri': '/v2/{name=projects/*/operations/*}:cancel', - }, -{ - 'method': 'post', - 'uri': '/v2/{name=projects/*/locations/*/operations/*}:cancel', - }, - ] - - request, metadata = self._interceptor.pre_cancel_operation(request, metadata) - request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode( - http_options, **request_kwargs) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json.dumps(transcoded_request['query_params'])) - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - return self._interceptor.post_cancel_operation(None) - - @property - def get_operation(self): - return self._GetOperation(self._session, self._host, self._interceptor) # type: ignore - - class _GetOperation(ConversationsRestStub): - def __call__(self, - request: operations_pb2.GetOperationRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> operations_pb2.Operation: - - r"""Call the get operation method over HTTP. - - Args: - request (operations_pb2.GetOperationRequest): - The request object for GetOperation method. - 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: - operations_pb2.Operation: Response from GetOperation method. - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v2/{name=projects/*/operations/*}', - }, -{ - 'method': 'get', - 'uri': '/v2/{name=projects/*/locations/*/operations/*}', - }, - ] - - request, metadata = self._interceptor.pre_get_operation(request, metadata) - request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode( - http_options, **request_kwargs) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json.dumps(transcoded_request['query_params'])) - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - resp = operations_pb2.Operation() - resp = json_format.Parse(response.content.decode("utf-8"), resp) - resp = self._interceptor.post_get_operation(resp) - return resp - - @property - def list_operations(self): - return self._ListOperations(self._session, self._host, self._interceptor) # type: ignore - - class _ListOperations(ConversationsRestStub): - def __call__(self, - request: operations_pb2.ListOperationsRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> operations_pb2.ListOperationsResponse: - - r"""Call the list operations method over HTTP. - - Args: - request (operations_pb2.ListOperationsRequest): - The request object for ListOperations method. - 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: - operations_pb2.ListOperationsResponse: Response from ListOperations method. - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v2/{name=projects/*}/operations', - }, -{ - 'method': 'get', - 'uri': '/v2/{name=projects/*/locations/*}/operations', - }, - ] - - request, metadata = self._interceptor.pre_list_operations(request, metadata) - request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode( - http_options, **request_kwargs) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json.dumps(transcoded_request['query_params'])) - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - resp = operations_pb2.ListOperationsResponse() - resp = json_format.Parse(response.content.decode("utf-8"), resp) - resp = self._interceptor.post_list_operations(resp) - return resp - - @property - def kind(self) -> str: - return "rest" - - def close(self): - self._session.close() - - -__all__=( - 'ConversationsRestTransport', -) diff --git a/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/documents/__init__.py b/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/documents/__init__.py deleted file mode 100644 index b54da36c3..000000000 --- a/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/documents/__init__.py +++ /dev/null @@ -1,22 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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 DocumentsClient -from .async_client import DocumentsAsyncClient - -__all__ = ( - 'DocumentsClient', - 'DocumentsAsyncClient', -) diff --git a/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/documents/async_client.py b/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/documents/async_client.py deleted file mode 100644 index 0c2eaeb43..000000000 --- a/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/documents/async_client.py +++ /dev/null @@ -1,1491 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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, Mapping, MutableMapping, MutableSequence, Optional, Sequence, Tuple, Type, Union - -from google.cloud.dialogflow_v2 import gapic_version as package_version - -from google.api_core.client_options import ClientOptions -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import retry as retries -from google.auth import credentials as ga_credentials # type: ignore -from google.oauth2 import service_account # type: ignore - -try: - OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] -except AttributeError: # pragma: NO COVER - OptionalRetry = Union[retries.Retry, object] # type: ignore - -from google.api_core import operation # type: ignore -from google.api_core import operation_async # type: ignore -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.cloud.location import locations_pb2 # type: ignore -from google.longrunning import operations_pb2 -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 - - -class DocumentsAsyncClient: - """Service for managing knowledge - [Documents][google.cloud.dialogflow.v2.Document]. - """ - - _client: DocumentsClient - - DEFAULT_ENDPOINT = DocumentsClient.DEFAULT_ENDPOINT - DEFAULT_MTLS_ENDPOINT = DocumentsClient.DEFAULT_MTLS_ENDPOINT - - 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) - - @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: - DocumentsAsyncClient: The constructed client. - """ - return DocumentsClient.from_service_account_info.__func__(DocumentsAsyncClient, 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: - DocumentsAsyncClient: The constructed client. - """ - return DocumentsClient.from_service_account_file.__func__(DocumentsAsyncClient, filename, *args, **kwargs) # type: ignore - - from_service_account_json = from_service_account_file - - @classmethod - def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[ClientOptions] = None): - """Return the API endpoint and client cert source for mutual TLS. - - The client cert source is determined in the following order: - (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the - client cert source is None. - (2) if `client_options.client_cert_source` is provided, use the provided one; if the - default client cert source exists, use the default one; otherwise the client cert - source is None. - - The API endpoint is determined in the following order: - (1) if `client_options.api_endpoint` if provided, use the provided one. - (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the - default mTLS endpoint; if the environment variable is "never", use the default API - endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise - use the default API endpoint. - - More details can be found at https://google.aip.dev/auth/4114. - - Args: - client_options (google.api_core.client_options.ClientOptions): Custom options for the - client. Only the `api_endpoint` and `client_cert_source` properties may be used - in this method. - - Returns: - Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the - client cert source to use. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If any errors happen. - """ - return DocumentsClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore - - @property - def transport(self) -> DocumentsTransport: - """Returns the transport used by the client instance. - - Returns: - DocumentsTransport: The transport used by the client instance. - """ - return self._client.transport - - get_transport_class = functools.partial(type(DocumentsClient).get_transport_class, type(DocumentsClient)) - - def __init__(self, *, - credentials: Optional[ga_credentials.Credentials] = None, - transport: Union[str, DocumentsTransport] = "grpc_asyncio", - client_options: Optional[ClientOptions] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the documents 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, ~.DocumentsTransport]): 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 = DocumentsClient( - credentials=credentials, - transport=transport, - client_options=client_options, - client_info=client_info, - - ) - - async def list_documents(self, - request: Optional[Union[document.ListDocumentsRequest, dict]] = None, - *, - parent: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListDocumentsAsyncPager: - r"""Returns the list of all documents of the knowledge - base. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import dialogflow_v2 - - async def sample_list_documents(): - # Create a client - client = dialogflow_v2.DocumentsAsyncClient() - - # Initialize request argument(s) - request = dialogflow_v2.ListDocumentsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_documents(request=request) - - # Handle the response - async for response in page_result: - print(response) - - Args: - request (Optional[Union[google.cloud.dialogflow_v2.types.ListDocumentsRequest, dict]]): - The request object. Request message for - [Documents.ListDocuments][google.cloud.dialogflow.v2.Documents.ListDocuments]. - parent (:class:`str`): - Required. The knowledge base to list all documents for. - Format: - ``projects//locations//knowledgeBases/``. - - 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.documents.pagers.ListDocumentsAsyncPager: - Response message for - [Documents.ListDocuments][google.cloud.dialogflow.v2.Documents.ListDocuments]. - - Iterating over this object will yield results and - resolve additional pages automatically. - - """ - # Create or coerce a protobuf request object. - # Quick 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 = document.ListDocumentsRequest(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_documents, - 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.ListDocumentsAsyncPager( - method=rpc, - request=request, - response=response, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def get_document(self, - request: Optional[Union[document.GetDocumentRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> document.Document: - r"""Retrieves the specified document. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import dialogflow_v2 - - async def sample_get_document(): - # Create a client - client = dialogflow_v2.DocumentsAsyncClient() - - # Initialize request argument(s) - request = dialogflow_v2.GetDocumentRequest( - name="name_value", - ) - - # Make the request - response = await client.get_document(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.dialogflow_v2.types.GetDocumentRequest, dict]]): - The request object. Request message for - [Documents.GetDocument][google.cloud.dialogflow.v2.Documents.GetDocument]. - name (:class:`str`): - Required. The name of the document to retrieve. Format - ``projects//locations//knowledgeBases//documents/``. - - 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.Document: - A knowledge document to be used by a - [KnowledgeBase][google.cloud.dialogflow.v2.KnowledgeBase]. - - For more information, see the [knowledge base - guide](\ https://cloud.google.com/dialogflow/docs/how/knowledge-bases). - - Note: The projects.agent.knowledgeBases.documents - resource is deprecated; only use - projects.knowledgeBases.documents. - - """ - # Create or coerce a protobuf request object. - # Quick 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 = document.GetDocumentRequest(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_document, - 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_document(self, - request: Optional[Union[gcd_document.CreateDocumentRequest, dict]] = None, - *, - parent: Optional[str] = None, - document: Optional[gcd_document.Document] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation_async.AsyncOperation: - r"""Creates a new document. - - This method is a `long-running - operation `__. - The returned ``Operation`` type has the following - method-specific fields: - - - ``metadata``: - [KnowledgeOperationMetadata][google.cloud.dialogflow.v2.KnowledgeOperationMetadata] - - ``response``: [Document][google.cloud.dialogflow.v2.Document] - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import dialogflow_v2 - - async def sample_create_document(): - # Create a client - client = dialogflow_v2.DocumentsAsyncClient() - - # Initialize request argument(s) - document = dialogflow_v2.Document() - document.content_uri = "content_uri_value" - document.display_name = "display_name_value" - document.mime_type = "mime_type_value" - document.knowledge_types = ['AGENT_FACING_SMART_REPLY'] - - request = dialogflow_v2.CreateDocumentRequest( - parent="parent_value", - document=document, - ) - - # Make the request - operation = client.create_document(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.dialogflow_v2.types.CreateDocumentRequest, dict]]): - The request object. Request message for - [Documents.CreateDocument][google.cloud.dialogflow.v2.Documents.CreateDocument]. - parent (:class:`str`): - Required. The knowledge base to create a document for. - Format: - ``projects//locations//knowledgeBases/``. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - document (:class:`google.cloud.dialogflow_v2.types.Document`): - Required. The document to create. - 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. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.api_core.operation_async.AsyncOperation: - An object representing a long-running operation. - - The result type for the operation will be :class:`google.cloud.dialogflow_v2.types.Document` A knowledge document to be used by a - [KnowledgeBase][google.cloud.dialogflow.v2.KnowledgeBase]. - - For more information, see the [knowledge base - guide](\ https://cloud.google.com/dialogflow/docs/how/knowledge-bases). - - Note: The projects.agent.knowledgeBases.documents - resource is deprecated; only use - projects.knowledgeBases.documents. - - """ - # Create or coerce a protobuf request object. - # Quick 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, document]) - 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_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: - request.document = document - - # 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_document, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Wrap the response in an operation future. - response = operation_async.from_gapic( - response, - self._client._transport.operations_client, - gcd_document.Document, - metadata_type=gcd_document.KnowledgeOperationMetadata, - ) - - # Done; return the response. - return response - - async def import_documents(self, - request: Optional[Union[document.ImportDocumentsRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation_async.AsyncOperation: - r"""Creates documents by importing data from external sources. - Dialogflow supports up to 350 documents in each request. If you - try to import more, Dialogflow will return an error. - - This method is a `long-running - operation `__. - The returned ``Operation`` type has the following - method-specific fields: - - - ``metadata``: - [KnowledgeOperationMetadata][google.cloud.dialogflow.v2.KnowledgeOperationMetadata] - - ``response``: - [ImportDocumentsResponse][google.cloud.dialogflow.v2.ImportDocumentsResponse] - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import dialogflow_v2 - - async def sample_import_documents(): - # Create a client - client = dialogflow_v2.DocumentsAsyncClient() - - # Initialize request argument(s) - gcs_source = dialogflow_v2.GcsSources() - gcs_source.uris = ['uris_value1', 'uris_value2'] - - document_template = dialogflow_v2.ImportDocumentTemplate() - document_template.mime_type = "mime_type_value" - document_template.knowledge_types = ['AGENT_FACING_SMART_REPLY'] - - request = dialogflow_v2.ImportDocumentsRequest( - gcs_source=gcs_source, - parent="parent_value", - document_template=document_template, - ) - - # Make the request - operation = client.import_documents(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.dialogflow_v2.types.ImportDocumentsRequest, dict]]): - The request object. Request message for - [Documents.ImportDocuments][google.cloud.dialogflow.v2.Documents.ImportDocuments]. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.api_core.operation_async.AsyncOperation: - An object representing a long-running operation. - - The result type for the operation will be :class:`google.cloud.dialogflow_v2.types.ImportDocumentsResponse` Response message for - [Documents.ImportDocuments][google.cloud.dialogflow.v2.Documents.ImportDocuments]. - - """ - # Create or coerce a protobuf request object. - request = document.ImportDocumentsRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.import_documents, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Wrap the response in an operation future. - response = operation_async.from_gapic( - response, - self._client._transport.operations_client, - document.ImportDocumentsResponse, - metadata_type=document.KnowledgeOperationMetadata, - ) - - # Done; return the response. - return response - - async def delete_document(self, - request: Optional[Union[document.DeleteDocumentRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation_async.AsyncOperation: - r"""Deletes the specified document. - - This method is a `long-running - operation `__. - The returned ``Operation`` type has the following - method-specific fields: - - - ``metadata``: - [KnowledgeOperationMetadata][google.cloud.dialogflow.v2.KnowledgeOperationMetadata] - - ``response``: An `Empty - message `__ - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import dialogflow_v2 - - async def sample_delete_document(): - # Create a client - client = dialogflow_v2.DocumentsAsyncClient() - - # Initialize request argument(s) - request = dialogflow_v2.DeleteDocumentRequest( - name="name_value", - ) - - # Make the request - operation = client.delete_document(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.dialogflow_v2.types.DeleteDocumentRequest, dict]]): - The request object. Request message for - [Documents.DeleteDocument][google.cloud.dialogflow.v2.Documents.DeleteDocument]. - name (:class:`str`): - Required. The name of the document to delete. Format: - ``projects//locations//knowledgeBases//documents/``. - - 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.api_core.operation_async.AsyncOperation: - An object representing a long-running operation. - - The result type for the operation will be :class:`google.protobuf.empty_pb2.Empty` A generic empty message that you can re-use to avoid defining duplicated - empty messages in your APIs. A typical example is to - use it as the request or the response type of an API - method. For instance: - - service Foo { - rpc Bar(google.protobuf.Empty) returns - (google.protobuf.Empty); - - } - - """ - # Create or coerce a protobuf request object. - # Quick 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 = document.DeleteDocumentRequest(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_document, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Wrap the response in an operation future. - response = operation_async.from_gapic( - response, - self._client._transport.operations_client, - empty_pb2.Empty, - metadata_type=document.KnowledgeOperationMetadata, - ) - - # Done; return the response. - return response - - async def update_document(self, - request: Optional[Union[gcd_document.UpdateDocumentRequest, dict]] = None, - *, - document: Optional[gcd_document.Document] = None, - update_mask: Optional[field_mask_pb2.FieldMask] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation_async.AsyncOperation: - r"""Updates the specified document. - - This method is a `long-running - operation `__. - The returned ``Operation`` type has the following - method-specific fields: - - - ``metadata``: - [KnowledgeOperationMetadata][google.cloud.dialogflow.v2.KnowledgeOperationMetadata] - - ``response``: [Document][google.cloud.dialogflow.v2.Document] - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import dialogflow_v2 - - async def sample_update_document(): - # Create a client - client = dialogflow_v2.DocumentsAsyncClient() - - # Initialize request argument(s) - document = dialogflow_v2.Document() - document.content_uri = "content_uri_value" - document.display_name = "display_name_value" - document.mime_type = "mime_type_value" - document.knowledge_types = ['AGENT_FACING_SMART_REPLY'] - - request = dialogflow_v2.UpdateDocumentRequest( - document=document, - ) - - # Make the request - operation = client.update_document(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.dialogflow_v2.types.UpdateDocumentRequest, dict]]): - The request object. Request message for - [Documents.UpdateDocument][google.cloud.dialogflow.v2.Documents.UpdateDocument]. - document (:class:`google.cloud.dialogflow_v2.types.Document`): - Required. The document to update. - This corresponds to the ``document`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - update_mask (:class:`google.protobuf.field_mask_pb2.FieldMask`): - Optional. Not specified means ``update all``. Currently, - only ``display_name`` can be updated, an InvalidArgument - will be returned for attempting to update other fields. - - 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.api_core.operation_async.AsyncOperation: - An object representing a long-running operation. - - The result type for the operation will be :class:`google.cloud.dialogflow_v2.types.Document` A knowledge document to be used by a - [KnowledgeBase][google.cloud.dialogflow.v2.KnowledgeBase]. - - For more information, see the [knowledge base - guide](\ https://cloud.google.com/dialogflow/docs/how/knowledge-bases). - - Note: The projects.agent.knowledgeBases.documents - resource is deprecated; only use - projects.knowledgeBases.documents. - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([document, 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_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: - 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_document, - 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(( - ("document.name", request.document.name), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Wrap the response in an operation future. - response = operation_async.from_gapic( - response, - self._client._transport.operations_client, - gcd_document.Document, - metadata_type=gcd_document.KnowledgeOperationMetadata, - ) - - # Done; return the response. - return response - - async def reload_document(self, - request: Optional[Union[document.ReloadDocumentRequest, dict]] = None, - *, - name: Optional[str] = None, - content_uri: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation_async.AsyncOperation: - r"""Reloads the specified document from its specified source, - content_uri or content. The previously loaded content of the - document will be deleted. Note: Even when the content of the - document has not changed, there still may be side effects - because of internal implementation changes. - - This method is a `long-running - operation `__. - The returned ``Operation`` type has the following - method-specific fields: - - - ``metadata``: - [KnowledgeOperationMetadata][google.cloud.dialogflow.v2.KnowledgeOperationMetadata] - - ``response``: [Document][google.cloud.dialogflow.v2.Document] - - Note: The ``projects.agent.knowledgeBases.documents`` resource - is deprecated; only use ``projects.knowledgeBases.documents``. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import dialogflow_v2 - - async def sample_reload_document(): - # Create a client - client = dialogflow_v2.DocumentsAsyncClient() - - # Initialize request argument(s) - request = dialogflow_v2.ReloadDocumentRequest( - content_uri="content_uri_value", - name="name_value", - ) - - # Make the request - operation = client.reload_document(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.dialogflow_v2.types.ReloadDocumentRequest, dict]]): - The request object. Request message for - [Documents.ReloadDocument][google.cloud.dialogflow.v2.Documents.ReloadDocument]. - name (:class:`str`): - Required. The name of the document to reload. Format: - ``projects//locations//knowledgeBases//documents/`` - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - content_uri (:class:`str`): - Optional. The path of gcs source file for reloading - document content. For now, only gcs uri is supported. - - For documents stored in Google Cloud Storage, these URIs - must have the form ``gs:///``. - - 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. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.api_core.operation_async.AsyncOperation: - An object representing a long-running operation. - - The result type for the operation will be :class:`google.cloud.dialogflow_v2.types.Document` A knowledge document to be used by a - [KnowledgeBase][google.cloud.dialogflow.v2.KnowledgeBase]. - - For more information, see the [knowledge base - guide](\ https://cloud.google.com/dialogflow/docs/how/knowledge-bases). - - Note: The projects.agent.knowledgeBases.documents - resource is deprecated; only use - projects.knowledgeBases.documents. - - """ - # Create or coerce a protobuf request object. - # Quick 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, content_uri]) - 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 = 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: - request.content_uri = content_uri - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.reload_document, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Wrap the response in an operation future. - response = operation_async.from_gapic( - response, - self._client._transport.operations_client, - document.Document, - metadata_type=document.KnowledgeOperationMetadata, - ) - - # Done; return the response. - return response - - async def export_document(self, - request: Optional[Union[document.ExportDocumentRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation_async.AsyncOperation: - r"""Exports a smart messaging candidate document into the specified - destination. - - This method is a `long-running - operation `__. - The returned ``Operation`` type has the following - method-specific fields: - - - ``metadata``: - [KnowledgeOperationMetadata][google.cloud.dialogflow.v2.KnowledgeOperationMetadata] - - ``response``: [Document][google.cloud.dialogflow.v2.Document] - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import dialogflow_v2 - - async def sample_export_document(): - # Create a client - client = dialogflow_v2.DocumentsAsyncClient() - - # Initialize request argument(s) - request = dialogflow_v2.ExportDocumentRequest( - name="name_value", - ) - - # Make the request - operation = client.export_document(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.dialogflow_v2.types.ExportDocumentRequest, dict]]): - The request object. Request message for - [Documents.ExportDocument][google.cloud.dialogflow.v2.Documents.ExportDocument]. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.api_core.operation_async.AsyncOperation: - An object representing a long-running operation. - - The result type for the operation will be :class:`google.cloud.dialogflow_v2.types.Document` A knowledge document to be used by a - [KnowledgeBase][google.cloud.dialogflow.v2.KnowledgeBase]. - - For more information, see the [knowledge base - guide](\ https://cloud.google.com/dialogflow/docs/how/knowledge-bases). - - Note: The projects.agent.knowledgeBases.documents - resource is deprecated; only use - projects.knowledgeBases.documents. - - """ - # Create or coerce a protobuf request object. - request = document.ExportDocumentRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.export_document, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Wrap the response in an operation future. - response = operation_async.from_gapic( - response, - self._client._transport.operations_client, - document.Document, - metadata_type=document.KnowledgeOperationMetadata, - ) - - # Done; return the response. - return response - - async def list_operations( - self, - request: Optional[operations_pb2.ListOperationsRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operations_pb2.ListOperationsResponse: - r"""Lists operations that match the specified filter in the request. - - Args: - request (:class:`~.operations_pb2.ListOperationsRequest`): - The request object. Request message for - `ListOperations` method. - 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: - ~.operations_pb2.ListOperationsResponse: - Response message for ``ListOperations`` method. - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = operations_pb2.ListOperationsRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._client._transport.list_operations, - 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 get_operation( - self, - request: Optional[operations_pb2.GetOperationRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operations_pb2.Operation: - r"""Gets the latest state of a long-running operation. - - Args: - request (:class:`~.operations_pb2.GetOperationRequest`): - The request object. Request message for - `GetOperation` method. - 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: - ~.operations_pb2.Operation: - An ``Operation`` object. - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = operations_pb2.GetOperationRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._client._transport.get_operation, - 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 cancel_operation( - self, - request: Optional[operations_pb2.CancelOperationRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> None: - r"""Starts asynchronous cancellation on a long-running operation. - - The server makes a best effort to cancel the operation, but success - is not guaranteed. If the server doesn't support this method, it returns - `google.rpc.Code.UNIMPLEMENTED`. - - Args: - request (:class:`~.operations_pb2.CancelOperationRequest`): - The request object. Request message for - `CancelOperation` method. - 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: - None - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = operations_pb2.CancelOperationRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._client._transport.cancel_operation, - 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_location( - self, - request: Optional[locations_pb2.GetLocationRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> locations_pb2.Location: - r"""Gets information about a location. - - Args: - request (:class:`~.location_pb2.GetLocationRequest`): - The request object. Request message for - `GetLocation` method. - 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: - ~.location_pb2.Location: - Location object. - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = locations_pb2.GetLocationRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._client._transport.get_location, - 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 list_locations( - self, - request: Optional[locations_pb2.ListLocationsRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> locations_pb2.ListLocationsResponse: - r"""Lists information about the supported locations for this service. - - Args: - request (:class:`~.location_pb2.ListLocationsRequest`): - The request object. Request message for - `ListLocations` method. - 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: - ~.location_pb2.ListLocationsResponse: - Response message for ``ListLocations`` method. - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = locations_pb2.ListLocationsRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._client._transport.list_locations, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("name", request.name),)), - ) - - # Send the request. - response = await rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - async def __aenter__(self): - return self - - async def __aexit__(self, exc_type, exc, tb): - await self.transport.close() - -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) - - -__all__ = ( - "DocumentsAsyncClient", -) diff --git a/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/documents/client.py b/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/documents/client.py deleted file mode 100644 index 310f158f0..000000000 --- a/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/documents/client.py +++ /dev/null @@ -1,1692 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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 os -import re -from typing import Dict, Mapping, MutableMapping, MutableSequence, Optional, Sequence, Tuple, Type, Union, cast - -from google.cloud.dialogflow_v2 import gapic_version as package_version - -from google.api_core import client_options as client_options_lib -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import retry as retries -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 - -try: - OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] -except AttributeError: # pragma: NO COVER - OptionalRetry = Union[retries.Retry, object] # type: ignore - -from google.api_core import operation # type: ignore -from google.api_core import operation_async # type: ignore -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.cloud.location import locations_pb2 # type: ignore -from google.longrunning import operations_pb2 -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 -from .transports.rest import DocumentsRestTransport - - -class DocumentsClientMeta(type): - """Metaclass for the Documents 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[DocumentsTransport]] - _transport_registry["grpc"] = DocumentsGrpcTransport - _transport_registry["grpc_asyncio"] = DocumentsGrpcAsyncIOTransport - _transport_registry["rest"] = DocumentsRestTransport - - def get_transport_class(cls, - label: Optional[str] = None, - ) -> Type[DocumentsTransport]: - """Returns an appropriate transport class. - - Args: - label: The name of the desired transport. If none is - provided, then the first transport in the registry is used. - - Returns: - The transport class to use. - """ - # If a specific transport is requested, return that one. - if label: - return cls._transport_registry[label] - - # No transport is requested; return the default (that is, the first one - # in the dictionary). - return next(iter(cls._transport_registry.values())) - - -class DocumentsClient(metaclass=DocumentsClientMeta): - """Service for managing knowledge - [Documents][google.cloud.dialogflow.v2.Document]. - """ - - @staticmethod - def _get_default_mtls_endpoint(api_endpoint): - """Converts api endpoint to mTLS endpoint. - - Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to - "*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively. - Args: - api_endpoint (Optional[str]): the api endpoint to convert. - Returns: - str: converted mTLS api endpoint. - """ - if not api_endpoint: - return api_endpoint - - mtls_endpoint_re = re.compile( - r"(?P[^.]+)(?P\.mtls)?(?P\.sandbox)?(?P\.googleapis\.com)?" - ) - - m = mtls_endpoint_re.match(api_endpoint) - name, mtls, sandbox, googledomain = m.groups() - if mtls or not googledomain: - return api_endpoint - - if sandbox: - return api_endpoint.replace( - "sandbox.googleapis.com", "mtls.sandbox.googleapis.com" - ) - - return api_endpoint.replace(".googleapis.com", ".mtls.googleapis.com") - - DEFAULT_ENDPOINT = "dialogflow.googleapis.com" - DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore - DEFAULT_ENDPOINT - ) - - @classmethod - def from_service_account_info(cls, info: dict, *args, **kwargs): - """Creates an instance of this client using the provided credentials - info. - - Args: - info (dict): The service account private key info. - args: Additional arguments to pass to the constructor. - kwargs: Additional arguments to pass to the constructor. - - Returns: - DocumentsClient: 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: - DocumentsClient: 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) -> DocumentsTransport: - """Returns the transport used by the client instance. - - Returns: - DocumentsTransport: The transport used by the client - instance. - """ - return self._transport - - @staticmethod - def document_path(project: str,knowledge_base: str,document: str,) -> str: - """Returns a fully-qualified document string.""" - return "projects/{project}/knowledgeBases/{knowledge_base}/documents/{document}".format(project=project, knowledge_base=knowledge_base, document=document, ) - - @staticmethod - def parse_document_path(path: str) -> Dict[str,str]: - """Parses a document path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/knowledgeBases/(?P.+?)/documents/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_billing_account_path(billing_account: str, ) -> str: - """Returns a fully-qualified billing_account string.""" - return "billingAccounts/{billing_account}".format(billing_account=billing_account, ) - - @staticmethod - def parse_common_billing_account_path(path: str) -> Dict[str,str]: - """Parse a billing_account path into its component segments.""" - m = re.match(r"^billingAccounts/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_folder_path(folder: str, ) -> str: - """Returns a fully-qualified folder string.""" - return "folders/{folder}".format(folder=folder, ) - - @staticmethod - def parse_common_folder_path(path: str) -> Dict[str,str]: - """Parse a folder path into its component segments.""" - m = re.match(r"^folders/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_organization_path(organization: str, ) -> str: - """Returns a fully-qualified organization string.""" - return "organizations/{organization}".format(organization=organization, ) - - @staticmethod - def parse_common_organization_path(path: str) -> Dict[str,str]: - """Parse a organization path into its component segments.""" - m = re.match(r"^organizations/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_project_path(project: str, ) -> str: - """Returns a fully-qualified project string.""" - return "projects/{project}".format(project=project, ) - - @staticmethod - def parse_common_project_path(path: str) -> Dict[str,str]: - """Parse a project path into its component segments.""" - m = re.match(r"^projects/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_location_path(project: str, location: str, ) -> str: - """Returns a fully-qualified location string.""" - return "projects/{project}/locations/{location}".format(project=project, location=location, ) - - @staticmethod - def parse_common_location_path(path: str) -> Dict[str,str]: - """Parse a location path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)$", path) - return m.groupdict() if m else {} - - @classmethod - def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[client_options_lib.ClientOptions] = None): - """Return the API endpoint and client cert source for mutual TLS. - - The client cert source is determined in the following order: - (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the - client cert source is None. - (2) if `client_options.client_cert_source` is provided, use the provided one; if the - default client cert source exists, use the default one; otherwise the client cert - source is None. - - The API endpoint is determined in the following order: - (1) if `client_options.api_endpoint` if provided, use the provided one. - (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the - default mTLS endpoint; if the environment variable is "never", use the default API - endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise - use the default API endpoint. - - More details can be found at https://google.aip.dev/auth/4114. - - Args: - client_options (google.api_core.client_options.ClientOptions): Custom options for the - client. Only the `api_endpoint` and `client_cert_source` properties may be used - in this method. - - Returns: - Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the - client cert source to use. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If any errors happen. - """ - if client_options is None: - client_options = client_options_lib.ClientOptions() - use_client_cert = os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false") - use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") - if use_client_cert not in ("true", "false"): - raise ValueError("Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`") - if use_mtls_endpoint not in ("auto", "never", "always"): - raise MutualTLSChannelError("Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`") - - # Figure out the client cert source to use. - client_cert_source = None - if use_client_cert == "true": - if client_options.client_cert_source: - client_cert_source = client_options.client_cert_source - elif mtls.has_default_client_cert_source(): - client_cert_source = mtls.default_client_cert_source() - - # Figure out which api endpoint to use. - if client_options.api_endpoint is not None: - api_endpoint = client_options.api_endpoint - elif use_mtls_endpoint == "always" or (use_mtls_endpoint == "auto" and client_cert_source): - api_endpoint = cls.DEFAULT_MTLS_ENDPOINT - else: - api_endpoint = cls.DEFAULT_ENDPOINT - - return api_endpoint, client_cert_source - - def __init__(self, *, - credentials: Optional[ga_credentials.Credentials] = None, - transport: Optional[Union[str, DocumentsTransport]] = None, - client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the documents 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, DocumentsTransport]): The - transport to use. If set to None, a transport is chosen - automatically. - client_options (Optional[Union[google.api_core.client_options.ClientOptions, dict]]): 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() - client_options = cast(client_options_lib.ClientOptions, client_options) - - api_endpoint, client_cert_source_func = self.get_mtls_endpoint_and_cert_source(client_options) - - api_key_value = getattr(client_options, "api_key", None) - if api_key_value and credentials: - raise ValueError("client_options.api_key and credentials are mutually exclusive") - - # 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, DocumentsTransport): - # transport is a DocumentsTransport instance. - if credentials or client_options.credentials_file or api_key_value: - 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: - import google.auth._default # type: ignore - - if api_key_value and hasattr(google.auth._default, "get_api_key_credentials"): - credentials = google.auth._default.get_api_key_credentials(api_key_value) - - Transport = type(self).get_transport_class(transport) - self._transport = Transport( - credentials=credentials, - credentials_file=client_options.credentials_file, - host=api_endpoint, - scopes=client_options.scopes, - client_cert_source_for_mtls=client_cert_source_func, - quota_project_id=client_options.quota_project_id, - client_info=client_info, - always_use_jwt_access=True, - api_audience=client_options.api_audience, - ) - - def list_documents(self, - request: Optional[Union[document.ListDocumentsRequest, dict]] = None, - *, - parent: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListDocumentsPager: - r"""Returns the list of all documents of the knowledge - base. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import dialogflow_v2 - - def sample_list_documents(): - # Create a client - client = dialogflow_v2.DocumentsClient() - - # Initialize request argument(s) - request = dialogflow_v2.ListDocumentsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_documents(request=request) - - # Handle the response - for response in page_result: - print(response) - - Args: - request (Union[google.cloud.dialogflow_v2.types.ListDocumentsRequest, dict]): - The request object. Request message for - [Documents.ListDocuments][google.cloud.dialogflow.v2.Documents.ListDocuments]. - parent (str): - Required. The knowledge base to list all documents for. - Format: - ``projects//locations//knowledgeBases/``. - - 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.documents.pagers.ListDocumentsPager: - Response message for - [Documents.ListDocuments][google.cloud.dialogflow.v2.Documents.ListDocuments]. - - Iterating over this object will yield results and - resolve additional pages automatically. - - """ - # Create or coerce a protobuf request object. - # Quick 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 document.ListDocumentsRequest. - # There's no risk of modifying the input as we've already verified - # 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 - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.list_documents] - - # 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.ListDocumentsPager( - method=rpc, - request=request, - response=response, - metadata=metadata, - ) - - # Done; return the response. - return response - - def get_document(self, - request: Optional[Union[document.GetDocumentRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> document.Document: - r"""Retrieves the specified document. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import dialogflow_v2 - - def sample_get_document(): - # Create a client - client = dialogflow_v2.DocumentsClient() - - # Initialize request argument(s) - request = dialogflow_v2.GetDocumentRequest( - name="name_value", - ) - - # Make the request - response = client.get_document(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.dialogflow_v2.types.GetDocumentRequest, dict]): - The request object. Request message for - [Documents.GetDocument][google.cloud.dialogflow.v2.Documents.GetDocument]. - name (str): - Required. The name of the document to retrieve. Format - ``projects//locations//knowledgeBases//documents/``. - - 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.Document: - A knowledge document to be used by a - [KnowledgeBase][google.cloud.dialogflow.v2.KnowledgeBase]. - - For more information, see the [knowledge base - guide](\ https://cloud.google.com/dialogflow/docs/how/knowledge-bases). - - Note: The projects.agent.knowledgeBases.documents - resource is deprecated; only use - projects.knowledgeBases.documents. - - """ - # Create or coerce a protobuf request object. - # Quick 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 document.GetDocumentRequest. - # There's no risk of modifying the input as we've already verified - # 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 - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.get_document] - - # 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_document(self, - request: Optional[Union[gcd_document.CreateDocumentRequest, dict]] = None, - *, - parent: Optional[str] = None, - document: Optional[gcd_document.Document] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation.Operation: - r"""Creates a new document. - - This method is a `long-running - operation `__. - The returned ``Operation`` type has the following - method-specific fields: - - - ``metadata``: - [KnowledgeOperationMetadata][google.cloud.dialogflow.v2.KnowledgeOperationMetadata] - - ``response``: [Document][google.cloud.dialogflow.v2.Document] - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import dialogflow_v2 - - def sample_create_document(): - # Create a client - client = dialogflow_v2.DocumentsClient() - - # Initialize request argument(s) - document = dialogflow_v2.Document() - document.content_uri = "content_uri_value" - document.display_name = "display_name_value" - document.mime_type = "mime_type_value" - document.knowledge_types = ['AGENT_FACING_SMART_REPLY'] - - request = dialogflow_v2.CreateDocumentRequest( - parent="parent_value", - document=document, - ) - - # Make the request - operation = client.create_document(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.dialogflow_v2.types.CreateDocumentRequest, dict]): - The request object. Request message for - [Documents.CreateDocument][google.cloud.dialogflow.v2.Documents.CreateDocument]. - parent (str): - Required. The knowledge base to create a document for. - Format: - ``projects//locations//knowledgeBases/``. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - document (google.cloud.dialogflow_v2.types.Document): - Required. The document to create. - 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. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.api_core.operation.Operation: - An object representing a long-running operation. - - The result type for the operation will be :class:`google.cloud.dialogflow_v2.types.Document` A knowledge document to be used by a - [KnowledgeBase][google.cloud.dialogflow.v2.KnowledgeBase]. - - For more information, see the [knowledge base - guide](\ https://cloud.google.com/dialogflow/docs/how/knowledge-bases). - - Note: The projects.agent.knowledgeBases.documents - resource is deprecated; only use - projects.knowledgeBases.documents. - - """ - # Create or coerce a protobuf request object. - # Quick 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, document]) - 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_document.CreateDocumentRequest. - # There's no risk of modifying the input as we've already verified - # 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: - request.document = document - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.create_document] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Wrap the response in an operation future. - response = operation.from_gapic( - response, - self._transport.operations_client, - gcd_document.Document, - metadata_type=gcd_document.KnowledgeOperationMetadata, - ) - - # Done; return the response. - return response - - def import_documents(self, - request: Optional[Union[document.ImportDocumentsRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation.Operation: - r"""Creates documents by importing data from external sources. - Dialogflow supports up to 350 documents in each request. If you - try to import more, Dialogflow will return an error. - - This method is a `long-running - operation `__. - The returned ``Operation`` type has the following - method-specific fields: - - - ``metadata``: - [KnowledgeOperationMetadata][google.cloud.dialogflow.v2.KnowledgeOperationMetadata] - - ``response``: - [ImportDocumentsResponse][google.cloud.dialogflow.v2.ImportDocumentsResponse] - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import dialogflow_v2 - - def sample_import_documents(): - # Create a client - client = dialogflow_v2.DocumentsClient() - - # Initialize request argument(s) - gcs_source = dialogflow_v2.GcsSources() - gcs_source.uris = ['uris_value1', 'uris_value2'] - - document_template = dialogflow_v2.ImportDocumentTemplate() - document_template.mime_type = "mime_type_value" - document_template.knowledge_types = ['AGENT_FACING_SMART_REPLY'] - - request = dialogflow_v2.ImportDocumentsRequest( - gcs_source=gcs_source, - parent="parent_value", - document_template=document_template, - ) - - # Make the request - operation = client.import_documents(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.dialogflow_v2.types.ImportDocumentsRequest, dict]): - The request object. Request message for - [Documents.ImportDocuments][google.cloud.dialogflow.v2.Documents.ImportDocuments]. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.api_core.operation.Operation: - An object representing a long-running operation. - - The result type for the operation will be :class:`google.cloud.dialogflow_v2.types.ImportDocumentsResponse` Response message for - [Documents.ImportDocuments][google.cloud.dialogflow.v2.Documents.ImportDocuments]. - - """ - # 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 - # there are no flattened fields. - if not isinstance(request, document.ImportDocumentsRequest): - request = document.ImportDocumentsRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.import_documents] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Wrap the response in an operation future. - response = operation.from_gapic( - response, - self._transport.operations_client, - document.ImportDocumentsResponse, - metadata_type=document.KnowledgeOperationMetadata, - ) - - # Done; return the response. - return response - - def delete_document(self, - request: Optional[Union[document.DeleteDocumentRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation.Operation: - r"""Deletes the specified document. - - This method is a `long-running - operation `__. - The returned ``Operation`` type has the following - method-specific fields: - - - ``metadata``: - [KnowledgeOperationMetadata][google.cloud.dialogflow.v2.KnowledgeOperationMetadata] - - ``response``: An `Empty - message `__ - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import dialogflow_v2 - - def sample_delete_document(): - # Create a client - client = dialogflow_v2.DocumentsClient() - - # Initialize request argument(s) - request = dialogflow_v2.DeleteDocumentRequest( - name="name_value", - ) - - # Make the request - operation = client.delete_document(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.dialogflow_v2.types.DeleteDocumentRequest, dict]): - The request object. Request message for - [Documents.DeleteDocument][google.cloud.dialogflow.v2.Documents.DeleteDocument]. - name (str): - Required. The name of the document to delete. Format: - ``projects//locations//knowledgeBases//documents/``. - - 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.api_core.operation.Operation: - An object representing a long-running operation. - - The result type for the operation will be :class:`google.protobuf.empty_pb2.Empty` A generic empty message that you can re-use to avoid defining duplicated - empty messages in your APIs. A typical example is to - use it as the request or the response type of an API - method. For instance: - - service Foo { - rpc Bar(google.protobuf.Empty) returns - (google.protobuf.Empty); - - } - - """ - # Create or coerce a protobuf request object. - # Quick 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 document.DeleteDocumentRequest. - # There's no risk of modifying the input as we've already verified - # 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 - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.delete_document] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Wrap the response in an operation future. - response = operation.from_gapic( - response, - self._transport.operations_client, - empty_pb2.Empty, - metadata_type=document.KnowledgeOperationMetadata, - ) - - # Done; return the response. - return response - - def update_document(self, - request: Optional[Union[gcd_document.UpdateDocumentRequest, dict]] = None, - *, - document: Optional[gcd_document.Document] = None, - update_mask: Optional[field_mask_pb2.FieldMask] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation.Operation: - r"""Updates the specified document. - - This method is a `long-running - operation `__. - The returned ``Operation`` type has the following - method-specific fields: - - - ``metadata``: - [KnowledgeOperationMetadata][google.cloud.dialogflow.v2.KnowledgeOperationMetadata] - - ``response``: [Document][google.cloud.dialogflow.v2.Document] - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import dialogflow_v2 - - def sample_update_document(): - # Create a client - client = dialogflow_v2.DocumentsClient() - - # Initialize request argument(s) - document = dialogflow_v2.Document() - document.content_uri = "content_uri_value" - document.display_name = "display_name_value" - document.mime_type = "mime_type_value" - document.knowledge_types = ['AGENT_FACING_SMART_REPLY'] - - request = dialogflow_v2.UpdateDocumentRequest( - document=document, - ) - - # Make the request - operation = client.update_document(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.dialogflow_v2.types.UpdateDocumentRequest, dict]): - The request object. Request message for - [Documents.UpdateDocument][google.cloud.dialogflow.v2.Documents.UpdateDocument]. - document (google.cloud.dialogflow_v2.types.Document): - Required. The document to update. - This corresponds to the ``document`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - update_mask (google.protobuf.field_mask_pb2.FieldMask): - Optional. Not specified means ``update all``. Currently, - only ``display_name`` can be updated, an InvalidArgument - will be returned for attempting to update other fields. - - 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.api_core.operation.Operation: - An object representing a long-running operation. - - The result type for the operation will be :class:`google.cloud.dialogflow_v2.types.Document` A knowledge document to be used by a - [KnowledgeBase][google.cloud.dialogflow.v2.KnowledgeBase]. - - For more information, see the [knowledge base - guide](\ https://cloud.google.com/dialogflow/docs/how/knowledge-bases). - - Note: The projects.agent.knowledgeBases.documents - resource is deprecated; only use - projects.knowledgeBases.documents. - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([document, 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_document.UpdateDocumentRequest. - # There's no risk of modifying the input as we've already verified - # 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: - 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_document] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("document.name", request.document.name), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Wrap the response in an operation future. - response = operation.from_gapic( - response, - self._transport.operations_client, - gcd_document.Document, - metadata_type=gcd_document.KnowledgeOperationMetadata, - ) - - # Done; return the response. - return response - - def reload_document(self, - request: Optional[Union[document.ReloadDocumentRequest, dict]] = None, - *, - name: Optional[str] = None, - content_uri: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation.Operation: - r"""Reloads the specified document from its specified source, - content_uri or content. The previously loaded content of the - document will be deleted. Note: Even when the content of the - document has not changed, there still may be side effects - because of internal implementation changes. - - This method is a `long-running - operation `__. - The returned ``Operation`` type has the following - method-specific fields: - - - ``metadata``: - [KnowledgeOperationMetadata][google.cloud.dialogflow.v2.KnowledgeOperationMetadata] - - ``response``: [Document][google.cloud.dialogflow.v2.Document] - - Note: The ``projects.agent.knowledgeBases.documents`` resource - is deprecated; only use ``projects.knowledgeBases.documents``. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import dialogflow_v2 - - def sample_reload_document(): - # Create a client - client = dialogflow_v2.DocumentsClient() - - # Initialize request argument(s) - request = dialogflow_v2.ReloadDocumentRequest( - content_uri="content_uri_value", - name="name_value", - ) - - # Make the request - operation = client.reload_document(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.dialogflow_v2.types.ReloadDocumentRequest, dict]): - The request object. Request message for - [Documents.ReloadDocument][google.cloud.dialogflow.v2.Documents.ReloadDocument]. - name (str): - Required. The name of the document to reload. Format: - ``projects//locations//knowledgeBases//documents/`` - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - content_uri (str): - Optional. The path of gcs source file for reloading - document content. For now, only gcs uri is supported. - - For documents stored in Google Cloud Storage, these URIs - must have the form ``gs:///``. - - 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. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.api_core.operation.Operation: - An object representing a long-running operation. - - The result type for the operation will be :class:`google.cloud.dialogflow_v2.types.Document` A knowledge document to be used by a - [KnowledgeBase][google.cloud.dialogflow.v2.KnowledgeBase]. - - For more information, see the [knowledge base - guide](\ https://cloud.google.com/dialogflow/docs/how/knowledge-bases). - - Note: The projects.agent.knowledgeBases.documents - resource is deprecated; only use - projects.knowledgeBases.documents. - - """ - # Create or coerce a protobuf request object. - # Quick 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, content_uri]) - 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 document.ReloadDocumentRequest. - # There's no risk of modifying the input as we've already verified - # 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: - request.content_uri = content_uri - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.reload_document] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Wrap the response in an operation future. - response = operation.from_gapic( - response, - self._transport.operations_client, - document.Document, - metadata_type=document.KnowledgeOperationMetadata, - ) - - # Done; return the response. - return response - - def export_document(self, - request: Optional[Union[document.ExportDocumentRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation.Operation: - r"""Exports a smart messaging candidate document into the specified - destination. - - This method is a `long-running - operation `__. - The returned ``Operation`` type has the following - method-specific fields: - - - ``metadata``: - [KnowledgeOperationMetadata][google.cloud.dialogflow.v2.KnowledgeOperationMetadata] - - ``response``: [Document][google.cloud.dialogflow.v2.Document] - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import dialogflow_v2 - - def sample_export_document(): - # Create a client - client = dialogflow_v2.DocumentsClient() - - # Initialize request argument(s) - request = dialogflow_v2.ExportDocumentRequest( - name="name_value", - ) - - # Make the request - operation = client.export_document(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.dialogflow_v2.types.ExportDocumentRequest, dict]): - The request object. Request message for - [Documents.ExportDocument][google.cloud.dialogflow.v2.Documents.ExportDocument]. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.api_core.operation.Operation: - An object representing a long-running operation. - - The result type for the operation will be :class:`google.cloud.dialogflow_v2.types.Document` A knowledge document to be used by a - [KnowledgeBase][google.cloud.dialogflow.v2.KnowledgeBase]. - - For more information, see the [knowledge base - guide](\ https://cloud.google.com/dialogflow/docs/how/knowledge-bases). - - Note: The projects.agent.knowledgeBases.documents - resource is deprecated; only use - projects.knowledgeBases.documents. - - """ - # Create or coerce a protobuf request object. - # Minor optimization to avoid making a copy if the user passes - # in a document.ExportDocumentRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, document.ExportDocumentRequest): - request = document.ExportDocumentRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.export_document] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Wrap the response in an operation future. - response = operation.from_gapic( - response, - self._transport.operations_client, - document.Document, - metadata_type=document.KnowledgeOperationMetadata, - ) - - # Done; return the response. - return response - - def __enter__(self) -> "DocumentsClient": - return self - - def __exit__(self, type, value, traceback): - """Releases underlying transport's resources. - - .. warning:: - ONLY use as a context manager if the transport is NOT shared - with other clients! Exiting the with block will CLOSE the transport - and may cause errors in other clients! - """ - self.transport.close() - - def list_operations( - self, - request: Optional[operations_pb2.ListOperationsRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operations_pb2.ListOperationsResponse: - r"""Lists operations that match the specified filter in the request. - - Args: - request (:class:`~.operations_pb2.ListOperationsRequest`): - The request object. Request message for - `ListOperations` method. - 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: - ~.operations_pb2.ListOperationsResponse: - Response message for ``ListOperations`` method. - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = operations_pb2.ListOperationsRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._transport.list_operations, - 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 = rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - def get_operation( - self, - request: Optional[operations_pb2.GetOperationRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operations_pb2.Operation: - r"""Gets the latest state of a long-running operation. - - Args: - request (:class:`~.operations_pb2.GetOperationRequest`): - The request object. Request message for - `GetOperation` method. - 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: - ~.operations_pb2.Operation: - An ``Operation`` object. - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = operations_pb2.GetOperationRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._transport.get_operation, - 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 = rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - def cancel_operation( - self, - request: Optional[operations_pb2.CancelOperationRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> None: - r"""Starts asynchronous cancellation on a long-running operation. - - The server makes a best effort to cancel the operation, but success - is not guaranteed. If the server doesn't support this method, it returns - `google.rpc.Code.UNIMPLEMENTED`. - - Args: - request (:class:`~.operations_pb2.CancelOperationRequest`): - The request object. Request message for - `CancelOperation` method. - 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: - None - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = operations_pb2.CancelOperationRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._transport.cancel_operation, - 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. - rpc(request, retry=retry, timeout=timeout, metadata=metadata,) - - def get_location( - self, - request: Optional[locations_pb2.GetLocationRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> locations_pb2.Location: - r"""Gets information about a location. - - Args: - request (:class:`~.location_pb2.GetLocationRequest`): - The request object. Request message for - `GetLocation` method. - 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: - ~.location_pb2.Location: - Location object. - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = locations_pb2.GetLocationRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._transport.get_location, - 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 = rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - def list_locations( - self, - request: Optional[locations_pb2.ListLocationsRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> locations_pb2.ListLocationsResponse: - r"""Lists information about the supported locations for this service. - - Args: - request (:class:`~.location_pb2.ListLocationsRequest`): - The request object. Request message for - `ListLocations` method. - 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: - ~.location_pb2.ListLocationsResponse: - Response message for ``ListLocations`` method. - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = locations_pb2.ListLocationsRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._transport.list_locations, - 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 = rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) - - -__all__ = ( - "DocumentsClient", -) diff --git a/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/documents/pagers.py b/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/documents/pagers.py deleted file mode 100644 index df8de9cd4..000000000 --- a/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/documents/pagers.py +++ /dev/null @@ -1,139 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from typing import Any, AsyncIterator, Awaitable, Callable, Sequence, Tuple, Optional, Iterator - -from google.cloud.dialogflow_v2.types import document - - -class ListDocumentsPager: - """A pager for iterating through ``list_documents`` requests. - - This class thinly wraps an initial - :class:`google.cloud.dialogflow_v2.types.ListDocumentsResponse` object, and - provides an ``__iter__`` method to iterate through its - ``documents`` field. - - If there are more pages, the ``__iter__`` method will make additional - ``ListDocuments`` requests and continue to iterate - through the ``documents`` field on the - corresponding responses. - - All the usual :class:`google.cloud.dialogflow_v2.types.ListDocumentsResponse` - 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[..., document.ListDocumentsResponse], - request: document.ListDocumentsRequest, - response: document.ListDocumentsResponse, - *, - 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.ListDocumentsRequest): - The initial request object. - response (google.cloud.dialogflow_v2.types.ListDocumentsResponse): - 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 = document.ListDocumentsRequest(request) - self._response = response - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - def pages(self) -> Iterator[document.ListDocumentsResponse]: - yield self._response - while self._response.next_page_token: - self._request.page_token = self._response.next_page_token - self._response = self._method(self._request, metadata=self._metadata) - yield self._response - - def __iter__(self) -> Iterator[document.Document]: - for page in self.pages: - yield from page.documents - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListDocumentsAsyncPager: - """A pager for iterating through ``list_documents`` requests. - - This class thinly wraps an initial - :class:`google.cloud.dialogflow_v2.types.ListDocumentsResponse` object, and - provides an ``__aiter__`` method to iterate through its - ``documents`` field. - - If there are more pages, the ``__aiter__`` method will make additional - ``ListDocuments`` requests and continue to iterate - through the ``documents`` field on the - corresponding responses. - - All the usual :class:`google.cloud.dialogflow_v2.types.ListDocumentsResponse` - 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[document.ListDocumentsResponse]], - request: document.ListDocumentsRequest, - response: document.ListDocumentsResponse, - *, - metadata: Sequence[Tuple[str, str]] = ()): - """Instantiates the pager. - - Args: - method (Callable): The method that was originally called, and - which instantiated this pager. - request (google.cloud.dialogflow_v2.types.ListDocumentsRequest): - The initial request object. - response (google.cloud.dialogflow_v2.types.ListDocumentsResponse): - 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 = document.ListDocumentsRequest(request) - self._response = response - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - async def pages(self) -> AsyncIterator[document.ListDocumentsResponse]: - yield self._response - while self._response.next_page_token: - self._request.page_token = self._response.next_page_token - self._response = await self._method(self._request, metadata=self._metadata) - yield self._response - def __aiter__(self) -> AsyncIterator[document.Document]: - async def async_generator(): - async for page in self.pages: - for response in page.documents: - yield response - - return async_generator() - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) diff --git a/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/documents/transports/__init__.py b/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/documents/transports/__init__.py deleted file mode 100644 index 4eb72cff2..000000000 --- a/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/documents/transports/__init__.py +++ /dev/null @@ -1,38 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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 DocumentsTransport -from .grpc import DocumentsGrpcTransport -from .grpc_asyncio import DocumentsGrpcAsyncIOTransport -from .rest import DocumentsRestTransport -from .rest import DocumentsRestInterceptor - - -# Compile a registry of transports. -_transport_registry = OrderedDict() # type: Dict[str, Type[DocumentsTransport]] -_transport_registry['grpc'] = DocumentsGrpcTransport -_transport_registry['grpc_asyncio'] = DocumentsGrpcAsyncIOTransport -_transport_registry['rest'] = DocumentsRestTransport - -__all__ = ( - 'DocumentsTransport', - 'DocumentsGrpcTransport', - 'DocumentsGrpcAsyncIOTransport', - 'DocumentsRestTransport', - 'DocumentsRestInterceptor', -) diff --git a/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/documents/transports/base.py b/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/documents/transports/base.py deleted file mode 100644 index 71ed25099..000000000 --- a/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/documents/transports/base.py +++ /dev/null @@ -1,300 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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 - -from google.cloud.dialogflow_v2 import gapic_version as package_version - -import google.auth # type: ignore -import google.api_core -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import retry as retries -from google.api_core import operations_v1 -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 document -from google.cloud.dialogflow_v2.types import document as gcd_document -from google.cloud.location import locations_pb2 # type: ignore -from google.longrunning import operations_pb2 -from google.longrunning import operations_pb2 # type: ignore - -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) - - -class DocumentsTransport(abc.ABC): - """Abstract transport class for Documents.""" - - 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: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - api_audience: Optional[str] = None, - **kwargs, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. - scopes (Optional[Sequence[str]]): A list of scopes. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - """ - - scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} - - # Save the scopes. - self._scopes = scopes - - # If no credentials are provided, then determine the appropriate - # defaults. - if credentials and credentials_file: - raise core_exceptions.DuplicateCredentialArgs("'credentials_file' and 'credentials' are mutually exclusive") - - if credentials_file is not None: - credentials, _ = google.auth.load_credentials_from_file( - credentials_file, - **scopes_kwargs, - quota_project_id=quota_project_id - ) - elif credentials is None: - credentials, _ = google.auth.default(**scopes_kwargs, quota_project_id=quota_project_id) - # Don't apply audience if the credentials file passed from user. - if hasattr(credentials, "with_gdch_audience"): - credentials = credentials.with_gdch_audience(api_audience if api_audience else host) - - # If the credentials are service account credentials, then always try to use self signed JWT. - if always_use_jwt_access and isinstance(credentials, service_account.Credentials) and hasattr(service_account.Credentials, "with_always_use_jwt_access"): - credentials = credentials.with_always_use_jwt_access(True) - - # Save the credentials. - self._credentials = credentials - - # Save the hostname. Default to port 443 (HTTPS) if none is specified. - if ':' not in host: - host += ':443' - self._host = host - - def _prep_wrapped_messages(self, client_info): - # Precompute the wrapped methods. - self._wrapped_methods = { - self.list_documents: gapic_v1.method.wrap_method( - self.list_documents, - default_timeout=None, - client_info=client_info, - ), - self.get_document: gapic_v1.method.wrap_method( - self.get_document, - default_timeout=None, - client_info=client_info, - ), - self.create_document: gapic_v1.method.wrap_method( - self.create_document, - default_timeout=None, - client_info=client_info, - ), - self.import_documents: gapic_v1.method.wrap_method( - self.import_documents, - default_timeout=None, - client_info=client_info, - ), - self.delete_document: gapic_v1.method.wrap_method( - self.delete_document, - default_timeout=None, - client_info=client_info, - ), - self.update_document: gapic_v1.method.wrap_method( - self.update_document, - default_timeout=None, - client_info=client_info, - ), - self.reload_document: gapic_v1.method.wrap_method( - self.reload_document, - default_timeout=None, - client_info=client_info, - ), - self.export_document: gapic_v1.method.wrap_method( - self.export_document, - default_timeout=None, - client_info=client_info, - ), - } - - def close(self): - """Closes resources associated with the transport. - - .. warning:: - Only call this method if the transport is NOT shared - with other clients - this may cause errors in other clients! - """ - raise NotImplementedError() - - @property - def operations_client(self): - """Return the client designed to process long-running operations.""" - raise NotImplementedError() - - @property - def list_documents(self) -> Callable[ - [document.ListDocumentsRequest], - Union[ - document.ListDocumentsResponse, - Awaitable[document.ListDocumentsResponse] - ]]: - raise NotImplementedError() - - @property - def get_document(self) -> Callable[ - [document.GetDocumentRequest], - Union[ - document.Document, - Awaitable[document.Document] - ]]: - raise NotImplementedError() - - @property - def create_document(self) -> Callable[ - [gcd_document.CreateDocumentRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: - raise NotImplementedError() - - @property - def import_documents(self) -> Callable[ - [document.ImportDocumentsRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: - raise NotImplementedError() - - @property - def delete_document(self) -> Callable[ - [document.DeleteDocumentRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: - raise NotImplementedError() - - @property - def update_document(self) -> Callable[ - [gcd_document.UpdateDocumentRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: - raise NotImplementedError() - - @property - def reload_document(self) -> Callable[ - [document.ReloadDocumentRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: - raise NotImplementedError() - - @property - def export_document(self) -> Callable[ - [document.ExportDocumentRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: - raise NotImplementedError() - - @property - def list_operations( - self, - ) -> Callable[ - [operations_pb2.ListOperationsRequest], - Union[operations_pb2.ListOperationsResponse, Awaitable[operations_pb2.ListOperationsResponse]], - ]: - raise NotImplementedError() - - @property - def get_operation( - self, - ) -> Callable[ - [operations_pb2.GetOperationRequest], - Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], - ]: - raise NotImplementedError() - - @property - def cancel_operation( - self, - ) -> Callable[ - [operations_pb2.CancelOperationRequest], - None, - ]: - raise NotImplementedError() - - @property - def get_location(self, - ) -> Callable[ - [locations_pb2.GetLocationRequest], - Union[locations_pb2.Location, Awaitable[locations_pb2.Location]], - ]: - raise NotImplementedError() - - @property - def list_locations(self, - ) -> Callable[ - [locations_pb2.ListLocationsRequest], - Union[locations_pb2.ListLocationsResponse, Awaitable[locations_pb2.ListLocationsResponse]], - ]: - raise NotImplementedError() - - @property - def kind(self) -> str: - raise NotImplementedError() - - -__all__ = ( - 'DocumentsTransport', -) diff --git a/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/documents/transports/grpc.py b/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/documents/transports/grpc.py deleted file mode 100644 index 6e56f4cc4..000000000 --- a/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/documents/transports/grpc.py +++ /dev/null @@ -1,626 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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 -from google.api_core import operations_v1 -from google.api_core import gapic_v1 -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.cloud.location import locations_pb2 # type: ignore -from google.longrunning import operations_pb2 -from google.longrunning import operations_pb2 # type: ignore -from .base import DocumentsTransport, DEFAULT_CLIENT_INFO - - -class DocumentsGrpcTransport(DocumentsTransport): - """gRPC backend transport for Documents. - - Service for managing knowledge - [Documents][google.cloud.dialogflow.v2.Document]. - - 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: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - channel: Optional[grpc.Channel] = None, - api_mtls_endpoint: Optional[str] = None, - client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, - ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, - client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - api_audience: Optional[str] = None, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - This argument is ignored if ``channel`` is provided. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional(Sequence[str])): A list of scopes. This argument is - ignored if ``channel`` is provided. - channel (Optional[grpc.Channel]): A ``Channel`` instance through - which to make calls. - api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. - If provided, it overrides the ``host`` argument and tries to create - a mutual TLS channel with client SSL credentials from - ``client_cert_source`` or application default SSL credentials. - client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): - Deprecated. A callback to provide client SSL certificate bytes and - private key bytes, both in PEM format. It is ignored if - ``api_mtls_endpoint`` is None. - ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials - for the grpc channel. It is ignored if ``channel`` is provided. - client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): - A callback to provide client certificate bytes and private key bytes, - both in PEM format. It is used to configure a mutual TLS channel. It is - ignored if ``channel`` or ``ssl_channel_credentials`` is provided. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport - creation failed for any reason. - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - self._grpc_channel = None - self._ssl_channel_credentials = ssl_channel_credentials - self._stubs: Dict[str, Callable] = {} - self._operations_client: Optional[operations_v1.OperationsClient] = None - - if api_mtls_endpoint: - warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) - if client_cert_source: - warnings.warn("client_cert_source is deprecated", DeprecationWarning) - - if channel: - # Ignore credentials if a channel was passed. - credentials = False - # If a channel was explicitly provided, set it. - self._grpc_channel = channel - self._ssl_channel_credentials = None - - else: - if api_mtls_endpoint: - host = api_mtls_endpoint - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - self._ssl_channel_credentials = SslCredentials().ssl_credentials - - else: - if client_cert_source_for_mtls and not ssl_channel_credentials: - cert, key = client_cert_source_for_mtls() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - - # The base transport sets the host, credentials and scopes - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes, - quota_project_id=quota_project_id, - client_info=client_info, - always_use_jwt_access=always_use_jwt_access, - api_audience=api_audience, - ) - - if not self._grpc_channel: - self._grpc_channel = type(self).create_channel( - self._host, - # use the credentials which are saved - credentials=self._credentials, - # Set ``credentials_file`` to ``None`` here as - # the credentials that we saved earlier should be used. - credentials_file=None, - 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: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - **kwargs) -> grpc.Channel: - """Create and return a gRPC channel object. - Args: - host (Optional[str]): The host for the channel to use. - credentials (Optional[~.Credentials]): The - authorization credentials to attach to requests. These - credentials identify this application to the service. If - none are specified, the client will attempt to ascertain - the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - kwargs (Optional[dict]): Keyword arguments, which are passed to the - channel creation. - Returns: - grpc.Channel: A gRPC channel object. - - Raises: - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - - return grpc_helpers.create_channel( - host, - credentials=credentials, - credentials_file=credentials_file, - quota_project_id=quota_project_id, - default_scopes=cls.AUTH_SCOPES, - scopes=scopes, - default_host=cls.DEFAULT_HOST, - **kwargs - ) - - @property - def grpc_channel(self) -> grpc.Channel: - """Return the channel designed to connect to this service. - """ - return self._grpc_channel - - @property - def operations_client(self) -> operations_v1.OperationsClient: - """Create the client designed to process long-running operations. - - This property caches on the instance; repeated calls return the same - client. - """ - # Quick check: Only create a new client if we do not already have one. - if self._operations_client is None: - self._operations_client = operations_v1.OperationsClient( - self.grpc_channel - ) - - # Return the client from cache. - return self._operations_client - - @property - def list_documents(self) -> Callable[ - [document.ListDocumentsRequest], - document.ListDocumentsResponse]: - r"""Return a callable for the list documents method over gRPC. - - Returns the list of all documents of the knowledge - base. - - Returns: - Callable[[~.ListDocumentsRequest], - ~.ListDocumentsResponse]: - 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_documents' not in self._stubs: - self._stubs['list_documents'] = self.grpc_channel.unary_unary( - '/google.cloud.dialogflow.v2.Documents/ListDocuments', - request_serializer=document.ListDocumentsRequest.serialize, - response_deserializer=document.ListDocumentsResponse.deserialize, - ) - return self._stubs['list_documents'] - - @property - def get_document(self) -> Callable[ - [document.GetDocumentRequest], - document.Document]: - r"""Return a callable for the get document method over gRPC. - - Retrieves the specified document. - - Returns: - Callable[[~.GetDocumentRequest], - ~.Document]: - 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_document' not in self._stubs: - self._stubs['get_document'] = self.grpc_channel.unary_unary( - '/google.cloud.dialogflow.v2.Documents/GetDocument', - request_serializer=document.GetDocumentRequest.serialize, - response_deserializer=document.Document.deserialize, - ) - return self._stubs['get_document'] - - @property - def create_document(self) -> Callable[ - [gcd_document.CreateDocumentRequest], - operations_pb2.Operation]: - r"""Return a callable for the create document method over gRPC. - - Creates a new document. - - This method is a `long-running - operation `__. - The returned ``Operation`` type has the following - method-specific fields: - - - ``metadata``: - [KnowledgeOperationMetadata][google.cloud.dialogflow.v2.KnowledgeOperationMetadata] - - ``response``: [Document][google.cloud.dialogflow.v2.Document] - - Returns: - Callable[[~.CreateDocumentRequest], - ~.Operation]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'create_document' not in self._stubs: - self._stubs['create_document'] = self.grpc_channel.unary_unary( - '/google.cloud.dialogflow.v2.Documents/CreateDocument', - request_serializer=gcd_document.CreateDocumentRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['create_document'] - - @property - def import_documents(self) -> Callable[ - [document.ImportDocumentsRequest], - operations_pb2.Operation]: - r"""Return a callable for the import documents method over gRPC. - - Creates documents by importing data from external sources. - Dialogflow supports up to 350 documents in each request. If you - try to import more, Dialogflow will return an error. - - This method is a `long-running - operation `__. - The returned ``Operation`` type has the following - method-specific fields: - - - ``metadata``: - [KnowledgeOperationMetadata][google.cloud.dialogflow.v2.KnowledgeOperationMetadata] - - ``response``: - [ImportDocumentsResponse][google.cloud.dialogflow.v2.ImportDocumentsResponse] - - Returns: - Callable[[~.ImportDocumentsRequest], - ~.Operation]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'import_documents' not in self._stubs: - self._stubs['import_documents'] = self.grpc_channel.unary_unary( - '/google.cloud.dialogflow.v2.Documents/ImportDocuments', - request_serializer=document.ImportDocumentsRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['import_documents'] - - @property - def delete_document(self) -> Callable[ - [document.DeleteDocumentRequest], - operations_pb2.Operation]: - r"""Return a callable for the delete document method over gRPC. - - Deletes the specified document. - - This method is a `long-running - operation `__. - The returned ``Operation`` type has the following - method-specific fields: - - - ``metadata``: - [KnowledgeOperationMetadata][google.cloud.dialogflow.v2.KnowledgeOperationMetadata] - - ``response``: An `Empty - message `__ - - Returns: - Callable[[~.DeleteDocumentRequest], - ~.Operation]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'delete_document' not in self._stubs: - self._stubs['delete_document'] = self.grpc_channel.unary_unary( - '/google.cloud.dialogflow.v2.Documents/DeleteDocument', - request_serializer=document.DeleteDocumentRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['delete_document'] - - @property - def update_document(self) -> Callable[ - [gcd_document.UpdateDocumentRequest], - operations_pb2.Operation]: - r"""Return a callable for the update document method over gRPC. - - Updates the specified document. - - This method is a `long-running - operation `__. - The returned ``Operation`` type has the following - method-specific fields: - - - ``metadata``: - [KnowledgeOperationMetadata][google.cloud.dialogflow.v2.KnowledgeOperationMetadata] - - ``response``: [Document][google.cloud.dialogflow.v2.Document] - - Returns: - Callable[[~.UpdateDocumentRequest], - ~.Operation]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'update_document' not in self._stubs: - self._stubs['update_document'] = self.grpc_channel.unary_unary( - '/google.cloud.dialogflow.v2.Documents/UpdateDocument', - request_serializer=gcd_document.UpdateDocumentRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['update_document'] - - @property - def reload_document(self) -> 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, - content_uri or content. The previously loaded content of the - document will be deleted. Note: Even when the content of the - document has not changed, there still may be side effects - because of internal implementation changes. - - This method is a `long-running - operation `__. - The returned ``Operation`` type has the following - method-specific fields: - - - ``metadata``: - [KnowledgeOperationMetadata][google.cloud.dialogflow.v2.KnowledgeOperationMetadata] - - ``response``: [Document][google.cloud.dialogflow.v2.Document] - - Note: The ``projects.agent.knowledgeBases.documents`` resource - is deprecated; only use ``projects.knowledgeBases.documents``. - - Returns: - Callable[[~.ReloadDocumentRequest], - ~.Operation]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'reload_document' not in self._stubs: - self._stubs['reload_document'] = self.grpc_channel.unary_unary( - '/google.cloud.dialogflow.v2.Documents/ReloadDocument', - request_serializer=document.ReloadDocumentRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['reload_document'] - - @property - def export_document(self) -> Callable[ - [document.ExportDocumentRequest], - operations_pb2.Operation]: - r"""Return a callable for the export document method over gRPC. - - Exports a smart messaging candidate document into the specified - destination. - - This method is a `long-running - operation `__. - The returned ``Operation`` type has the following - method-specific fields: - - - ``metadata``: - [KnowledgeOperationMetadata][google.cloud.dialogflow.v2.KnowledgeOperationMetadata] - - ``response``: [Document][google.cloud.dialogflow.v2.Document] - - Returns: - Callable[[~.ExportDocumentRequest], - ~.Operation]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'export_document' not in self._stubs: - self._stubs['export_document'] = self.grpc_channel.unary_unary( - '/google.cloud.dialogflow.v2.Documents/ExportDocument', - request_serializer=document.ExportDocumentRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['export_document'] - - def close(self): - self.grpc_channel.close() - - @property - def cancel_operation( - self, - ) -> Callable[[operations_pb2.CancelOperationRequest], None]: - r"""Return a callable for the cancel_operation method over gRPC. - """ - # 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 "cancel_operation" not in self._stubs: - self._stubs["cancel_operation"] = self.grpc_channel.unary_unary( - "/google.longrunning.Operations/CancelOperation", - request_serializer=operations_pb2.CancelOperationRequest.SerializeToString, - response_deserializer=None, - ) - return self._stubs["cancel_operation"] - - @property - def get_operation( - self, - ) -> Callable[[operations_pb2.GetOperationRequest], operations_pb2.Operation]: - r"""Return a callable for the get_operation method over gRPC. - """ - # 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_operation" not in self._stubs: - self._stubs["get_operation"] = self.grpc_channel.unary_unary( - "/google.longrunning.Operations/GetOperation", - request_serializer=operations_pb2.GetOperationRequest.SerializeToString, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs["get_operation"] - - @property - def list_operations( - self, - ) -> Callable[[operations_pb2.ListOperationsRequest], operations_pb2.ListOperationsResponse]: - r"""Return a callable for the list_operations method over gRPC. - """ - # 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_operations" not in self._stubs: - self._stubs["list_operations"] = self.grpc_channel.unary_unary( - "/google.longrunning.Operations/ListOperations", - request_serializer=operations_pb2.ListOperationsRequest.SerializeToString, - response_deserializer=operations_pb2.ListOperationsResponse.FromString, - ) - return self._stubs["list_operations"] - - @property - def list_locations( - self, - ) -> Callable[[locations_pb2.ListLocationsRequest], locations_pb2.ListLocationsResponse]: - r"""Return a callable for the list locations method over gRPC. - """ - # 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_locations" not in self._stubs: - self._stubs["list_locations"] = self.grpc_channel.unary_unary( - "/google.cloud.location.Locations/ListLocations", - request_serializer=locations_pb2.ListLocationsRequest.SerializeToString, - response_deserializer=locations_pb2.ListLocationsResponse.FromString, - ) - return self._stubs["list_locations"] - - @property - def get_location( - self, - ) -> Callable[[locations_pb2.GetLocationRequest], locations_pb2.Location]: - r"""Return a callable for the list locations method over gRPC. - """ - # 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_location" not in self._stubs: - self._stubs["get_location"] = self.grpc_channel.unary_unary( - "/google.cloud.location.Locations/GetLocation", - request_serializer=locations_pb2.GetLocationRequest.SerializeToString, - response_deserializer=locations_pb2.Location.FromString, - ) - return self._stubs["get_location"] - - @property - def kind(self) -> str: - return "grpc" - - -__all__ = ( - 'DocumentsGrpcTransport', -) diff --git a/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/documents/transports/grpc_asyncio.py b/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/documents/transports/grpc_asyncio.py deleted file mode 100644 index 1467a4ca7..000000000 --- a/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/documents/transports/grpc_asyncio.py +++ /dev/null @@ -1,625 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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 -from google.api_core import grpc_helpers_async -from google.api_core import operations_v1 -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore - -import grpc # type: ignore -from grpc.experimental import aio # type: ignore - -from google.cloud.dialogflow_v2.types import document -from google.cloud.dialogflow_v2.types import document as gcd_document -from google.cloud.location import locations_pb2 # type: ignore -from google.longrunning import operations_pb2 -from google.longrunning import operations_pb2 # type: ignore -from .base import DocumentsTransport, DEFAULT_CLIENT_INFO -from .grpc import DocumentsGrpcTransport - - -class DocumentsGrpcAsyncIOTransport(DocumentsTransport): - """gRPC AsyncIO backend transport for Documents. - - Service for managing knowledge - [Documents][google.cloud.dialogflow.v2.Document]. - - 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: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - **kwargs) -> aio.Channel: - """Create and return a gRPC AsyncIO channel object. - Args: - host (Optional[str]): The host for the channel to use. - credentials (Optional[~.Credentials]): The - authorization credentials to attach to requests. These - credentials identify this application to the service. If - none are specified, the client will attempt to ascertain - the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - kwargs (Optional[dict]): Keyword arguments, which are passed to the - channel creation. - Returns: - aio.Channel: A gRPC AsyncIO channel object. - """ - - return grpc_helpers_async.create_channel( - host, - credentials=credentials, - credentials_file=credentials_file, - quota_project_id=quota_project_id, - default_scopes=cls.AUTH_SCOPES, - scopes=scopes, - default_host=cls.DEFAULT_HOST, - **kwargs - ) - - def __init__(self, *, - host: str = 'dialogflow.googleapis.com', - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - channel: Optional[aio.Channel] = None, - api_mtls_endpoint: Optional[str] = None, - client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, - ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, - client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - api_audience: Optional[str] = None, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - This argument is ignored if ``channel`` is provided. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - channel (Optional[aio.Channel]): A ``Channel`` instance through - which to make calls. - api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. - If provided, it overrides the ``host`` argument and tries to create - a mutual TLS channel with client SSL credentials from - ``client_cert_source`` or application default SSL credentials. - client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): - Deprecated. A callback to provide client SSL certificate bytes and - private key bytes, both in PEM format. It is ignored if - ``api_mtls_endpoint`` is None. - ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials - for the grpc channel. It is ignored if ``channel`` is provided. - client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): - A callback to provide client certificate bytes and private key bytes, - both in PEM format. It is used to configure a mutual TLS channel. It is - ignored if ``channel`` or ``ssl_channel_credentials`` is provided. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - - Raises: - google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport - creation failed for any reason. - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - self._grpc_channel = None - self._ssl_channel_credentials = ssl_channel_credentials - self._stubs: Dict[str, Callable] = {} - self._operations_client: Optional[operations_v1.OperationsAsyncClient] = None - - if api_mtls_endpoint: - warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) - if client_cert_source: - warnings.warn("client_cert_source is deprecated", DeprecationWarning) - - if channel: - # Ignore credentials if a channel was passed. - credentials = False - # If a channel was explicitly provided, set it. - self._grpc_channel = channel - self._ssl_channel_credentials = None - else: - if api_mtls_endpoint: - host = api_mtls_endpoint - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - self._ssl_channel_credentials = SslCredentials().ssl_credentials - - else: - if client_cert_source_for_mtls and not ssl_channel_credentials: - cert, key = client_cert_source_for_mtls() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - - # The base transport sets the host, credentials and scopes - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes, - quota_project_id=quota_project_id, - client_info=client_info, - always_use_jwt_access=always_use_jwt_access, - api_audience=api_audience, - ) - - if not self._grpc_channel: - self._grpc_channel = type(self).create_channel( - self._host, - # use the credentials which are saved - credentials=self._credentials, - # Set ``credentials_file`` to ``None`` here as - # the credentials that we saved earlier should be used. - credentials_file=None, - 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 operations_client(self) -> operations_v1.OperationsAsyncClient: - """Create the client designed to process long-running operations. - - This property caches on the instance; repeated calls return the same - client. - """ - # Quick check: Only create a new client if we do not already have one. - if self._operations_client is None: - self._operations_client = operations_v1.OperationsAsyncClient( - self.grpc_channel - ) - - # Return the client from cache. - return self._operations_client - - @property - def list_documents(self) -> Callable[ - [document.ListDocumentsRequest], - Awaitable[document.ListDocumentsResponse]]: - r"""Return a callable for the list documents method over gRPC. - - Returns the list of all documents of the knowledge - base. - - Returns: - Callable[[~.ListDocumentsRequest], - Awaitable[~.ListDocumentsResponse]]: - 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_documents' not in self._stubs: - self._stubs['list_documents'] = self.grpc_channel.unary_unary( - '/google.cloud.dialogflow.v2.Documents/ListDocuments', - request_serializer=document.ListDocumentsRequest.serialize, - response_deserializer=document.ListDocumentsResponse.deserialize, - ) - return self._stubs['list_documents'] - - @property - def get_document(self) -> Callable[ - [document.GetDocumentRequest], - Awaitable[document.Document]]: - r"""Return a callable for the get document method over gRPC. - - Retrieves the specified document. - - Returns: - Callable[[~.GetDocumentRequest], - Awaitable[~.Document]]: - 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_document' not in self._stubs: - self._stubs['get_document'] = self.grpc_channel.unary_unary( - '/google.cloud.dialogflow.v2.Documents/GetDocument', - request_serializer=document.GetDocumentRequest.serialize, - response_deserializer=document.Document.deserialize, - ) - return self._stubs['get_document'] - - @property - def create_document(self) -> Callable[ - [gcd_document.CreateDocumentRequest], - Awaitable[operations_pb2.Operation]]: - r"""Return a callable for the create document method over gRPC. - - Creates a new document. - - This method is a `long-running - operation `__. - The returned ``Operation`` type has the following - method-specific fields: - - - ``metadata``: - [KnowledgeOperationMetadata][google.cloud.dialogflow.v2.KnowledgeOperationMetadata] - - ``response``: [Document][google.cloud.dialogflow.v2.Document] - - Returns: - Callable[[~.CreateDocumentRequest], - Awaitable[~.Operation]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'create_document' not in self._stubs: - self._stubs['create_document'] = self.grpc_channel.unary_unary( - '/google.cloud.dialogflow.v2.Documents/CreateDocument', - request_serializer=gcd_document.CreateDocumentRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['create_document'] - - @property - def import_documents(self) -> Callable[ - [document.ImportDocumentsRequest], - Awaitable[operations_pb2.Operation]]: - r"""Return a callable for the import documents method over gRPC. - - Creates documents by importing data from external sources. - Dialogflow supports up to 350 documents in each request. If you - try to import more, Dialogflow will return an error. - - This method is a `long-running - operation `__. - The returned ``Operation`` type has the following - method-specific fields: - - - ``metadata``: - [KnowledgeOperationMetadata][google.cloud.dialogflow.v2.KnowledgeOperationMetadata] - - ``response``: - [ImportDocumentsResponse][google.cloud.dialogflow.v2.ImportDocumentsResponse] - - Returns: - Callable[[~.ImportDocumentsRequest], - Awaitable[~.Operation]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'import_documents' not in self._stubs: - self._stubs['import_documents'] = self.grpc_channel.unary_unary( - '/google.cloud.dialogflow.v2.Documents/ImportDocuments', - request_serializer=document.ImportDocumentsRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['import_documents'] - - @property - def delete_document(self) -> Callable[ - [document.DeleteDocumentRequest], - Awaitable[operations_pb2.Operation]]: - r"""Return a callable for the delete document method over gRPC. - - Deletes the specified document. - - This method is a `long-running - operation `__. - The returned ``Operation`` type has the following - method-specific fields: - - - ``metadata``: - [KnowledgeOperationMetadata][google.cloud.dialogflow.v2.KnowledgeOperationMetadata] - - ``response``: An `Empty - message `__ - - Returns: - Callable[[~.DeleteDocumentRequest], - Awaitable[~.Operation]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'delete_document' not in self._stubs: - self._stubs['delete_document'] = self.grpc_channel.unary_unary( - '/google.cloud.dialogflow.v2.Documents/DeleteDocument', - request_serializer=document.DeleteDocumentRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['delete_document'] - - @property - def update_document(self) -> Callable[ - [gcd_document.UpdateDocumentRequest], - Awaitable[operations_pb2.Operation]]: - r"""Return a callable for the update document method over gRPC. - - Updates the specified document. - - This method is a `long-running - operation `__. - The returned ``Operation`` type has the following - method-specific fields: - - - ``metadata``: - [KnowledgeOperationMetadata][google.cloud.dialogflow.v2.KnowledgeOperationMetadata] - - ``response``: [Document][google.cloud.dialogflow.v2.Document] - - Returns: - Callable[[~.UpdateDocumentRequest], - Awaitable[~.Operation]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'update_document' not in self._stubs: - self._stubs['update_document'] = self.grpc_channel.unary_unary( - '/google.cloud.dialogflow.v2.Documents/UpdateDocument', - request_serializer=gcd_document.UpdateDocumentRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['update_document'] - - @property - def reload_document(self) -> 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, - content_uri or content. The previously loaded content of the - document will be deleted. Note: Even when the content of the - document has not changed, there still may be side effects - because of internal implementation changes. - - This method is a `long-running - operation `__. - The returned ``Operation`` type has the following - method-specific fields: - - - ``metadata``: - [KnowledgeOperationMetadata][google.cloud.dialogflow.v2.KnowledgeOperationMetadata] - - ``response``: [Document][google.cloud.dialogflow.v2.Document] - - Note: The ``projects.agent.knowledgeBases.documents`` resource - is deprecated; only use ``projects.knowledgeBases.documents``. - - Returns: - Callable[[~.ReloadDocumentRequest], - Awaitable[~.Operation]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'reload_document' not in self._stubs: - self._stubs['reload_document'] = self.grpc_channel.unary_unary( - '/google.cloud.dialogflow.v2.Documents/ReloadDocument', - request_serializer=document.ReloadDocumentRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['reload_document'] - - @property - def export_document(self) -> Callable[ - [document.ExportDocumentRequest], - Awaitable[operations_pb2.Operation]]: - r"""Return a callable for the export document method over gRPC. - - Exports a smart messaging candidate document into the specified - destination. - - This method is a `long-running - operation `__. - The returned ``Operation`` type has the following - method-specific fields: - - - ``metadata``: - [KnowledgeOperationMetadata][google.cloud.dialogflow.v2.KnowledgeOperationMetadata] - - ``response``: [Document][google.cloud.dialogflow.v2.Document] - - Returns: - Callable[[~.ExportDocumentRequest], - Awaitable[~.Operation]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'export_document' not in self._stubs: - self._stubs['export_document'] = self.grpc_channel.unary_unary( - '/google.cloud.dialogflow.v2.Documents/ExportDocument', - request_serializer=document.ExportDocumentRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['export_document'] - - def close(self): - return self.grpc_channel.close() - - @property - def cancel_operation( - self, - ) -> Callable[[operations_pb2.CancelOperationRequest], None]: - r"""Return a callable for the cancel_operation method over gRPC. - """ - # 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 "cancel_operation" not in self._stubs: - self._stubs["cancel_operation"] = self.grpc_channel.unary_unary( - "/google.longrunning.Operations/CancelOperation", - request_serializer=operations_pb2.CancelOperationRequest.SerializeToString, - response_deserializer=None, - ) - return self._stubs["cancel_operation"] - - @property - def get_operation( - self, - ) -> Callable[[operations_pb2.GetOperationRequest], operations_pb2.Operation]: - r"""Return a callable for the get_operation method over gRPC. - """ - # 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_operation" not in self._stubs: - self._stubs["get_operation"] = self.grpc_channel.unary_unary( - "/google.longrunning.Operations/GetOperation", - request_serializer=operations_pb2.GetOperationRequest.SerializeToString, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs["get_operation"] - - @property - def list_operations( - self, - ) -> Callable[[operations_pb2.ListOperationsRequest], operations_pb2.ListOperationsResponse]: - r"""Return a callable for the list_operations method over gRPC. - """ - # 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_operations" not in self._stubs: - self._stubs["list_operations"] = self.grpc_channel.unary_unary( - "/google.longrunning.Operations/ListOperations", - request_serializer=operations_pb2.ListOperationsRequest.SerializeToString, - response_deserializer=operations_pb2.ListOperationsResponse.FromString, - ) - return self._stubs["list_operations"] - - @property - def list_locations( - self, - ) -> Callable[[locations_pb2.ListLocationsRequest], locations_pb2.ListLocationsResponse]: - r"""Return a callable for the list locations method over gRPC. - """ - # 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_locations" not in self._stubs: - self._stubs["list_locations"] = self.grpc_channel.unary_unary( - "/google.cloud.location.Locations/ListLocations", - request_serializer=locations_pb2.ListLocationsRequest.SerializeToString, - response_deserializer=locations_pb2.ListLocationsResponse.FromString, - ) - return self._stubs["list_locations"] - - @property - def get_location( - self, - ) -> Callable[[locations_pb2.GetLocationRequest], locations_pb2.Location]: - r"""Return a callable for the list locations method over gRPC. - """ - # 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_location" not in self._stubs: - self._stubs["get_location"] = self.grpc_channel.unary_unary( - "/google.cloud.location.Locations/GetLocation", - request_serializer=locations_pb2.GetLocationRequest.SerializeToString, - response_deserializer=locations_pb2.Location.FromString, - ) - return self._stubs["get_location"] - - -__all__ = ( - 'DocumentsGrpcAsyncIOTransport', -) diff --git a/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/documents/transports/rest.py b/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/documents/transports/rest.py deleted file mode 100644 index 56aa31842..000000000 --- a/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/documents/transports/rest.py +++ /dev/null @@ -1,1686 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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 google.auth.transport.requests import AuthorizedSession # type: ignore -import json # type: ignore -import grpc # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore -from google.auth import credentials as ga_credentials # type: ignore -from google.api_core import exceptions as core_exceptions -from google.api_core import retry as retries -from google.api_core import rest_helpers -from google.api_core import rest_streaming -from google.api_core import path_template -from google.api_core import gapic_v1 - -from google.protobuf import json_format -from google.api_core import operations_v1 -from google.cloud.location import locations_pb2 # type: ignore -from google.longrunning import operations_pb2 -from requests import __version__ as requests_version -import dataclasses -import re -from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union -import warnings - -try: - OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] -except AttributeError: # pragma: NO COVER - OptionalRetry = Union[retries.Retry, object] # 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 # type: ignore - -from .base import DocumentsTransport, DEFAULT_CLIENT_INFO as BASE_DEFAULT_CLIENT_INFO - - -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=BASE_DEFAULT_CLIENT_INFO.gapic_version, - grpc_version=None, - rest_version=requests_version, -) - - -class DocumentsRestInterceptor: - """Interceptor for Documents. - - Interceptors are used to manipulate requests, request metadata, and responses - in arbitrary ways. - Example use cases include: - * Logging - * Verifying requests according to service or custom semantics - * Stripping extraneous information from responses - - These use cases and more can be enabled by injecting an - instance of a custom subclass when constructing the DocumentsRestTransport. - - .. code-block:: python - class MyCustomDocumentsInterceptor(DocumentsRestInterceptor): - def pre_create_document(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_create_document(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_delete_document(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_delete_document(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_export_document(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_export_document(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_get_document(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_get_document(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_import_documents(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_import_documents(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_list_documents(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_list_documents(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_reload_document(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_reload_document(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_update_document(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_update_document(self, response): - logging.log(f"Received response: {response}") - return response - - transport = DocumentsRestTransport(interceptor=MyCustomDocumentsInterceptor()) - client = DocumentsClient(transport=transport) - - - """ - def pre_create_document(self, request: gcd_document.CreateDocumentRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[gcd_document.CreateDocumentRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for create_document - - Override in a subclass to manipulate the request or metadata - before they are sent to the Documents server. - """ - return request, metadata - - def post_create_document(self, response: operations_pb2.Operation) -> operations_pb2.Operation: - """Post-rpc interceptor for create_document - - Override in a subclass to manipulate the response - after it is returned by the Documents server but before - it is returned to user code. - """ - return response - def pre_delete_document(self, request: document.DeleteDocumentRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[document.DeleteDocumentRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for delete_document - - Override in a subclass to manipulate the request or metadata - before they are sent to the Documents server. - """ - return request, metadata - - def post_delete_document(self, response: operations_pb2.Operation) -> operations_pb2.Operation: - """Post-rpc interceptor for delete_document - - Override in a subclass to manipulate the response - after it is returned by the Documents server but before - it is returned to user code. - """ - return response - def pre_export_document(self, request: document.ExportDocumentRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[document.ExportDocumentRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for export_document - - Override in a subclass to manipulate the request or metadata - before they are sent to the Documents server. - """ - return request, metadata - - def post_export_document(self, response: operations_pb2.Operation) -> operations_pb2.Operation: - """Post-rpc interceptor for export_document - - Override in a subclass to manipulate the response - after it is returned by the Documents server but before - it is returned to user code. - """ - return response - def pre_get_document(self, request: document.GetDocumentRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[document.GetDocumentRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for get_document - - Override in a subclass to manipulate the request or metadata - before they are sent to the Documents server. - """ - return request, metadata - - def post_get_document(self, response: document.Document) -> document.Document: - """Post-rpc interceptor for get_document - - Override in a subclass to manipulate the response - after it is returned by the Documents server but before - it is returned to user code. - """ - return response - def pre_import_documents(self, request: document.ImportDocumentsRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[document.ImportDocumentsRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for import_documents - - Override in a subclass to manipulate the request or metadata - before they are sent to the Documents server. - """ - return request, metadata - - def post_import_documents(self, response: operations_pb2.Operation) -> operations_pb2.Operation: - """Post-rpc interceptor for import_documents - - Override in a subclass to manipulate the response - after it is returned by the Documents server but before - it is returned to user code. - """ - return response - def pre_list_documents(self, request: document.ListDocumentsRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[document.ListDocumentsRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for list_documents - - Override in a subclass to manipulate the request or metadata - before they are sent to the Documents server. - """ - return request, metadata - - def post_list_documents(self, response: document.ListDocumentsResponse) -> document.ListDocumentsResponse: - """Post-rpc interceptor for list_documents - - Override in a subclass to manipulate the response - after it is returned by the Documents server but before - it is returned to user code. - """ - return response - def pre_reload_document(self, request: document.ReloadDocumentRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[document.ReloadDocumentRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for reload_document - - Override in a subclass to manipulate the request or metadata - before they are sent to the Documents server. - """ - return request, metadata - - def post_reload_document(self, response: operations_pb2.Operation) -> operations_pb2.Operation: - """Post-rpc interceptor for reload_document - - Override in a subclass to manipulate the response - after it is returned by the Documents server but before - it is returned to user code. - """ - return response - def pre_update_document(self, request: gcd_document.UpdateDocumentRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[gcd_document.UpdateDocumentRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for update_document - - Override in a subclass to manipulate the request or metadata - before they are sent to the Documents server. - """ - return request, metadata - - def post_update_document(self, response: operations_pb2.Operation) -> operations_pb2.Operation: - """Post-rpc interceptor for update_document - - Override in a subclass to manipulate the response - after it is returned by the Documents server but before - it is returned to user code. - """ - return response - - def pre_get_location( - self, request: locations_pb2.GetLocationRequest, metadata: Sequence[Tuple[str, str]] - ) -> Tuple[locations_pb2.GetLocationRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for get_location - - Override in a subclass to manipulate the request or metadata - before they are sent to the Documents server. - """ - return request, metadata - - def post_get_location( - self, response: locations_pb2.Location - ) -> locations_pb2.Location: - """Post-rpc interceptor for get_location - - Override in a subclass to manipulate the response - after it is returned by the Documents server but before - it is returned to user code. - """ - return response - def pre_list_locations( - self, request: locations_pb2.ListLocationsRequest, metadata: Sequence[Tuple[str, str]] - ) -> Tuple[locations_pb2.ListLocationsRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for list_locations - - Override in a subclass to manipulate the request or metadata - before they are sent to the Documents server. - """ - return request, metadata - - def post_list_locations( - self, response: locations_pb2.ListLocationsResponse - ) -> locations_pb2.ListLocationsResponse: - """Post-rpc interceptor for list_locations - - Override in a subclass to manipulate the response - after it is returned by the Documents server but before - it is returned to user code. - """ - return response - def pre_cancel_operation( - self, request: operations_pb2.CancelOperationRequest, metadata: Sequence[Tuple[str, str]] - ) -> Tuple[operations_pb2.CancelOperationRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for cancel_operation - - Override in a subclass to manipulate the request or metadata - before they are sent to the Documents server. - """ - return request, metadata - - def post_cancel_operation( - self, response: None - ) -> None: - """Post-rpc interceptor for cancel_operation - - Override in a subclass to manipulate the response - after it is returned by the Documents server but before - it is returned to user code. - """ - return response - def pre_get_operation( - self, request: operations_pb2.GetOperationRequest, metadata: Sequence[Tuple[str, str]] - ) -> Tuple[operations_pb2.GetOperationRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for get_operation - - Override in a subclass to manipulate the request or metadata - before they are sent to the Documents server. - """ - return request, metadata - - def post_get_operation( - self, response: operations_pb2.Operation - ) -> operations_pb2.Operation: - """Post-rpc interceptor for get_operation - - Override in a subclass to manipulate the response - after it is returned by the Documents server but before - it is returned to user code. - """ - return response - def pre_list_operations( - self, request: operations_pb2.ListOperationsRequest, metadata: Sequence[Tuple[str, str]] - ) -> Tuple[operations_pb2.ListOperationsRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for list_operations - - Override in a subclass to manipulate the request or metadata - before they are sent to the Documents server. - """ - return request, metadata - - def post_list_operations( - self, response: operations_pb2.ListOperationsResponse - ) -> operations_pb2.ListOperationsResponse: - """Post-rpc interceptor for list_operations - - Override in a subclass to manipulate the response - after it is returned by the Documents server but before - it is returned to user code. - """ - return response - - -@dataclasses.dataclass -class DocumentsRestStub: - _session: AuthorizedSession - _host: str - _interceptor: DocumentsRestInterceptor - - -class DocumentsRestTransport(DocumentsTransport): - """REST backend transport for Documents. - - Service for managing knowledge - [Documents][google.cloud.dialogflow.v2.Document]. - - 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 JSON representations of protocol buffers over HTTP/1.1 - - """ - - def __init__(self, *, - host: str = 'dialogflow.googleapis.com', - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - client_cert_source_for_mtls: Optional[Callable[[ - ], Tuple[bytes, bytes]]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - url_scheme: str = 'https', - interceptor: Optional[DocumentsRestInterceptor] = None, - api_audience: Optional[str] = None, - ) -> 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 ignored if ``channel`` is provided. - scopes (Optional(Sequence[str])): A list of scopes. This argument is - ignored if ``channel`` is provided. - client_cert_source_for_mtls (Callable[[], Tuple[bytes, bytes]]): Client - certificate to configure mutual TLS HTTP channel. It is ignored - if ``channel`` is provided. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you are developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - url_scheme: the protocol scheme for the API endpoint. Normally - "https", but for testing or local servers, - "http" can be specified. - """ - # Run the base constructor - # TODO(yon-mg): resolve other ctor params i.e. scopes, quota, etc. - # TODO: When custom host (api_endpoint) is set, `scopes` must *also* be set on the - # credentials object - maybe_url_match = re.match("^(?Phttp(?:s)?://)?(?P.*)$", host) - if maybe_url_match is None: - raise ValueError(f"Unexpected hostname structure: {host}") # pragma: NO COVER - - url_match_items = maybe_url_match.groupdict() - - host = f"{url_scheme}://{host}" if not url_match_items["scheme"] else host - - super().__init__( - host=host, - credentials=credentials, - client_info=client_info, - always_use_jwt_access=always_use_jwt_access, - api_audience=api_audience - ) - self._session = AuthorizedSession( - self._credentials, default_host=self.DEFAULT_HOST) - self._operations_client: Optional[operations_v1.AbstractOperationsClient] = None - if client_cert_source_for_mtls: - self._session.configure_mtls_channel(client_cert_source_for_mtls) - self._interceptor = interceptor or DocumentsRestInterceptor() - self._prep_wrapped_messages(client_info) - - @property - def operations_client(self) -> operations_v1.AbstractOperationsClient: - """Create the client designed to process long-running operations. - - This property caches on the instance; repeated calls return the same - client. - """ - # Only create a new client if we do not already have one. - if self._operations_client is None: - http_options: Dict[str, List[Dict[str, str]]] = { - 'google.longrunning.Operations.CancelOperation': [ - { - 'method': 'post', - 'uri': '/v2/{name=projects/*/operations/*}:cancel', - }, - { - 'method': 'post', - 'uri': '/v2/{name=projects/*/locations/*/operations/*}:cancel', - }, - ], - 'google.longrunning.Operations.GetOperation': [ - { - 'method': 'get', - 'uri': '/v2/{name=projects/*/operations/*}', - }, - { - 'method': 'get', - 'uri': '/v2/{name=projects/*/locations/*/operations/*}', - }, - ], - 'google.longrunning.Operations.ListOperations': [ - { - 'method': 'get', - 'uri': '/v2/{name=projects/*}/operations', - }, - { - 'method': 'get', - 'uri': '/v2/{name=projects/*/locations/*}/operations', - }, - ], - } - - rest_transport = operations_v1.OperationsRestTransport( - host=self._host, - # use the credentials which are saved - credentials=self._credentials, - scopes=self._scopes, - http_options=http_options, - path_prefix="v2") - - self._operations_client = operations_v1.AbstractOperationsClient(transport=rest_transport) - - # Return the client from cache. - return self._operations_client - - class _CreateDocument(DocumentsRestStub): - def __hash__(self): - return hash("CreateDocument") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: gcd_document.CreateDocumentRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> operations_pb2.Operation: - r"""Call the create document method over HTTP. - - Args: - request (~.gcd_document.CreateDocumentRequest): - The request object. Request message for - [Documents.CreateDocument][google.cloud.dialogflow.v2.Documents.CreateDocument]. - 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: - ~.operations_pb2.Operation: - This resource represents a - long-running operation that is the - result of a network API call. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'post', - 'uri': '/v2/{parent=projects/*/knowledgeBases/*}/documents', - 'body': 'document', - }, -{ - 'method': 'post', - 'uri': '/v2/{parent=projects/*/locations/*/knowledgeBases/*}/documents', - 'body': 'document', - }, -{ - 'method': 'post', - 'uri': '/v2/{parent=projects/*/agent/knowledgeBases/*}/documents', - 'body': 'document', - }, - ] - request, metadata = self._interceptor.pre_create_document(request, metadata) - pb_request = gcd_document.CreateDocumentRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request['body'], - including_default_value_fields=False, - use_integers_for_enums=True - ) - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - including_default_value_fields=False, - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = operations_pb2.Operation() - json_format.Parse(response.content, resp, ignore_unknown_fields=True) - resp = self._interceptor.post_create_document(resp) - return resp - - class _DeleteDocument(DocumentsRestStub): - def __hash__(self): - return hash("DeleteDocument") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: document.DeleteDocumentRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> operations_pb2.Operation: - r"""Call the delete document method over HTTP. - - Args: - request (~.document.DeleteDocumentRequest): - The request object. Request message for - [Documents.DeleteDocument][google.cloud.dialogflow.v2.Documents.DeleteDocument]. - 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: - ~.operations_pb2.Operation: - This resource represents a - long-running operation that is the - result of a network API call. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'delete', - 'uri': '/v2/{name=projects/*/knowledgeBases/*/documents/*}', - }, -{ - 'method': 'delete', - 'uri': '/v2/{name=projects/*/locations/*/knowledgeBases/*/documents/*}', - }, -{ - 'method': 'delete', - 'uri': '/v2/{name=projects/*/agent/knowledgeBases/*/documents/*}', - }, - ] - request, metadata = self._interceptor.pre_delete_document(request, metadata) - pb_request = document.DeleteDocumentRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - including_default_value_fields=False, - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = operations_pb2.Operation() - json_format.Parse(response.content, resp, ignore_unknown_fields=True) - resp = self._interceptor.post_delete_document(resp) - return resp - - class _ExportDocument(DocumentsRestStub): - def __hash__(self): - return hash("ExportDocument") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: document.ExportDocumentRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> operations_pb2.Operation: - r"""Call the export document method over HTTP. - - Args: - request (~.document.ExportDocumentRequest): - The request object. Request message for - [Documents.ExportDocument][google.cloud.dialogflow.v2.Documents.ExportDocument]. - 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: - ~.operations_pb2.Operation: - This resource represents a - long-running operation that is the - result of a network API call. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'post', - 'uri': '/v2/{name=projects/*/knowledgeBases/*/documents/*}:export', - 'body': '*', - }, -{ - 'method': 'post', - 'uri': '/v2/{name=projects/*/locations/*/knowledgeBases/*/documents/*}:export', - 'body': '*', - }, - ] - request, metadata = self._interceptor.pre_export_document(request, metadata) - pb_request = document.ExportDocumentRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request['body'], - including_default_value_fields=False, - use_integers_for_enums=True - ) - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - including_default_value_fields=False, - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = operations_pb2.Operation() - json_format.Parse(response.content, resp, ignore_unknown_fields=True) - resp = self._interceptor.post_export_document(resp) - return resp - - class _GetDocument(DocumentsRestStub): - def __hash__(self): - return hash("GetDocument") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: document.GetDocumentRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> document.Document: - r"""Call the get document method over HTTP. - - Args: - request (~.document.GetDocumentRequest): - The request object. Request message for - [Documents.GetDocument][google.cloud.dialogflow.v2.Documents.GetDocument]. - 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: - ~.document.Document: - A knowledge document to be used by a - [KnowledgeBase][google.cloud.dialogflow.v2.KnowledgeBase]. - - For more information, see the `knowledge base - guide `__. - - Note: The ``projects.agent.knowledgeBases.documents`` - resource is deprecated; only use - ``projects.knowledgeBases.documents``. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v2/{name=projects/*/knowledgeBases/*/documents/*}', - }, -{ - 'method': 'get', - 'uri': '/v2/{name=projects/*/locations/*/knowledgeBases/*/documents/*}', - }, -{ - 'method': 'get', - 'uri': '/v2/{name=projects/*/agent/knowledgeBases/*/documents/*}', - }, - ] - request, metadata = self._interceptor.pre_get_document(request, metadata) - pb_request = document.GetDocumentRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - including_default_value_fields=False, - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = document.Document() - pb_resp = document.Document.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_get_document(resp) - return resp - - class _ImportDocuments(DocumentsRestStub): - def __hash__(self): - return hash("ImportDocuments") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: document.ImportDocumentsRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> operations_pb2.Operation: - r"""Call the import documents method over HTTP. - - Args: - request (~.document.ImportDocumentsRequest): - The request object. Request message for - [Documents.ImportDocuments][google.cloud.dialogflow.v2.Documents.ImportDocuments]. - 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: - ~.operations_pb2.Operation: - This resource represents a - long-running operation that is the - result of a network API call. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'post', - 'uri': '/v2/{parent=projects/*/knowledgeBases/*}/documents:import', - 'body': '*', - }, -{ - 'method': 'post', - 'uri': '/v2/{parent=projects/*/locations/*/knowledgeBases/*}/documents:import', - 'body': '*', - }, - ] - request, metadata = self._interceptor.pre_import_documents(request, metadata) - pb_request = document.ImportDocumentsRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request['body'], - including_default_value_fields=False, - use_integers_for_enums=True - ) - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - including_default_value_fields=False, - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = operations_pb2.Operation() - json_format.Parse(response.content, resp, ignore_unknown_fields=True) - resp = self._interceptor.post_import_documents(resp) - return resp - - class _ListDocuments(DocumentsRestStub): - def __hash__(self): - return hash("ListDocuments") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: document.ListDocumentsRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> document.ListDocumentsResponse: - r"""Call the list documents method over HTTP. - - Args: - request (~.document.ListDocumentsRequest): - The request object. Request message for - [Documents.ListDocuments][google.cloud.dialogflow.v2.Documents.ListDocuments]. - 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: - ~.document.ListDocumentsResponse: - Response message for - [Documents.ListDocuments][google.cloud.dialogflow.v2.Documents.ListDocuments]. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v2/{parent=projects/*/knowledgeBases/*}/documents', - }, -{ - 'method': 'get', - 'uri': '/v2/{parent=projects/*/locations/*/knowledgeBases/*}/documents', - }, -{ - 'method': 'get', - 'uri': '/v2/{parent=projects/*/agent/knowledgeBases/*}/documents', - }, - ] - request, metadata = self._interceptor.pre_list_documents(request, metadata) - pb_request = document.ListDocumentsRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - including_default_value_fields=False, - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = document.ListDocumentsResponse() - pb_resp = document.ListDocumentsResponse.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_list_documents(resp) - return resp - - class _ReloadDocument(DocumentsRestStub): - def __hash__(self): - return hash("ReloadDocument") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: document.ReloadDocumentRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> operations_pb2.Operation: - r"""Call the reload document method over HTTP. - - Args: - request (~.document.ReloadDocumentRequest): - The request object. Request message for - [Documents.ReloadDocument][google.cloud.dialogflow.v2.Documents.ReloadDocument]. - 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: - ~.operations_pb2.Operation: - This resource represents a - long-running operation that is the - result of a network API call. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'post', - 'uri': '/v2/{name=projects/*/knowledgeBases/*/documents/*}:reload', - 'body': '*', - }, -{ - 'method': 'post', - 'uri': '/v2/{name=projects/*/locations/*/knowledgeBases/*/documents/*}:reload', - 'body': '*', - }, -{ - 'method': 'post', - 'uri': '/v2/{name=projects/*/agent/knowledgeBases/*/documents/*}:reload', - 'body': '*', - }, - ] - request, metadata = self._interceptor.pre_reload_document(request, metadata) - pb_request = document.ReloadDocumentRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request['body'], - including_default_value_fields=False, - use_integers_for_enums=True - ) - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - including_default_value_fields=False, - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = operations_pb2.Operation() - json_format.Parse(response.content, resp, ignore_unknown_fields=True) - resp = self._interceptor.post_reload_document(resp) - return resp - - class _UpdateDocument(DocumentsRestStub): - def __hash__(self): - return hash("UpdateDocument") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: gcd_document.UpdateDocumentRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> operations_pb2.Operation: - r"""Call the update document method over HTTP. - - Args: - request (~.gcd_document.UpdateDocumentRequest): - The request object. Request message for - [Documents.UpdateDocument][google.cloud.dialogflow.v2.Documents.UpdateDocument]. - 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: - ~.operations_pb2.Operation: - This resource represents a - long-running operation that is the - result of a network API call. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'patch', - 'uri': '/v2/{document.name=projects/*/knowledgeBases/*/documents/*}', - 'body': 'document', - }, -{ - 'method': 'patch', - 'uri': '/v2/{document.name=projects/*/locations/*/knowledgeBases/*/documents/*}', - 'body': 'document', - }, -{ - 'method': 'patch', - 'uri': '/v2/{document.name=projects/*/agent/knowledgeBases/*/documents/*}', - 'body': 'document', - }, - ] - request, metadata = self._interceptor.pre_update_document(request, metadata) - pb_request = gcd_document.UpdateDocumentRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request['body'], - including_default_value_fields=False, - use_integers_for_enums=True - ) - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - including_default_value_fields=False, - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = operations_pb2.Operation() - json_format.Parse(response.content, resp, ignore_unknown_fields=True) - resp = self._interceptor.post_update_document(resp) - return resp - - @property - def create_document(self) -> Callable[ - [gcd_document.CreateDocumentRequest], - operations_pb2.Operation]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._CreateDocument(self._session, self._host, self._interceptor) # type: ignore - - @property - def delete_document(self) -> Callable[ - [document.DeleteDocumentRequest], - operations_pb2.Operation]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._DeleteDocument(self._session, self._host, self._interceptor) # type: ignore - - @property - def export_document(self) -> Callable[ - [document.ExportDocumentRequest], - operations_pb2.Operation]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._ExportDocument(self._session, self._host, self._interceptor) # type: ignore - - @property - def get_document(self) -> Callable[ - [document.GetDocumentRequest], - document.Document]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._GetDocument(self._session, self._host, self._interceptor) # type: ignore - - @property - def import_documents(self) -> Callable[ - [document.ImportDocumentsRequest], - operations_pb2.Operation]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._ImportDocuments(self._session, self._host, self._interceptor) # type: ignore - - @property - def list_documents(self) -> Callable[ - [document.ListDocumentsRequest], - document.ListDocumentsResponse]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._ListDocuments(self._session, self._host, self._interceptor) # type: ignore - - @property - def reload_document(self) -> Callable[ - [document.ReloadDocumentRequest], - operations_pb2.Operation]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._ReloadDocument(self._session, self._host, self._interceptor) # type: ignore - - @property - def update_document(self) -> Callable[ - [gcd_document.UpdateDocumentRequest], - operations_pb2.Operation]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._UpdateDocument(self._session, self._host, self._interceptor) # type: ignore - - @property - def get_location(self): - return self._GetLocation(self._session, self._host, self._interceptor) # type: ignore - - class _GetLocation(DocumentsRestStub): - def __call__(self, - request: locations_pb2.GetLocationRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> locations_pb2.Location: - - r"""Call the get location method over HTTP. - - Args: - request (locations_pb2.GetLocationRequest): - The request object for GetLocation method. - 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: - locations_pb2.Location: Response from GetLocation method. - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v2/{name=projects/*/locations/*}', - }, - ] - - request, metadata = self._interceptor.pre_get_location(request, metadata) - request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode( - http_options, **request_kwargs) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json.dumps(transcoded_request['query_params'])) - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - resp = locations_pb2.Location() - resp = json_format.Parse(response.content.decode("utf-8"), resp) - resp = self._interceptor.post_get_location(resp) - return resp - - @property - def list_locations(self): - return self._ListLocations(self._session, self._host, self._interceptor) # type: ignore - - class _ListLocations(DocumentsRestStub): - def __call__(self, - request: locations_pb2.ListLocationsRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> locations_pb2.ListLocationsResponse: - - r"""Call the list locations method over HTTP. - - Args: - request (locations_pb2.ListLocationsRequest): - The request object for ListLocations method. - 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: - locations_pb2.ListLocationsResponse: Response from ListLocations method. - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v2/{name=projects/*}/locations', - }, - ] - - request, metadata = self._interceptor.pre_list_locations(request, metadata) - request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode( - http_options, **request_kwargs) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json.dumps(transcoded_request['query_params'])) - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - resp = locations_pb2.ListLocationsResponse() - resp = json_format.Parse(response.content.decode("utf-8"), resp) - resp = self._interceptor.post_list_locations(resp) - return resp - - @property - def cancel_operation(self): - return self._CancelOperation(self._session, self._host, self._interceptor) # type: ignore - - class _CancelOperation(DocumentsRestStub): - def __call__(self, - request: operations_pb2.CancelOperationRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> None: - - r"""Call the cancel operation method over HTTP. - - Args: - request (operations_pb2.CancelOperationRequest): - The request object for CancelOperation method. - 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. - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'post', - 'uri': '/v2/{name=projects/*/operations/*}:cancel', - }, -{ - 'method': 'post', - 'uri': '/v2/{name=projects/*/locations/*/operations/*}:cancel', - }, - ] - - request, metadata = self._interceptor.pre_cancel_operation(request, metadata) - request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode( - http_options, **request_kwargs) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json.dumps(transcoded_request['query_params'])) - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - return self._interceptor.post_cancel_operation(None) - - @property - def get_operation(self): - return self._GetOperation(self._session, self._host, self._interceptor) # type: ignore - - class _GetOperation(DocumentsRestStub): - def __call__(self, - request: operations_pb2.GetOperationRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> operations_pb2.Operation: - - r"""Call the get operation method over HTTP. - - Args: - request (operations_pb2.GetOperationRequest): - The request object for GetOperation method. - 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: - operations_pb2.Operation: Response from GetOperation method. - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v2/{name=projects/*/operations/*}', - }, -{ - 'method': 'get', - 'uri': '/v2/{name=projects/*/locations/*/operations/*}', - }, - ] - - request, metadata = self._interceptor.pre_get_operation(request, metadata) - request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode( - http_options, **request_kwargs) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json.dumps(transcoded_request['query_params'])) - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - resp = operations_pb2.Operation() - resp = json_format.Parse(response.content.decode("utf-8"), resp) - resp = self._interceptor.post_get_operation(resp) - return resp - - @property - def list_operations(self): - return self._ListOperations(self._session, self._host, self._interceptor) # type: ignore - - class _ListOperations(DocumentsRestStub): - def __call__(self, - request: operations_pb2.ListOperationsRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> operations_pb2.ListOperationsResponse: - - r"""Call the list operations method over HTTP. - - Args: - request (operations_pb2.ListOperationsRequest): - The request object for ListOperations method. - 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: - operations_pb2.ListOperationsResponse: Response from ListOperations method. - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v2/{name=projects/*}/operations', - }, -{ - 'method': 'get', - 'uri': '/v2/{name=projects/*/locations/*}/operations', - }, - ] - - request, metadata = self._interceptor.pre_list_operations(request, metadata) - request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode( - http_options, **request_kwargs) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json.dumps(transcoded_request['query_params'])) - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - resp = operations_pb2.ListOperationsResponse() - resp = json_format.Parse(response.content.decode("utf-8"), resp) - resp = self._interceptor.post_list_operations(resp) - return resp - - @property - def kind(self) -> str: - return "rest" - - def close(self): - self._session.close() - - -__all__=( - 'DocumentsRestTransport', -) diff --git a/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/entity_types/__init__.py b/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/entity_types/__init__.py deleted file mode 100644 index 829926f31..000000000 --- a/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/entity_types/__init__.py +++ /dev/null @@ -1,22 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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 EntityTypesClient -from .async_client import EntityTypesAsyncClient - -__all__ = ( - 'EntityTypesClient', - 'EntityTypesAsyncClient', -) diff --git a/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/entity_types/async_client.py b/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/entity_types/async_client.py deleted file mode 100644 index a67c48493..000000000 --- a/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/entity_types/async_client.py +++ /dev/null @@ -1,1839 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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, Mapping, MutableMapping, MutableSequence, Optional, Sequence, Tuple, Type, Union - -from google.cloud.dialogflow_v2 import gapic_version as package_version - -from google.api_core.client_options import ClientOptions -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import retry as retries -from google.auth import credentials as ga_credentials # type: ignore -from google.oauth2 import service_account # type: ignore - -try: - OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] -except AttributeError: # pragma: NO COVER - OptionalRetry = Union[retries.Retry, object] # type: ignore - -from google.api_core import operation # type: ignore -from google.api_core import operation_async # type: ignore -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.cloud.location import locations_pb2 # type: ignore -from google.longrunning import operations_pb2 -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 - - -class EntityTypesAsyncClient: - """Service for managing - [EntityTypes][google.cloud.dialogflow.v2.EntityType]. - """ - - _client: EntityTypesClient - - DEFAULT_ENDPOINT = EntityTypesClient.DEFAULT_ENDPOINT - DEFAULT_MTLS_ENDPOINT = EntityTypesClient.DEFAULT_MTLS_ENDPOINT - - 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) - - @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: - EntityTypesAsyncClient: The constructed client. - """ - return EntityTypesClient.from_service_account_info.__func__(EntityTypesAsyncClient, 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: - EntityTypesAsyncClient: The constructed client. - """ - return EntityTypesClient.from_service_account_file.__func__(EntityTypesAsyncClient, filename, *args, **kwargs) # type: ignore - - from_service_account_json = from_service_account_file - - @classmethod - def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[ClientOptions] = None): - """Return the API endpoint and client cert source for mutual TLS. - - The client cert source is determined in the following order: - (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the - client cert source is None. - (2) if `client_options.client_cert_source` is provided, use the provided one; if the - default client cert source exists, use the default one; otherwise the client cert - source is None. - - The API endpoint is determined in the following order: - (1) if `client_options.api_endpoint` if provided, use the provided one. - (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the - default mTLS endpoint; if the environment variable is "never", use the default API - endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise - use the default API endpoint. - - More details can be found at https://google.aip.dev/auth/4114. - - Args: - client_options (google.api_core.client_options.ClientOptions): Custom options for the - client. Only the `api_endpoint` and `client_cert_source` properties may be used - in this method. - - Returns: - Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the - client cert source to use. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If any errors happen. - """ - return EntityTypesClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore - - @property - def transport(self) -> EntityTypesTransport: - """Returns the transport used by the client instance. - - Returns: - EntityTypesTransport: The transport used by the client instance. - """ - return self._client.transport - - get_transport_class = functools.partial(type(EntityTypesClient).get_transport_class, type(EntityTypesClient)) - - def __init__(self, *, - credentials: Optional[ga_credentials.Credentials] = None, - transport: Union[str, EntityTypesTransport] = "grpc_asyncio", - client_options: Optional[ClientOptions] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the entity types 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, ~.EntityTypesTransport]): 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 = EntityTypesClient( - credentials=credentials, - transport=transport, - client_options=client_options, - client_info=client_info, - - ) - - async def list_entity_types(self, - request: Optional[Union[entity_type.ListEntityTypesRequest, dict]] = None, - *, - parent: Optional[str] = None, - language_code: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListEntityTypesAsyncPager: - r"""Returns the list of all entity types in the specified - agent. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import dialogflow_v2 - - async def sample_list_entity_types(): - # Create a client - client = dialogflow_v2.EntityTypesAsyncClient() - - # Initialize request argument(s) - request = dialogflow_v2.ListEntityTypesRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_entity_types(request=request) - - # Handle the response - async for response in page_result: - print(response) - - Args: - request (Optional[Union[google.cloud.dialogflow_v2.types.ListEntityTypesRequest, dict]]): - The request object. The request message for - [EntityTypes.ListEntityTypes][google.cloud.dialogflow.v2.EntityTypes.ListEntityTypes]. - parent (:class:`str`): - Required. The agent to list all entity types from. - Format: ``projects//agent``. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - language_code (:class:`str`): - Optional. The language used to access language-specific - data. If not specified, the agent's default language is - used. For more information, see `Multilingual intent and - entity - data `__. - - 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. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.dialogflow_v2.services.entity_types.pagers.ListEntityTypesAsyncPager: - The response message for - [EntityTypes.ListEntityTypes][google.cloud.dialogflow.v2.EntityTypes.ListEntityTypes]. - - Iterating over this object will yield results and - resolve additional pages automatically. - - """ - # Create or coerce a protobuf request object. - # Quick 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, language_code]) - 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 = 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: - request.language_code = language_code - - # 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_entity_types, - 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.ListEntityTypesAsyncPager( - method=rpc, - request=request, - response=response, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def get_entity_type(self, - request: Optional[Union[entity_type.GetEntityTypeRequest, dict]] = None, - *, - name: Optional[str] = None, - language_code: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> entity_type.EntityType: - r"""Retrieves the specified entity type. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import dialogflow_v2 - - async def sample_get_entity_type(): - # Create a client - client = dialogflow_v2.EntityTypesAsyncClient() - - # Initialize request argument(s) - request = dialogflow_v2.GetEntityTypeRequest( - name="name_value", - ) - - # Make the request - response = await client.get_entity_type(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.dialogflow_v2.types.GetEntityTypeRequest, dict]]): - The request object. The request message for - [EntityTypes.GetEntityType][google.cloud.dialogflow.v2.EntityTypes.GetEntityType]. - name (:class:`str`): - Required. The name of the entity type. Format: - ``projects//agent/entityTypes/``. - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - language_code (:class:`str`): - Optional. The language used to access language-specific - data. If not specified, the agent's default language is - used. For more information, see `Multilingual intent and - entity - data `__. - - 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. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.dialogflow_v2.types.EntityType: - Each intent parameter has a type, called the entity type, which dictates - exactly how data from an end-user expression is - extracted. - - Dialogflow provides predefined system entities that - can match many common types of data. For example, - there are system entities for matching dates, times, - colors, email addresses, and so on. You can also - create your own custom entities for matching custom - data. For example, you could define a vegetable - entity that can match the types of vegetables - available for purchase with a grocery store agent. - - For more information, see the [Entity - guide](\ https://cloud.google.com/dialogflow/docs/entities-overview). - - """ - # Create or coerce a protobuf request object. - # Quick 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, language_code]) - 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 = 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: - request.language_code = language_code - - # 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_entity_type, - 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_entity_type(self, - request: Optional[Union[gcd_entity_type.CreateEntityTypeRequest, dict]] = None, - *, - parent: Optional[str] = None, - entity_type: Optional[gcd_entity_type.EntityType] = None, - language_code: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gcd_entity_type.EntityType: - r"""Creates an entity type in the specified agent. - - Note: You should always train an agent prior to sending it - queries. See the `training - documentation `__. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import dialogflow_v2 - - async def sample_create_entity_type(): - # Create a client - client = dialogflow_v2.EntityTypesAsyncClient() - - # Initialize request argument(s) - entity_type = dialogflow_v2.EntityType() - entity_type.display_name = "display_name_value" - entity_type.kind = "KIND_REGEXP" - - request = dialogflow_v2.CreateEntityTypeRequest( - parent="parent_value", - entity_type=entity_type, - ) - - # Make the request - response = await client.create_entity_type(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.dialogflow_v2.types.CreateEntityTypeRequest, dict]]): - The request object. The request message for - [EntityTypes.CreateEntityType][google.cloud.dialogflow.v2.EntityTypes.CreateEntityType]. - parent (:class:`str`): - Required. The agent to create a entity type for. Format: - ``projects//agent``. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - entity_type (:class:`google.cloud.dialogflow_v2.types.EntityType`): - Required. The entity type to create. - This corresponds to the ``entity_type`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - language_code (:class:`str`): - Optional. The language used to access language-specific - data. If not specified, the agent's default language is - used. For more information, see `Multilingual intent and - entity - data `__. - - 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. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.dialogflow_v2.types.EntityType: - Each intent parameter has a type, called the entity type, which dictates - exactly how data from an end-user expression is - extracted. - - Dialogflow provides predefined system entities that - can match many common types of data. For example, - there are system entities for matching dates, times, - colors, email addresses, and so on. You can also - create your own custom entities for matching custom - data. For example, you could define a vegetable - entity that can match the types of vegetables - available for purchase with a grocery store agent. - - For more information, see the [Entity - guide](\ https://cloud.google.com/dialogflow/docs/entities-overview). - - """ - # Create or coerce a protobuf request object. - # Quick 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, entity_type, language_code]) - 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_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: - request.entity_type = entity_type - if language_code is not None: - request.language_code = language_code - - # 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_entity_type, - 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_entity_type(self, - request: Optional[Union[gcd_entity_type.UpdateEntityTypeRequest, dict]] = None, - *, - entity_type: Optional[gcd_entity_type.EntityType] = None, - language_code: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gcd_entity_type.EntityType: - r"""Updates the specified entity type. - - Note: You should always train an agent prior to sending it - queries. See the `training - documentation `__. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import dialogflow_v2 - - async def sample_update_entity_type(): - # Create a client - client = dialogflow_v2.EntityTypesAsyncClient() - - # Initialize request argument(s) - entity_type = dialogflow_v2.EntityType() - entity_type.display_name = "display_name_value" - entity_type.kind = "KIND_REGEXP" - - request = dialogflow_v2.UpdateEntityTypeRequest( - entity_type=entity_type, - ) - - # Make the request - response = await client.update_entity_type(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.dialogflow_v2.types.UpdateEntityTypeRequest, dict]]): - The request object. The request message for - [EntityTypes.UpdateEntityType][google.cloud.dialogflow.v2.EntityTypes.UpdateEntityType]. - entity_type (:class:`google.cloud.dialogflow_v2.types.EntityType`): - Required. The entity type to update. - This corresponds to the ``entity_type`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - language_code (:class:`str`): - Optional. The language used to access language-specific - data. If not specified, the agent's default language is - used. For more information, see `Multilingual intent and - entity - data `__. - - 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. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.dialogflow_v2.types.EntityType: - Each intent parameter has a type, called the entity type, which dictates - exactly how data from an end-user expression is - extracted. - - Dialogflow provides predefined system entities that - can match many common types of data. For example, - there are system entities for matching dates, times, - colors, email addresses, and so on. You can also - create your own custom entities for matching custom - data. For example, you could define a vegetable - entity that can match the types of vegetables - available for purchase with a grocery store agent. - - For more information, see the [Entity - guide](\ https://cloud.google.com/dialogflow/docs/entities-overview). - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([entity_type, language_code]) - 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_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: - request.language_code = language_code - - # 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_entity_type, - 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(( - ("entity_type.name", request.entity_type.name), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def delete_entity_type(self, - request: Optional[Union[entity_type.DeleteEntityTypeRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> None: - r"""Deletes the specified entity type. - - Note: You should always train an agent prior to sending it - queries. See the `training - documentation `__. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import dialogflow_v2 - - async def sample_delete_entity_type(): - # Create a client - client = dialogflow_v2.EntityTypesAsyncClient() - - # Initialize request argument(s) - request = dialogflow_v2.DeleteEntityTypeRequest( - name="name_value", - ) - - # Make the request - await client.delete_entity_type(request=request) - - Args: - request (Optional[Union[google.cloud.dialogflow_v2.types.DeleteEntityTypeRequest, dict]]): - The request object. The request message for - [EntityTypes.DeleteEntityType][google.cloud.dialogflow.v2.EntityTypes.DeleteEntityType]. - name (:class:`str`): - Required. The name of the entity type to delete. Format: - ``projects//agent/entityTypes/``. - - 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. - # Quick 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 = 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 - - # 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_entity_type, - 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 batch_update_entity_types(self, - request: Optional[Union[entity_type.BatchUpdateEntityTypesRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation_async.AsyncOperation: - r"""Updates/Creates multiple entity types in the specified agent. - - This method is a `long-running - operation `__. - The returned ``Operation`` type has the following - method-specific fields: - - - ``metadata``: An empty `Struct - message `__ - - ``response``: - [BatchUpdateEntityTypesResponse][google.cloud.dialogflow.v2.BatchUpdateEntityTypesResponse] - - Note: You should always train an agent prior to sending it - queries. See the `training - documentation `__. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import dialogflow_v2 - - async def sample_batch_update_entity_types(): - # Create a client - client = dialogflow_v2.EntityTypesAsyncClient() - - # Initialize request argument(s) - request = dialogflow_v2.BatchUpdateEntityTypesRequest( - entity_type_batch_uri="entity_type_batch_uri_value", - parent="parent_value", - ) - - # Make the request - operation = client.batch_update_entity_types(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.dialogflow_v2.types.BatchUpdateEntityTypesRequest, dict]]): - 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. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.api_core.operation_async.AsyncOperation: - An object representing a long-running operation. - - The result type for the operation will be :class:`google.cloud.dialogflow_v2.types.BatchUpdateEntityTypesResponse` The response message for - [EntityTypes.BatchUpdateEntityTypes][google.cloud.dialogflow.v2.EntityTypes.BatchUpdateEntityTypes]. - - """ - # Create or coerce a protobuf request object. - request = entity_type.BatchUpdateEntityTypesRequest(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.batch_update_entity_types, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Wrap the response in an operation future. - response = operation_async.from_gapic( - response, - self._client._transport.operations_client, - entity_type.BatchUpdateEntityTypesResponse, - metadata_type=struct_pb2.Struct, - ) - - # Done; return the response. - return response - - async def batch_delete_entity_types(self, - request: Optional[Union[entity_type.BatchDeleteEntityTypesRequest, dict]] = None, - *, - parent: Optional[str] = None, - entity_type_names: Optional[MutableSequence[str]] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation_async.AsyncOperation: - r"""Deletes entity types in the specified agent. - - This method is a `long-running - operation `__. - The returned ``Operation`` type has the following - method-specific fields: - - - ``metadata``: An empty `Struct - message `__ - - ``response``: An `Empty - message `__ - - Note: You should always train an agent prior to sending it - queries. See the `training - documentation `__. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import dialogflow_v2 - - async def sample_batch_delete_entity_types(): - # Create a client - client = dialogflow_v2.EntityTypesAsyncClient() - - # Initialize request argument(s) - request = dialogflow_v2.BatchDeleteEntityTypesRequest( - parent="parent_value", - entity_type_names=['entity_type_names_value1', 'entity_type_names_value2'], - ) - - # Make the request - operation = client.batch_delete_entity_types(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.dialogflow_v2.types.BatchDeleteEntityTypesRequest, dict]]): - The request object. The request message for - [EntityTypes.BatchDeleteEntityTypes][google.cloud.dialogflow.v2.EntityTypes.BatchDeleteEntityTypes]. - parent (:class:`str`): - Required. The name of the agent to delete all entities - types for. Format: ``projects//agent``. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - entity_type_names (:class:`MutableSequence[str]`): - Required. The names entity types to delete. All names - must point to the same agent as ``parent``. - - 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. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.api_core.operation_async.AsyncOperation: - An object representing a long-running operation. - - The result type for the operation will be :class:`google.protobuf.empty_pb2.Empty` A generic empty message that you can re-use to avoid defining duplicated - empty messages in your APIs. A typical example is to - use it as the request or the response type of an API - method. For instance: - - service Foo { - rpc Bar(google.protobuf.Empty) returns - (google.protobuf.Empty); - - } - - """ - # Create or coerce a protobuf request object. - # Quick 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, entity_type_names]) - 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 = 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: - request.entity_type_names.extend(entity_type_names) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.batch_delete_entity_types, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Wrap the response in an operation future. - response = operation_async.from_gapic( - response, - self._client._transport.operations_client, - empty_pb2.Empty, - metadata_type=struct_pb2.Struct, - ) - - # Done; return the response. - return response - - async def batch_create_entities(self, - request: Optional[Union[entity_type.BatchCreateEntitiesRequest, dict]] = None, - *, - parent: Optional[str] = None, - entities: Optional[MutableSequence[entity_type.EntityType.Entity]] = None, - language_code: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation_async.AsyncOperation: - r"""Creates multiple new entities in the specified entity type. - - This method is a `long-running - operation `__. - The returned ``Operation`` type has the following - method-specific fields: - - - ``metadata``: An empty `Struct - message `__ - - ``response``: An `Empty - message `__ - - Note: You should always train an agent prior to sending it - queries. See the `training - documentation `__. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import dialogflow_v2 - - async def sample_batch_create_entities(): - # Create a client - client = dialogflow_v2.EntityTypesAsyncClient() - - # Initialize request argument(s) - entities = dialogflow_v2.Entity() - entities.value = "value_value" - entities.synonyms = ['synonyms_value1', 'synonyms_value2'] - - request = dialogflow_v2.BatchCreateEntitiesRequest( - parent="parent_value", - entities=entities, - ) - - # Make the request - operation = client.batch_create_entities(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.dialogflow_v2.types.BatchCreateEntitiesRequest, dict]]): - The request object. The request message for - [EntityTypes.BatchCreateEntities][google.cloud.dialogflow.v2.EntityTypes.BatchCreateEntities]. - parent (:class:`str`): - Required. The name of the entity type to create entities - in. Format: - ``projects//agent/entityTypes/``. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - entities (:class:`MutableSequence[google.cloud.dialogflow_v2.types.EntityType.Entity]`): - Required. The entities to create. - This corresponds to the ``entities`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - language_code (:class:`str`): - Optional. The language used to access language-specific - data. If not specified, the agent's default language is - used. For more information, see `Multilingual intent and - entity - data `__. - - 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. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.api_core.operation_async.AsyncOperation: - An object representing a long-running operation. - - The result type for the operation will be :class:`google.protobuf.empty_pb2.Empty` A generic empty message that you can re-use to avoid defining duplicated - empty messages in your APIs. A typical example is to - use it as the request or the response type of an API - method. For instance: - - service Foo { - rpc Bar(google.protobuf.Empty) returns - (google.protobuf.Empty); - - } - - """ - # Create or coerce a protobuf request object. - # Quick 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, entities, language_code]) - 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 = 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 language_code is not None: - request.language_code = language_code - if entities: - request.entities.extend(entities) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.batch_create_entities, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Wrap the response in an operation future. - response = operation_async.from_gapic( - response, - self._client._transport.operations_client, - empty_pb2.Empty, - metadata_type=struct_pb2.Struct, - ) - - # Done; return the response. - return response - - async def batch_update_entities(self, - request: Optional[Union[entity_type.BatchUpdateEntitiesRequest, dict]] = None, - *, - parent: Optional[str] = None, - entities: Optional[MutableSequence[entity_type.EntityType.Entity]] = None, - language_code: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation_async.AsyncOperation: - r"""Updates or creates multiple entities in the specified entity - type. This method does not affect entities in the entity type - that aren't explicitly specified in the request. - - This method is a `long-running - operation `__. - The returned ``Operation`` type has the following - method-specific fields: - - - ``metadata``: An empty `Struct - message `__ - - ``response``: An `Empty - message `__ - - Note: You should always train an agent prior to sending it - queries. See the `training - documentation `__. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import dialogflow_v2 - - async def sample_batch_update_entities(): - # Create a client - client = dialogflow_v2.EntityTypesAsyncClient() - - # Initialize request argument(s) - entities = dialogflow_v2.Entity() - entities.value = "value_value" - entities.synonyms = ['synonyms_value1', 'synonyms_value2'] - - request = dialogflow_v2.BatchUpdateEntitiesRequest( - parent="parent_value", - entities=entities, - ) - - # Make the request - operation = client.batch_update_entities(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.dialogflow_v2.types.BatchUpdateEntitiesRequest, dict]]): - The request object. The request message for - [EntityTypes.BatchUpdateEntities][google.cloud.dialogflow.v2.EntityTypes.BatchUpdateEntities]. - parent (:class:`str`): - Required. The name of the entity type to update or - create entities in. Format: - ``projects//agent/entityTypes/``. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - entities (:class:`MutableSequence[google.cloud.dialogflow_v2.types.EntityType.Entity]`): - Required. The entities to update or - create. - - This corresponds to the ``entities`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - language_code (:class:`str`): - Optional. The language used to access language-specific - data. If not specified, the agent's default language is - used. For more information, see `Multilingual intent and - entity - data `__. - - 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. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.api_core.operation_async.AsyncOperation: - An object representing a long-running operation. - - The result type for the operation will be :class:`google.protobuf.empty_pb2.Empty` A generic empty message that you can re-use to avoid defining duplicated - empty messages in your APIs. A typical example is to - use it as the request or the response type of an API - method. For instance: - - service Foo { - rpc Bar(google.protobuf.Empty) returns - (google.protobuf.Empty); - - } - - """ - # Create or coerce a protobuf request object. - # Quick 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, entities, language_code]) - 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 = 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 language_code is not None: - request.language_code = language_code - if entities: - request.entities.extend(entities) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.batch_update_entities, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Wrap the response in an operation future. - response = operation_async.from_gapic( - response, - self._client._transport.operations_client, - empty_pb2.Empty, - metadata_type=struct_pb2.Struct, - ) - - # Done; return the response. - return response - - async def batch_delete_entities(self, - request: Optional[Union[entity_type.BatchDeleteEntitiesRequest, dict]] = None, - *, - parent: Optional[str] = None, - entity_values: Optional[MutableSequence[str]] = None, - language_code: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation_async.AsyncOperation: - r"""Deletes entities in the specified entity type. - - This method is a `long-running - operation `__. - The returned ``Operation`` type has the following - method-specific fields: - - - ``metadata``: An empty `Struct - message `__ - - ``response``: An `Empty - message `__ - - Note: You should always train an agent prior to sending it - queries. See the `training - documentation `__. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import dialogflow_v2 - - async def sample_batch_delete_entities(): - # Create a client - client = dialogflow_v2.EntityTypesAsyncClient() - - # Initialize request argument(s) - request = dialogflow_v2.BatchDeleteEntitiesRequest( - parent="parent_value", - entity_values=['entity_values_value1', 'entity_values_value2'], - ) - - # Make the request - operation = client.batch_delete_entities(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.dialogflow_v2.types.BatchDeleteEntitiesRequest, dict]]): - The request object. The request message for - [EntityTypes.BatchDeleteEntities][google.cloud.dialogflow.v2.EntityTypes.BatchDeleteEntities]. - parent (:class:`str`): - Required. The name of the entity type to delete entries - for. Format: - ``projects//agent/entityTypes/``. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - entity_values (:class:`MutableSequence[str]`): - Required. The reference ``values`` of the entities to - delete. Note that these are not fully-qualified names, - i.e. they don't start with ``projects/``. - - This corresponds to the ``entity_values`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - language_code (:class:`str`): - Optional. The language used to access language-specific - data. If not specified, the agent's default language is - used. For more information, see `Multilingual intent and - entity - data `__. - - 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. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.api_core.operation_async.AsyncOperation: - An object representing a long-running operation. - - The result type for the operation will be :class:`google.protobuf.empty_pb2.Empty` A generic empty message that you can re-use to avoid defining duplicated - empty messages in your APIs. A typical example is to - use it as the request or the response type of an API - method. For instance: - - service Foo { - rpc Bar(google.protobuf.Empty) returns - (google.protobuf.Empty); - - } - - """ - # Create or coerce a protobuf request object. - # Quick 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, entity_values, language_code]) - 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 = 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 language_code is not None: - request.language_code = language_code - if entity_values: - request.entity_values.extend(entity_values) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.batch_delete_entities, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Wrap the response in an operation future. - response = operation_async.from_gapic( - response, - self._client._transport.operations_client, - empty_pb2.Empty, - metadata_type=struct_pb2.Struct, - ) - - # Done; return the response. - return response - - async def list_operations( - self, - request: Optional[operations_pb2.ListOperationsRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operations_pb2.ListOperationsResponse: - r"""Lists operations that match the specified filter in the request. - - Args: - request (:class:`~.operations_pb2.ListOperationsRequest`): - The request object. Request message for - `ListOperations` method. - 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: - ~.operations_pb2.ListOperationsResponse: - Response message for ``ListOperations`` method. - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = operations_pb2.ListOperationsRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._client._transport.list_operations, - 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 get_operation( - self, - request: Optional[operations_pb2.GetOperationRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operations_pb2.Operation: - r"""Gets the latest state of a long-running operation. - - Args: - request (:class:`~.operations_pb2.GetOperationRequest`): - The request object. Request message for - `GetOperation` method. - 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: - ~.operations_pb2.Operation: - An ``Operation`` object. - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = operations_pb2.GetOperationRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._client._transport.get_operation, - 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 cancel_operation( - self, - request: Optional[operations_pb2.CancelOperationRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> None: - r"""Starts asynchronous cancellation on a long-running operation. - - The server makes a best effort to cancel the operation, but success - is not guaranteed. If the server doesn't support this method, it returns - `google.rpc.Code.UNIMPLEMENTED`. - - Args: - request (:class:`~.operations_pb2.CancelOperationRequest`): - The request object. Request message for - `CancelOperation` method. - 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: - None - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = operations_pb2.CancelOperationRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._client._transport.cancel_operation, - 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_location( - self, - request: Optional[locations_pb2.GetLocationRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> locations_pb2.Location: - r"""Gets information about a location. - - Args: - request (:class:`~.location_pb2.GetLocationRequest`): - The request object. Request message for - `GetLocation` method. - 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: - ~.location_pb2.Location: - Location object. - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = locations_pb2.GetLocationRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._client._transport.get_location, - 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 list_locations( - self, - request: Optional[locations_pb2.ListLocationsRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> locations_pb2.ListLocationsResponse: - r"""Lists information about the supported locations for this service. - - Args: - request (:class:`~.location_pb2.ListLocationsRequest`): - The request object. Request message for - `ListLocations` method. - 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: - ~.location_pb2.ListLocationsResponse: - Response message for ``ListLocations`` method. - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = locations_pb2.ListLocationsRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._client._transport.list_locations, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("name", request.name),)), - ) - - # Send the request. - response = await rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - async def __aenter__(self): - return self - - async def __aexit__(self, exc_type, exc, tb): - await self.transport.close() - -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) - - -__all__ = ( - "EntityTypesAsyncClient", -) diff --git a/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/entity_types/client.py b/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/entity_types/client.py deleted file mode 100644 index 6fb1c552e..000000000 --- a/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/entity_types/client.py +++ /dev/null @@ -1,2039 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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 os -import re -from typing import Dict, Mapping, MutableMapping, MutableSequence, Optional, Sequence, Tuple, Type, Union, cast - -from google.cloud.dialogflow_v2 import gapic_version as package_version - -from google.api_core import client_options as client_options_lib -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import retry as retries -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 - -try: - OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] -except AttributeError: # pragma: NO COVER - OptionalRetry = Union[retries.Retry, object] # type: ignore - -from google.api_core import operation # type: ignore -from google.api_core import operation_async # type: ignore -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.cloud.location import locations_pb2 # type: ignore -from google.longrunning import operations_pb2 -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 -from .transports.rest import EntityTypesRestTransport - - -class EntityTypesClientMeta(type): - """Metaclass for the EntityTypes 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[EntityTypesTransport]] - _transport_registry["grpc"] = EntityTypesGrpcTransport - _transport_registry["grpc_asyncio"] = EntityTypesGrpcAsyncIOTransport - _transport_registry["rest"] = EntityTypesRestTransport - - def get_transport_class(cls, - label: Optional[str] = None, - ) -> Type[EntityTypesTransport]: - """Returns an appropriate transport class. - - Args: - label: The name of the desired transport. If none is - provided, then the first transport in the registry is used. - - Returns: - The transport class to use. - """ - # If a specific transport is requested, return that one. - if label: - return cls._transport_registry[label] - - # No transport is requested; return the default (that is, the first one - # in the dictionary). - return next(iter(cls._transport_registry.values())) - - -class EntityTypesClient(metaclass=EntityTypesClientMeta): - """Service for managing - [EntityTypes][google.cloud.dialogflow.v2.EntityType]. - """ - - @staticmethod - def _get_default_mtls_endpoint(api_endpoint): - """Converts api endpoint to mTLS endpoint. - - Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to - "*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively. - Args: - api_endpoint (Optional[str]): the api endpoint to convert. - Returns: - str: converted mTLS api endpoint. - """ - if not api_endpoint: - return api_endpoint - - mtls_endpoint_re = re.compile( - r"(?P[^.]+)(?P\.mtls)?(?P\.sandbox)?(?P\.googleapis\.com)?" - ) - - m = mtls_endpoint_re.match(api_endpoint) - name, mtls, sandbox, googledomain = m.groups() - if mtls or not googledomain: - return api_endpoint - - if sandbox: - return api_endpoint.replace( - "sandbox.googleapis.com", "mtls.sandbox.googleapis.com" - ) - - return api_endpoint.replace(".googleapis.com", ".mtls.googleapis.com") - - DEFAULT_ENDPOINT = "dialogflow.googleapis.com" - DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore - DEFAULT_ENDPOINT - ) - - @classmethod - def from_service_account_info(cls, info: dict, *args, **kwargs): - """Creates an instance of this client using the provided credentials - info. - - Args: - info (dict): The service account private key info. - args: Additional arguments to pass to the constructor. - kwargs: Additional arguments to pass to the constructor. - - Returns: - EntityTypesClient: 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: - EntityTypesClient: 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) -> EntityTypesTransport: - """Returns the transport used by the client instance. - - Returns: - EntityTypesTransport: The transport used by the client - instance. - """ - return self._transport - - @staticmethod - def entity_type_path(project: str,entity_type: str,) -> str: - """Returns a fully-qualified entity_type string.""" - return "projects/{project}/agent/entityTypes/{entity_type}".format(project=project, entity_type=entity_type, ) - - @staticmethod - def parse_entity_type_path(path: str) -> Dict[str,str]: - """Parses a entity_type path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/agent/entityTypes/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_billing_account_path(billing_account: str, ) -> str: - """Returns a fully-qualified billing_account string.""" - return "billingAccounts/{billing_account}".format(billing_account=billing_account, ) - - @staticmethod - def parse_common_billing_account_path(path: str) -> Dict[str,str]: - """Parse a billing_account path into its component segments.""" - m = re.match(r"^billingAccounts/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_folder_path(folder: str, ) -> str: - """Returns a fully-qualified folder string.""" - return "folders/{folder}".format(folder=folder, ) - - @staticmethod - def parse_common_folder_path(path: str) -> Dict[str,str]: - """Parse a folder path into its component segments.""" - m = re.match(r"^folders/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_organization_path(organization: str, ) -> str: - """Returns a fully-qualified organization string.""" - return "organizations/{organization}".format(organization=organization, ) - - @staticmethod - def parse_common_organization_path(path: str) -> Dict[str,str]: - """Parse a organization path into its component segments.""" - m = re.match(r"^organizations/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_project_path(project: str, ) -> str: - """Returns a fully-qualified project string.""" - return "projects/{project}".format(project=project, ) - - @staticmethod - def parse_common_project_path(path: str) -> Dict[str,str]: - """Parse a project path into its component segments.""" - m = re.match(r"^projects/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_location_path(project: str, location: str, ) -> str: - """Returns a fully-qualified location string.""" - return "projects/{project}/locations/{location}".format(project=project, location=location, ) - - @staticmethod - def parse_common_location_path(path: str) -> Dict[str,str]: - """Parse a location path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)$", path) - return m.groupdict() if m else {} - - @classmethod - def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[client_options_lib.ClientOptions] = None): - """Return the API endpoint and client cert source for mutual TLS. - - The client cert source is determined in the following order: - (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the - client cert source is None. - (2) if `client_options.client_cert_source` is provided, use the provided one; if the - default client cert source exists, use the default one; otherwise the client cert - source is None. - - The API endpoint is determined in the following order: - (1) if `client_options.api_endpoint` if provided, use the provided one. - (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the - default mTLS endpoint; if the environment variable is "never", use the default API - endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise - use the default API endpoint. - - More details can be found at https://google.aip.dev/auth/4114. - - Args: - client_options (google.api_core.client_options.ClientOptions): Custom options for the - client. Only the `api_endpoint` and `client_cert_source` properties may be used - in this method. - - Returns: - Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the - client cert source to use. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If any errors happen. - """ - if client_options is None: - client_options = client_options_lib.ClientOptions() - use_client_cert = os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false") - use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") - if use_client_cert not in ("true", "false"): - raise ValueError("Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`") - if use_mtls_endpoint not in ("auto", "never", "always"): - raise MutualTLSChannelError("Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`") - - # Figure out the client cert source to use. - client_cert_source = None - if use_client_cert == "true": - if client_options.client_cert_source: - client_cert_source = client_options.client_cert_source - elif mtls.has_default_client_cert_source(): - client_cert_source = mtls.default_client_cert_source() - - # Figure out which api endpoint to use. - if client_options.api_endpoint is not None: - api_endpoint = client_options.api_endpoint - elif use_mtls_endpoint == "always" or (use_mtls_endpoint == "auto" and client_cert_source): - api_endpoint = cls.DEFAULT_MTLS_ENDPOINT - else: - api_endpoint = cls.DEFAULT_ENDPOINT - - return api_endpoint, client_cert_source - - def __init__(self, *, - credentials: Optional[ga_credentials.Credentials] = None, - transport: Optional[Union[str, EntityTypesTransport]] = None, - client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the entity types 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, EntityTypesTransport]): The - transport to use. If set to None, a transport is chosen - automatically. - client_options (Optional[Union[google.api_core.client_options.ClientOptions, dict]]): 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() - client_options = cast(client_options_lib.ClientOptions, client_options) - - api_endpoint, client_cert_source_func = self.get_mtls_endpoint_and_cert_source(client_options) - - api_key_value = getattr(client_options, "api_key", None) - if api_key_value and credentials: - raise ValueError("client_options.api_key and credentials are mutually exclusive") - - # 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, EntityTypesTransport): - # transport is a EntityTypesTransport instance. - if credentials or client_options.credentials_file or api_key_value: - 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: - import google.auth._default # type: ignore - - if api_key_value and hasattr(google.auth._default, "get_api_key_credentials"): - credentials = google.auth._default.get_api_key_credentials(api_key_value) - - Transport = type(self).get_transport_class(transport) - self._transport = Transport( - credentials=credentials, - credentials_file=client_options.credentials_file, - host=api_endpoint, - scopes=client_options.scopes, - client_cert_source_for_mtls=client_cert_source_func, - quota_project_id=client_options.quota_project_id, - client_info=client_info, - always_use_jwt_access=True, - api_audience=client_options.api_audience, - ) - - def list_entity_types(self, - request: Optional[Union[entity_type.ListEntityTypesRequest, dict]] = None, - *, - parent: Optional[str] = None, - language_code: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListEntityTypesPager: - r"""Returns the list of all entity types in the specified - agent. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import dialogflow_v2 - - def sample_list_entity_types(): - # Create a client - client = dialogflow_v2.EntityTypesClient() - - # Initialize request argument(s) - request = dialogflow_v2.ListEntityTypesRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_entity_types(request=request) - - # Handle the response - for response in page_result: - print(response) - - Args: - request (Union[google.cloud.dialogflow_v2.types.ListEntityTypesRequest, dict]): - The request object. The request message for - [EntityTypes.ListEntityTypes][google.cloud.dialogflow.v2.EntityTypes.ListEntityTypes]. - parent (str): - Required. The agent to list all entity types from. - Format: ``projects//agent``. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - language_code (str): - Optional. The language used to access language-specific - data. If not specified, the agent's default language is - used. For more information, see `Multilingual intent and - entity - data `__. - - 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. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.dialogflow_v2.services.entity_types.pagers.ListEntityTypesPager: - The response message for - [EntityTypes.ListEntityTypes][google.cloud.dialogflow.v2.EntityTypes.ListEntityTypes]. - - Iterating over this object will yield results and - resolve additional pages automatically. - - """ - # Create or coerce a protobuf request object. - # Quick 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, language_code]) - 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 entity_type.ListEntityTypesRequest. - # There's no risk of modifying the input as we've already verified - # 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: - request.language_code = language_code - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.list_entity_types] - - # 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.ListEntityTypesPager( - method=rpc, - request=request, - response=response, - metadata=metadata, - ) - - # Done; return the response. - return response - - def get_entity_type(self, - request: Optional[Union[entity_type.GetEntityTypeRequest, dict]] = None, - *, - name: Optional[str] = None, - language_code: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> entity_type.EntityType: - r"""Retrieves the specified entity type. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import dialogflow_v2 - - def sample_get_entity_type(): - # Create a client - client = dialogflow_v2.EntityTypesClient() - - # Initialize request argument(s) - request = dialogflow_v2.GetEntityTypeRequest( - name="name_value", - ) - - # Make the request - response = client.get_entity_type(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.dialogflow_v2.types.GetEntityTypeRequest, dict]): - The request object. The request message for - [EntityTypes.GetEntityType][google.cloud.dialogflow.v2.EntityTypes.GetEntityType]. - name (str): - Required. The name of the entity type. Format: - ``projects//agent/entityTypes/``. - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - language_code (str): - Optional. The language used to access language-specific - data. If not specified, the agent's default language is - used. For more information, see `Multilingual intent and - entity - data `__. - - 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. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.dialogflow_v2.types.EntityType: - Each intent parameter has a type, called the entity type, which dictates - exactly how data from an end-user expression is - extracted. - - Dialogflow provides predefined system entities that - can match many common types of data. For example, - there are system entities for matching dates, times, - colors, email addresses, and so on. You can also - create your own custom entities for matching custom - data. For example, you could define a vegetable - entity that can match the types of vegetables - available for purchase with a grocery store agent. - - For more information, see the [Entity - guide](\ https://cloud.google.com/dialogflow/docs/entities-overview). - - """ - # Create or coerce a protobuf request object. - # Quick 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, language_code]) - 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 entity_type.GetEntityTypeRequest. - # There's no risk of modifying the input as we've already verified - # 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: - request.language_code = language_code - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.get_entity_type] - - # 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_entity_type(self, - request: Optional[Union[gcd_entity_type.CreateEntityTypeRequest, dict]] = None, - *, - parent: Optional[str] = None, - entity_type: Optional[gcd_entity_type.EntityType] = None, - language_code: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gcd_entity_type.EntityType: - r"""Creates an entity type in the specified agent. - - Note: You should always train an agent prior to sending it - queries. See the `training - documentation `__. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import dialogflow_v2 - - def sample_create_entity_type(): - # Create a client - client = dialogflow_v2.EntityTypesClient() - - # Initialize request argument(s) - entity_type = dialogflow_v2.EntityType() - entity_type.display_name = "display_name_value" - entity_type.kind = "KIND_REGEXP" - - request = dialogflow_v2.CreateEntityTypeRequest( - parent="parent_value", - entity_type=entity_type, - ) - - # Make the request - response = client.create_entity_type(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.dialogflow_v2.types.CreateEntityTypeRequest, dict]): - The request object. The request message for - [EntityTypes.CreateEntityType][google.cloud.dialogflow.v2.EntityTypes.CreateEntityType]. - parent (str): - Required. The agent to create a entity type for. Format: - ``projects//agent``. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - entity_type (google.cloud.dialogflow_v2.types.EntityType): - Required. The entity type to create. - This corresponds to the ``entity_type`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - language_code (str): - Optional. The language used to access language-specific - data. If not specified, the agent's default language is - used. For more information, see `Multilingual intent and - entity - data `__. - - 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. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.dialogflow_v2.types.EntityType: - Each intent parameter has a type, called the entity type, which dictates - exactly how data from an end-user expression is - extracted. - - Dialogflow provides predefined system entities that - can match many common types of data. For example, - there are system entities for matching dates, times, - colors, email addresses, and so on. You can also - create your own custom entities for matching custom - data. For example, you could define a vegetable - entity that can match the types of vegetables - available for purchase with a grocery store agent. - - For more information, see the [Entity - guide](\ https://cloud.google.com/dialogflow/docs/entities-overview). - - """ - # Create or coerce a protobuf request object. - # Quick 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, entity_type, language_code]) - 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_entity_type.CreateEntityTypeRequest. - # There's no risk of modifying the input as we've already verified - # 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: - request.entity_type = entity_type - if language_code is not None: - request.language_code = language_code - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.create_entity_type] - - # 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_entity_type(self, - request: Optional[Union[gcd_entity_type.UpdateEntityTypeRequest, dict]] = None, - *, - entity_type: Optional[gcd_entity_type.EntityType] = None, - language_code: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gcd_entity_type.EntityType: - r"""Updates the specified entity type. - - Note: You should always train an agent prior to sending it - queries. See the `training - documentation `__. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import dialogflow_v2 - - def sample_update_entity_type(): - # Create a client - client = dialogflow_v2.EntityTypesClient() - - # Initialize request argument(s) - entity_type = dialogflow_v2.EntityType() - entity_type.display_name = "display_name_value" - entity_type.kind = "KIND_REGEXP" - - request = dialogflow_v2.UpdateEntityTypeRequest( - entity_type=entity_type, - ) - - # Make the request - response = client.update_entity_type(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.dialogflow_v2.types.UpdateEntityTypeRequest, dict]): - The request object. The request message for - [EntityTypes.UpdateEntityType][google.cloud.dialogflow.v2.EntityTypes.UpdateEntityType]. - entity_type (google.cloud.dialogflow_v2.types.EntityType): - Required. The entity type to update. - This corresponds to the ``entity_type`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - language_code (str): - Optional. The language used to access language-specific - data. If not specified, the agent's default language is - used. For more information, see `Multilingual intent and - entity - data `__. - - 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. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.dialogflow_v2.types.EntityType: - Each intent parameter has a type, called the entity type, which dictates - exactly how data from an end-user expression is - extracted. - - Dialogflow provides predefined system entities that - can match many common types of data. For example, - there are system entities for matching dates, times, - colors, email addresses, and so on. You can also - create your own custom entities for matching custom - data. For example, you could define a vegetable - entity that can match the types of vegetables - available for purchase with a grocery store agent. - - For more information, see the [Entity - guide](\ https://cloud.google.com/dialogflow/docs/entities-overview). - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([entity_type, language_code]) - 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_entity_type.UpdateEntityTypeRequest. - # There's no risk of modifying the input as we've already verified - # 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: - request.language_code = language_code - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.update_entity_type] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("entity_type.name", request.entity_type.name), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def delete_entity_type(self, - request: Optional[Union[entity_type.DeleteEntityTypeRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> None: - r"""Deletes the specified entity type. - - Note: You should always train an agent prior to sending it - queries. See the `training - documentation `__. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import dialogflow_v2 - - def sample_delete_entity_type(): - # Create a client - client = dialogflow_v2.EntityTypesClient() - - # Initialize request argument(s) - request = dialogflow_v2.DeleteEntityTypeRequest( - name="name_value", - ) - - # Make the request - client.delete_entity_type(request=request) - - Args: - request (Union[google.cloud.dialogflow_v2.types.DeleteEntityTypeRequest, dict]): - The request object. The request message for - [EntityTypes.DeleteEntityType][google.cloud.dialogflow.v2.EntityTypes.DeleteEntityType]. - name (str): - Required. The name of the entity type to delete. Format: - ``projects//agent/entityTypes/``. - - 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. - # Quick 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 entity_type.DeleteEntityTypeRequest. - # There's no risk of modifying the input as we've already verified - # 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 - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.delete_entity_type] - - # 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 batch_update_entity_types(self, - request: Optional[Union[entity_type.BatchUpdateEntityTypesRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation.Operation: - r"""Updates/Creates multiple entity types in the specified agent. - - This method is a `long-running - operation `__. - The returned ``Operation`` type has the following - method-specific fields: - - - ``metadata``: An empty `Struct - message `__ - - ``response``: - [BatchUpdateEntityTypesResponse][google.cloud.dialogflow.v2.BatchUpdateEntityTypesResponse] - - Note: You should always train an agent prior to sending it - queries. See the `training - documentation `__. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import dialogflow_v2 - - def sample_batch_update_entity_types(): - # Create a client - client = dialogflow_v2.EntityTypesClient() - - # Initialize request argument(s) - request = dialogflow_v2.BatchUpdateEntityTypesRequest( - entity_type_batch_uri="entity_type_batch_uri_value", - parent="parent_value", - ) - - # Make the request - operation = client.batch_update_entity_types(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.dialogflow_v2.types.BatchUpdateEntityTypesRequest, dict]): - 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. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.api_core.operation.Operation: - An object representing a long-running operation. - - The result type for the operation will be :class:`google.cloud.dialogflow_v2.types.BatchUpdateEntityTypesResponse` The response message for - [EntityTypes.BatchUpdateEntityTypes][google.cloud.dialogflow.v2.EntityTypes.BatchUpdateEntityTypes]. - - """ - # 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 - # there are no flattened fields. - if not isinstance(request, entity_type.BatchUpdateEntityTypesRequest): - request = entity_type.BatchUpdateEntityTypesRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.batch_update_entity_types] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Wrap the response in an operation future. - response = operation.from_gapic( - response, - self._transport.operations_client, - entity_type.BatchUpdateEntityTypesResponse, - metadata_type=struct_pb2.Struct, - ) - - # Done; return the response. - return response - - def batch_delete_entity_types(self, - request: Optional[Union[entity_type.BatchDeleteEntityTypesRequest, dict]] = None, - *, - parent: Optional[str] = None, - entity_type_names: Optional[MutableSequence[str]] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation.Operation: - r"""Deletes entity types in the specified agent. - - This method is a `long-running - operation `__. - The returned ``Operation`` type has the following - method-specific fields: - - - ``metadata``: An empty `Struct - message `__ - - ``response``: An `Empty - message `__ - - Note: You should always train an agent prior to sending it - queries. See the `training - documentation `__. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import dialogflow_v2 - - def sample_batch_delete_entity_types(): - # Create a client - client = dialogflow_v2.EntityTypesClient() - - # Initialize request argument(s) - request = dialogflow_v2.BatchDeleteEntityTypesRequest( - parent="parent_value", - entity_type_names=['entity_type_names_value1', 'entity_type_names_value2'], - ) - - # Make the request - operation = client.batch_delete_entity_types(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.dialogflow_v2.types.BatchDeleteEntityTypesRequest, dict]): - The request object. The request message for - [EntityTypes.BatchDeleteEntityTypes][google.cloud.dialogflow.v2.EntityTypes.BatchDeleteEntityTypes]. - parent (str): - Required. The name of the agent to delete all entities - types for. Format: ``projects//agent``. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - entity_type_names (MutableSequence[str]): - Required. The names entity types to delete. All names - must point to the same agent as ``parent``. - - 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. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.api_core.operation.Operation: - An object representing a long-running operation. - - The result type for the operation will be :class:`google.protobuf.empty_pb2.Empty` A generic empty message that you can re-use to avoid defining duplicated - empty messages in your APIs. A typical example is to - use it as the request or the response type of an API - method. For instance: - - service Foo { - rpc Bar(google.protobuf.Empty) returns - (google.protobuf.Empty); - - } - - """ - # Create or coerce a protobuf request object. - # Quick 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, entity_type_names]) - 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 entity_type.BatchDeleteEntityTypesRequest. - # There's no risk of modifying the input as we've already verified - # 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: - request.entity_type_names = entity_type_names - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.batch_delete_entity_types] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Wrap the response in an operation future. - response = operation.from_gapic( - response, - self._transport.operations_client, - empty_pb2.Empty, - metadata_type=struct_pb2.Struct, - ) - - # Done; return the response. - return response - - def batch_create_entities(self, - request: Optional[Union[entity_type.BatchCreateEntitiesRequest, dict]] = None, - *, - parent: Optional[str] = None, - entities: Optional[MutableSequence[entity_type.EntityType.Entity]] = None, - language_code: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation.Operation: - r"""Creates multiple new entities in the specified entity type. - - This method is a `long-running - operation `__. - The returned ``Operation`` type has the following - method-specific fields: - - - ``metadata``: An empty `Struct - message `__ - - ``response``: An `Empty - message `__ - - Note: You should always train an agent prior to sending it - queries. See the `training - documentation `__. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import dialogflow_v2 - - def sample_batch_create_entities(): - # Create a client - client = dialogflow_v2.EntityTypesClient() - - # Initialize request argument(s) - entities = dialogflow_v2.Entity() - entities.value = "value_value" - entities.synonyms = ['synonyms_value1', 'synonyms_value2'] - - request = dialogflow_v2.BatchCreateEntitiesRequest( - parent="parent_value", - entities=entities, - ) - - # Make the request - operation = client.batch_create_entities(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.dialogflow_v2.types.BatchCreateEntitiesRequest, dict]): - The request object. The request message for - [EntityTypes.BatchCreateEntities][google.cloud.dialogflow.v2.EntityTypes.BatchCreateEntities]. - parent (str): - Required. The name of the entity type to create entities - in. Format: - ``projects//agent/entityTypes/``. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - entities (MutableSequence[google.cloud.dialogflow_v2.types.EntityType.Entity]): - Required. The entities to create. - This corresponds to the ``entities`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - language_code (str): - Optional. The language used to access language-specific - data. If not specified, the agent's default language is - used. For more information, see `Multilingual intent and - entity - data `__. - - 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. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.api_core.operation.Operation: - An object representing a long-running operation. - - The result type for the operation will be :class:`google.protobuf.empty_pb2.Empty` A generic empty message that you can re-use to avoid defining duplicated - empty messages in your APIs. A typical example is to - use it as the request or the response type of an API - method. For instance: - - service Foo { - rpc Bar(google.protobuf.Empty) returns - (google.protobuf.Empty); - - } - - """ - # Create or coerce a protobuf request object. - # Quick 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, entities, language_code]) - 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 entity_type.BatchCreateEntitiesRequest. - # There's no risk of modifying the input as we've already verified - # 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: - request.entities = entities - if language_code is not None: - request.language_code = language_code - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.batch_create_entities] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Wrap the response in an operation future. - response = operation.from_gapic( - response, - self._transport.operations_client, - empty_pb2.Empty, - metadata_type=struct_pb2.Struct, - ) - - # Done; return the response. - return response - - def batch_update_entities(self, - request: Optional[Union[entity_type.BatchUpdateEntitiesRequest, dict]] = None, - *, - parent: Optional[str] = None, - entities: Optional[MutableSequence[entity_type.EntityType.Entity]] = None, - language_code: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation.Operation: - r"""Updates or creates multiple entities in the specified entity - type. This method does not affect entities in the entity type - that aren't explicitly specified in the request. - - This method is a `long-running - operation `__. - The returned ``Operation`` type has the following - method-specific fields: - - - ``metadata``: An empty `Struct - message `__ - - ``response``: An `Empty - message `__ - - Note: You should always train an agent prior to sending it - queries. See the `training - documentation `__. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import dialogflow_v2 - - def sample_batch_update_entities(): - # Create a client - client = dialogflow_v2.EntityTypesClient() - - # Initialize request argument(s) - entities = dialogflow_v2.Entity() - entities.value = "value_value" - entities.synonyms = ['synonyms_value1', 'synonyms_value2'] - - request = dialogflow_v2.BatchUpdateEntitiesRequest( - parent="parent_value", - entities=entities, - ) - - # Make the request - operation = client.batch_update_entities(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.dialogflow_v2.types.BatchUpdateEntitiesRequest, dict]): - The request object. The request message for - [EntityTypes.BatchUpdateEntities][google.cloud.dialogflow.v2.EntityTypes.BatchUpdateEntities]. - parent (str): - Required. The name of the entity type to update or - create entities in. Format: - ``projects//agent/entityTypes/``. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - entities (MutableSequence[google.cloud.dialogflow_v2.types.EntityType.Entity]): - Required. The entities to update or - create. - - This corresponds to the ``entities`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - language_code (str): - Optional. The language used to access language-specific - data. If not specified, the agent's default language is - used. For more information, see `Multilingual intent and - entity - data `__. - - 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. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.api_core.operation.Operation: - An object representing a long-running operation. - - The result type for the operation will be :class:`google.protobuf.empty_pb2.Empty` A generic empty message that you can re-use to avoid defining duplicated - empty messages in your APIs. A typical example is to - use it as the request or the response type of an API - method. For instance: - - service Foo { - rpc Bar(google.protobuf.Empty) returns - (google.protobuf.Empty); - - } - - """ - # Create or coerce a protobuf request object. - # Quick 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, entities, language_code]) - 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 entity_type.BatchUpdateEntitiesRequest. - # There's no risk of modifying the input as we've already verified - # 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: - request.entities = entities - if language_code is not None: - request.language_code = language_code - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.batch_update_entities] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Wrap the response in an operation future. - response = operation.from_gapic( - response, - self._transport.operations_client, - empty_pb2.Empty, - metadata_type=struct_pb2.Struct, - ) - - # Done; return the response. - return response - - def batch_delete_entities(self, - request: Optional[Union[entity_type.BatchDeleteEntitiesRequest, dict]] = None, - *, - parent: Optional[str] = None, - entity_values: Optional[MutableSequence[str]] = None, - language_code: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation.Operation: - r"""Deletes entities in the specified entity type. - - This method is a `long-running - operation `__. - The returned ``Operation`` type has the following - method-specific fields: - - - ``metadata``: An empty `Struct - message `__ - - ``response``: An `Empty - message `__ - - Note: You should always train an agent prior to sending it - queries. See the `training - documentation `__. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import dialogflow_v2 - - def sample_batch_delete_entities(): - # Create a client - client = dialogflow_v2.EntityTypesClient() - - # Initialize request argument(s) - request = dialogflow_v2.BatchDeleteEntitiesRequest( - parent="parent_value", - entity_values=['entity_values_value1', 'entity_values_value2'], - ) - - # Make the request - operation = client.batch_delete_entities(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.dialogflow_v2.types.BatchDeleteEntitiesRequest, dict]): - The request object. The request message for - [EntityTypes.BatchDeleteEntities][google.cloud.dialogflow.v2.EntityTypes.BatchDeleteEntities]. - parent (str): - Required. The name of the entity type to delete entries - for. Format: - ``projects//agent/entityTypes/``. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - entity_values (MutableSequence[str]): - Required. The reference ``values`` of the entities to - delete. Note that these are not fully-qualified names, - i.e. they don't start with ``projects/``. - - This corresponds to the ``entity_values`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - language_code (str): - Optional. The language used to access language-specific - data. If not specified, the agent's default language is - used. For more information, see `Multilingual intent and - entity - data `__. - - 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. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.api_core.operation.Operation: - An object representing a long-running operation. - - The result type for the operation will be :class:`google.protobuf.empty_pb2.Empty` A generic empty message that you can re-use to avoid defining duplicated - empty messages in your APIs. A typical example is to - use it as the request or the response type of an API - method. For instance: - - service Foo { - rpc Bar(google.protobuf.Empty) returns - (google.protobuf.Empty); - - } - - """ - # Create or coerce a protobuf request object. - # Quick 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, entity_values, language_code]) - 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 entity_type.BatchDeleteEntitiesRequest. - # There's no risk of modifying the input as we've already verified - # 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: - request.entity_values = entity_values - if language_code is not None: - request.language_code = language_code - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.batch_delete_entities] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Wrap the response in an operation future. - response = operation.from_gapic( - response, - self._transport.operations_client, - empty_pb2.Empty, - metadata_type=struct_pb2.Struct, - ) - - # Done; return the response. - return response - - def __enter__(self) -> "EntityTypesClient": - return self - - def __exit__(self, type, value, traceback): - """Releases underlying transport's resources. - - .. warning:: - ONLY use as a context manager if the transport is NOT shared - with other clients! Exiting the with block will CLOSE the transport - and may cause errors in other clients! - """ - self.transport.close() - - def list_operations( - self, - request: Optional[operations_pb2.ListOperationsRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operations_pb2.ListOperationsResponse: - r"""Lists operations that match the specified filter in the request. - - Args: - request (:class:`~.operations_pb2.ListOperationsRequest`): - The request object. Request message for - `ListOperations` method. - 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: - ~.operations_pb2.ListOperationsResponse: - Response message for ``ListOperations`` method. - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = operations_pb2.ListOperationsRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._transport.list_operations, - 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 = rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - def get_operation( - self, - request: Optional[operations_pb2.GetOperationRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operations_pb2.Operation: - r"""Gets the latest state of a long-running operation. - - Args: - request (:class:`~.operations_pb2.GetOperationRequest`): - The request object. Request message for - `GetOperation` method. - 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: - ~.operations_pb2.Operation: - An ``Operation`` object. - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = operations_pb2.GetOperationRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._transport.get_operation, - 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 = rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - def cancel_operation( - self, - request: Optional[operations_pb2.CancelOperationRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> None: - r"""Starts asynchronous cancellation on a long-running operation. - - The server makes a best effort to cancel the operation, but success - is not guaranteed. If the server doesn't support this method, it returns - `google.rpc.Code.UNIMPLEMENTED`. - - Args: - request (:class:`~.operations_pb2.CancelOperationRequest`): - The request object. Request message for - `CancelOperation` method. - 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: - None - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = operations_pb2.CancelOperationRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._transport.cancel_operation, - 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. - rpc(request, retry=retry, timeout=timeout, metadata=metadata,) - - def get_location( - self, - request: Optional[locations_pb2.GetLocationRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> locations_pb2.Location: - r"""Gets information about a location. - - Args: - request (:class:`~.location_pb2.GetLocationRequest`): - The request object. Request message for - `GetLocation` method. - 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: - ~.location_pb2.Location: - Location object. - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = locations_pb2.GetLocationRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._transport.get_location, - 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 = rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - def list_locations( - self, - request: Optional[locations_pb2.ListLocationsRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> locations_pb2.ListLocationsResponse: - r"""Lists information about the supported locations for this service. - - Args: - request (:class:`~.location_pb2.ListLocationsRequest`): - The request object. Request message for - `ListLocations` method. - 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: - ~.location_pb2.ListLocationsResponse: - Response message for ``ListLocations`` method. - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = locations_pb2.ListLocationsRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._transport.list_locations, - 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 = rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) - - -__all__ = ( - "EntityTypesClient", -) diff --git a/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/entity_types/pagers.py b/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/entity_types/pagers.py deleted file mode 100644 index 4eafd1a54..000000000 --- a/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/entity_types/pagers.py +++ /dev/null @@ -1,139 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from typing import Any, AsyncIterator, Awaitable, Callable, Sequence, Tuple, Optional, Iterator - -from google.cloud.dialogflow_v2.types import entity_type - - -class ListEntityTypesPager: - """A pager for iterating through ``list_entity_types`` requests. - - This class thinly wraps an initial - :class:`google.cloud.dialogflow_v2.types.ListEntityTypesResponse` object, and - provides an ``__iter__`` method to iterate through its - ``entity_types`` field. - - If there are more pages, the ``__iter__`` method will make additional - ``ListEntityTypes`` requests and continue to iterate - through the ``entity_types`` field on the - corresponding responses. - - All the usual :class:`google.cloud.dialogflow_v2.types.ListEntityTypesResponse` - 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[..., entity_type.ListEntityTypesResponse], - request: entity_type.ListEntityTypesRequest, - response: entity_type.ListEntityTypesResponse, - *, - 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.ListEntityTypesRequest): - The initial request object. - response (google.cloud.dialogflow_v2.types.ListEntityTypesResponse): - 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 = entity_type.ListEntityTypesRequest(request) - self._response = response - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - def pages(self) -> Iterator[entity_type.ListEntityTypesResponse]: - yield self._response - while self._response.next_page_token: - self._request.page_token = self._response.next_page_token - self._response = self._method(self._request, metadata=self._metadata) - yield self._response - - def __iter__(self) -> Iterator[entity_type.EntityType]: - for page in self.pages: - yield from page.entity_types - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListEntityTypesAsyncPager: - """A pager for iterating through ``list_entity_types`` requests. - - This class thinly wraps an initial - :class:`google.cloud.dialogflow_v2.types.ListEntityTypesResponse` object, and - provides an ``__aiter__`` method to iterate through its - ``entity_types`` field. - - If there are more pages, the ``__aiter__`` method will make additional - ``ListEntityTypes`` requests and continue to iterate - through the ``entity_types`` field on the - corresponding responses. - - All the usual :class:`google.cloud.dialogflow_v2.types.ListEntityTypesResponse` - 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[entity_type.ListEntityTypesResponse]], - request: entity_type.ListEntityTypesRequest, - response: entity_type.ListEntityTypesResponse, - *, - metadata: Sequence[Tuple[str, str]] = ()): - """Instantiates the pager. - - Args: - method (Callable): The method that was originally called, and - which instantiated this pager. - request (google.cloud.dialogflow_v2.types.ListEntityTypesRequest): - The initial request object. - response (google.cloud.dialogflow_v2.types.ListEntityTypesResponse): - 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 = entity_type.ListEntityTypesRequest(request) - self._response = response - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - async def pages(self) -> AsyncIterator[entity_type.ListEntityTypesResponse]: - yield self._response - while self._response.next_page_token: - self._request.page_token = self._response.next_page_token - self._response = await self._method(self._request, metadata=self._metadata) - yield self._response - def __aiter__(self) -> AsyncIterator[entity_type.EntityType]: - async def async_generator(): - async for page in self.pages: - for response in page.entity_types: - yield response - - return async_generator() - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) diff --git a/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/entity_types/transports/__init__.py b/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/entity_types/transports/__init__.py deleted file mode 100644 index 3f9feda31..000000000 --- a/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/entity_types/transports/__init__.py +++ /dev/null @@ -1,38 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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 EntityTypesTransport -from .grpc import EntityTypesGrpcTransport -from .grpc_asyncio import EntityTypesGrpcAsyncIOTransport -from .rest import EntityTypesRestTransport -from .rest import EntityTypesRestInterceptor - - -# Compile a registry of transports. -_transport_registry = OrderedDict() # type: Dict[str, Type[EntityTypesTransport]] -_transport_registry['grpc'] = EntityTypesGrpcTransport -_transport_registry['grpc_asyncio'] = EntityTypesGrpcAsyncIOTransport -_transport_registry['rest'] = EntityTypesRestTransport - -__all__ = ( - 'EntityTypesTransport', - 'EntityTypesGrpcTransport', - 'EntityTypesGrpcAsyncIOTransport', - 'EntityTypesRestTransport', - 'EntityTypesRestInterceptor', -) diff --git a/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/entity_types/transports/base.py b/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/entity_types/transports/base.py deleted file mode 100644 index aafc44f0b..000000000 --- a/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/entity_types/transports/base.py +++ /dev/null @@ -1,329 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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 - -from google.cloud.dialogflow_v2 import gapic_version as package_version - -import google.auth # type: ignore -import google.api_core -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import retry as retries -from google.api_core import operations_v1 -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 entity_type -from google.cloud.dialogflow_v2.types import entity_type as gcd_entity_type -from google.cloud.location import locations_pb2 # type: ignore -from google.longrunning import operations_pb2 -from google.longrunning import operations_pb2 # type: ignore -from google.protobuf import empty_pb2 # type: ignore - -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) - - -class EntityTypesTransport(abc.ABC): - """Abstract transport class for EntityTypes.""" - - 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: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - api_audience: Optional[str] = None, - **kwargs, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. - scopes (Optional[Sequence[str]]): A list of scopes. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - """ - - scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} - - # Save the scopes. - self._scopes = scopes - - # If no credentials are provided, then determine the appropriate - # defaults. - if credentials and credentials_file: - raise core_exceptions.DuplicateCredentialArgs("'credentials_file' and 'credentials' are mutually exclusive") - - if credentials_file is not None: - credentials, _ = google.auth.load_credentials_from_file( - credentials_file, - **scopes_kwargs, - quota_project_id=quota_project_id - ) - elif credentials is None: - credentials, _ = google.auth.default(**scopes_kwargs, quota_project_id=quota_project_id) - # Don't apply audience if the credentials file passed from user. - if hasattr(credentials, "with_gdch_audience"): - credentials = credentials.with_gdch_audience(api_audience if api_audience else host) - - # If the credentials are service account credentials, then always try to use self signed JWT. - if always_use_jwt_access and isinstance(credentials, service_account.Credentials) and hasattr(service_account.Credentials, "with_always_use_jwt_access"): - credentials = credentials.with_always_use_jwt_access(True) - - # Save the credentials. - self._credentials = credentials - - # Save the hostname. Default to port 443 (HTTPS) if none is specified. - if ':' not in host: - host += ':443' - self._host = host - - def _prep_wrapped_messages(self, client_info): - # Precompute the wrapped methods. - self._wrapped_methods = { - self.list_entity_types: gapic_v1.method.wrap_method( - self.list_entity_types, - default_timeout=None, - client_info=client_info, - ), - self.get_entity_type: gapic_v1.method.wrap_method( - self.get_entity_type, - default_timeout=None, - client_info=client_info, - ), - self.create_entity_type: gapic_v1.method.wrap_method( - self.create_entity_type, - default_timeout=None, - client_info=client_info, - ), - self.update_entity_type: gapic_v1.method.wrap_method( - self.update_entity_type, - default_timeout=None, - client_info=client_info, - ), - self.delete_entity_type: gapic_v1.method.wrap_method( - self.delete_entity_type, - default_timeout=None, - client_info=client_info, - ), - self.batch_update_entity_types: gapic_v1.method.wrap_method( - self.batch_update_entity_types, - default_timeout=None, - client_info=client_info, - ), - self.batch_delete_entity_types: gapic_v1.method.wrap_method( - self.batch_delete_entity_types, - default_timeout=None, - client_info=client_info, - ), - self.batch_create_entities: gapic_v1.method.wrap_method( - self.batch_create_entities, - default_timeout=None, - client_info=client_info, - ), - self.batch_update_entities: gapic_v1.method.wrap_method( - self.batch_update_entities, - default_timeout=None, - client_info=client_info, - ), - self.batch_delete_entities: gapic_v1.method.wrap_method( - self.batch_delete_entities, - default_timeout=None, - client_info=client_info, - ), - } - - def close(self): - """Closes resources associated with the transport. - - .. warning:: - Only call this method if the transport is NOT shared - with other clients - this may cause errors in other clients! - """ - raise NotImplementedError() - - @property - def operations_client(self): - """Return the client designed to process long-running operations.""" - raise NotImplementedError() - - @property - def list_entity_types(self) -> Callable[ - [entity_type.ListEntityTypesRequest], - Union[ - entity_type.ListEntityTypesResponse, - Awaitable[entity_type.ListEntityTypesResponse] - ]]: - raise NotImplementedError() - - @property - def get_entity_type(self) -> Callable[ - [entity_type.GetEntityTypeRequest], - Union[ - entity_type.EntityType, - Awaitable[entity_type.EntityType] - ]]: - raise NotImplementedError() - - @property - def create_entity_type(self) -> Callable[ - [gcd_entity_type.CreateEntityTypeRequest], - Union[ - gcd_entity_type.EntityType, - Awaitable[gcd_entity_type.EntityType] - ]]: - raise NotImplementedError() - - @property - def update_entity_type(self) -> Callable[ - [gcd_entity_type.UpdateEntityTypeRequest], - Union[ - gcd_entity_type.EntityType, - Awaitable[gcd_entity_type.EntityType] - ]]: - raise NotImplementedError() - - @property - def delete_entity_type(self) -> Callable[ - [entity_type.DeleteEntityTypeRequest], - Union[ - empty_pb2.Empty, - Awaitable[empty_pb2.Empty] - ]]: - raise NotImplementedError() - - @property - def batch_update_entity_types(self) -> Callable[ - [entity_type.BatchUpdateEntityTypesRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: - raise NotImplementedError() - - @property - def batch_delete_entity_types(self) -> Callable[ - [entity_type.BatchDeleteEntityTypesRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: - raise NotImplementedError() - - @property - def batch_create_entities(self) -> Callable[ - [entity_type.BatchCreateEntitiesRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: - raise NotImplementedError() - - @property - def batch_update_entities(self) -> Callable[ - [entity_type.BatchUpdateEntitiesRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: - raise NotImplementedError() - - @property - def batch_delete_entities(self) -> Callable[ - [entity_type.BatchDeleteEntitiesRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: - raise NotImplementedError() - - @property - def list_operations( - self, - ) -> Callable[ - [operations_pb2.ListOperationsRequest], - Union[operations_pb2.ListOperationsResponse, Awaitable[operations_pb2.ListOperationsResponse]], - ]: - raise NotImplementedError() - - @property - def get_operation( - self, - ) -> Callable[ - [operations_pb2.GetOperationRequest], - Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], - ]: - raise NotImplementedError() - - @property - def cancel_operation( - self, - ) -> Callable[ - [operations_pb2.CancelOperationRequest], - None, - ]: - raise NotImplementedError() - - @property - def get_location(self, - ) -> Callable[ - [locations_pb2.GetLocationRequest], - Union[locations_pb2.Location, Awaitable[locations_pb2.Location]], - ]: - raise NotImplementedError() - - @property - def list_locations(self, - ) -> Callable[ - [locations_pb2.ListLocationsRequest], - Union[locations_pb2.ListLocationsResponse, Awaitable[locations_pb2.ListLocationsResponse]], - ]: - raise NotImplementedError() - - @property - def kind(self) -> str: - raise NotImplementedError() - - -__all__ = ( - 'EntityTypesTransport', -) diff --git a/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/entity_types/transports/grpc.py b/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/entity_types/transports/grpc.py deleted file mode 100644 index 3c090e30a..000000000 --- a/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/entity_types/transports/grpc.py +++ /dev/null @@ -1,697 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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 -from google.api_core import operations_v1 -from google.api_core import gapic_v1 -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.cloud.location import locations_pb2 # type: ignore -from google.longrunning import operations_pb2 -from google.longrunning import operations_pb2 # type: ignore -from google.protobuf import empty_pb2 # type: ignore -from .base import EntityTypesTransport, DEFAULT_CLIENT_INFO - - -class EntityTypesGrpcTransport(EntityTypesTransport): - """gRPC backend transport for EntityTypes. - - Service for managing - [EntityTypes][google.cloud.dialogflow.v2.EntityType]. - - 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: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - channel: Optional[grpc.Channel] = None, - api_mtls_endpoint: Optional[str] = None, - client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, - ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, - client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - api_audience: Optional[str] = None, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - This argument is ignored if ``channel`` is provided. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional(Sequence[str])): A list of scopes. This argument is - ignored if ``channel`` is provided. - channel (Optional[grpc.Channel]): A ``Channel`` instance through - which to make calls. - api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. - If provided, it overrides the ``host`` argument and tries to create - a mutual TLS channel with client SSL credentials from - ``client_cert_source`` or application default SSL credentials. - client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): - Deprecated. A callback to provide client SSL certificate bytes and - private key bytes, both in PEM format. It is ignored if - ``api_mtls_endpoint`` is None. - ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials - for the grpc channel. It is ignored if ``channel`` is provided. - client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): - A callback to provide client certificate bytes and private key bytes, - both in PEM format. It is used to configure a mutual TLS channel. It is - ignored if ``channel`` or ``ssl_channel_credentials`` is provided. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport - creation failed for any reason. - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - self._grpc_channel = None - self._ssl_channel_credentials = ssl_channel_credentials - self._stubs: Dict[str, Callable] = {} - self._operations_client: Optional[operations_v1.OperationsClient] = None - - if api_mtls_endpoint: - warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) - if client_cert_source: - warnings.warn("client_cert_source is deprecated", DeprecationWarning) - - if channel: - # Ignore credentials if a channel was passed. - credentials = False - # If a channel was explicitly provided, set it. - self._grpc_channel = channel - self._ssl_channel_credentials = None - - else: - if api_mtls_endpoint: - host = api_mtls_endpoint - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - self._ssl_channel_credentials = SslCredentials().ssl_credentials - - else: - if client_cert_source_for_mtls and not ssl_channel_credentials: - cert, key = client_cert_source_for_mtls() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - - # The base transport sets the host, credentials and scopes - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes, - quota_project_id=quota_project_id, - client_info=client_info, - always_use_jwt_access=always_use_jwt_access, - api_audience=api_audience, - ) - - if not self._grpc_channel: - self._grpc_channel = type(self).create_channel( - self._host, - # use the credentials which are saved - credentials=self._credentials, - # Set ``credentials_file`` to ``None`` here as - # the credentials that we saved earlier should be used. - credentials_file=None, - 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: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - **kwargs) -> grpc.Channel: - """Create and return a gRPC channel object. - Args: - host (Optional[str]): The host for the channel to use. - credentials (Optional[~.Credentials]): The - authorization credentials to attach to requests. These - credentials identify this application to the service. If - none are specified, the client will attempt to ascertain - the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - kwargs (Optional[dict]): Keyword arguments, which are passed to the - channel creation. - Returns: - grpc.Channel: A gRPC channel object. - - Raises: - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - - return grpc_helpers.create_channel( - host, - credentials=credentials, - credentials_file=credentials_file, - quota_project_id=quota_project_id, - default_scopes=cls.AUTH_SCOPES, - scopes=scopes, - default_host=cls.DEFAULT_HOST, - **kwargs - ) - - @property - def grpc_channel(self) -> grpc.Channel: - """Return the channel designed to connect to this service. - """ - return self._grpc_channel - - @property - def operations_client(self) -> operations_v1.OperationsClient: - """Create the client designed to process long-running operations. - - This property caches on the instance; repeated calls return the same - client. - """ - # Quick check: Only create a new client if we do not already have one. - if self._operations_client is None: - self._operations_client = operations_v1.OperationsClient( - self.grpc_channel - ) - - # Return the client from cache. - return self._operations_client - - @property - def list_entity_types(self) -> Callable[ - [entity_type.ListEntityTypesRequest], - entity_type.ListEntityTypesResponse]: - r"""Return a callable for the list entity types method over gRPC. - - Returns the list of all entity types in the specified - agent. - - Returns: - Callable[[~.ListEntityTypesRequest], - ~.ListEntityTypesResponse]: - 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_entity_types' not in self._stubs: - self._stubs['list_entity_types'] = self.grpc_channel.unary_unary( - '/google.cloud.dialogflow.v2.EntityTypes/ListEntityTypes', - request_serializer=entity_type.ListEntityTypesRequest.serialize, - response_deserializer=entity_type.ListEntityTypesResponse.deserialize, - ) - return self._stubs['list_entity_types'] - - @property - def get_entity_type(self) -> Callable[ - [entity_type.GetEntityTypeRequest], - entity_type.EntityType]: - r"""Return a callable for the get entity type method over gRPC. - - Retrieves the specified entity type. - - Returns: - Callable[[~.GetEntityTypeRequest], - ~.EntityType]: - 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_entity_type' not in self._stubs: - self._stubs['get_entity_type'] = self.grpc_channel.unary_unary( - '/google.cloud.dialogflow.v2.EntityTypes/GetEntityType', - request_serializer=entity_type.GetEntityTypeRequest.serialize, - response_deserializer=entity_type.EntityType.deserialize, - ) - return self._stubs['get_entity_type'] - - @property - def create_entity_type(self) -> Callable[ - [gcd_entity_type.CreateEntityTypeRequest], - gcd_entity_type.EntityType]: - r"""Return a callable for the create entity type method over gRPC. - - Creates an entity type in the specified agent. - - Note: You should always train an agent prior to sending it - queries. See the `training - documentation `__. - - Returns: - Callable[[~.CreateEntityTypeRequest], - ~.EntityType]: - 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_entity_type' not in self._stubs: - self._stubs['create_entity_type'] = self.grpc_channel.unary_unary( - '/google.cloud.dialogflow.v2.EntityTypes/CreateEntityType', - request_serializer=gcd_entity_type.CreateEntityTypeRequest.serialize, - response_deserializer=gcd_entity_type.EntityType.deserialize, - ) - return self._stubs['create_entity_type'] - - @property - def update_entity_type(self) -> Callable[ - [gcd_entity_type.UpdateEntityTypeRequest], - gcd_entity_type.EntityType]: - r"""Return a callable for the update entity type method over gRPC. - - Updates the specified entity type. - - Note: You should always train an agent prior to sending it - queries. See the `training - documentation `__. - - Returns: - Callable[[~.UpdateEntityTypeRequest], - ~.EntityType]: - 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_entity_type' not in self._stubs: - self._stubs['update_entity_type'] = self.grpc_channel.unary_unary( - '/google.cloud.dialogflow.v2.EntityTypes/UpdateEntityType', - request_serializer=gcd_entity_type.UpdateEntityTypeRequest.serialize, - response_deserializer=gcd_entity_type.EntityType.deserialize, - ) - return self._stubs['update_entity_type'] - - @property - def delete_entity_type(self) -> Callable[ - [entity_type.DeleteEntityTypeRequest], - empty_pb2.Empty]: - r"""Return a callable for the delete entity type method over gRPC. - - Deletes the specified entity type. - - Note: You should always train an agent prior to sending it - queries. See the `training - documentation `__. - - Returns: - Callable[[~.DeleteEntityTypeRequest], - ~.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_entity_type' not in self._stubs: - 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_pb2.Empty.FromString, - ) - return self._stubs['delete_entity_type'] - - @property - def batch_update_entity_types(self) -> 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. - - This method is a `long-running - operation `__. - The returned ``Operation`` type has the following - method-specific fields: - - - ``metadata``: An empty `Struct - message `__ - - ``response``: - [BatchUpdateEntityTypesResponse][google.cloud.dialogflow.v2.BatchUpdateEntityTypesResponse] - - Note: You should always train an agent prior to sending it - queries. See the `training - documentation `__. - - Returns: - Callable[[~.BatchUpdateEntityTypesRequest], - ~.Operation]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'batch_update_entity_types' not in self._stubs: - 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_pb2.Operation.FromString, - ) - return self._stubs['batch_update_entity_types'] - - @property - def batch_delete_entity_types(self) -> 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. - - This method is a `long-running - operation `__. - The returned ``Operation`` type has the following - method-specific fields: - - - ``metadata``: An empty `Struct - message `__ - - ``response``: An `Empty - message `__ - - Note: You should always train an agent prior to sending it - queries. See the `training - documentation `__. - - Returns: - Callable[[~.BatchDeleteEntityTypesRequest], - ~.Operation]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'batch_delete_entity_types' not in self._stubs: - 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_pb2.Operation.FromString, - ) - return self._stubs['batch_delete_entity_types'] - - @property - def batch_create_entities(self) -> 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. - - This method is a `long-running - operation `__. - The returned ``Operation`` type has the following - method-specific fields: - - - ``metadata``: An empty `Struct - message `__ - - ``response``: An `Empty - message `__ - - Note: You should always train an agent prior to sending it - queries. See the `training - documentation `__. - - Returns: - Callable[[~.BatchCreateEntitiesRequest], - ~.Operation]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'batch_create_entities' not in self._stubs: - 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_pb2.Operation.FromString, - ) - return self._stubs['batch_create_entities'] - - @property - def batch_update_entities(self) -> 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 - type. This method does not affect entities in the entity type - that aren't explicitly specified in the request. - - This method is a `long-running - operation `__. - The returned ``Operation`` type has the following - method-specific fields: - - - ``metadata``: An empty `Struct - message `__ - - ``response``: An `Empty - message `__ - - Note: You should always train an agent prior to sending it - queries. See the `training - documentation `__. - - Returns: - Callable[[~.BatchUpdateEntitiesRequest], - ~.Operation]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'batch_update_entities' not in self._stubs: - 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_pb2.Operation.FromString, - ) - return self._stubs['batch_update_entities'] - - @property - def batch_delete_entities(self) -> 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. - - This method is a `long-running - operation `__. - The returned ``Operation`` type has the following - method-specific fields: - - - ``metadata``: An empty `Struct - message `__ - - ``response``: An `Empty - message `__ - - Note: You should always train an agent prior to sending it - queries. See the `training - documentation `__. - - Returns: - Callable[[~.BatchDeleteEntitiesRequest], - ~.Operation]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'batch_delete_entities' not in self._stubs: - 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_pb2.Operation.FromString, - ) - return self._stubs['batch_delete_entities'] - - def close(self): - self.grpc_channel.close() - - @property - def cancel_operation( - self, - ) -> Callable[[operations_pb2.CancelOperationRequest], None]: - r"""Return a callable for the cancel_operation method over gRPC. - """ - # 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 "cancel_operation" not in self._stubs: - self._stubs["cancel_operation"] = self.grpc_channel.unary_unary( - "/google.longrunning.Operations/CancelOperation", - request_serializer=operations_pb2.CancelOperationRequest.SerializeToString, - response_deserializer=None, - ) - return self._stubs["cancel_operation"] - - @property - def get_operation( - self, - ) -> Callable[[operations_pb2.GetOperationRequest], operations_pb2.Operation]: - r"""Return a callable for the get_operation method over gRPC. - """ - # 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_operation" not in self._stubs: - self._stubs["get_operation"] = self.grpc_channel.unary_unary( - "/google.longrunning.Operations/GetOperation", - request_serializer=operations_pb2.GetOperationRequest.SerializeToString, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs["get_operation"] - - @property - def list_operations( - self, - ) -> Callable[[operations_pb2.ListOperationsRequest], operations_pb2.ListOperationsResponse]: - r"""Return a callable for the list_operations method over gRPC. - """ - # 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_operations" not in self._stubs: - self._stubs["list_operations"] = self.grpc_channel.unary_unary( - "/google.longrunning.Operations/ListOperations", - request_serializer=operations_pb2.ListOperationsRequest.SerializeToString, - response_deserializer=operations_pb2.ListOperationsResponse.FromString, - ) - return self._stubs["list_operations"] - - @property - def list_locations( - self, - ) -> Callable[[locations_pb2.ListLocationsRequest], locations_pb2.ListLocationsResponse]: - r"""Return a callable for the list locations method over gRPC. - """ - # 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_locations" not in self._stubs: - self._stubs["list_locations"] = self.grpc_channel.unary_unary( - "/google.cloud.location.Locations/ListLocations", - request_serializer=locations_pb2.ListLocationsRequest.SerializeToString, - response_deserializer=locations_pb2.ListLocationsResponse.FromString, - ) - return self._stubs["list_locations"] - - @property - def get_location( - self, - ) -> Callable[[locations_pb2.GetLocationRequest], locations_pb2.Location]: - r"""Return a callable for the list locations method over gRPC. - """ - # 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_location" not in self._stubs: - self._stubs["get_location"] = self.grpc_channel.unary_unary( - "/google.cloud.location.Locations/GetLocation", - request_serializer=locations_pb2.GetLocationRequest.SerializeToString, - response_deserializer=locations_pb2.Location.FromString, - ) - return self._stubs["get_location"] - - @property - def kind(self) -> str: - return "grpc" - - -__all__ = ( - 'EntityTypesGrpcTransport', -) diff --git a/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/entity_types/transports/grpc_asyncio.py b/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/entity_types/transports/grpc_asyncio.py deleted file mode 100644 index 972ec90ab..000000000 --- a/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/entity_types/transports/grpc_asyncio.py +++ /dev/null @@ -1,696 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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 -from google.api_core import grpc_helpers_async -from google.api_core import operations_v1 -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore - -import grpc # type: ignore -from grpc.experimental import aio # type: ignore - -from google.cloud.dialogflow_v2.types import entity_type -from google.cloud.dialogflow_v2.types import entity_type as gcd_entity_type -from google.cloud.location import locations_pb2 # type: ignore -from google.longrunning import operations_pb2 -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 - - -class EntityTypesGrpcAsyncIOTransport(EntityTypesTransport): - """gRPC AsyncIO backend transport for EntityTypes. - - Service for managing - [EntityTypes][google.cloud.dialogflow.v2.EntityType]. - - 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: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - **kwargs) -> aio.Channel: - """Create and return a gRPC AsyncIO channel object. - Args: - host (Optional[str]): The host for the channel to use. - credentials (Optional[~.Credentials]): The - authorization credentials to attach to requests. These - credentials identify this application to the service. If - none are specified, the client will attempt to ascertain - the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - kwargs (Optional[dict]): Keyword arguments, which are passed to the - channel creation. - Returns: - aio.Channel: A gRPC AsyncIO channel object. - """ - - return grpc_helpers_async.create_channel( - host, - credentials=credentials, - credentials_file=credentials_file, - quota_project_id=quota_project_id, - default_scopes=cls.AUTH_SCOPES, - scopes=scopes, - default_host=cls.DEFAULT_HOST, - **kwargs - ) - - def __init__(self, *, - host: str = 'dialogflow.googleapis.com', - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - channel: Optional[aio.Channel] = None, - api_mtls_endpoint: Optional[str] = None, - client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, - ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, - client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - api_audience: Optional[str] = None, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - This argument is ignored if ``channel`` is provided. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - channel (Optional[aio.Channel]): A ``Channel`` instance through - which to make calls. - api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. - If provided, it overrides the ``host`` argument and tries to create - a mutual TLS channel with client SSL credentials from - ``client_cert_source`` or application default SSL credentials. - client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): - Deprecated. A callback to provide client SSL certificate bytes and - private key bytes, both in PEM format. It is ignored if - ``api_mtls_endpoint`` is None. - ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials - for the grpc channel. It is ignored if ``channel`` is provided. - client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): - A callback to provide client certificate bytes and private key bytes, - both in PEM format. It is used to configure a mutual TLS channel. It is - ignored if ``channel`` or ``ssl_channel_credentials`` is provided. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - - Raises: - google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport - creation failed for any reason. - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - self._grpc_channel = None - self._ssl_channel_credentials = ssl_channel_credentials - self._stubs: Dict[str, Callable] = {} - self._operations_client: Optional[operations_v1.OperationsAsyncClient] = None - - if api_mtls_endpoint: - warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) - if client_cert_source: - warnings.warn("client_cert_source is deprecated", DeprecationWarning) - - if channel: - # Ignore credentials if a channel was passed. - credentials = False - # If a channel was explicitly provided, set it. - self._grpc_channel = channel - self._ssl_channel_credentials = None - else: - if api_mtls_endpoint: - host = api_mtls_endpoint - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - self._ssl_channel_credentials = SslCredentials().ssl_credentials - - else: - if client_cert_source_for_mtls and not ssl_channel_credentials: - cert, key = client_cert_source_for_mtls() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - - # The base transport sets the host, credentials and scopes - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes, - quota_project_id=quota_project_id, - client_info=client_info, - always_use_jwt_access=always_use_jwt_access, - api_audience=api_audience, - ) - - if not self._grpc_channel: - self._grpc_channel = type(self).create_channel( - self._host, - # use the credentials which are saved - credentials=self._credentials, - # Set ``credentials_file`` to ``None`` here as - # the credentials that we saved earlier should be used. - credentials_file=None, - 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 operations_client(self) -> operations_v1.OperationsAsyncClient: - """Create the client designed to process long-running operations. - - This property caches on the instance; repeated calls return the same - client. - """ - # Quick check: Only create a new client if we do not already have one. - if self._operations_client is None: - self._operations_client = operations_v1.OperationsAsyncClient( - self.grpc_channel - ) - - # Return the client from cache. - return self._operations_client - - @property - def list_entity_types(self) -> Callable[ - [entity_type.ListEntityTypesRequest], - Awaitable[entity_type.ListEntityTypesResponse]]: - r"""Return a callable for the list entity types method over gRPC. - - Returns the list of all entity types in the specified - agent. - - Returns: - Callable[[~.ListEntityTypesRequest], - Awaitable[~.ListEntityTypesResponse]]: - 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_entity_types' not in self._stubs: - self._stubs['list_entity_types'] = self.grpc_channel.unary_unary( - '/google.cloud.dialogflow.v2.EntityTypes/ListEntityTypes', - request_serializer=entity_type.ListEntityTypesRequest.serialize, - response_deserializer=entity_type.ListEntityTypesResponse.deserialize, - ) - return self._stubs['list_entity_types'] - - @property - def get_entity_type(self) -> Callable[ - [entity_type.GetEntityTypeRequest], - Awaitable[entity_type.EntityType]]: - r"""Return a callable for the get entity type method over gRPC. - - Retrieves the specified entity type. - - Returns: - Callable[[~.GetEntityTypeRequest], - Awaitable[~.EntityType]]: - 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_entity_type' not in self._stubs: - self._stubs['get_entity_type'] = self.grpc_channel.unary_unary( - '/google.cloud.dialogflow.v2.EntityTypes/GetEntityType', - request_serializer=entity_type.GetEntityTypeRequest.serialize, - response_deserializer=entity_type.EntityType.deserialize, - ) - return self._stubs['get_entity_type'] - - @property - def create_entity_type(self) -> Callable[ - [gcd_entity_type.CreateEntityTypeRequest], - Awaitable[gcd_entity_type.EntityType]]: - r"""Return a callable for the create entity type method over gRPC. - - Creates an entity type in the specified agent. - - Note: You should always train an agent prior to sending it - queries. See the `training - documentation `__. - - Returns: - Callable[[~.CreateEntityTypeRequest], - Awaitable[~.EntityType]]: - 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_entity_type' not in self._stubs: - self._stubs['create_entity_type'] = self.grpc_channel.unary_unary( - '/google.cloud.dialogflow.v2.EntityTypes/CreateEntityType', - request_serializer=gcd_entity_type.CreateEntityTypeRequest.serialize, - response_deserializer=gcd_entity_type.EntityType.deserialize, - ) - return self._stubs['create_entity_type'] - - @property - def update_entity_type(self) -> Callable[ - [gcd_entity_type.UpdateEntityTypeRequest], - Awaitable[gcd_entity_type.EntityType]]: - r"""Return a callable for the update entity type method over gRPC. - - Updates the specified entity type. - - Note: You should always train an agent prior to sending it - queries. See the `training - documentation `__. - - Returns: - Callable[[~.UpdateEntityTypeRequest], - Awaitable[~.EntityType]]: - 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_entity_type' not in self._stubs: - self._stubs['update_entity_type'] = self.grpc_channel.unary_unary( - '/google.cloud.dialogflow.v2.EntityTypes/UpdateEntityType', - request_serializer=gcd_entity_type.UpdateEntityTypeRequest.serialize, - response_deserializer=gcd_entity_type.EntityType.deserialize, - ) - return self._stubs['update_entity_type'] - - @property - def delete_entity_type(self) -> 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. - - Note: You should always train an agent prior to sending it - queries. See the `training - documentation `__. - - Returns: - Callable[[~.DeleteEntityTypeRequest], - 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_entity_type' not in self._stubs: - 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_pb2.Empty.FromString, - ) - return self._stubs['delete_entity_type'] - - @property - def batch_update_entity_types(self) -> Callable[ - [entity_type.BatchUpdateEntityTypesRequest], - Awaitable[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. - - This method is a `long-running - operation `__. - The returned ``Operation`` type has the following - method-specific fields: - - - ``metadata``: An empty `Struct - message `__ - - ``response``: - [BatchUpdateEntityTypesResponse][google.cloud.dialogflow.v2.BatchUpdateEntityTypesResponse] - - Note: You should always train an agent prior to sending it - queries. See the `training - documentation `__. - - Returns: - Callable[[~.BatchUpdateEntityTypesRequest], - Awaitable[~.Operation]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'batch_update_entity_types' not in self._stubs: - 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_pb2.Operation.FromString, - ) - return self._stubs['batch_update_entity_types'] - - @property - def batch_delete_entity_types(self) -> Callable[ - [entity_type.BatchDeleteEntityTypesRequest], - Awaitable[operations_pb2.Operation]]: - r"""Return a callable for the batch delete entity types method over gRPC. - - Deletes entity types in the specified agent. - - This method is a `long-running - operation `__. - The returned ``Operation`` type has the following - method-specific fields: - - - ``metadata``: An empty `Struct - message `__ - - ``response``: An `Empty - message `__ - - Note: You should always train an agent prior to sending it - queries. See the `training - documentation `__. - - Returns: - Callable[[~.BatchDeleteEntityTypesRequest], - Awaitable[~.Operation]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'batch_delete_entity_types' not in self._stubs: - 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_pb2.Operation.FromString, - ) - return self._stubs['batch_delete_entity_types'] - - @property - def batch_create_entities(self) -> Callable[ - [entity_type.BatchCreateEntitiesRequest], - Awaitable[operations_pb2.Operation]]: - r"""Return a callable for the batch create entities method over gRPC. - - Creates multiple new entities in the specified entity type. - - This method is a `long-running - operation `__. - The returned ``Operation`` type has the following - method-specific fields: - - - ``metadata``: An empty `Struct - message `__ - - ``response``: An `Empty - message `__ - - Note: You should always train an agent prior to sending it - queries. See the `training - documentation `__. - - Returns: - Callable[[~.BatchCreateEntitiesRequest], - Awaitable[~.Operation]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'batch_create_entities' not in self._stubs: - 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_pb2.Operation.FromString, - ) - return self._stubs['batch_create_entities'] - - @property - def batch_update_entities(self) -> Callable[ - [entity_type.BatchUpdateEntitiesRequest], - Awaitable[operations_pb2.Operation]]: - r"""Return a callable for the batch update entities method over gRPC. - - Updates or creates multiple entities in the specified entity - type. This method does not affect entities in the entity type - that aren't explicitly specified in the request. - - This method is a `long-running - operation `__. - The returned ``Operation`` type has the following - method-specific fields: - - - ``metadata``: An empty `Struct - message `__ - - ``response``: An `Empty - message `__ - - Note: You should always train an agent prior to sending it - queries. See the `training - documentation `__. - - Returns: - Callable[[~.BatchUpdateEntitiesRequest], - Awaitable[~.Operation]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'batch_update_entities' not in self._stubs: - 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_pb2.Operation.FromString, - ) - return self._stubs['batch_update_entities'] - - @property - def batch_delete_entities(self) -> Callable[ - [entity_type.BatchDeleteEntitiesRequest], - Awaitable[operations_pb2.Operation]]: - r"""Return a callable for the batch delete entities method over gRPC. - - Deletes entities in the specified entity type. - - This method is a `long-running - operation `__. - The returned ``Operation`` type has the following - method-specific fields: - - - ``metadata``: An empty `Struct - message `__ - - ``response``: An `Empty - message `__ - - Note: You should always train an agent prior to sending it - queries. See the `training - documentation `__. - - Returns: - Callable[[~.BatchDeleteEntitiesRequest], - Awaitable[~.Operation]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'batch_delete_entities' not in self._stubs: - 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_pb2.Operation.FromString, - ) - return self._stubs['batch_delete_entities'] - - def close(self): - return self.grpc_channel.close() - - @property - def cancel_operation( - self, - ) -> Callable[[operations_pb2.CancelOperationRequest], None]: - r"""Return a callable for the cancel_operation method over gRPC. - """ - # 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 "cancel_operation" not in self._stubs: - self._stubs["cancel_operation"] = self.grpc_channel.unary_unary( - "/google.longrunning.Operations/CancelOperation", - request_serializer=operations_pb2.CancelOperationRequest.SerializeToString, - response_deserializer=None, - ) - return self._stubs["cancel_operation"] - - @property - def get_operation( - self, - ) -> Callable[[operations_pb2.GetOperationRequest], operations_pb2.Operation]: - r"""Return a callable for the get_operation method over gRPC. - """ - # 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_operation" not in self._stubs: - self._stubs["get_operation"] = self.grpc_channel.unary_unary( - "/google.longrunning.Operations/GetOperation", - request_serializer=operations_pb2.GetOperationRequest.SerializeToString, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs["get_operation"] - - @property - def list_operations( - self, - ) -> Callable[[operations_pb2.ListOperationsRequest], operations_pb2.ListOperationsResponse]: - r"""Return a callable for the list_operations method over gRPC. - """ - # 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_operations" not in self._stubs: - self._stubs["list_operations"] = self.grpc_channel.unary_unary( - "/google.longrunning.Operations/ListOperations", - request_serializer=operations_pb2.ListOperationsRequest.SerializeToString, - response_deserializer=operations_pb2.ListOperationsResponse.FromString, - ) - return self._stubs["list_operations"] - - @property - def list_locations( - self, - ) -> Callable[[locations_pb2.ListLocationsRequest], locations_pb2.ListLocationsResponse]: - r"""Return a callable for the list locations method over gRPC. - """ - # 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_locations" not in self._stubs: - self._stubs["list_locations"] = self.grpc_channel.unary_unary( - "/google.cloud.location.Locations/ListLocations", - request_serializer=locations_pb2.ListLocationsRequest.SerializeToString, - response_deserializer=locations_pb2.ListLocationsResponse.FromString, - ) - return self._stubs["list_locations"] - - @property - def get_location( - self, - ) -> Callable[[locations_pb2.GetLocationRequest], locations_pb2.Location]: - r"""Return a callable for the list locations method over gRPC. - """ - # 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_location" not in self._stubs: - self._stubs["get_location"] = self.grpc_channel.unary_unary( - "/google.cloud.location.Locations/GetLocation", - request_serializer=locations_pb2.GetLocationRequest.SerializeToString, - response_deserializer=locations_pb2.Location.FromString, - ) - return self._stubs["get_location"] - - -__all__ = ( - 'EntityTypesGrpcAsyncIOTransport', -) diff --git a/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/entity_types/transports/rest.py b/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/entity_types/transports/rest.py deleted file mode 100644 index 7cffabd2c..000000000 --- a/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/entity_types/transports/rest.py +++ /dev/null @@ -1,1921 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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 google.auth.transport.requests import AuthorizedSession # type: ignore -import json # type: ignore -import grpc # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore -from google.auth import credentials as ga_credentials # type: ignore -from google.api_core import exceptions as core_exceptions -from google.api_core import retry as retries -from google.api_core import rest_helpers -from google.api_core import rest_streaming -from google.api_core import path_template -from google.api_core import gapic_v1 - -from google.protobuf import json_format -from google.api_core import operations_v1 -from google.cloud.location import locations_pb2 # type: ignore -from google.longrunning import operations_pb2 -from requests import __version__ as requests_version -import dataclasses -import re -from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union -import warnings - -try: - OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] -except AttributeError: # pragma: NO COVER - OptionalRetry = Union[retries.Retry, object] # 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 # type: ignore -from google.protobuf import empty_pb2 # type: ignore - -from .base import EntityTypesTransport, DEFAULT_CLIENT_INFO as BASE_DEFAULT_CLIENT_INFO - - -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=BASE_DEFAULT_CLIENT_INFO.gapic_version, - grpc_version=None, - rest_version=requests_version, -) - - -class EntityTypesRestInterceptor: - """Interceptor for EntityTypes. - - Interceptors are used to manipulate requests, request metadata, and responses - in arbitrary ways. - Example use cases include: - * Logging - * Verifying requests according to service or custom semantics - * Stripping extraneous information from responses - - These use cases and more can be enabled by injecting an - instance of a custom subclass when constructing the EntityTypesRestTransport. - - .. code-block:: python - class MyCustomEntityTypesInterceptor(EntityTypesRestInterceptor): - def pre_batch_create_entities(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_batch_create_entities(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_batch_delete_entities(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_batch_delete_entities(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_batch_delete_entity_types(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_batch_delete_entity_types(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_batch_update_entities(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_batch_update_entities(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_batch_update_entity_types(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_batch_update_entity_types(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_create_entity_type(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_create_entity_type(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_delete_entity_type(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def pre_get_entity_type(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_get_entity_type(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_list_entity_types(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_list_entity_types(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_update_entity_type(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_update_entity_type(self, response): - logging.log(f"Received response: {response}") - return response - - transport = EntityTypesRestTransport(interceptor=MyCustomEntityTypesInterceptor()) - client = EntityTypesClient(transport=transport) - - - """ - def pre_batch_create_entities(self, request: entity_type.BatchCreateEntitiesRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[entity_type.BatchCreateEntitiesRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for batch_create_entities - - Override in a subclass to manipulate the request or metadata - before they are sent to the EntityTypes server. - """ - return request, metadata - - def post_batch_create_entities(self, response: operations_pb2.Operation) -> operations_pb2.Operation: - """Post-rpc interceptor for batch_create_entities - - Override in a subclass to manipulate the response - after it is returned by the EntityTypes server but before - it is returned to user code. - """ - return response - def pre_batch_delete_entities(self, request: entity_type.BatchDeleteEntitiesRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[entity_type.BatchDeleteEntitiesRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for batch_delete_entities - - Override in a subclass to manipulate the request or metadata - before they are sent to the EntityTypes server. - """ - return request, metadata - - def post_batch_delete_entities(self, response: operations_pb2.Operation) -> operations_pb2.Operation: - """Post-rpc interceptor for batch_delete_entities - - Override in a subclass to manipulate the response - after it is returned by the EntityTypes server but before - it is returned to user code. - """ - return response - def pre_batch_delete_entity_types(self, request: entity_type.BatchDeleteEntityTypesRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[entity_type.BatchDeleteEntityTypesRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for batch_delete_entity_types - - Override in a subclass to manipulate the request or metadata - before they are sent to the EntityTypes server. - """ - return request, metadata - - def post_batch_delete_entity_types(self, response: operations_pb2.Operation) -> operations_pb2.Operation: - """Post-rpc interceptor for batch_delete_entity_types - - Override in a subclass to manipulate the response - after it is returned by the EntityTypes server but before - it is returned to user code. - """ - return response - def pre_batch_update_entities(self, request: entity_type.BatchUpdateEntitiesRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[entity_type.BatchUpdateEntitiesRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for batch_update_entities - - Override in a subclass to manipulate the request or metadata - before they are sent to the EntityTypes server. - """ - return request, metadata - - def post_batch_update_entities(self, response: operations_pb2.Operation) -> operations_pb2.Operation: - """Post-rpc interceptor for batch_update_entities - - Override in a subclass to manipulate the response - after it is returned by the EntityTypes server but before - it is returned to user code. - """ - return response - def pre_batch_update_entity_types(self, request: entity_type.BatchUpdateEntityTypesRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[entity_type.BatchUpdateEntityTypesRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for batch_update_entity_types - - Override in a subclass to manipulate the request or metadata - before they are sent to the EntityTypes server. - """ - return request, metadata - - def post_batch_update_entity_types(self, response: operations_pb2.Operation) -> operations_pb2.Operation: - """Post-rpc interceptor for batch_update_entity_types - - Override in a subclass to manipulate the response - after it is returned by the EntityTypes server but before - it is returned to user code. - """ - return response - def pre_create_entity_type(self, request: gcd_entity_type.CreateEntityTypeRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[gcd_entity_type.CreateEntityTypeRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for create_entity_type - - Override in a subclass to manipulate the request or metadata - before they are sent to the EntityTypes server. - """ - return request, metadata - - def post_create_entity_type(self, response: gcd_entity_type.EntityType) -> gcd_entity_type.EntityType: - """Post-rpc interceptor for create_entity_type - - Override in a subclass to manipulate the response - after it is returned by the EntityTypes server but before - it is returned to user code. - """ - return response - def pre_delete_entity_type(self, request: entity_type.DeleteEntityTypeRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[entity_type.DeleteEntityTypeRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for delete_entity_type - - Override in a subclass to manipulate the request or metadata - before they are sent to the EntityTypes server. - """ - return request, metadata - - def pre_get_entity_type(self, request: entity_type.GetEntityTypeRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[entity_type.GetEntityTypeRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for get_entity_type - - Override in a subclass to manipulate the request or metadata - before they are sent to the EntityTypes server. - """ - return request, metadata - - def post_get_entity_type(self, response: entity_type.EntityType) -> entity_type.EntityType: - """Post-rpc interceptor for get_entity_type - - Override in a subclass to manipulate the response - after it is returned by the EntityTypes server but before - it is returned to user code. - """ - return response - def pre_list_entity_types(self, request: entity_type.ListEntityTypesRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[entity_type.ListEntityTypesRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for list_entity_types - - Override in a subclass to manipulate the request or metadata - before they are sent to the EntityTypes server. - """ - return request, metadata - - def post_list_entity_types(self, response: entity_type.ListEntityTypesResponse) -> entity_type.ListEntityTypesResponse: - """Post-rpc interceptor for list_entity_types - - Override in a subclass to manipulate the response - after it is returned by the EntityTypes server but before - it is returned to user code. - """ - return response - def pre_update_entity_type(self, request: gcd_entity_type.UpdateEntityTypeRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[gcd_entity_type.UpdateEntityTypeRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for update_entity_type - - Override in a subclass to manipulate the request or metadata - before they are sent to the EntityTypes server. - """ - return request, metadata - - def post_update_entity_type(self, response: gcd_entity_type.EntityType) -> gcd_entity_type.EntityType: - """Post-rpc interceptor for update_entity_type - - Override in a subclass to manipulate the response - after it is returned by the EntityTypes server but before - it is returned to user code. - """ - return response - - def pre_get_location( - self, request: locations_pb2.GetLocationRequest, metadata: Sequence[Tuple[str, str]] - ) -> Tuple[locations_pb2.GetLocationRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for get_location - - Override in a subclass to manipulate the request or metadata - before they are sent to the EntityTypes server. - """ - return request, metadata - - def post_get_location( - self, response: locations_pb2.Location - ) -> locations_pb2.Location: - """Post-rpc interceptor for get_location - - Override in a subclass to manipulate the response - after it is returned by the EntityTypes server but before - it is returned to user code. - """ - return response - def pre_list_locations( - self, request: locations_pb2.ListLocationsRequest, metadata: Sequence[Tuple[str, str]] - ) -> Tuple[locations_pb2.ListLocationsRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for list_locations - - Override in a subclass to manipulate the request or metadata - before they are sent to the EntityTypes server. - """ - return request, metadata - - def post_list_locations( - self, response: locations_pb2.ListLocationsResponse - ) -> locations_pb2.ListLocationsResponse: - """Post-rpc interceptor for list_locations - - Override in a subclass to manipulate the response - after it is returned by the EntityTypes server but before - it is returned to user code. - """ - return response - def pre_cancel_operation( - self, request: operations_pb2.CancelOperationRequest, metadata: Sequence[Tuple[str, str]] - ) -> Tuple[operations_pb2.CancelOperationRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for cancel_operation - - Override in a subclass to manipulate the request or metadata - before they are sent to the EntityTypes server. - """ - return request, metadata - - def post_cancel_operation( - self, response: None - ) -> None: - """Post-rpc interceptor for cancel_operation - - Override in a subclass to manipulate the response - after it is returned by the EntityTypes server but before - it is returned to user code. - """ - return response - def pre_get_operation( - self, request: operations_pb2.GetOperationRequest, metadata: Sequence[Tuple[str, str]] - ) -> Tuple[operations_pb2.GetOperationRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for get_operation - - Override in a subclass to manipulate the request or metadata - before they are sent to the EntityTypes server. - """ - return request, metadata - - def post_get_operation( - self, response: operations_pb2.Operation - ) -> operations_pb2.Operation: - """Post-rpc interceptor for get_operation - - Override in a subclass to manipulate the response - after it is returned by the EntityTypes server but before - it is returned to user code. - """ - return response - def pre_list_operations( - self, request: operations_pb2.ListOperationsRequest, metadata: Sequence[Tuple[str, str]] - ) -> Tuple[operations_pb2.ListOperationsRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for list_operations - - Override in a subclass to manipulate the request or metadata - before they are sent to the EntityTypes server. - """ - return request, metadata - - def post_list_operations( - self, response: operations_pb2.ListOperationsResponse - ) -> operations_pb2.ListOperationsResponse: - """Post-rpc interceptor for list_operations - - Override in a subclass to manipulate the response - after it is returned by the EntityTypes server but before - it is returned to user code. - """ - return response - - -@dataclasses.dataclass -class EntityTypesRestStub: - _session: AuthorizedSession - _host: str - _interceptor: EntityTypesRestInterceptor - - -class EntityTypesRestTransport(EntityTypesTransport): - """REST backend transport for EntityTypes. - - Service for managing - [EntityTypes][google.cloud.dialogflow.v2.EntityType]. - - 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 JSON representations of protocol buffers over HTTP/1.1 - - """ - - def __init__(self, *, - host: str = 'dialogflow.googleapis.com', - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - client_cert_source_for_mtls: Optional[Callable[[ - ], Tuple[bytes, bytes]]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - url_scheme: str = 'https', - interceptor: Optional[EntityTypesRestInterceptor] = None, - api_audience: Optional[str] = None, - ) -> 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 ignored if ``channel`` is provided. - scopes (Optional(Sequence[str])): A list of scopes. This argument is - ignored if ``channel`` is provided. - client_cert_source_for_mtls (Callable[[], Tuple[bytes, bytes]]): Client - certificate to configure mutual TLS HTTP channel. It is ignored - if ``channel`` is provided. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you are developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - url_scheme: the protocol scheme for the API endpoint. Normally - "https", but for testing or local servers, - "http" can be specified. - """ - # Run the base constructor - # TODO(yon-mg): resolve other ctor params i.e. scopes, quota, etc. - # TODO: When custom host (api_endpoint) is set, `scopes` must *also* be set on the - # credentials object - maybe_url_match = re.match("^(?Phttp(?:s)?://)?(?P.*)$", host) - if maybe_url_match is None: - raise ValueError(f"Unexpected hostname structure: {host}") # pragma: NO COVER - - url_match_items = maybe_url_match.groupdict() - - host = f"{url_scheme}://{host}" if not url_match_items["scheme"] else host - - super().__init__( - host=host, - credentials=credentials, - client_info=client_info, - always_use_jwt_access=always_use_jwt_access, - api_audience=api_audience - ) - self._session = AuthorizedSession( - self._credentials, default_host=self.DEFAULT_HOST) - self._operations_client: Optional[operations_v1.AbstractOperationsClient] = None - if client_cert_source_for_mtls: - self._session.configure_mtls_channel(client_cert_source_for_mtls) - self._interceptor = interceptor or EntityTypesRestInterceptor() - self._prep_wrapped_messages(client_info) - - @property - def operations_client(self) -> operations_v1.AbstractOperationsClient: - """Create the client designed to process long-running operations. - - This property caches on the instance; repeated calls return the same - client. - """ - # Only create a new client if we do not already have one. - if self._operations_client is None: - http_options: Dict[str, List[Dict[str, str]]] = { - 'google.longrunning.Operations.CancelOperation': [ - { - 'method': 'post', - 'uri': '/v2/{name=projects/*/operations/*}:cancel', - }, - { - 'method': 'post', - 'uri': '/v2/{name=projects/*/locations/*/operations/*}:cancel', - }, - ], - 'google.longrunning.Operations.GetOperation': [ - { - 'method': 'get', - 'uri': '/v2/{name=projects/*/operations/*}', - }, - { - 'method': 'get', - 'uri': '/v2/{name=projects/*/locations/*/operations/*}', - }, - ], - 'google.longrunning.Operations.ListOperations': [ - { - 'method': 'get', - 'uri': '/v2/{name=projects/*}/operations', - }, - { - 'method': 'get', - 'uri': '/v2/{name=projects/*/locations/*}/operations', - }, - ], - } - - rest_transport = operations_v1.OperationsRestTransport( - host=self._host, - # use the credentials which are saved - credentials=self._credentials, - scopes=self._scopes, - http_options=http_options, - path_prefix="v2") - - self._operations_client = operations_v1.AbstractOperationsClient(transport=rest_transport) - - # Return the client from cache. - return self._operations_client - - class _BatchCreateEntities(EntityTypesRestStub): - def __hash__(self): - return hash("BatchCreateEntities") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: entity_type.BatchCreateEntitiesRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> operations_pb2.Operation: - r"""Call the batch create entities method over HTTP. - - Args: - request (~.entity_type.BatchCreateEntitiesRequest): - The request object. The request message for - [EntityTypes.BatchCreateEntities][google.cloud.dialogflow.v2.EntityTypes.BatchCreateEntities]. - 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: - ~.operations_pb2.Operation: - This resource represents a - long-running operation that is the - result of a network API call. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'post', - 'uri': '/v2/{parent=projects/*/agent/entityTypes/*}/entities:batchCreate', - 'body': '*', - }, -{ - 'method': 'post', - 'uri': '/v2/{parent=projects/*/locations/*/agent/entityTypes/*}/entities:batchCreate', - 'body': '*', - }, - ] - request, metadata = self._interceptor.pre_batch_create_entities(request, metadata) - pb_request = entity_type.BatchCreateEntitiesRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request['body'], - including_default_value_fields=False, - use_integers_for_enums=True - ) - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - including_default_value_fields=False, - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = operations_pb2.Operation() - json_format.Parse(response.content, resp, ignore_unknown_fields=True) - resp = self._interceptor.post_batch_create_entities(resp) - return resp - - class _BatchDeleteEntities(EntityTypesRestStub): - def __hash__(self): - return hash("BatchDeleteEntities") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: entity_type.BatchDeleteEntitiesRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> operations_pb2.Operation: - r"""Call the batch delete entities method over HTTP. - - Args: - request (~.entity_type.BatchDeleteEntitiesRequest): - The request object. The request message for - [EntityTypes.BatchDeleteEntities][google.cloud.dialogflow.v2.EntityTypes.BatchDeleteEntities]. - 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: - ~.operations_pb2.Operation: - This resource represents a - long-running operation that is the - result of a network API call. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'post', - 'uri': '/v2/{parent=projects/*/agent/entityTypes/*}/entities:batchDelete', - 'body': '*', - }, -{ - 'method': 'post', - 'uri': '/v2/{parent=projects/*/locations/*/agent/entityTypes/*}/entities:batchDelete', - 'body': '*', - }, - ] - request, metadata = self._interceptor.pre_batch_delete_entities(request, metadata) - pb_request = entity_type.BatchDeleteEntitiesRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request['body'], - including_default_value_fields=False, - use_integers_for_enums=True - ) - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - including_default_value_fields=False, - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = operations_pb2.Operation() - json_format.Parse(response.content, resp, ignore_unknown_fields=True) - resp = self._interceptor.post_batch_delete_entities(resp) - return resp - - class _BatchDeleteEntityTypes(EntityTypesRestStub): - def __hash__(self): - return hash("BatchDeleteEntityTypes") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: entity_type.BatchDeleteEntityTypesRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> operations_pb2.Operation: - r"""Call the batch delete entity types method over HTTP. - - Args: - request (~.entity_type.BatchDeleteEntityTypesRequest): - The request object. The request message for - [EntityTypes.BatchDeleteEntityTypes][google.cloud.dialogflow.v2.EntityTypes.BatchDeleteEntityTypes]. - 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: - ~.operations_pb2.Operation: - This resource represents a - long-running operation that is the - result of a network API call. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'post', - 'uri': '/v2/{parent=projects/*/agent}/entityTypes:batchDelete', - 'body': '*', - }, -{ - 'method': 'post', - 'uri': '/v2/{parent=projects/*/locations/*/agent}/entityTypes:batchDelete', - 'body': '*', - }, - ] - request, metadata = self._interceptor.pre_batch_delete_entity_types(request, metadata) - pb_request = entity_type.BatchDeleteEntityTypesRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request['body'], - including_default_value_fields=False, - use_integers_for_enums=True - ) - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - including_default_value_fields=False, - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = operations_pb2.Operation() - json_format.Parse(response.content, resp, ignore_unknown_fields=True) - resp = self._interceptor.post_batch_delete_entity_types(resp) - return resp - - class _BatchUpdateEntities(EntityTypesRestStub): - def __hash__(self): - return hash("BatchUpdateEntities") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: entity_type.BatchUpdateEntitiesRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> operations_pb2.Operation: - r"""Call the batch update entities method over HTTP. - - Args: - request (~.entity_type.BatchUpdateEntitiesRequest): - The request object. The request message for - [EntityTypes.BatchUpdateEntities][google.cloud.dialogflow.v2.EntityTypes.BatchUpdateEntities]. - 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: - ~.operations_pb2.Operation: - This resource represents a - long-running operation that is the - result of a network API call. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'post', - 'uri': '/v2/{parent=projects/*/agent/entityTypes/*}/entities:batchUpdate', - 'body': '*', - }, -{ - 'method': 'post', - 'uri': '/v2/{parent=projects/*/locations/*/agent/entityTypes/*}/entities:batchUpdate', - 'body': '*', - }, - ] - request, metadata = self._interceptor.pre_batch_update_entities(request, metadata) - pb_request = entity_type.BatchUpdateEntitiesRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request['body'], - including_default_value_fields=False, - use_integers_for_enums=True - ) - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - including_default_value_fields=False, - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = operations_pb2.Operation() - json_format.Parse(response.content, resp, ignore_unknown_fields=True) - resp = self._interceptor.post_batch_update_entities(resp) - return resp - - class _BatchUpdateEntityTypes(EntityTypesRestStub): - def __hash__(self): - return hash("BatchUpdateEntityTypes") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: entity_type.BatchUpdateEntityTypesRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> operations_pb2.Operation: - r"""Call the batch update entity types method over HTTP. - - Args: - request (~.entity_type.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. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.operations_pb2.Operation: - This resource represents a - long-running operation that is the - result of a network API call. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'post', - 'uri': '/v2/{parent=projects/*/agent}/entityTypes:batchUpdate', - 'body': '*', - }, -{ - 'method': 'post', - 'uri': '/v2/{parent=projects/*/locations/*/agent}/entityTypes:batchUpdate', - 'body': '*', - }, - ] - request, metadata = self._interceptor.pre_batch_update_entity_types(request, metadata) - pb_request = entity_type.BatchUpdateEntityTypesRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request['body'], - including_default_value_fields=False, - use_integers_for_enums=True - ) - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - including_default_value_fields=False, - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = operations_pb2.Operation() - json_format.Parse(response.content, resp, ignore_unknown_fields=True) - resp = self._interceptor.post_batch_update_entity_types(resp) - return resp - - class _CreateEntityType(EntityTypesRestStub): - def __hash__(self): - return hash("CreateEntityType") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: gcd_entity_type.CreateEntityTypeRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> gcd_entity_type.EntityType: - r"""Call the create entity type method over HTTP. - - Args: - request (~.gcd_entity_type.CreateEntityTypeRequest): - The request object. The request message for - [EntityTypes.CreateEntityType][google.cloud.dialogflow.v2.EntityTypes.CreateEntityType]. - 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: - ~.gcd_entity_type.EntityType: - Each intent parameter has a type, called the entity - type, which dictates exactly how data from an end-user - expression is extracted. - - Dialogflow provides predefined system entities that can - match many common types of data. For example, there are - system entities for matching dates, times, colors, email - addresses, and so on. You can also create your own - custom entities for matching custom data. For example, - you could define a vegetable entity that can match the - types of vegetables available for purchase with a - grocery store agent. - - For more information, see the `Entity - guide `__. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'post', - 'uri': '/v2/{parent=projects/*/agent}/entityTypes', - 'body': 'entity_type', - }, -{ - 'method': 'post', - 'uri': '/v2/{parent=projects/*/locations/*/agent}/entityTypes', - 'body': 'entity_type', - }, - ] - request, metadata = self._interceptor.pre_create_entity_type(request, metadata) - pb_request = gcd_entity_type.CreateEntityTypeRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request['body'], - including_default_value_fields=False, - use_integers_for_enums=True - ) - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - including_default_value_fields=False, - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = gcd_entity_type.EntityType() - pb_resp = gcd_entity_type.EntityType.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_create_entity_type(resp) - return resp - - class _DeleteEntityType(EntityTypesRestStub): - def __hash__(self): - return hash("DeleteEntityType") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: entity_type.DeleteEntityTypeRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ): - r"""Call the delete entity type method over HTTP. - - Args: - request (~.entity_type.DeleteEntityTypeRequest): - The request object. The request message for - [EntityTypes.DeleteEntityType][google.cloud.dialogflow.v2.EntityTypes.DeleteEntityType]. - 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. - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'delete', - 'uri': '/v2/{name=projects/*/agent/entityTypes/*}', - }, -{ - 'method': 'delete', - 'uri': '/v2/{name=projects/*/locations/*/agent/entityTypes/*}', - }, - ] - request, metadata = self._interceptor.pre_delete_entity_type(request, metadata) - pb_request = entity_type.DeleteEntityTypeRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - including_default_value_fields=False, - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - class _GetEntityType(EntityTypesRestStub): - def __hash__(self): - return hash("GetEntityType") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: entity_type.GetEntityTypeRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> entity_type.EntityType: - r"""Call the get entity type method over HTTP. - - Args: - request (~.entity_type.GetEntityTypeRequest): - The request object. The request message for - [EntityTypes.GetEntityType][google.cloud.dialogflow.v2.EntityTypes.GetEntityType]. - 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: - ~.entity_type.EntityType: - Each intent parameter has a type, called the entity - type, which dictates exactly how data from an end-user - expression is extracted. - - Dialogflow provides predefined system entities that can - match many common types of data. For example, there are - system entities for matching dates, times, colors, email - addresses, and so on. You can also create your own - custom entities for matching custom data. For example, - you could define a vegetable entity that can match the - types of vegetables available for purchase with a - grocery store agent. - - For more information, see the `Entity - guide `__. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v2/{name=projects/*/agent/entityTypes/*}', - }, -{ - 'method': 'get', - 'uri': '/v2/{name=projects/*/locations/*/agent/entityTypes/*}', - }, - ] - request, metadata = self._interceptor.pre_get_entity_type(request, metadata) - pb_request = entity_type.GetEntityTypeRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - including_default_value_fields=False, - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = entity_type.EntityType() - pb_resp = entity_type.EntityType.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_get_entity_type(resp) - return resp - - class _ListEntityTypes(EntityTypesRestStub): - def __hash__(self): - return hash("ListEntityTypes") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: entity_type.ListEntityTypesRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> entity_type.ListEntityTypesResponse: - r"""Call the list entity types method over HTTP. - - Args: - request (~.entity_type.ListEntityTypesRequest): - The request object. The request message for - [EntityTypes.ListEntityTypes][google.cloud.dialogflow.v2.EntityTypes.ListEntityTypes]. - 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: - ~.entity_type.ListEntityTypesResponse: - The response message for - [EntityTypes.ListEntityTypes][google.cloud.dialogflow.v2.EntityTypes.ListEntityTypes]. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v2/{parent=projects/*/agent}/entityTypes', - }, -{ - 'method': 'get', - 'uri': '/v2/{parent=projects/*/locations/*/agent}/entityTypes', - }, - ] - request, metadata = self._interceptor.pre_list_entity_types(request, metadata) - pb_request = entity_type.ListEntityTypesRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - including_default_value_fields=False, - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = entity_type.ListEntityTypesResponse() - pb_resp = entity_type.ListEntityTypesResponse.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_list_entity_types(resp) - return resp - - class _UpdateEntityType(EntityTypesRestStub): - def __hash__(self): - return hash("UpdateEntityType") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: gcd_entity_type.UpdateEntityTypeRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> gcd_entity_type.EntityType: - r"""Call the update entity type method over HTTP. - - Args: - request (~.gcd_entity_type.UpdateEntityTypeRequest): - The request object. The request message for - [EntityTypes.UpdateEntityType][google.cloud.dialogflow.v2.EntityTypes.UpdateEntityType]. - 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: - ~.gcd_entity_type.EntityType: - Each intent parameter has a type, called the entity - type, which dictates exactly how data from an end-user - expression is extracted. - - Dialogflow provides predefined system entities that can - match many common types of data. For example, there are - system entities for matching dates, times, colors, email - addresses, and so on. You can also create your own - custom entities for matching custom data. For example, - you could define a vegetable entity that can match the - types of vegetables available for purchase with a - grocery store agent. - - For more information, see the `Entity - guide `__. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'patch', - 'uri': '/v2/{entity_type.name=projects/*/agent/entityTypes/*}', - 'body': 'entity_type', - }, -{ - 'method': 'patch', - 'uri': '/v2/{entity_type.name=projects/*/locations/*/agent/entityTypes/*}', - 'body': 'entity_type', - }, - ] - request, metadata = self._interceptor.pre_update_entity_type(request, metadata) - pb_request = gcd_entity_type.UpdateEntityTypeRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request['body'], - including_default_value_fields=False, - use_integers_for_enums=True - ) - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - including_default_value_fields=False, - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = gcd_entity_type.EntityType() - pb_resp = gcd_entity_type.EntityType.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_update_entity_type(resp) - return resp - - @property - def batch_create_entities(self) -> Callable[ - [entity_type.BatchCreateEntitiesRequest], - operations_pb2.Operation]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._BatchCreateEntities(self._session, self._host, self._interceptor) # type: ignore - - @property - def batch_delete_entities(self) -> Callable[ - [entity_type.BatchDeleteEntitiesRequest], - operations_pb2.Operation]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._BatchDeleteEntities(self._session, self._host, self._interceptor) # type: ignore - - @property - def batch_delete_entity_types(self) -> Callable[ - [entity_type.BatchDeleteEntityTypesRequest], - operations_pb2.Operation]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._BatchDeleteEntityTypes(self._session, self._host, self._interceptor) # type: ignore - - @property - def batch_update_entities(self) -> Callable[ - [entity_type.BatchUpdateEntitiesRequest], - operations_pb2.Operation]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._BatchUpdateEntities(self._session, self._host, self._interceptor) # type: ignore - - @property - def batch_update_entity_types(self) -> Callable[ - [entity_type.BatchUpdateEntityTypesRequest], - operations_pb2.Operation]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._BatchUpdateEntityTypes(self._session, self._host, self._interceptor) # type: ignore - - @property - def create_entity_type(self) -> Callable[ - [gcd_entity_type.CreateEntityTypeRequest], - gcd_entity_type.EntityType]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._CreateEntityType(self._session, self._host, self._interceptor) # type: ignore - - @property - def delete_entity_type(self) -> Callable[ - [entity_type.DeleteEntityTypeRequest], - empty_pb2.Empty]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._DeleteEntityType(self._session, self._host, self._interceptor) # type: ignore - - @property - def get_entity_type(self) -> Callable[ - [entity_type.GetEntityTypeRequest], - entity_type.EntityType]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._GetEntityType(self._session, self._host, self._interceptor) # type: ignore - - @property - def list_entity_types(self) -> Callable[ - [entity_type.ListEntityTypesRequest], - entity_type.ListEntityTypesResponse]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._ListEntityTypes(self._session, self._host, self._interceptor) # type: ignore - - @property - def update_entity_type(self) -> Callable[ - [gcd_entity_type.UpdateEntityTypeRequest], - gcd_entity_type.EntityType]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._UpdateEntityType(self._session, self._host, self._interceptor) # type: ignore - - @property - def get_location(self): - return self._GetLocation(self._session, self._host, self._interceptor) # type: ignore - - class _GetLocation(EntityTypesRestStub): - def __call__(self, - request: locations_pb2.GetLocationRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> locations_pb2.Location: - - r"""Call the get location method over HTTP. - - Args: - request (locations_pb2.GetLocationRequest): - The request object for GetLocation method. - 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: - locations_pb2.Location: Response from GetLocation method. - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v2/{name=projects/*/locations/*}', - }, - ] - - request, metadata = self._interceptor.pre_get_location(request, metadata) - request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode( - http_options, **request_kwargs) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json.dumps(transcoded_request['query_params'])) - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - resp = locations_pb2.Location() - resp = json_format.Parse(response.content.decode("utf-8"), resp) - resp = self._interceptor.post_get_location(resp) - return resp - - @property - def list_locations(self): - return self._ListLocations(self._session, self._host, self._interceptor) # type: ignore - - class _ListLocations(EntityTypesRestStub): - def __call__(self, - request: locations_pb2.ListLocationsRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> locations_pb2.ListLocationsResponse: - - r"""Call the list locations method over HTTP. - - Args: - request (locations_pb2.ListLocationsRequest): - The request object for ListLocations method. - 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: - locations_pb2.ListLocationsResponse: Response from ListLocations method. - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v2/{name=projects/*}/locations', - }, - ] - - request, metadata = self._interceptor.pre_list_locations(request, metadata) - request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode( - http_options, **request_kwargs) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json.dumps(transcoded_request['query_params'])) - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - resp = locations_pb2.ListLocationsResponse() - resp = json_format.Parse(response.content.decode("utf-8"), resp) - resp = self._interceptor.post_list_locations(resp) - return resp - - @property - def cancel_operation(self): - return self._CancelOperation(self._session, self._host, self._interceptor) # type: ignore - - class _CancelOperation(EntityTypesRestStub): - def __call__(self, - request: operations_pb2.CancelOperationRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> None: - - r"""Call the cancel operation method over HTTP. - - Args: - request (operations_pb2.CancelOperationRequest): - The request object for CancelOperation method. - 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. - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'post', - 'uri': '/v2/{name=projects/*/operations/*}:cancel', - }, -{ - 'method': 'post', - 'uri': '/v2/{name=projects/*/locations/*/operations/*}:cancel', - }, - ] - - request, metadata = self._interceptor.pre_cancel_operation(request, metadata) - request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode( - http_options, **request_kwargs) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json.dumps(transcoded_request['query_params'])) - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - return self._interceptor.post_cancel_operation(None) - - @property - def get_operation(self): - return self._GetOperation(self._session, self._host, self._interceptor) # type: ignore - - class _GetOperation(EntityTypesRestStub): - def __call__(self, - request: operations_pb2.GetOperationRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> operations_pb2.Operation: - - r"""Call the get operation method over HTTP. - - Args: - request (operations_pb2.GetOperationRequest): - The request object for GetOperation method. - 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: - operations_pb2.Operation: Response from GetOperation method. - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v2/{name=projects/*/operations/*}', - }, -{ - 'method': 'get', - 'uri': '/v2/{name=projects/*/locations/*/operations/*}', - }, - ] - - request, metadata = self._interceptor.pre_get_operation(request, metadata) - request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode( - http_options, **request_kwargs) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json.dumps(transcoded_request['query_params'])) - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - resp = operations_pb2.Operation() - resp = json_format.Parse(response.content.decode("utf-8"), resp) - resp = self._interceptor.post_get_operation(resp) - return resp - - @property - def list_operations(self): - return self._ListOperations(self._session, self._host, self._interceptor) # type: ignore - - class _ListOperations(EntityTypesRestStub): - def __call__(self, - request: operations_pb2.ListOperationsRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> operations_pb2.ListOperationsResponse: - - r"""Call the list operations method over HTTP. - - Args: - request (operations_pb2.ListOperationsRequest): - The request object for ListOperations method. - 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: - operations_pb2.ListOperationsResponse: Response from ListOperations method. - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v2/{name=projects/*}/operations', - }, -{ - 'method': 'get', - 'uri': '/v2/{name=projects/*/locations/*}/operations', - }, - ] - - request, metadata = self._interceptor.pre_list_operations(request, metadata) - request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode( - http_options, **request_kwargs) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json.dumps(transcoded_request['query_params'])) - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - resp = operations_pb2.ListOperationsResponse() - resp = json_format.Parse(response.content.decode("utf-8"), resp) - resp = self._interceptor.post_list_operations(resp) - return resp - - @property - def kind(self) -> str: - return "rest" - - def close(self): - self._session.close() - - -__all__=( - 'EntityTypesRestTransport', -) diff --git a/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/environments/__init__.py b/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/environments/__init__.py deleted file mode 100644 index 63bae46ea..000000000 --- a/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/environments/__init__.py +++ /dev/null @@ -1,22 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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 EnvironmentsClient -from .async_client import EnvironmentsAsyncClient - -__all__ = ( - 'EnvironmentsClient', - 'EnvironmentsAsyncClient', -) diff --git a/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/environments/async_client.py b/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/environments/async_client.py deleted file mode 100644 index f4f425d45..000000000 --- a/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/environments/async_client.py +++ /dev/null @@ -1,1056 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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, Mapping, MutableMapping, MutableSequence, Optional, Sequence, Tuple, Type, Union - -from google.cloud.dialogflow_v2 import gapic_version as package_version - -from google.api_core.client_options import ClientOptions -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import retry as retries -from google.auth import credentials as ga_credentials # type: ignore -from google.oauth2 import service_account # type: ignore - -try: - OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] -except AttributeError: # pragma: NO COVER - OptionalRetry = Union[retries.Retry, object] # 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.cloud.location import locations_pb2 # type: ignore -from google.longrunning import operations_pb2 -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 - - -class EnvironmentsAsyncClient: - """Service for managing - [Environments][google.cloud.dialogflow.v2.Environment]. - """ - - _client: EnvironmentsClient - - DEFAULT_ENDPOINT = EnvironmentsClient.DEFAULT_ENDPOINT - DEFAULT_MTLS_ENDPOINT = EnvironmentsClient.DEFAULT_MTLS_ENDPOINT - - 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) - version_path = staticmethod(EnvironmentsClient.version_path) - parse_version_path = staticmethod(EnvironmentsClient.parse_version_path) - common_billing_account_path = staticmethod(EnvironmentsClient.common_billing_account_path) - parse_common_billing_account_path = staticmethod(EnvironmentsClient.parse_common_billing_account_path) - common_folder_path = staticmethod(EnvironmentsClient.common_folder_path) - parse_common_folder_path = staticmethod(EnvironmentsClient.parse_common_folder_path) - common_organization_path = staticmethod(EnvironmentsClient.common_organization_path) - parse_common_organization_path = staticmethod(EnvironmentsClient.parse_common_organization_path) - common_project_path = staticmethod(EnvironmentsClient.common_project_path) - parse_common_project_path = staticmethod(EnvironmentsClient.parse_common_project_path) - common_location_path = staticmethod(EnvironmentsClient.common_location_path) - parse_common_location_path = staticmethod(EnvironmentsClient.parse_common_location_path) - - @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: - EnvironmentsAsyncClient: The constructed client. - """ - return EnvironmentsClient.from_service_account_info.__func__(EnvironmentsAsyncClient, 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: - EnvironmentsAsyncClient: The constructed client. - """ - return EnvironmentsClient.from_service_account_file.__func__(EnvironmentsAsyncClient, filename, *args, **kwargs) # type: ignore - - from_service_account_json = from_service_account_file - - @classmethod - def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[ClientOptions] = None): - """Return the API endpoint and client cert source for mutual TLS. - - The client cert source is determined in the following order: - (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the - client cert source is None. - (2) if `client_options.client_cert_source` is provided, use the provided one; if the - default client cert source exists, use the default one; otherwise the client cert - source is None. - - The API endpoint is determined in the following order: - (1) if `client_options.api_endpoint` if provided, use the provided one. - (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the - default mTLS endpoint; if the environment variable is "never", use the default API - endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise - use the default API endpoint. - - More details can be found at https://google.aip.dev/auth/4114. - - Args: - client_options (google.api_core.client_options.ClientOptions): Custom options for the - client. Only the `api_endpoint` and `client_cert_source` properties may be used - in this method. - - Returns: - Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the - client cert source to use. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If any errors happen. - """ - return EnvironmentsClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore - - @property - def transport(self) -> EnvironmentsTransport: - """Returns the transport used by the client instance. - - Returns: - EnvironmentsTransport: The transport used by the client instance. - """ - return self._client.transport - - get_transport_class = functools.partial(type(EnvironmentsClient).get_transport_class, type(EnvironmentsClient)) - - def __init__(self, *, - credentials: Optional[ga_credentials.Credentials] = None, - transport: Union[str, EnvironmentsTransport] = "grpc_asyncio", - client_options: Optional[ClientOptions] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the environments 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, ~.EnvironmentsTransport]): 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 = EnvironmentsClient( - credentials=credentials, - transport=transport, - client_options=client_options, - client_info=client_info, - - ) - - async def list_environments(self, - request: Optional[Union[environment.ListEnvironmentsRequest, dict]] = None, - *, - parent: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListEnvironmentsAsyncPager: - r"""Returns the list of all non-default environments of - the specified agent. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import dialogflow_v2 - - async def sample_list_environments(): - # Create a client - client = dialogflow_v2.EnvironmentsAsyncClient() - - # Initialize request argument(s) - request = dialogflow_v2.ListEnvironmentsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_environments(request=request) - - # Handle the response - async for response in page_result: - print(response) - - Args: - request (Optional[Union[google.cloud.dialogflow_v2.types.ListEnvironmentsRequest, dict]]): - 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. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.dialogflow_v2.services.environments.pagers.ListEnvironmentsAsyncPager: - The response message for - [Environments.ListEnvironments][google.cloud.dialogflow.v2.Environments.ListEnvironments]. - - Iterating over this object will yield results and - resolve additional pages automatically. - - """ - # Create or coerce a protobuf request object. - # Quick 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( - self._client._transport.list_environments, - 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.ListEnvironmentsAsyncPager( - method=rpc, - request=request, - response=response, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def get_environment(self, - request: Optional[Union[environment.GetEnvironmentRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> environment.Environment: - r"""Retrieves the specified agent environment. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import dialogflow_v2 - - async def sample_get_environment(): - # Create a client - client = dialogflow_v2.EnvironmentsAsyncClient() - - # Initialize request argument(s) - request = dialogflow_v2.GetEnvironmentRequest( - name="name_value", - ) - - # Make the request - response = await client.get_environment(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.dialogflow_v2.types.GetEnvironmentRequest, dict]]): - 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: Optional[Union[environment.CreateEnvironmentRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> environment.Environment: - r"""Creates an agent environment. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import dialogflow_v2 - - async def sample_create_environment(): - # Create a client - client = dialogflow_v2.EnvironmentsAsyncClient() - - # Initialize request argument(s) - request = dialogflow_v2.CreateEnvironmentRequest( - parent="parent_value", - environment_id="environment_id_value", - ) - - # Make the request - response = await client.create_environment(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.dialogflow_v2.types.CreateEnvironmentRequest, dict]]): - 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: Optional[Union[environment.UpdateEnvironmentRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - 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 continues 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 - an agent version in the default environment. WARNING: this will - negate all recent changes to the draft agent and can't be - undone. You may want to save the draft agent to a version before - calling this method. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import dialogflow_v2 - - async def sample_update_environment(): - # Create a client - client = dialogflow_v2.EnvironmentsAsyncClient() - - # Initialize request argument(s) - request = dialogflow_v2.UpdateEnvironmentRequest( - ) - - # Make the request - response = await client.update_environment(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.dialogflow_v2.types.UpdateEnvironmentRequest, dict]]): - 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: Optional[Union[environment.DeleteEnvironmentRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> None: - r"""Deletes the specified agent environment. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import dialogflow_v2 - - async def sample_delete_environment(): - # Create a client - client = dialogflow_v2.EnvironmentsAsyncClient() - - # Initialize request argument(s) - request = dialogflow_v2.DeleteEnvironmentRequest( - name="name_value", - ) - - # Make the request - await client.delete_environment(request=request) - - Args: - request (Optional[Union[google.cloud.dialogflow_v2.types.DeleteEnvironmentRequest, dict]]): - 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: Optional[Union[environment.GetEnvironmentHistoryRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.GetEnvironmentHistoryAsyncPager: - r"""Gets the history of the specified environment. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import dialogflow_v2 - - async def sample_get_environment_history(): - # Create a client - client = dialogflow_v2.EnvironmentsAsyncClient() - - # Initialize request argument(s) - request = dialogflow_v2.GetEnvironmentHistoryRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.get_environment_history(request=request) - - # Handle the response - async for response in page_result: - print(response) - - Args: - request (Optional[Union[google.cloud.dialogflow_v2.types.GetEnvironmentHistoryRequest, dict]]): - 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 - - async def list_operations( - self, - request: Optional[operations_pb2.ListOperationsRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operations_pb2.ListOperationsResponse: - r"""Lists operations that match the specified filter in the request. - - Args: - request (:class:`~.operations_pb2.ListOperationsRequest`): - The request object. Request message for - `ListOperations` method. - 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: - ~.operations_pb2.ListOperationsResponse: - Response message for ``ListOperations`` method. - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = operations_pb2.ListOperationsRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._client._transport.list_operations, - 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 get_operation( - self, - request: Optional[operations_pb2.GetOperationRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operations_pb2.Operation: - r"""Gets the latest state of a long-running operation. - - Args: - request (:class:`~.operations_pb2.GetOperationRequest`): - The request object. Request message for - `GetOperation` method. - 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: - ~.operations_pb2.Operation: - An ``Operation`` object. - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = operations_pb2.GetOperationRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._client._transport.get_operation, - 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 cancel_operation( - self, - request: Optional[operations_pb2.CancelOperationRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> None: - r"""Starts asynchronous cancellation on a long-running operation. - - The server makes a best effort to cancel the operation, but success - is not guaranteed. If the server doesn't support this method, it returns - `google.rpc.Code.UNIMPLEMENTED`. - - Args: - request (:class:`~.operations_pb2.CancelOperationRequest`): - The request object. Request message for - `CancelOperation` method. - 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: - None - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = operations_pb2.CancelOperationRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._client._transport.cancel_operation, - 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_location( - self, - request: Optional[locations_pb2.GetLocationRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> locations_pb2.Location: - r"""Gets information about a location. - - Args: - request (:class:`~.location_pb2.GetLocationRequest`): - The request object. Request message for - `GetLocation` method. - 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: - ~.location_pb2.Location: - Location object. - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = locations_pb2.GetLocationRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._client._transport.get_location, - 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 list_locations( - self, - request: Optional[locations_pb2.ListLocationsRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> locations_pb2.ListLocationsResponse: - r"""Lists information about the supported locations for this service. - - Args: - request (:class:`~.location_pb2.ListLocationsRequest`): - The request object. Request message for - `ListLocations` method. - 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: - ~.location_pb2.ListLocationsResponse: - Response message for ``ListLocations`` method. - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = locations_pb2.ListLocationsRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._client._transport.list_locations, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("name", request.name),)), - ) - - # Send the request. - response = await rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - async def __aenter__(self): - return self - - async def __aexit__(self, exc_type, exc, tb): - await self.transport.close() - -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) - - -__all__ = ( - "EnvironmentsAsyncClient", -) diff --git a/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/environments/client.py b/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/environments/client.py deleted file mode 100644 index b035cec06..000000000 --- a/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/environments/client.py +++ /dev/null @@ -1,1278 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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 os -import re -from typing import Dict, Mapping, MutableMapping, MutableSequence, Optional, Sequence, Tuple, Type, Union, cast - -from google.cloud.dialogflow_v2 import gapic_version as package_version - -from google.api_core import client_options as client_options_lib -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import retry as retries -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 - -try: - OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] -except AttributeError: # pragma: NO COVER - OptionalRetry = Union[retries.Retry, object] # 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.cloud.location import locations_pb2 # type: ignore -from google.longrunning import operations_pb2 -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 -from .transports.rest import EnvironmentsRestTransport - - -class EnvironmentsClientMeta(type): - """Metaclass for the Environments 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[EnvironmentsTransport]] - _transport_registry["grpc"] = EnvironmentsGrpcTransport - _transport_registry["grpc_asyncio"] = EnvironmentsGrpcAsyncIOTransport - _transport_registry["rest"] = EnvironmentsRestTransport - - def get_transport_class(cls, - label: Optional[str] = None, - ) -> Type[EnvironmentsTransport]: - """Returns an appropriate transport class. - - Args: - label: The name of the desired transport. If none is - provided, then the first transport in the registry is used. - - Returns: - The transport class to use. - """ - # If a specific transport is requested, return that one. - if label: - return cls._transport_registry[label] - - # No transport is requested; return the default (that is, the first one - # in the dictionary). - return next(iter(cls._transport_registry.values())) - - -class EnvironmentsClient(metaclass=EnvironmentsClientMeta): - """Service for managing - [Environments][google.cloud.dialogflow.v2.Environment]. - """ - - @staticmethod - def _get_default_mtls_endpoint(api_endpoint): - """Converts api endpoint to mTLS endpoint. - - Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to - "*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively. - Args: - api_endpoint (Optional[str]): the api endpoint to convert. - Returns: - str: converted mTLS api endpoint. - """ - if not api_endpoint: - return api_endpoint - - mtls_endpoint_re = re.compile( - r"(?P[^.]+)(?P\.mtls)?(?P\.sandbox)?(?P\.googleapis\.com)?" - ) - - m = mtls_endpoint_re.match(api_endpoint) - name, mtls, sandbox, googledomain = m.groups() - if mtls or not googledomain: - return api_endpoint - - if sandbox: - return api_endpoint.replace( - "sandbox.googleapis.com", "mtls.sandbox.googleapis.com" - ) - - return api_endpoint.replace(".googleapis.com", ".mtls.googleapis.com") - - DEFAULT_ENDPOINT = "dialogflow.googleapis.com" - DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore - DEFAULT_ENDPOINT - ) - - @classmethod - def from_service_account_info(cls, info: dict, *args, **kwargs): - """Creates an instance of this client using the provided credentials - info. - - Args: - info (dict): The service account private key info. - args: Additional arguments to pass to the constructor. - kwargs: Additional arguments to pass to the constructor. - - Returns: - EnvironmentsClient: 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: - EnvironmentsClient: 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) -> EnvironmentsTransport: - """Returns the transport used by the client instance. - - Returns: - EnvironmentsTransport: The transport used by the client - instance. - """ - return self._transport - - @staticmethod - def environment_path(project: str,environment: str,) -> str: - """Returns a fully-qualified environment string.""" - return "projects/{project}/agent/environments/{environment}".format(project=project, environment=environment, ) - - @staticmethod - def parse_environment_path(path: str) -> Dict[str,str]: - """Parses a environment path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/agent/environments/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def fulfillment_path(project: str,) -> str: - """Returns a fully-qualified fulfillment string.""" - return "projects/{project}/agent/fulfillment".format(project=project, ) - - @staticmethod - def parse_fulfillment_path(path: str) -> Dict[str,str]: - """Parses a fulfillment path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/agent/fulfillment$", path) - return m.groupdict() if m else {} - - @staticmethod - def version_path(project: str,version: str,) -> str: - """Returns 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]: - """Parses 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: - """Returns a fully-qualified billing_account string.""" - return "billingAccounts/{billing_account}".format(billing_account=billing_account, ) - - @staticmethod - def parse_common_billing_account_path(path: str) -> Dict[str,str]: - """Parse a billing_account path into its component segments.""" - m = re.match(r"^billingAccounts/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_folder_path(folder: str, ) -> str: - """Returns a fully-qualified folder string.""" - return "folders/{folder}".format(folder=folder, ) - - @staticmethod - def parse_common_folder_path(path: str) -> Dict[str,str]: - """Parse a folder path into its component segments.""" - m = re.match(r"^folders/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_organization_path(organization: str, ) -> str: - """Returns a fully-qualified organization string.""" - return "organizations/{organization}".format(organization=organization, ) - - @staticmethod - def parse_common_organization_path(path: str) -> Dict[str,str]: - """Parse a organization path into its component segments.""" - m = re.match(r"^organizations/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_project_path(project: str, ) -> str: - """Returns a fully-qualified project string.""" - return "projects/{project}".format(project=project, ) - - @staticmethod - def parse_common_project_path(path: str) -> Dict[str,str]: - """Parse a project path into its component segments.""" - m = re.match(r"^projects/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_location_path(project: str, location: str, ) -> str: - """Returns a fully-qualified location string.""" - return "projects/{project}/locations/{location}".format(project=project, location=location, ) - - @staticmethod - def parse_common_location_path(path: str) -> Dict[str,str]: - """Parse a location path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)$", path) - return m.groupdict() if m else {} - - @classmethod - def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[client_options_lib.ClientOptions] = None): - """Return the API endpoint and client cert source for mutual TLS. - - The client cert source is determined in the following order: - (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the - client cert source is None. - (2) if `client_options.client_cert_source` is provided, use the provided one; if the - default client cert source exists, use the default one; otherwise the client cert - source is None. - - The API endpoint is determined in the following order: - (1) if `client_options.api_endpoint` if provided, use the provided one. - (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the - default mTLS endpoint; if the environment variable is "never", use the default API - endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise - use the default API endpoint. - - More details can be found at https://google.aip.dev/auth/4114. - - Args: - client_options (google.api_core.client_options.ClientOptions): Custom options for the - client. Only the `api_endpoint` and `client_cert_source` properties may be used - in this method. - - Returns: - Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the - client cert source to use. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If any errors happen. - """ - if client_options is None: - client_options = client_options_lib.ClientOptions() - use_client_cert = os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false") - use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") - if use_client_cert not in ("true", "false"): - raise ValueError("Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`") - if use_mtls_endpoint not in ("auto", "never", "always"): - raise MutualTLSChannelError("Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`") - - # Figure out the client cert source to use. - client_cert_source = None - if use_client_cert == "true": - if client_options.client_cert_source: - client_cert_source = client_options.client_cert_source - elif mtls.has_default_client_cert_source(): - client_cert_source = mtls.default_client_cert_source() - - # Figure out which api endpoint to use. - if client_options.api_endpoint is not None: - api_endpoint = client_options.api_endpoint - elif use_mtls_endpoint == "always" or (use_mtls_endpoint == "auto" and client_cert_source): - api_endpoint = cls.DEFAULT_MTLS_ENDPOINT - else: - api_endpoint = cls.DEFAULT_ENDPOINT - - return api_endpoint, client_cert_source - - def __init__(self, *, - credentials: Optional[ga_credentials.Credentials] = None, - transport: Optional[Union[str, EnvironmentsTransport]] = None, - client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the environments 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, EnvironmentsTransport]): The - transport to use. If set to None, a transport is chosen - automatically. - client_options (Optional[Union[google.api_core.client_options.ClientOptions, dict]]): 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() - client_options = cast(client_options_lib.ClientOptions, client_options) - - api_endpoint, client_cert_source_func = self.get_mtls_endpoint_and_cert_source(client_options) - - api_key_value = getattr(client_options, "api_key", None) - if api_key_value and credentials: - raise ValueError("client_options.api_key and credentials are mutually exclusive") - - # 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, EnvironmentsTransport): - # transport is a EnvironmentsTransport instance. - if credentials or client_options.credentials_file or api_key_value: - 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: - import google.auth._default # type: ignore - - if api_key_value and hasattr(google.auth._default, "get_api_key_credentials"): - credentials = google.auth._default.get_api_key_credentials(api_key_value) - - Transport = type(self).get_transport_class(transport) - self._transport = Transport( - credentials=credentials, - credentials_file=client_options.credentials_file, - host=api_endpoint, - scopes=client_options.scopes, - client_cert_source_for_mtls=client_cert_source_func, - quota_project_id=client_options.quota_project_id, - client_info=client_info, - always_use_jwt_access=True, - api_audience=client_options.api_audience, - ) - - def list_environments(self, - request: Optional[Union[environment.ListEnvironmentsRequest, dict]] = None, - *, - parent: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListEnvironmentsPager: - r"""Returns the list of all non-default environments of - the specified agent. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import dialogflow_v2 - - def sample_list_environments(): - # Create a client - client = dialogflow_v2.EnvironmentsClient() - - # Initialize request argument(s) - request = dialogflow_v2.ListEnvironmentsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_environments(request=request) - - # Handle the response - for response in page_result: - print(response) - - Args: - request (Union[google.cloud.dialogflow_v2.types.ListEnvironmentsRequest, dict]): - 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. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.dialogflow_v2.services.environments.pagers.ListEnvironmentsPager: - The response message for - [Environments.ListEnvironments][google.cloud.dialogflow.v2.Environments.ListEnvironments]. - - Iterating over this object will yield results and - resolve additional pages automatically. - - """ - # Create or coerce a protobuf request object. - # Quick 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. - # There's no risk of modifying the input as we've already verified - # 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. - rpc = self._transport._wrapped_methods[self._transport.list_environments] - - # 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.ListEnvironmentsPager( - method=rpc, - request=request, - response=response, - metadata=metadata, - ) - - # Done; return the response. - return response - - def get_environment(self, - request: Optional[Union[environment.GetEnvironmentRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> environment.Environment: - r"""Retrieves the specified agent environment. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import dialogflow_v2 - - def sample_get_environment(): - # Create a client - client = dialogflow_v2.EnvironmentsClient() - - # Initialize request argument(s) - request = dialogflow_v2.GetEnvironmentRequest( - name="name_value", - ) - - # Make the request - response = client.get_environment(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.dialogflow_v2.types.GetEnvironmentRequest, dict]): - 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: Optional[Union[environment.CreateEnvironmentRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> environment.Environment: - r"""Creates an agent environment. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import dialogflow_v2 - - def sample_create_environment(): - # Create a client - client = dialogflow_v2.EnvironmentsClient() - - # Initialize request argument(s) - request = dialogflow_v2.CreateEnvironmentRequest( - parent="parent_value", - environment_id="environment_id_value", - ) - - # Make the request - response = client.create_environment(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.dialogflow_v2.types.CreateEnvironmentRequest, dict]): - 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: Optional[Union[environment.UpdateEnvironmentRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - 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 continues 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 - an agent version in the default environment. WARNING: this will - negate all recent changes to the draft agent and can't be - undone. You may want to save the draft agent to a version before - calling this method. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import dialogflow_v2 - - def sample_update_environment(): - # Create a client - client = dialogflow_v2.EnvironmentsClient() - - # Initialize request argument(s) - request = dialogflow_v2.UpdateEnvironmentRequest( - ) - - # Make the request - response = client.update_environment(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.dialogflow_v2.types.UpdateEnvironmentRequest, dict]): - 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: Optional[Union[environment.DeleteEnvironmentRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> None: - r"""Deletes the specified agent environment. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import dialogflow_v2 - - def sample_delete_environment(): - # Create a client - client = dialogflow_v2.EnvironmentsClient() - - # Initialize request argument(s) - request = dialogflow_v2.DeleteEnvironmentRequest( - name="name_value", - ) - - # Make the request - client.delete_environment(request=request) - - Args: - request (Union[google.cloud.dialogflow_v2.types.DeleteEnvironmentRequest, dict]): - 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: Optional[Union[environment.GetEnvironmentHistoryRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.GetEnvironmentHistoryPager: - r"""Gets the history of the specified environment. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import dialogflow_v2 - - def sample_get_environment_history(): - # Create a client - client = dialogflow_v2.EnvironmentsClient() - - # Initialize request argument(s) - request = dialogflow_v2.GetEnvironmentHistoryRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.get_environment_history(request=request) - - # Handle the response - for response in page_result: - print(response) - - Args: - request (Union[google.cloud.dialogflow_v2.types.GetEnvironmentHistoryRequest, dict]): - 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 - - def __enter__(self) -> "EnvironmentsClient": - return self - - def __exit__(self, type, value, traceback): - """Releases underlying transport's resources. - - .. warning:: - ONLY use as a context manager if the transport is NOT shared - with other clients! Exiting the with block will CLOSE the transport - and may cause errors in other clients! - """ - self.transport.close() - - def list_operations( - self, - request: Optional[operations_pb2.ListOperationsRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operations_pb2.ListOperationsResponse: - r"""Lists operations that match the specified filter in the request. - - Args: - request (:class:`~.operations_pb2.ListOperationsRequest`): - The request object. Request message for - `ListOperations` method. - 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: - ~.operations_pb2.ListOperationsResponse: - Response message for ``ListOperations`` method. - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = operations_pb2.ListOperationsRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._transport.list_operations, - 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 = rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - def get_operation( - self, - request: Optional[operations_pb2.GetOperationRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operations_pb2.Operation: - r"""Gets the latest state of a long-running operation. - - Args: - request (:class:`~.operations_pb2.GetOperationRequest`): - The request object. Request message for - `GetOperation` method. - 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: - ~.operations_pb2.Operation: - An ``Operation`` object. - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = operations_pb2.GetOperationRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._transport.get_operation, - 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 = rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - def cancel_operation( - self, - request: Optional[operations_pb2.CancelOperationRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> None: - r"""Starts asynchronous cancellation on a long-running operation. - - The server makes a best effort to cancel the operation, but success - is not guaranteed. If the server doesn't support this method, it returns - `google.rpc.Code.UNIMPLEMENTED`. - - Args: - request (:class:`~.operations_pb2.CancelOperationRequest`): - The request object. Request message for - `CancelOperation` method. - 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: - None - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = operations_pb2.CancelOperationRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._transport.cancel_operation, - 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. - rpc(request, retry=retry, timeout=timeout, metadata=metadata,) - - def get_location( - self, - request: Optional[locations_pb2.GetLocationRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> locations_pb2.Location: - r"""Gets information about a location. - - Args: - request (:class:`~.location_pb2.GetLocationRequest`): - The request object. Request message for - `GetLocation` method. - 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: - ~.location_pb2.Location: - Location object. - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = locations_pb2.GetLocationRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._transport.get_location, - 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 = rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - def list_locations( - self, - request: Optional[locations_pb2.ListLocationsRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> locations_pb2.ListLocationsResponse: - r"""Lists information about the supported locations for this service. - - Args: - request (:class:`~.location_pb2.ListLocationsRequest`): - The request object. Request message for - `ListLocations` method. - 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: - ~.location_pb2.ListLocationsResponse: - Response message for ``ListLocations`` method. - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = locations_pb2.ListLocationsRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._transport.list_locations, - 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 = rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) - - -__all__ = ( - "EnvironmentsClient", -) diff --git a/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/environments/pagers.py b/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/environments/pagers.py deleted file mode 100644 index 75003e32f..000000000 --- a/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/environments/pagers.py +++ /dev/null @@ -1,260 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from typing import Any, AsyncIterator, Awaitable, Callable, Sequence, Tuple, Optional, Iterator - -from google.cloud.dialogflow_v2.types import environment - - -class ListEnvironmentsPager: - """A pager for iterating through ``list_environments`` requests. - - This class thinly wraps an initial - :class:`google.cloud.dialogflow_v2.types.ListEnvironmentsResponse` object, and - provides an ``__iter__`` method to iterate through its - ``environments`` field. - - If there are more pages, the ``__iter__`` method will make additional - ``ListEnvironments`` requests and continue to iterate - through the ``environments`` field on the - corresponding responses. - - All the usual :class:`google.cloud.dialogflow_v2.types.ListEnvironmentsResponse` - 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.ListEnvironmentsResponse], - request: environment.ListEnvironmentsRequest, - response: environment.ListEnvironmentsResponse, - *, - 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.ListEnvironmentsRequest): - The initial request object. - response (google.cloud.dialogflow_v2.types.ListEnvironmentsResponse): - 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.ListEnvironmentsRequest(request) - self._response = response - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - def pages(self) -> Iterator[environment.ListEnvironmentsResponse]: - yield self._response - while self._response.next_page_token: - self._request.page_token = self._response.next_page_token - self._response = self._method(self._request, metadata=self._metadata) - yield self._response - - def __iter__(self) -> Iterator[environment.Environment]: - for page in self.pages: - yield from page.environments - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListEnvironmentsAsyncPager: - """A pager for iterating through ``list_environments`` requests. - - This class thinly wraps an initial - :class:`google.cloud.dialogflow_v2.types.ListEnvironmentsResponse` object, and - provides an ``__aiter__`` method to iterate through its - ``environments`` field. - - If there are more pages, the ``__aiter__`` method will make additional - ``ListEnvironments`` requests and continue to iterate - through the ``environments`` field on the - corresponding responses. - - All the usual :class:`google.cloud.dialogflow_v2.types.ListEnvironmentsResponse` - 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.ListEnvironmentsResponse]], - request: environment.ListEnvironmentsRequest, - response: environment.ListEnvironmentsResponse, - *, - metadata: Sequence[Tuple[str, str]] = ()): - """Instantiates the pager. - - Args: - method (Callable): The method that was originally called, and - which instantiated this pager. - request (google.cloud.dialogflow_v2.types.ListEnvironmentsRequest): - The initial request object. - response (google.cloud.dialogflow_v2.types.ListEnvironmentsResponse): - 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.ListEnvironmentsRequest(request) - self._response = response - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - async def pages(self) -> AsyncIterator[environment.ListEnvironmentsResponse]: - yield self._response - while self._response.next_page_token: - self._request.page_token = self._response.next_page_token - self._response = await self._method(self._request, metadata=self._metadata) - yield self._response - def __aiter__(self) -> AsyncIterator[environment.Environment]: - async def async_generator(): - async for page in self.pages: - for response in page.environments: - yield response - - return 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) -> Iterator[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) -> Iterator[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]] = ()): - """Instantiates 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) -> AsyncIterator[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) -> AsyncIterator[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/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/environments/transports/__init__.py b/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/environments/transports/__init__.py deleted file mode 100644 index 9384fe0b2..000000000 --- a/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/environments/transports/__init__.py +++ /dev/null @@ -1,38 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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 EnvironmentsTransport -from .grpc import EnvironmentsGrpcTransport -from .grpc_asyncio import EnvironmentsGrpcAsyncIOTransport -from .rest import EnvironmentsRestTransport -from .rest import EnvironmentsRestInterceptor - - -# Compile a registry of transports. -_transport_registry = OrderedDict() # type: Dict[str, Type[EnvironmentsTransport]] -_transport_registry['grpc'] = EnvironmentsGrpcTransport -_transport_registry['grpc_asyncio'] = EnvironmentsGrpcAsyncIOTransport -_transport_registry['rest'] = EnvironmentsRestTransport - -__all__ = ( - 'EnvironmentsTransport', - 'EnvironmentsGrpcTransport', - 'EnvironmentsGrpcAsyncIOTransport', - 'EnvironmentsRestTransport', - 'EnvironmentsRestInterceptor', -) diff --git a/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/environments/transports/base.py b/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/environments/transports/base.py deleted file mode 100644 index 7addb3a7b..000000000 --- a/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/environments/transports/base.py +++ /dev/null @@ -1,265 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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 - -from google.cloud.dialogflow_v2 import gapic_version as package_version - -import google.auth # type: ignore -import google.api_core -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import retry as retries -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 environment -from google.cloud.location import locations_pb2 # type: ignore -from google.longrunning import operations_pb2 -from google.protobuf import empty_pb2 # type: ignore - -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) - - -class EnvironmentsTransport(abc.ABC): - """Abstract transport class for Environments.""" - - 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: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - api_audience: Optional[str] = None, - **kwargs, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. - scopes (Optional[Sequence[str]]): A list of scopes. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - """ - - scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} - - # Save the scopes. - self._scopes = scopes - - # If no credentials are provided, then determine the appropriate - # defaults. - if credentials and credentials_file: - raise core_exceptions.DuplicateCredentialArgs("'credentials_file' and 'credentials' are mutually exclusive") - - if credentials_file is not None: - credentials, _ = google.auth.load_credentials_from_file( - credentials_file, - **scopes_kwargs, - quota_project_id=quota_project_id - ) - elif credentials is None: - credentials, _ = google.auth.default(**scopes_kwargs, quota_project_id=quota_project_id) - # Don't apply audience if the credentials file passed from user. - if hasattr(credentials, "with_gdch_audience"): - credentials = credentials.with_gdch_audience(api_audience if api_audience else host) - - # If the credentials are service account credentials, then always try to use self signed JWT. - if always_use_jwt_access and isinstance(credentials, service_account.Credentials) and hasattr(service_account.Credentials, "with_always_use_jwt_access"): - credentials = credentials.with_always_use_jwt_access(True) - - # Save the credentials. - self._credentials = credentials - - # Save the hostname. Default to port 443 (HTTPS) if none is specified. - if ':' not in host: - host += ':443' - self._host = host - - 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, - ), - } - - def close(self): - """Closes resources associated with the transport. - - .. warning:: - Only call this method if the transport is NOT shared - with other clients - this may cause errors in other clients! - """ - raise NotImplementedError() - - @property - def list_environments(self) -> Callable[ - [environment.ListEnvironmentsRequest], - Union[ - 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() - - @property - def list_operations( - self, - ) -> Callable[ - [operations_pb2.ListOperationsRequest], - Union[operations_pb2.ListOperationsResponse, Awaitable[operations_pb2.ListOperationsResponse]], - ]: - raise NotImplementedError() - - @property - def get_operation( - self, - ) -> Callable[ - [operations_pb2.GetOperationRequest], - Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], - ]: - raise NotImplementedError() - - @property - def cancel_operation( - self, - ) -> Callable[ - [operations_pb2.CancelOperationRequest], - None, - ]: - raise NotImplementedError() - - @property - def get_location(self, - ) -> Callable[ - [locations_pb2.GetLocationRequest], - Union[locations_pb2.Location, Awaitable[locations_pb2.Location]], - ]: - raise NotImplementedError() - - @property - def list_locations(self, - ) -> Callable[ - [locations_pb2.ListLocationsRequest], - Union[locations_pb2.ListLocationsResponse, Awaitable[locations_pb2.ListLocationsResponse]], - ]: - raise NotImplementedError() - - @property - def kind(self) -> str: - raise NotImplementedError() - - -__all__ = ( - 'EnvironmentsTransport', -) diff --git a/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/environments/transports/grpc.py b/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/environments/transports/grpc.py deleted file mode 100644 index 22892bba2..000000000 --- a/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/environments/transports/grpc.py +++ /dev/null @@ -1,502 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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 -from google.api_core import gapic_v1 -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.cloud.location import locations_pb2 # type: ignore -from google.longrunning import operations_pb2 -from google.protobuf import empty_pb2 # type: ignore -from .base import EnvironmentsTransport, DEFAULT_CLIENT_INFO - - -class EnvironmentsGrpcTransport(EnvironmentsTransport): - """gRPC backend transport for Environments. - - Service for managing - [Environments][google.cloud.dialogflow.v2.Environment]. - - 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: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - channel: Optional[grpc.Channel] = None, - api_mtls_endpoint: Optional[str] = None, - client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, - ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, - client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - api_audience: Optional[str] = None, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - This argument is ignored if ``channel`` is provided. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional(Sequence[str])): A list of scopes. This argument is - ignored if ``channel`` is provided. - channel (Optional[grpc.Channel]): A ``Channel`` instance through - which to make calls. - api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. - If provided, it overrides the ``host`` argument and tries to create - a mutual TLS channel with client SSL credentials from - ``client_cert_source`` or application default SSL credentials. - client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): - Deprecated. A callback to provide client SSL certificate bytes and - private key bytes, both in PEM format. It is ignored if - ``api_mtls_endpoint`` is None. - ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials - for the grpc channel. It is ignored if ``channel`` is provided. - client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): - A callback to provide client certificate bytes and private key bytes, - both in PEM format. It is used to configure a mutual TLS channel. It is - ignored if ``channel`` or ``ssl_channel_credentials`` is provided. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport - creation failed for any reason. - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - self._grpc_channel = None - self._ssl_channel_credentials = ssl_channel_credentials - self._stubs: Dict[str, Callable] = {} - - if api_mtls_endpoint: - warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) - if client_cert_source: - warnings.warn("client_cert_source is deprecated", DeprecationWarning) - - if channel: - # Ignore credentials if a channel was passed. - credentials = False - # If a channel was explicitly provided, set it. - self._grpc_channel = channel - self._ssl_channel_credentials = None - - else: - if api_mtls_endpoint: - host = api_mtls_endpoint - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - self._ssl_channel_credentials = SslCredentials().ssl_credentials - - else: - if client_cert_source_for_mtls and not ssl_channel_credentials: - cert, key = client_cert_source_for_mtls() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - - # The base transport sets the host, credentials and scopes - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes, - quota_project_id=quota_project_id, - client_info=client_info, - always_use_jwt_access=always_use_jwt_access, - api_audience=api_audience, - ) - - if not self._grpc_channel: - self._grpc_channel = type(self).create_channel( - self._host, - # use the credentials which are saved - credentials=self._credentials, - # Set ``credentials_file`` to ``None`` here as - # the credentials that we saved earlier should be used. - credentials_file=None, - 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: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - **kwargs) -> grpc.Channel: - """Create and return a gRPC channel object. - Args: - host (Optional[str]): The host for the channel to use. - credentials (Optional[~.Credentials]): The - authorization credentials to attach to requests. These - credentials identify this application to the service. If - none are specified, the client will attempt to ascertain - the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - kwargs (Optional[dict]): Keyword arguments, which are passed to the - channel creation. - Returns: - grpc.Channel: A gRPC channel object. - - Raises: - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - - return grpc_helpers.create_channel( - host, - credentials=credentials, - credentials_file=credentials_file, - quota_project_id=quota_project_id, - default_scopes=cls.AUTH_SCOPES, - scopes=scopes, - default_host=cls.DEFAULT_HOST, - **kwargs - ) - - @property - def grpc_channel(self) -> grpc.Channel: - """Return the channel designed to connect to this service. - """ - return self._grpc_channel - - @property - def list_environments(self) -> Callable[ - [environment.ListEnvironmentsRequest], - environment.ListEnvironmentsResponse]: - r"""Return a callable for the list environments method over gRPC. - - Returns the list of all non-default environments of - the specified agent. - - Returns: - Callable[[~.ListEnvironmentsRequest], - ~.ListEnvironmentsResponse]: - 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_environments' not in self._stubs: - self._stubs['list_environments'] = self.grpc_channel.unary_unary( - '/google.cloud.dialogflow.v2.Environments/ListEnvironments', - request_serializer=environment.ListEnvironmentsRequest.serialize, - response_deserializer=environment.ListEnvironmentsResponse.deserialize, - ) - 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 continues 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 - an agent version in the default environment. WARNING: this will - negate all recent changes to the draft agent and can't be - undone. You may want to save the draft agent to a version before - calling this method. - - 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'] - - def close(self): - self.grpc_channel.close() - - @property - def cancel_operation( - self, - ) -> Callable[[operations_pb2.CancelOperationRequest], None]: - r"""Return a callable for the cancel_operation method over gRPC. - """ - # 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 "cancel_operation" not in self._stubs: - self._stubs["cancel_operation"] = self.grpc_channel.unary_unary( - "/google.longrunning.Operations/CancelOperation", - request_serializer=operations_pb2.CancelOperationRequest.SerializeToString, - response_deserializer=None, - ) - return self._stubs["cancel_operation"] - - @property - def get_operation( - self, - ) -> Callable[[operations_pb2.GetOperationRequest], operations_pb2.Operation]: - r"""Return a callable for the get_operation method over gRPC. - """ - # 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_operation" not in self._stubs: - self._stubs["get_operation"] = self.grpc_channel.unary_unary( - "/google.longrunning.Operations/GetOperation", - request_serializer=operations_pb2.GetOperationRequest.SerializeToString, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs["get_operation"] - - @property - def list_operations( - self, - ) -> Callable[[operations_pb2.ListOperationsRequest], operations_pb2.ListOperationsResponse]: - r"""Return a callable for the list_operations method over gRPC. - """ - # 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_operations" not in self._stubs: - self._stubs["list_operations"] = self.grpc_channel.unary_unary( - "/google.longrunning.Operations/ListOperations", - request_serializer=operations_pb2.ListOperationsRequest.SerializeToString, - response_deserializer=operations_pb2.ListOperationsResponse.FromString, - ) - return self._stubs["list_operations"] - - @property - def list_locations( - self, - ) -> Callable[[locations_pb2.ListLocationsRequest], locations_pb2.ListLocationsResponse]: - r"""Return a callable for the list locations method over gRPC. - """ - # 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_locations" not in self._stubs: - self._stubs["list_locations"] = self.grpc_channel.unary_unary( - "/google.cloud.location.Locations/ListLocations", - request_serializer=locations_pb2.ListLocationsRequest.SerializeToString, - response_deserializer=locations_pb2.ListLocationsResponse.FromString, - ) - return self._stubs["list_locations"] - - @property - def get_location( - self, - ) -> Callable[[locations_pb2.GetLocationRequest], locations_pb2.Location]: - r"""Return a callable for the list locations method over gRPC. - """ - # 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_location" not in self._stubs: - self._stubs["get_location"] = self.grpc_channel.unary_unary( - "/google.cloud.location.Locations/GetLocation", - request_serializer=locations_pb2.GetLocationRequest.SerializeToString, - response_deserializer=locations_pb2.Location.FromString, - ) - return self._stubs["get_location"] - - @property - def kind(self) -> str: - return "grpc" - - -__all__ = ( - 'EnvironmentsGrpcTransport', -) diff --git a/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/environments/transports/grpc_asyncio.py b/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/environments/transports/grpc_asyncio.py deleted file mode 100644 index 38ed11d45..000000000 --- a/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/environments/transports/grpc_asyncio.py +++ /dev/null @@ -1,501 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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 -from google.api_core import grpc_helpers_async -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore - -import grpc # type: ignore -from grpc.experimental import aio # type: ignore - -from google.cloud.dialogflow_v2.types import environment -from google.cloud.location import locations_pb2 # type: ignore -from google.longrunning import operations_pb2 -from google.protobuf import empty_pb2 # type: ignore -from .base import EnvironmentsTransport, DEFAULT_CLIENT_INFO -from .grpc import EnvironmentsGrpcTransport - - -class EnvironmentsGrpcAsyncIOTransport(EnvironmentsTransport): - """gRPC AsyncIO backend transport for Environments. - - Service for managing - [Environments][google.cloud.dialogflow.v2.Environment]. - - 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: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - **kwargs) -> aio.Channel: - """Create and return a gRPC AsyncIO channel object. - Args: - host (Optional[str]): The host for the channel to use. - credentials (Optional[~.Credentials]): The - authorization credentials to attach to requests. These - credentials identify this application to the service. If - none are specified, the client will attempt to ascertain - the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - kwargs (Optional[dict]): Keyword arguments, which are passed to the - channel creation. - Returns: - aio.Channel: A gRPC AsyncIO channel object. - """ - - return grpc_helpers_async.create_channel( - host, - credentials=credentials, - credentials_file=credentials_file, - quota_project_id=quota_project_id, - default_scopes=cls.AUTH_SCOPES, - scopes=scopes, - default_host=cls.DEFAULT_HOST, - **kwargs - ) - - def __init__(self, *, - host: str = 'dialogflow.googleapis.com', - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - channel: Optional[aio.Channel] = None, - api_mtls_endpoint: Optional[str] = None, - client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, - ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, - client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - api_audience: Optional[str] = None, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - This argument is ignored if ``channel`` is provided. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - channel (Optional[aio.Channel]): A ``Channel`` instance through - which to make calls. - api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. - If provided, it overrides the ``host`` argument and tries to create - a mutual TLS channel with client SSL credentials from - ``client_cert_source`` or application default SSL credentials. - client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): - Deprecated. A callback to provide client SSL certificate bytes and - private key bytes, both in PEM format. It is ignored if - ``api_mtls_endpoint`` is None. - ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials - for the grpc channel. It is ignored if ``channel`` is provided. - client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): - A callback to provide client certificate bytes and private key bytes, - both in PEM format. It is used to configure a mutual TLS channel. It is - ignored if ``channel`` or ``ssl_channel_credentials`` is provided. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - - Raises: - google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport - creation failed for any reason. - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - self._grpc_channel = None - self._ssl_channel_credentials = ssl_channel_credentials - self._stubs: Dict[str, Callable] = {} - - if api_mtls_endpoint: - warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) - if client_cert_source: - warnings.warn("client_cert_source is deprecated", DeprecationWarning) - - if channel: - # Ignore credentials if a channel was passed. - credentials = False - # If a channel was explicitly provided, set it. - self._grpc_channel = channel - self._ssl_channel_credentials = None - else: - if api_mtls_endpoint: - host = api_mtls_endpoint - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - self._ssl_channel_credentials = SslCredentials().ssl_credentials - - else: - if client_cert_source_for_mtls and not ssl_channel_credentials: - cert, key = client_cert_source_for_mtls() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - - # The base transport sets the host, credentials and scopes - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes, - quota_project_id=quota_project_id, - client_info=client_info, - always_use_jwt_access=always_use_jwt_access, - api_audience=api_audience, - ) - - if not self._grpc_channel: - self._grpc_channel = type(self).create_channel( - self._host, - # use the credentials which are saved - credentials=self._credentials, - # Set ``credentials_file`` to ``None`` here as - # the credentials that we saved earlier should be used. - credentials_file=None, - 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_environments(self) -> Callable[ - [environment.ListEnvironmentsRequest], - Awaitable[environment.ListEnvironmentsResponse]]: - r"""Return a callable for the list environments method over gRPC. - - Returns the list of all non-default environments of - the specified agent. - - Returns: - Callable[[~.ListEnvironmentsRequest], - Awaitable[~.ListEnvironmentsResponse]]: - 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_environments' not in self._stubs: - self._stubs['list_environments'] = self.grpc_channel.unary_unary( - '/google.cloud.dialogflow.v2.Environments/ListEnvironments', - request_serializer=environment.ListEnvironmentsRequest.serialize, - response_deserializer=environment.ListEnvironmentsResponse.deserialize, - ) - 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 continues 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 - an agent version in the default environment. WARNING: this will - negate all recent changes to the draft agent and can't be - undone. You may want to save the draft agent to a version before - calling this method. - - 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'] - - def close(self): - return self.grpc_channel.close() - - @property - def cancel_operation( - self, - ) -> Callable[[operations_pb2.CancelOperationRequest], None]: - r"""Return a callable for the cancel_operation method over gRPC. - """ - # 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 "cancel_operation" not in self._stubs: - self._stubs["cancel_operation"] = self.grpc_channel.unary_unary( - "/google.longrunning.Operations/CancelOperation", - request_serializer=operations_pb2.CancelOperationRequest.SerializeToString, - response_deserializer=None, - ) - return self._stubs["cancel_operation"] - - @property - def get_operation( - self, - ) -> Callable[[operations_pb2.GetOperationRequest], operations_pb2.Operation]: - r"""Return a callable for the get_operation method over gRPC. - """ - # 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_operation" not in self._stubs: - self._stubs["get_operation"] = self.grpc_channel.unary_unary( - "/google.longrunning.Operations/GetOperation", - request_serializer=operations_pb2.GetOperationRequest.SerializeToString, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs["get_operation"] - - @property - def list_operations( - self, - ) -> Callable[[operations_pb2.ListOperationsRequest], operations_pb2.ListOperationsResponse]: - r"""Return a callable for the list_operations method over gRPC. - """ - # 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_operations" not in self._stubs: - self._stubs["list_operations"] = self.grpc_channel.unary_unary( - "/google.longrunning.Operations/ListOperations", - request_serializer=operations_pb2.ListOperationsRequest.SerializeToString, - response_deserializer=operations_pb2.ListOperationsResponse.FromString, - ) - return self._stubs["list_operations"] - - @property - def list_locations( - self, - ) -> Callable[[locations_pb2.ListLocationsRequest], locations_pb2.ListLocationsResponse]: - r"""Return a callable for the list locations method over gRPC. - """ - # 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_locations" not in self._stubs: - self._stubs["list_locations"] = self.grpc_channel.unary_unary( - "/google.cloud.location.Locations/ListLocations", - request_serializer=locations_pb2.ListLocationsRequest.SerializeToString, - response_deserializer=locations_pb2.ListLocationsResponse.FromString, - ) - return self._stubs["list_locations"] - - @property - def get_location( - self, - ) -> Callable[[locations_pb2.GetLocationRequest], locations_pb2.Location]: - r"""Return a callable for the list locations method over gRPC. - """ - # 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_location" not in self._stubs: - self._stubs["get_location"] = self.grpc_channel.unary_unary( - "/google.cloud.location.Locations/GetLocation", - request_serializer=locations_pb2.GetLocationRequest.SerializeToString, - response_deserializer=locations_pb2.Location.FromString, - ) - return self._stubs["get_location"] - - -__all__ = ( - 'EnvironmentsGrpcAsyncIOTransport', -) diff --git a/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/environments/transports/rest.py b/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/environments/transports/rest.py deleted file mode 100644 index 696ed7519..000000000 --- a/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/environments/transports/rest.py +++ /dev/null @@ -1,1361 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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 google.auth.transport.requests import AuthorizedSession # type: ignore -import json # type: ignore -import grpc # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore -from google.auth import credentials as ga_credentials # type: ignore -from google.api_core import exceptions as core_exceptions -from google.api_core import retry as retries -from google.api_core import rest_helpers -from google.api_core import rest_streaming -from google.api_core import path_template -from google.api_core import gapic_v1 - -from google.protobuf import json_format -from google.cloud.location import locations_pb2 # type: ignore -from google.longrunning import operations_pb2 -from requests import __version__ as requests_version -import dataclasses -import re -from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union -import warnings - -try: - OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] -except AttributeError: # pragma: NO COVER - OptionalRetry = Union[retries.Retry, object] # 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 as BASE_DEFAULT_CLIENT_INFO - - -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=BASE_DEFAULT_CLIENT_INFO.gapic_version, - grpc_version=None, - rest_version=requests_version, -) - - -class EnvironmentsRestInterceptor: - """Interceptor for Environments. - - Interceptors are used to manipulate requests, request metadata, and responses - in arbitrary ways. - Example use cases include: - * Logging - * Verifying requests according to service or custom semantics - * Stripping extraneous information from responses - - These use cases and more can be enabled by injecting an - instance of a custom subclass when constructing the EnvironmentsRestTransport. - - .. code-block:: python - class MyCustomEnvironmentsInterceptor(EnvironmentsRestInterceptor): - def pre_create_environment(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_create_environment(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_delete_environment(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def pre_get_environment(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_get_environment(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_get_environment_history(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_get_environment_history(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_list_environments(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_list_environments(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_update_environment(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_update_environment(self, response): - logging.log(f"Received response: {response}") - return response - - transport = EnvironmentsRestTransport(interceptor=MyCustomEnvironmentsInterceptor()) - client = EnvironmentsClient(transport=transport) - - - """ - def pre_create_environment(self, request: environment.CreateEnvironmentRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[environment.CreateEnvironmentRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for create_environment - - Override in a subclass to manipulate the request or metadata - before they are sent to the Environments server. - """ - return request, metadata - - def post_create_environment(self, response: environment.Environment) -> environment.Environment: - """Post-rpc interceptor for create_environment - - Override in a subclass to manipulate the response - after it is returned by the Environments server but before - it is returned to user code. - """ - return response - def pre_delete_environment(self, request: environment.DeleteEnvironmentRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[environment.DeleteEnvironmentRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for delete_environment - - Override in a subclass to manipulate the request or metadata - before they are sent to the Environments server. - """ - return request, metadata - - def pre_get_environment(self, request: environment.GetEnvironmentRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[environment.GetEnvironmentRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for get_environment - - Override in a subclass to manipulate the request or metadata - before they are sent to the Environments server. - """ - return request, metadata - - def post_get_environment(self, response: environment.Environment) -> environment.Environment: - """Post-rpc interceptor for get_environment - - Override in a subclass to manipulate the response - after it is returned by the Environments server but before - it is returned to user code. - """ - return response - def pre_get_environment_history(self, request: environment.GetEnvironmentHistoryRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[environment.GetEnvironmentHistoryRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for get_environment_history - - Override in a subclass to manipulate the request or metadata - before they are sent to the Environments server. - """ - return request, metadata - - def post_get_environment_history(self, response: environment.EnvironmentHistory) -> environment.EnvironmentHistory: - """Post-rpc interceptor for get_environment_history - - Override in a subclass to manipulate the response - after it is returned by the Environments server but before - it is returned to user code. - """ - return response - def pre_list_environments(self, request: environment.ListEnvironmentsRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[environment.ListEnvironmentsRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for list_environments - - Override in a subclass to manipulate the request or metadata - before they are sent to the Environments server. - """ - return request, metadata - - def post_list_environments(self, response: environment.ListEnvironmentsResponse) -> environment.ListEnvironmentsResponse: - """Post-rpc interceptor for list_environments - - Override in a subclass to manipulate the response - after it is returned by the Environments server but before - it is returned to user code. - """ - return response - def pre_update_environment(self, request: environment.UpdateEnvironmentRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[environment.UpdateEnvironmentRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for update_environment - - Override in a subclass to manipulate the request or metadata - before they are sent to the Environments server. - """ - return request, metadata - - def post_update_environment(self, response: environment.Environment) -> environment.Environment: - """Post-rpc interceptor for update_environment - - Override in a subclass to manipulate the response - after it is returned by the Environments server but before - it is returned to user code. - """ - return response - - def pre_get_location( - self, request: locations_pb2.GetLocationRequest, metadata: Sequence[Tuple[str, str]] - ) -> Tuple[locations_pb2.GetLocationRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for get_location - - Override in a subclass to manipulate the request or metadata - before they are sent to the Environments server. - """ - return request, metadata - - def post_get_location( - self, response: locations_pb2.Location - ) -> locations_pb2.Location: - """Post-rpc interceptor for get_location - - Override in a subclass to manipulate the response - after it is returned by the Environments server but before - it is returned to user code. - """ - return response - def pre_list_locations( - self, request: locations_pb2.ListLocationsRequest, metadata: Sequence[Tuple[str, str]] - ) -> Tuple[locations_pb2.ListLocationsRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for list_locations - - Override in a subclass to manipulate the request or metadata - before they are sent to the Environments server. - """ - return request, metadata - - def post_list_locations( - self, response: locations_pb2.ListLocationsResponse - ) -> locations_pb2.ListLocationsResponse: - """Post-rpc interceptor for list_locations - - Override in a subclass to manipulate the response - after it is returned by the Environments server but before - it is returned to user code. - """ - return response - def pre_cancel_operation( - self, request: operations_pb2.CancelOperationRequest, metadata: Sequence[Tuple[str, str]] - ) -> Tuple[operations_pb2.CancelOperationRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for cancel_operation - - Override in a subclass to manipulate the request or metadata - before they are sent to the Environments server. - """ - return request, metadata - - def post_cancel_operation( - self, response: None - ) -> None: - """Post-rpc interceptor for cancel_operation - - Override in a subclass to manipulate the response - after it is returned by the Environments server but before - it is returned to user code. - """ - return response - def pre_get_operation( - self, request: operations_pb2.GetOperationRequest, metadata: Sequence[Tuple[str, str]] - ) -> Tuple[operations_pb2.GetOperationRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for get_operation - - Override in a subclass to manipulate the request or metadata - before they are sent to the Environments server. - """ - return request, metadata - - def post_get_operation( - self, response: operations_pb2.Operation - ) -> operations_pb2.Operation: - """Post-rpc interceptor for get_operation - - Override in a subclass to manipulate the response - after it is returned by the Environments server but before - it is returned to user code. - """ - return response - def pre_list_operations( - self, request: operations_pb2.ListOperationsRequest, metadata: Sequence[Tuple[str, str]] - ) -> Tuple[operations_pb2.ListOperationsRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for list_operations - - Override in a subclass to manipulate the request or metadata - before they are sent to the Environments server. - """ - return request, metadata - - def post_list_operations( - self, response: operations_pb2.ListOperationsResponse - ) -> operations_pb2.ListOperationsResponse: - """Post-rpc interceptor for list_operations - - Override in a subclass to manipulate the response - after it is returned by the Environments server but before - it is returned to user code. - """ - return response - - -@dataclasses.dataclass -class EnvironmentsRestStub: - _session: AuthorizedSession - _host: str - _interceptor: EnvironmentsRestInterceptor - - -class EnvironmentsRestTransport(EnvironmentsTransport): - """REST backend transport for Environments. - - Service for managing - [Environments][google.cloud.dialogflow.v2.Environment]. - - 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 JSON representations of protocol buffers over HTTP/1.1 - - """ - - def __init__(self, *, - host: str = 'dialogflow.googleapis.com', - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - client_cert_source_for_mtls: Optional[Callable[[ - ], Tuple[bytes, bytes]]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - url_scheme: str = 'https', - interceptor: Optional[EnvironmentsRestInterceptor] = None, - api_audience: Optional[str] = None, - ) -> 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 ignored if ``channel`` is provided. - scopes (Optional(Sequence[str])): A list of scopes. This argument is - ignored if ``channel`` is provided. - client_cert_source_for_mtls (Callable[[], Tuple[bytes, bytes]]): Client - certificate to configure mutual TLS HTTP channel. It is ignored - if ``channel`` is provided. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you are developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - url_scheme: the protocol scheme for the API endpoint. Normally - "https", but for testing or local servers, - "http" can be specified. - """ - # Run the base constructor - # TODO(yon-mg): resolve other ctor params i.e. scopes, quota, etc. - # TODO: When custom host (api_endpoint) is set, `scopes` must *also* be set on the - # credentials object - maybe_url_match = re.match("^(?Phttp(?:s)?://)?(?P.*)$", host) - if maybe_url_match is None: - raise ValueError(f"Unexpected hostname structure: {host}") # pragma: NO COVER - - url_match_items = maybe_url_match.groupdict() - - host = f"{url_scheme}://{host}" if not url_match_items["scheme"] else host - - super().__init__( - host=host, - credentials=credentials, - client_info=client_info, - always_use_jwt_access=always_use_jwt_access, - api_audience=api_audience - ) - self._session = AuthorizedSession( - self._credentials, default_host=self.DEFAULT_HOST) - if client_cert_source_for_mtls: - self._session.configure_mtls_channel(client_cert_source_for_mtls) - self._interceptor = interceptor or EnvironmentsRestInterceptor() - self._prep_wrapped_messages(client_info) - - class _CreateEnvironment(EnvironmentsRestStub): - def __hash__(self): - return hash("CreateEnvironment") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - "environmentId" : "", } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: environment.CreateEnvironmentRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> environment.Environment: - r"""Call the create environment method over HTTP. - - Args: - request (~.environment.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: - ~.environment.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 `__. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'post', - 'uri': '/v2/{parent=projects/*/agent}/environments', - 'body': 'environment', - }, -{ - 'method': 'post', - 'uri': '/v2/{parent=projects/*/locations/*/agent}/environments', - 'body': 'environment', - }, - ] - request, metadata = self._interceptor.pre_create_environment(request, metadata) - pb_request = environment.CreateEnvironmentRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request['body'], - including_default_value_fields=False, - use_integers_for_enums=True - ) - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - including_default_value_fields=False, - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = environment.Environment() - pb_resp = environment.Environment.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_create_environment(resp) - return resp - - class _DeleteEnvironment(EnvironmentsRestStub): - def __hash__(self): - return hash("DeleteEnvironment") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: environment.DeleteEnvironmentRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ): - r"""Call the delete environment method over HTTP. - - Args: - request (~.environment.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. - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'delete', - 'uri': '/v2/{name=projects/*/agent/environments/*}', - }, -{ - 'method': 'delete', - 'uri': '/v2/{name=projects/*/locations/*/agent/environments/*}', - }, - ] - request, metadata = self._interceptor.pre_delete_environment(request, metadata) - pb_request = environment.DeleteEnvironmentRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - including_default_value_fields=False, - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - class _GetEnvironment(EnvironmentsRestStub): - def __hash__(self): - return hash("GetEnvironment") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: environment.GetEnvironmentRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> environment.Environment: - r"""Call the get environment method over HTTP. - - Args: - request (~.environment.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: - ~.environment.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 `__. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v2/{name=projects/*/agent/environments/*}', - }, -{ - 'method': 'get', - 'uri': '/v2/{name=projects/*/locations/*/agent/environments/*}', - }, - ] - request, metadata = self._interceptor.pre_get_environment(request, metadata) - pb_request = environment.GetEnvironmentRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - including_default_value_fields=False, - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = environment.Environment() - pb_resp = environment.Environment.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_get_environment(resp) - return resp - - class _GetEnvironmentHistory(EnvironmentsRestStub): - def __hash__(self): - return hash("GetEnvironmentHistory") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: environment.GetEnvironmentHistoryRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> environment.EnvironmentHistory: - r"""Call the get environment history method over HTTP. - - Args: - request (~.environment.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: - ~.environment.EnvironmentHistory: - The response message for - [Environments.GetEnvironmentHistory][google.cloud.dialogflow.v2.Environments.GetEnvironmentHistory]. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v2/{parent=projects/*/agent/environments/*}/history', - }, -{ - 'method': 'get', - 'uri': '/v2/{parent=projects/*/locations/*/agent/environments/*}/history', - }, - ] - request, metadata = self._interceptor.pre_get_environment_history(request, metadata) - pb_request = environment.GetEnvironmentHistoryRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - including_default_value_fields=False, - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = environment.EnvironmentHistory() - pb_resp = environment.EnvironmentHistory.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_get_environment_history(resp) - return resp - - class _ListEnvironments(EnvironmentsRestStub): - def __hash__(self): - return hash("ListEnvironments") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: environment.ListEnvironmentsRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> environment.ListEnvironmentsResponse: - r"""Call the list environments method over HTTP. - - Args: - request (~.environment.ListEnvironmentsRequest): - The request object. The request message for - [Environments.ListEnvironments][google.cloud.dialogflow.v2.Environments.ListEnvironments]. - 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: - ~.environment.ListEnvironmentsResponse: - The response message for - [Environments.ListEnvironments][google.cloud.dialogflow.v2.Environments.ListEnvironments]. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v2/{parent=projects/*/agent}/environments', - }, -{ - 'method': 'get', - 'uri': '/v2/{parent=projects/*/locations/*/agent}/environments', - }, - ] - request, metadata = self._interceptor.pre_list_environments(request, metadata) - pb_request = environment.ListEnvironmentsRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - including_default_value_fields=False, - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = environment.ListEnvironmentsResponse() - pb_resp = environment.ListEnvironmentsResponse.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_list_environments(resp) - return resp - - class _UpdateEnvironment(EnvironmentsRestStub): - def __hash__(self): - return hash("UpdateEnvironment") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - "updateMask" : {}, } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: environment.UpdateEnvironmentRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> environment.Environment: - r"""Call the update environment method over HTTP. - - Args: - request (~.environment.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: - ~.environment.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 `__. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'patch', - 'uri': '/v2/{environment.name=projects/*/agent/environments/*}', - 'body': 'environment', - }, -{ - 'method': 'patch', - 'uri': '/v2/{environment.name=projects/*/locations/*/agent/environments/*}', - 'body': 'environment', - }, - ] - request, metadata = self._interceptor.pre_update_environment(request, metadata) - pb_request = environment.UpdateEnvironmentRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request['body'], - including_default_value_fields=False, - use_integers_for_enums=True - ) - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - including_default_value_fields=False, - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = environment.Environment() - pb_resp = environment.Environment.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_update_environment(resp) - return resp - - @property - def create_environment(self) -> Callable[ - [environment.CreateEnvironmentRequest], - environment.Environment]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._CreateEnvironment(self._session, self._host, self._interceptor) # type: ignore - - @property - def delete_environment(self) -> Callable[ - [environment.DeleteEnvironmentRequest], - empty_pb2.Empty]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._DeleteEnvironment(self._session, self._host, self._interceptor) # type: ignore - - @property - def get_environment(self) -> Callable[ - [environment.GetEnvironmentRequest], - environment.Environment]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._GetEnvironment(self._session, self._host, self._interceptor) # type: ignore - - @property - def get_environment_history(self) -> Callable[ - [environment.GetEnvironmentHistoryRequest], - environment.EnvironmentHistory]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._GetEnvironmentHistory(self._session, self._host, self._interceptor) # type: ignore - - @property - def list_environments(self) -> Callable[ - [environment.ListEnvironmentsRequest], - environment.ListEnvironmentsResponse]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._ListEnvironments(self._session, self._host, self._interceptor) # type: ignore - - @property - def update_environment(self) -> Callable[ - [environment.UpdateEnvironmentRequest], - environment.Environment]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._UpdateEnvironment(self._session, self._host, self._interceptor) # type: ignore - - @property - def get_location(self): - return self._GetLocation(self._session, self._host, self._interceptor) # type: ignore - - class _GetLocation(EnvironmentsRestStub): - def __call__(self, - request: locations_pb2.GetLocationRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> locations_pb2.Location: - - r"""Call the get location method over HTTP. - - Args: - request (locations_pb2.GetLocationRequest): - The request object for GetLocation method. - 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: - locations_pb2.Location: Response from GetLocation method. - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v2/{name=projects/*/locations/*}', - }, - ] - - request, metadata = self._interceptor.pre_get_location(request, metadata) - request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode( - http_options, **request_kwargs) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json.dumps(transcoded_request['query_params'])) - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - resp = locations_pb2.Location() - resp = json_format.Parse(response.content.decode("utf-8"), resp) - resp = self._interceptor.post_get_location(resp) - return resp - - @property - def list_locations(self): - return self._ListLocations(self._session, self._host, self._interceptor) # type: ignore - - class _ListLocations(EnvironmentsRestStub): - def __call__(self, - request: locations_pb2.ListLocationsRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> locations_pb2.ListLocationsResponse: - - r"""Call the list locations method over HTTP. - - Args: - request (locations_pb2.ListLocationsRequest): - The request object for ListLocations method. - 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: - locations_pb2.ListLocationsResponse: Response from ListLocations method. - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v2/{name=projects/*}/locations', - }, - ] - - request, metadata = self._interceptor.pre_list_locations(request, metadata) - request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode( - http_options, **request_kwargs) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json.dumps(transcoded_request['query_params'])) - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - resp = locations_pb2.ListLocationsResponse() - resp = json_format.Parse(response.content.decode("utf-8"), resp) - resp = self._interceptor.post_list_locations(resp) - return resp - - @property - def cancel_operation(self): - return self._CancelOperation(self._session, self._host, self._interceptor) # type: ignore - - class _CancelOperation(EnvironmentsRestStub): - def __call__(self, - request: operations_pb2.CancelOperationRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> None: - - r"""Call the cancel operation method over HTTP. - - Args: - request (operations_pb2.CancelOperationRequest): - The request object for CancelOperation method. - 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. - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'post', - 'uri': '/v2/{name=projects/*/operations/*}:cancel', - }, -{ - 'method': 'post', - 'uri': '/v2/{name=projects/*/locations/*/operations/*}:cancel', - }, - ] - - request, metadata = self._interceptor.pre_cancel_operation(request, metadata) - request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode( - http_options, **request_kwargs) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json.dumps(transcoded_request['query_params'])) - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - return self._interceptor.post_cancel_operation(None) - - @property - def get_operation(self): - return self._GetOperation(self._session, self._host, self._interceptor) # type: ignore - - class _GetOperation(EnvironmentsRestStub): - def __call__(self, - request: operations_pb2.GetOperationRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> operations_pb2.Operation: - - r"""Call the get operation method over HTTP. - - Args: - request (operations_pb2.GetOperationRequest): - The request object for GetOperation method. - 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: - operations_pb2.Operation: Response from GetOperation method. - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v2/{name=projects/*/operations/*}', - }, -{ - 'method': 'get', - 'uri': '/v2/{name=projects/*/locations/*/operations/*}', - }, - ] - - request, metadata = self._interceptor.pre_get_operation(request, metadata) - request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode( - http_options, **request_kwargs) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json.dumps(transcoded_request['query_params'])) - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - resp = operations_pb2.Operation() - resp = json_format.Parse(response.content.decode("utf-8"), resp) - resp = self._interceptor.post_get_operation(resp) - return resp - - @property - def list_operations(self): - return self._ListOperations(self._session, self._host, self._interceptor) # type: ignore - - class _ListOperations(EnvironmentsRestStub): - def __call__(self, - request: operations_pb2.ListOperationsRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> operations_pb2.ListOperationsResponse: - - r"""Call the list operations method over HTTP. - - Args: - request (operations_pb2.ListOperationsRequest): - The request object for ListOperations method. - 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: - operations_pb2.ListOperationsResponse: Response from ListOperations method. - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v2/{name=projects/*}/operations', - }, -{ - 'method': 'get', - 'uri': '/v2/{name=projects/*/locations/*}/operations', - }, - ] - - request, metadata = self._interceptor.pre_list_operations(request, metadata) - request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode( - http_options, **request_kwargs) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json.dumps(transcoded_request['query_params'])) - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - resp = operations_pb2.ListOperationsResponse() - resp = json_format.Parse(response.content.decode("utf-8"), resp) - resp = self._interceptor.post_list_operations(resp) - return resp - - @property - def kind(self) -> str: - return "rest" - - def close(self): - self._session.close() - - -__all__=( - 'EnvironmentsRestTransport', -) diff --git a/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/fulfillments/__init__.py b/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/fulfillments/__init__.py deleted file mode 100644 index ba9b6c08e..000000000 --- a/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/fulfillments/__init__.py +++ /dev/null @@ -1,22 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/fulfillments/async_client.py b/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/fulfillments/async_client.py deleted file mode 100644 index 1db99fb4b..000000000 --- a/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/fulfillments/async_client.py +++ /dev/null @@ -1,692 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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, Mapping, MutableMapping, MutableSequence, Optional, Sequence, Tuple, Type, Union - -from google.cloud.dialogflow_v2 import gapic_version as package_version - -from google.api_core.client_options import ClientOptions -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import retry as retries -from google.auth import credentials as ga_credentials # type: ignore -from google.oauth2 import service_account # type: ignore - -try: - OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] -except AttributeError: # pragma: NO COVER - OptionalRetry = Union[retries.Retry, object] # type: ignore - -from google.cloud.dialogflow_v2.types import fulfillment -from google.cloud.dialogflow_v2.types import fulfillment as gcd_fulfillment -from google.cloud.location import locations_pb2 # type: ignore -from google.longrunning import operations_pb2 -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 - - @classmethod - def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[ClientOptions] = None): - """Return the API endpoint and client cert source for mutual TLS. - - The client cert source is determined in the following order: - (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the - client cert source is None. - (2) if `client_options.client_cert_source` is provided, use the provided one; if the - default client cert source exists, use the default one; otherwise the client cert - source is None. - - The API endpoint is determined in the following order: - (1) if `client_options.api_endpoint` if provided, use the provided one. - (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the - default mTLS endpoint; if the environment variable is "never", use the default API - endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise - use the default API endpoint. - - More details can be found at https://google.aip.dev/auth/4114. - - Args: - client_options (google.api_core.client_options.ClientOptions): Custom options for the - client. Only the `api_endpoint` and `client_cert_source` properties may be used - in this method. - - Returns: - Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the - client cert source to use. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If any errors happen. - """ - return FulfillmentsClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore - - @property - def transport(self) -> FulfillmentsTransport: - """Returns 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: Optional[ga_credentials.Credentials] = None, - transport: Union[str, FulfillmentsTransport] = "grpc_asyncio", - client_options: Optional[ClientOptions] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates 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: Optional[Union[fulfillment.GetFulfillmentRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> fulfillment.Fulfillment: - r"""Retrieves the fulfillment. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import dialogflow_v2 - - async def sample_get_fulfillment(): - # Create a client - client = dialogflow_v2.FulfillmentsAsyncClient() - - # Initialize request argument(s) - request = dialogflow_v2.GetFulfillmentRequest( - name="name_value", - ) - - # Make the request - response = await client.get_fulfillment(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.dialogflow_v2.types.GetFulfillmentRequest, dict]]): - 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. - # Quick 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: Optional[Union[gcd_fulfillment.UpdateFulfillmentRequest, dict]] = None, - *, - fulfillment: Optional[gcd_fulfillment.Fulfillment] = None, - update_mask: Optional[field_mask_pb2.FieldMask] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gcd_fulfillment.Fulfillment: - r"""Updates the fulfillment. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import dialogflow_v2 - - async def sample_update_fulfillment(): - # Create a client - client = dialogflow_v2.FulfillmentsAsyncClient() - - # Initialize request argument(s) - fulfillment = dialogflow_v2.Fulfillment() - fulfillment.generic_web_service.uri = "uri_value" - fulfillment.name = "name_value" - - request = dialogflow_v2.UpdateFulfillmentRequest( - fulfillment=fulfillment, - ) - - # Make the request - response = await client.update_fulfillment(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.dialogflow_v2.types.UpdateFulfillmentRequest, dict]]): - 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. - # Quick 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 - - async def list_operations( - self, - request: Optional[operations_pb2.ListOperationsRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operations_pb2.ListOperationsResponse: - r"""Lists operations that match the specified filter in the request. - - Args: - request (:class:`~.operations_pb2.ListOperationsRequest`): - The request object. Request message for - `ListOperations` method. - 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: - ~.operations_pb2.ListOperationsResponse: - Response message for ``ListOperations`` method. - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = operations_pb2.ListOperationsRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._client._transport.list_operations, - 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 get_operation( - self, - request: Optional[operations_pb2.GetOperationRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operations_pb2.Operation: - r"""Gets the latest state of a long-running operation. - - Args: - request (:class:`~.operations_pb2.GetOperationRequest`): - The request object. Request message for - `GetOperation` method. - 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: - ~.operations_pb2.Operation: - An ``Operation`` object. - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = operations_pb2.GetOperationRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._client._transport.get_operation, - 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 cancel_operation( - self, - request: Optional[operations_pb2.CancelOperationRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> None: - r"""Starts asynchronous cancellation on a long-running operation. - - The server makes a best effort to cancel the operation, but success - is not guaranteed. If the server doesn't support this method, it returns - `google.rpc.Code.UNIMPLEMENTED`. - - Args: - request (:class:`~.operations_pb2.CancelOperationRequest`): - The request object. Request message for - `CancelOperation` method. - 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: - None - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = operations_pb2.CancelOperationRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._client._transport.cancel_operation, - 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_location( - self, - request: Optional[locations_pb2.GetLocationRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> locations_pb2.Location: - r"""Gets information about a location. - - Args: - request (:class:`~.location_pb2.GetLocationRequest`): - The request object. Request message for - `GetLocation` method. - 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: - ~.location_pb2.Location: - Location object. - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = locations_pb2.GetLocationRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._client._transport.get_location, - 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 list_locations( - self, - request: Optional[locations_pb2.ListLocationsRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> locations_pb2.ListLocationsResponse: - r"""Lists information about the supported locations for this service. - - Args: - request (:class:`~.location_pb2.ListLocationsRequest`): - The request object. Request message for - `ListLocations` method. - 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: - ~.location_pb2.ListLocationsResponse: - Response message for ``ListLocations`` method. - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = locations_pb2.ListLocationsRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._client._transport.list_locations, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("name", request.name),)), - ) - - # Send the request. - response = await rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - async def __aenter__(self): - return self - - async def __aexit__(self, exc_type, exc, tb): - await self.transport.close() - -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) - - -__all__ = ( - "FulfillmentsAsyncClient", -) diff --git a/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/fulfillments/client.py b/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/fulfillments/client.py deleted file mode 100644 index b4c616d4b..000000000 --- a/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/fulfillments/client.py +++ /dev/null @@ -1,891 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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 os -import re -from typing import Dict, Mapping, MutableMapping, MutableSequence, Optional, Sequence, Tuple, Type, Union, cast - -from google.cloud.dialogflow_v2 import gapic_version as package_version - -from google.api_core import client_options as client_options_lib -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import retry as retries -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 - -try: - OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] -except AttributeError: # pragma: NO COVER - OptionalRetry = Union[retries.Retry, object] # type: ignore - -from google.cloud.dialogflow_v2.types import fulfillment -from google.cloud.dialogflow_v2.types import fulfillment as gcd_fulfillment -from google.cloud.location import locations_pb2 # type: ignore -from google.longrunning import operations_pb2 -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 -from .transports.rest import FulfillmentsRestTransport - - -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 - _transport_registry["rest"] = FulfillmentsRestTransport - - def get_transport_class(cls, - label: Optional[str] = None, - ) -> Type[FulfillmentsTransport]: - """Returns an appropriate transport class. - - Args: - label: The name of the desired transport. If none is - provided, then the first transport in the registry is used. - - Returns: - The transport class to use. - """ - # If a specific transport is requested, return that one. - if label: - return cls._transport_registry[label] - - # No transport is requested; return the default (that is, the first one - # in the dictionary). - return next(iter(cls._transport_registry.values())) - - -class FulfillmentsClient(metaclass=FulfillmentsClientMeta): - """Service for managing - [Fulfillments][google.cloud.dialogflow.v2.Fulfillment]. - """ - - @staticmethod - def _get_default_mtls_endpoint(api_endpoint): - """Converts api endpoint to mTLS endpoint. - - Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to - "*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively. - Args: - api_endpoint (Optional[str]): the api endpoint to convert. - Returns: - str: converted mTLS api endpoint. - """ - if not api_endpoint: - return api_endpoint - - mtls_endpoint_re = re.compile( - r"(?P[^.]+)(?P\.mtls)?(?P\.sandbox)?(?P\.googleapis\.com)?" - ) - - m = mtls_endpoint_re.match(api_endpoint) - name, mtls, sandbox, googledomain = m.groups() - if mtls or not googledomain: - return api_endpoint - - if sandbox: - return api_endpoint.replace( - "sandbox.googleapis.com", "mtls.sandbox.googleapis.com" - ) - - return api_endpoint.replace(".googleapis.com", ".mtls.googleapis.com") - - DEFAULT_ENDPOINT = "dialogflow.googleapis.com" - DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore - DEFAULT_ENDPOINT - ) - - @classmethod - def from_service_account_info(cls, info: dict, *args, **kwargs): - """Creates an instance of this client using the provided credentials - info. - - Args: - info (dict): The service account private key info. - args: Additional arguments to pass to the constructor. - kwargs: Additional arguments to pass to the constructor. - - Returns: - 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: - """Returns 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: - """Returns a fully-qualified fulfillment string.""" - return "projects/{project}/agent/fulfillment".format(project=project, ) - - @staticmethod - def parse_fulfillment_path(path: str) -> Dict[str,str]: - """Parses 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: - """Returns a fully-qualified billing_account string.""" - return "billingAccounts/{billing_account}".format(billing_account=billing_account, ) - - @staticmethod - def parse_common_billing_account_path(path: str) -> Dict[str,str]: - """Parse a billing_account path into its component segments.""" - m = re.match(r"^billingAccounts/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_folder_path(folder: str, ) -> str: - """Returns a fully-qualified folder string.""" - return "folders/{folder}".format(folder=folder, ) - - @staticmethod - def parse_common_folder_path(path: str) -> Dict[str,str]: - """Parse a folder path into its component segments.""" - m = re.match(r"^folders/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_organization_path(organization: str, ) -> str: - """Returns a fully-qualified organization string.""" - return "organizations/{organization}".format(organization=organization, ) - - @staticmethod - def parse_common_organization_path(path: str) -> Dict[str,str]: - """Parse a organization path into its component segments.""" - m = re.match(r"^organizations/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_project_path(project: str, ) -> str: - """Returns a fully-qualified project string.""" - return "projects/{project}".format(project=project, ) - - @staticmethod - def parse_common_project_path(path: str) -> Dict[str,str]: - """Parse a project path into its component segments.""" - m = re.match(r"^projects/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_location_path(project: str, location: str, ) -> str: - """Returns a fully-qualified location string.""" - return "projects/{project}/locations/{location}".format(project=project, location=location, ) - - @staticmethod - def parse_common_location_path(path: str) -> Dict[str,str]: - """Parse a location path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)$", path) - return m.groupdict() if m else {} - - @classmethod - def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[client_options_lib.ClientOptions] = None): - """Return the API endpoint and client cert source for mutual TLS. - - The client cert source is determined in the following order: - (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the - client cert source is None. - (2) if `client_options.client_cert_source` is provided, use the provided one; if the - default client cert source exists, use the default one; otherwise the client cert - source is None. - - The API endpoint is determined in the following order: - (1) if `client_options.api_endpoint` if provided, use the provided one. - (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the - default mTLS endpoint; if the environment variable is "never", use the default API - endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise - use the default API endpoint. - - More details can be found at https://google.aip.dev/auth/4114. - - Args: - client_options (google.api_core.client_options.ClientOptions): Custom options for the - client. Only the `api_endpoint` and `client_cert_source` properties may be used - in this method. - - Returns: - Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the - client cert source to use. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If any errors happen. - """ - if client_options is None: - client_options = client_options_lib.ClientOptions() - use_client_cert = os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false") - use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") - if use_client_cert not in ("true", "false"): - raise ValueError("Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`") - if use_mtls_endpoint not in ("auto", "never", "always"): - raise MutualTLSChannelError("Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`") - - # Figure out the client cert source to use. - client_cert_source = None - if use_client_cert == "true": - if client_options.client_cert_source: - client_cert_source = client_options.client_cert_source - elif mtls.has_default_client_cert_source(): - client_cert_source = mtls.default_client_cert_source() - - # Figure out which api endpoint to use. - if client_options.api_endpoint is not None: - api_endpoint = client_options.api_endpoint - elif use_mtls_endpoint == "always" or (use_mtls_endpoint == "auto" and client_cert_source): - api_endpoint = cls.DEFAULT_MTLS_ENDPOINT - else: - api_endpoint = cls.DEFAULT_ENDPOINT - - return api_endpoint, client_cert_source - - def __init__(self, *, - credentials: Optional[ga_credentials.Credentials] = None, - transport: Optional[Union[str, FulfillmentsTransport]] = None, - client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates 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 (Optional[Union[google.api_core.client_options.ClientOptions, dict]]): 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() - client_options = cast(client_options_lib.ClientOptions, client_options) - - api_endpoint, client_cert_source_func = self.get_mtls_endpoint_and_cert_source(client_options) - - api_key_value = getattr(client_options, "api_key", None) - if api_key_value and credentials: - raise ValueError("client_options.api_key and credentials are mutually exclusive") - - # 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 or api_key_value: - 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: - import google.auth._default # type: ignore - - if api_key_value and hasattr(google.auth._default, "get_api_key_credentials"): - credentials = google.auth._default.get_api_key_credentials(api_key_value) - - Transport = type(self).get_transport_class(transport) - self._transport = Transport( - credentials=credentials, - credentials_file=client_options.credentials_file, - host=api_endpoint, - scopes=client_options.scopes, - client_cert_source_for_mtls=client_cert_source_func, - quota_project_id=client_options.quota_project_id, - client_info=client_info, - always_use_jwt_access=True, - api_audience=client_options.api_audience, - ) - - def get_fulfillment(self, - request: Optional[Union[fulfillment.GetFulfillmentRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> fulfillment.Fulfillment: - r"""Retrieves the fulfillment. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import dialogflow_v2 - - def sample_get_fulfillment(): - # Create a client - client = dialogflow_v2.FulfillmentsClient() - - # Initialize request argument(s) - request = dialogflow_v2.GetFulfillmentRequest( - name="name_value", - ) - - # Make the request - response = client.get_fulfillment(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.dialogflow_v2.types.GetFulfillmentRequest, dict]): - 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. - # Quick 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: Optional[Union[gcd_fulfillment.UpdateFulfillmentRequest, dict]] = None, - *, - fulfillment: Optional[gcd_fulfillment.Fulfillment] = None, - update_mask: Optional[field_mask_pb2.FieldMask] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gcd_fulfillment.Fulfillment: - r"""Updates the fulfillment. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import dialogflow_v2 - - def sample_update_fulfillment(): - # Create a client - client = dialogflow_v2.FulfillmentsClient() - - # Initialize request argument(s) - fulfillment = dialogflow_v2.Fulfillment() - fulfillment.generic_web_service.uri = "uri_value" - fulfillment.name = "name_value" - - request = dialogflow_v2.UpdateFulfillmentRequest( - fulfillment=fulfillment, - ) - - # Make the request - response = client.update_fulfillment(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.dialogflow_v2.types.UpdateFulfillmentRequest, dict]): - 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. - # Quick 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 - - def __enter__(self) -> "FulfillmentsClient": - return self - - def __exit__(self, type, value, traceback): - """Releases underlying transport's resources. - - .. warning:: - ONLY use as a context manager if the transport is NOT shared - with other clients! Exiting the with block will CLOSE the transport - and may cause errors in other clients! - """ - self.transport.close() - - def list_operations( - self, - request: Optional[operations_pb2.ListOperationsRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operations_pb2.ListOperationsResponse: - r"""Lists operations that match the specified filter in the request. - - Args: - request (:class:`~.operations_pb2.ListOperationsRequest`): - The request object. Request message for - `ListOperations` method. - 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: - ~.operations_pb2.ListOperationsResponse: - Response message for ``ListOperations`` method. - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = operations_pb2.ListOperationsRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._transport.list_operations, - 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 = rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - def get_operation( - self, - request: Optional[operations_pb2.GetOperationRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operations_pb2.Operation: - r"""Gets the latest state of a long-running operation. - - Args: - request (:class:`~.operations_pb2.GetOperationRequest`): - The request object. Request message for - `GetOperation` method. - 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: - ~.operations_pb2.Operation: - An ``Operation`` object. - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = operations_pb2.GetOperationRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._transport.get_operation, - 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 = rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - def cancel_operation( - self, - request: Optional[operations_pb2.CancelOperationRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> None: - r"""Starts asynchronous cancellation on a long-running operation. - - The server makes a best effort to cancel the operation, but success - is not guaranteed. If the server doesn't support this method, it returns - `google.rpc.Code.UNIMPLEMENTED`. - - Args: - request (:class:`~.operations_pb2.CancelOperationRequest`): - The request object. Request message for - `CancelOperation` method. - 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: - None - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = operations_pb2.CancelOperationRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._transport.cancel_operation, - 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. - rpc(request, retry=retry, timeout=timeout, metadata=metadata,) - - def get_location( - self, - request: Optional[locations_pb2.GetLocationRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> locations_pb2.Location: - r"""Gets information about a location. - - Args: - request (:class:`~.location_pb2.GetLocationRequest`): - The request object. Request message for - `GetLocation` method. - 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: - ~.location_pb2.Location: - Location object. - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = locations_pb2.GetLocationRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._transport.get_location, - 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 = rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - def list_locations( - self, - request: Optional[locations_pb2.ListLocationsRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> locations_pb2.ListLocationsResponse: - r"""Lists information about the supported locations for this service. - - Args: - request (:class:`~.location_pb2.ListLocationsRequest`): - The request object. Request message for - `ListLocations` method. - 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: - ~.location_pb2.ListLocationsResponse: - Response message for ``ListLocations`` method. - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = locations_pb2.ListLocationsRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._transport.list_locations, - 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 = rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) - - -__all__ = ( - "FulfillmentsClient", -) diff --git a/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/fulfillments/transports/__init__.py b/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/fulfillments/transports/__init__.py deleted file mode 100644 index bc9bf0c81..000000000 --- a/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/fulfillments/transports/__init__.py +++ /dev/null @@ -1,38 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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 -from .rest import FulfillmentsRestTransport -from .rest import FulfillmentsRestInterceptor - - -# Compile a registry of transports. -_transport_registry = OrderedDict() # type: Dict[str, Type[FulfillmentsTransport]] -_transport_registry['grpc'] = FulfillmentsGrpcTransport -_transport_registry['grpc_asyncio'] = FulfillmentsGrpcAsyncIOTransport -_transport_registry['rest'] = FulfillmentsRestTransport - -__all__ = ( - 'FulfillmentsTransport', - 'FulfillmentsGrpcTransport', - 'FulfillmentsGrpcAsyncIOTransport', - 'FulfillmentsRestTransport', - 'FulfillmentsRestInterceptor', -) diff --git a/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/fulfillments/transports/base.py b/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/fulfillments/transports/base.py deleted file mode 100644 index ea8ce82a6..000000000 --- a/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/fulfillments/transports/base.py +++ /dev/null @@ -1,209 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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 - -from google.cloud.dialogflow_v2 import gapic_version as package_version - -import google.auth # type: ignore -import google.api_core -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import retry as retries -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.cloud.location import locations_pb2 # type: ignore -from google.longrunning import operations_pb2 - -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__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: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - api_audience: Optional[str] = None, - **kwargs, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. - scopes (Optional[Sequence[str]]): A list of scopes. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - """ - - scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} - - # Save the scopes. - self._scopes = scopes - - # If no credentials are provided, then determine the appropriate - # defaults. - if credentials and credentials_file: - raise core_exceptions.DuplicateCredentialArgs("'credentials_file' and 'credentials' are mutually exclusive") - - if credentials_file is not None: - credentials, _ = google.auth.load_credentials_from_file( - credentials_file, - **scopes_kwargs, - quota_project_id=quota_project_id - ) - elif credentials is None: - credentials, _ = google.auth.default(**scopes_kwargs, quota_project_id=quota_project_id) - # Don't apply audience if the credentials file passed from user. - if hasattr(credentials, "with_gdch_audience"): - credentials = credentials.with_gdch_audience(api_audience if api_audience else host) - - # If the credentials are service account credentials, then always try to use self signed JWT. - if always_use_jwt_access and isinstance(credentials, service_account.Credentials) and hasattr(service_account.Credentials, "with_always_use_jwt_access"): - credentials = credentials.with_always_use_jwt_access(True) - - # Save the credentials. - self._credentials = credentials - - # Save the hostname. Default to port 443 (HTTPS) if none is specified. - if ':' not in host: - host += ':443' - self._host = host - - 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, - ), - } - - def close(self): - """Closes resources associated with the transport. - - .. warning:: - Only call this method if the transport is NOT shared - with other clients - this may cause errors in other clients! - """ - raise NotImplementedError() - - @property - def 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() - - @property - def list_operations( - self, - ) -> Callable[ - [operations_pb2.ListOperationsRequest], - Union[operations_pb2.ListOperationsResponse, Awaitable[operations_pb2.ListOperationsResponse]], - ]: - raise NotImplementedError() - - @property - def get_operation( - self, - ) -> Callable[ - [operations_pb2.GetOperationRequest], - Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], - ]: - raise NotImplementedError() - - @property - def cancel_operation( - self, - ) -> Callable[ - [operations_pb2.CancelOperationRequest], - None, - ]: - raise NotImplementedError() - - @property - def get_location(self, - ) -> Callable[ - [locations_pb2.GetLocationRequest], - Union[locations_pb2.Location, Awaitable[locations_pb2.Location]], - ]: - raise NotImplementedError() - - @property - def list_locations(self, - ) -> Callable[ - [locations_pb2.ListLocationsRequest], - Union[locations_pb2.ListLocationsResponse, Awaitable[locations_pb2.ListLocationsResponse]], - ]: - raise NotImplementedError() - - @property - def kind(self) -> str: - raise NotImplementedError() - - -__all__ = ( - 'FulfillmentsTransport', -) diff --git a/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/fulfillments/transports/grpc.py b/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/fulfillments/transports/grpc.py deleted file mode 100644 index 940063273..000000000 --- a/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/fulfillments/transports/grpc.py +++ /dev/null @@ -1,384 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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 -from google.api_core import gapic_v1 -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 google.cloud.location import locations_pb2 # type: ignore -from google.longrunning import operations_pb2 -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: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - channel: Optional[grpc.Channel] = None, - api_mtls_endpoint: Optional[str] = None, - client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, - ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, - client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - api_audience: Optional[str] = None, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - This argument is ignored if ``channel`` is provided. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional(Sequence[str])): A list of scopes. This argument is - ignored if ``channel`` is provided. - channel (Optional[grpc.Channel]): A ``Channel`` instance through - which to make calls. - api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. - If provided, it overrides the ``host`` argument and tries to create - a mutual TLS channel with client SSL credentials from - ``client_cert_source`` or application default SSL credentials. - client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): - Deprecated. A callback to provide client SSL certificate bytes and - private key bytes, both in PEM format. It is ignored if - ``api_mtls_endpoint`` is None. - ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials - for the grpc channel. It is ignored if ``channel`` is provided. - client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): - A callback to provide client certificate bytes and private key bytes, - both in PEM format. It is used to configure a mutual TLS channel. It is - ignored if ``channel`` or ``ssl_channel_credentials`` is provided. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport - creation failed for any reason. - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - self._grpc_channel = None - self._ssl_channel_credentials = ssl_channel_credentials - self._stubs: Dict[str, Callable] = {} - - if api_mtls_endpoint: - warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) - if client_cert_source: - warnings.warn("client_cert_source is deprecated", DeprecationWarning) - - if channel: - # Ignore credentials if a channel was passed. - credentials = False - # If a channel was explicitly provided, set it. - self._grpc_channel = channel - self._ssl_channel_credentials = None - - else: - if api_mtls_endpoint: - host = api_mtls_endpoint - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - self._ssl_channel_credentials = SslCredentials().ssl_credentials - - else: - if client_cert_source_for_mtls and not ssl_channel_credentials: - cert, key = client_cert_source_for_mtls() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - - # The base transport sets the host, credentials and scopes - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes, - quota_project_id=quota_project_id, - client_info=client_info, - always_use_jwt_access=always_use_jwt_access, - api_audience=api_audience, - ) - - if not self._grpc_channel: - self._grpc_channel = type(self).create_channel( - self._host, - # use the credentials which are saved - credentials=self._credentials, - # Set ``credentials_file`` to ``None`` here as - # the credentials that we saved earlier should be used. - credentials_file=None, - 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: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - **kwargs) -> grpc.Channel: - """Create and return a gRPC channel object. - Args: - host (Optional[str]): The host for the channel to use. - credentials (Optional[~.Credentials]): The - authorization credentials to attach to requests. These - credentials identify this application to the service. If - none are specified, the client will attempt to ascertain - the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - kwargs (Optional[dict]): Keyword arguments, which are passed to the - channel creation. - Returns: - grpc.Channel: A gRPC channel object. - - Raises: - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - - return grpc_helpers.create_channel( - host, - credentials=credentials, - credentials_file=credentials_file, - quota_project_id=quota_project_id, - default_scopes=cls.AUTH_SCOPES, - scopes=scopes, - default_host=cls.DEFAULT_HOST, - **kwargs - ) - - @property - def grpc_channel(self) -> grpc.Channel: - """Return the channel designed to connect to this service. - """ - return self._grpc_channel - - @property - def 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'] - - def close(self): - self.grpc_channel.close() - - @property - def cancel_operation( - self, - ) -> Callable[[operations_pb2.CancelOperationRequest], None]: - r"""Return a callable for the cancel_operation method over gRPC. - """ - # 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 "cancel_operation" not in self._stubs: - self._stubs["cancel_operation"] = self.grpc_channel.unary_unary( - "/google.longrunning.Operations/CancelOperation", - request_serializer=operations_pb2.CancelOperationRequest.SerializeToString, - response_deserializer=None, - ) - return self._stubs["cancel_operation"] - - @property - def get_operation( - self, - ) -> Callable[[operations_pb2.GetOperationRequest], operations_pb2.Operation]: - r"""Return a callable for the get_operation method over gRPC. - """ - # 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_operation" not in self._stubs: - self._stubs["get_operation"] = self.grpc_channel.unary_unary( - "/google.longrunning.Operations/GetOperation", - request_serializer=operations_pb2.GetOperationRequest.SerializeToString, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs["get_operation"] - - @property - def list_operations( - self, - ) -> Callable[[operations_pb2.ListOperationsRequest], operations_pb2.ListOperationsResponse]: - r"""Return a callable for the list_operations method over gRPC. - """ - # 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_operations" not in self._stubs: - self._stubs["list_operations"] = self.grpc_channel.unary_unary( - "/google.longrunning.Operations/ListOperations", - request_serializer=operations_pb2.ListOperationsRequest.SerializeToString, - response_deserializer=operations_pb2.ListOperationsResponse.FromString, - ) - return self._stubs["list_operations"] - - @property - def list_locations( - self, - ) -> Callable[[locations_pb2.ListLocationsRequest], locations_pb2.ListLocationsResponse]: - r"""Return a callable for the list locations method over gRPC. - """ - # 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_locations" not in self._stubs: - self._stubs["list_locations"] = self.grpc_channel.unary_unary( - "/google.cloud.location.Locations/ListLocations", - request_serializer=locations_pb2.ListLocationsRequest.SerializeToString, - response_deserializer=locations_pb2.ListLocationsResponse.FromString, - ) - return self._stubs["list_locations"] - - @property - def get_location( - self, - ) -> Callable[[locations_pb2.GetLocationRequest], locations_pb2.Location]: - r"""Return a callable for the list locations method over gRPC. - """ - # 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_location" not in self._stubs: - self._stubs["get_location"] = self.grpc_channel.unary_unary( - "/google.cloud.location.Locations/GetLocation", - request_serializer=locations_pb2.GetLocationRequest.SerializeToString, - response_deserializer=locations_pb2.Location.FromString, - ) - return self._stubs["get_location"] - - @property - def kind(self) -> str: - return "grpc" - - -__all__ = ( - 'FulfillmentsGrpcTransport', -) diff --git a/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/fulfillments/transports/grpc_asyncio.py b/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/fulfillments/transports/grpc_asyncio.py deleted file mode 100644 index 5fa1ea793..000000000 --- a/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/fulfillments/transports/grpc_asyncio.py +++ /dev/null @@ -1,383 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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 -from google.api_core import grpc_helpers_async -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore - -import grpc # type: ignore -from grpc.experimental import aio # type: ignore - -from google.cloud.dialogflow_v2.types import fulfillment -from google.cloud.dialogflow_v2.types import fulfillment as gcd_fulfillment -from google.cloud.location import locations_pb2 # type: ignore -from google.longrunning import operations_pb2 -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: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - **kwargs) -> aio.Channel: - """Create and return a gRPC AsyncIO channel object. - Args: - host (Optional[str]): The host for the channel to use. - credentials (Optional[~.Credentials]): The - authorization credentials to attach to requests. These - credentials identify this application to the service. If - none are specified, the client will attempt to ascertain - the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - kwargs (Optional[dict]): Keyword arguments, which are passed to the - channel creation. - Returns: - aio.Channel: A gRPC AsyncIO channel object. - """ - - return grpc_helpers_async.create_channel( - host, - credentials=credentials, - credentials_file=credentials_file, - quota_project_id=quota_project_id, - default_scopes=cls.AUTH_SCOPES, - scopes=scopes, - default_host=cls.DEFAULT_HOST, - **kwargs - ) - - def __init__(self, *, - host: str = 'dialogflow.googleapis.com', - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - channel: Optional[aio.Channel] = None, - api_mtls_endpoint: Optional[str] = None, - client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, - ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, - client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - api_audience: Optional[str] = None, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - This argument is ignored if ``channel`` is provided. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - channel (Optional[aio.Channel]): A ``Channel`` instance through - which to make calls. - api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. - If provided, it overrides the ``host`` argument and tries to create - a mutual TLS channel with client SSL credentials from - ``client_cert_source`` or application default SSL credentials. - client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): - Deprecated. A callback to provide client SSL certificate bytes and - private key bytes, both in PEM format. It is ignored if - ``api_mtls_endpoint`` is None. - ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials - for the grpc channel. It is ignored if ``channel`` is provided. - client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): - A callback to provide client certificate bytes and private key bytes, - both in PEM format. It is used to configure a mutual TLS channel. It is - ignored if ``channel`` or ``ssl_channel_credentials`` is provided. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - - Raises: - google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport - creation failed for any reason. - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - self._grpc_channel = None - self._ssl_channel_credentials = ssl_channel_credentials - self._stubs: Dict[str, Callable] = {} - - if api_mtls_endpoint: - warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) - if client_cert_source: - warnings.warn("client_cert_source is deprecated", DeprecationWarning) - - if channel: - # Ignore credentials if a channel was passed. - credentials = False - # If a channel was explicitly provided, set it. - self._grpc_channel = channel - self._ssl_channel_credentials = None - else: - if api_mtls_endpoint: - host = api_mtls_endpoint - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - self._ssl_channel_credentials = SslCredentials().ssl_credentials - - else: - if client_cert_source_for_mtls and not ssl_channel_credentials: - cert, key = client_cert_source_for_mtls() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - - # The base transport sets the host, credentials and scopes - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes, - quota_project_id=quota_project_id, - client_info=client_info, - always_use_jwt_access=always_use_jwt_access, - api_audience=api_audience, - ) - - if not self._grpc_channel: - self._grpc_channel = type(self).create_channel( - self._host, - # use the credentials which are saved - credentials=self._credentials, - # Set ``credentials_file`` to ``None`` here as - # the credentials that we saved earlier should be used. - credentials_file=None, - 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'] - - def close(self): - return self.grpc_channel.close() - - @property - def cancel_operation( - self, - ) -> Callable[[operations_pb2.CancelOperationRequest], None]: - r"""Return a callable for the cancel_operation method over gRPC. - """ - # 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 "cancel_operation" not in self._stubs: - self._stubs["cancel_operation"] = self.grpc_channel.unary_unary( - "/google.longrunning.Operations/CancelOperation", - request_serializer=operations_pb2.CancelOperationRequest.SerializeToString, - response_deserializer=None, - ) - return self._stubs["cancel_operation"] - - @property - def get_operation( - self, - ) -> Callable[[operations_pb2.GetOperationRequest], operations_pb2.Operation]: - r"""Return a callable for the get_operation method over gRPC. - """ - # 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_operation" not in self._stubs: - self._stubs["get_operation"] = self.grpc_channel.unary_unary( - "/google.longrunning.Operations/GetOperation", - request_serializer=operations_pb2.GetOperationRequest.SerializeToString, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs["get_operation"] - - @property - def list_operations( - self, - ) -> Callable[[operations_pb2.ListOperationsRequest], operations_pb2.ListOperationsResponse]: - r"""Return a callable for the list_operations method over gRPC. - """ - # 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_operations" not in self._stubs: - self._stubs["list_operations"] = self.grpc_channel.unary_unary( - "/google.longrunning.Operations/ListOperations", - request_serializer=operations_pb2.ListOperationsRequest.SerializeToString, - response_deserializer=operations_pb2.ListOperationsResponse.FromString, - ) - return self._stubs["list_operations"] - - @property - def list_locations( - self, - ) -> Callable[[locations_pb2.ListLocationsRequest], locations_pb2.ListLocationsResponse]: - r"""Return a callable for the list locations method over gRPC. - """ - # 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_locations" not in self._stubs: - self._stubs["list_locations"] = self.grpc_channel.unary_unary( - "/google.cloud.location.Locations/ListLocations", - request_serializer=locations_pb2.ListLocationsRequest.SerializeToString, - response_deserializer=locations_pb2.ListLocationsResponse.FromString, - ) - return self._stubs["list_locations"] - - @property - def get_location( - self, - ) -> Callable[[locations_pb2.GetLocationRequest], locations_pb2.Location]: - r"""Return a callable for the list locations method over gRPC. - """ - # 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_location" not in self._stubs: - self._stubs["get_location"] = self.grpc_channel.unary_unary( - "/google.cloud.location.Locations/GetLocation", - request_serializer=locations_pb2.GetLocationRequest.SerializeToString, - response_deserializer=locations_pb2.Location.FromString, - ) - return self._stubs["get_location"] - - -__all__ = ( - 'FulfillmentsGrpcAsyncIOTransport', -) diff --git a/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/fulfillments/transports/rest.py b/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/fulfillments/transports/rest.py deleted file mode 100644 index adfee3b3d..000000000 --- a/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/fulfillments/transports/rest.py +++ /dev/null @@ -1,878 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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 google.auth.transport.requests import AuthorizedSession # type: ignore -import json # type: ignore -import grpc # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore -from google.auth import credentials as ga_credentials # type: ignore -from google.api_core import exceptions as core_exceptions -from google.api_core import retry as retries -from google.api_core import rest_helpers -from google.api_core import rest_streaming -from google.api_core import path_template -from google.api_core import gapic_v1 - -from google.protobuf import json_format -from google.cloud.location import locations_pb2 # type: ignore -from google.longrunning import operations_pb2 -from requests import __version__ as requests_version -import dataclasses -import re -from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union -import warnings - -try: - OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] -except AttributeError: # pragma: NO COVER - OptionalRetry = Union[retries.Retry, object] # 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 as BASE_DEFAULT_CLIENT_INFO - - -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=BASE_DEFAULT_CLIENT_INFO.gapic_version, - grpc_version=None, - rest_version=requests_version, -) - - -class FulfillmentsRestInterceptor: - """Interceptor for Fulfillments. - - Interceptors are used to manipulate requests, request metadata, and responses - in arbitrary ways. - Example use cases include: - * Logging - * Verifying requests according to service or custom semantics - * Stripping extraneous information from responses - - These use cases and more can be enabled by injecting an - instance of a custom subclass when constructing the FulfillmentsRestTransport. - - .. code-block:: python - class MyCustomFulfillmentsInterceptor(FulfillmentsRestInterceptor): - def pre_get_fulfillment(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_get_fulfillment(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_update_fulfillment(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_update_fulfillment(self, response): - logging.log(f"Received response: {response}") - return response - - transport = FulfillmentsRestTransport(interceptor=MyCustomFulfillmentsInterceptor()) - client = FulfillmentsClient(transport=transport) - - - """ - def pre_get_fulfillment(self, request: fulfillment.GetFulfillmentRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[fulfillment.GetFulfillmentRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for get_fulfillment - - Override in a subclass to manipulate the request or metadata - before they are sent to the Fulfillments server. - """ - return request, metadata - - def post_get_fulfillment(self, response: fulfillment.Fulfillment) -> fulfillment.Fulfillment: - """Post-rpc interceptor for get_fulfillment - - Override in a subclass to manipulate the response - after it is returned by the Fulfillments server but before - it is returned to user code. - """ - return response - def pre_update_fulfillment(self, request: gcd_fulfillment.UpdateFulfillmentRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[gcd_fulfillment.UpdateFulfillmentRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for update_fulfillment - - Override in a subclass to manipulate the request or metadata - before they are sent to the Fulfillments server. - """ - return request, metadata - - def post_update_fulfillment(self, response: gcd_fulfillment.Fulfillment) -> gcd_fulfillment.Fulfillment: - """Post-rpc interceptor for update_fulfillment - - Override in a subclass to manipulate the response - after it is returned by the Fulfillments server but before - it is returned to user code. - """ - return response - - def pre_get_location( - self, request: locations_pb2.GetLocationRequest, metadata: Sequence[Tuple[str, str]] - ) -> Tuple[locations_pb2.GetLocationRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for get_location - - Override in a subclass to manipulate the request or metadata - before they are sent to the Fulfillments server. - """ - return request, metadata - - def post_get_location( - self, response: locations_pb2.Location - ) -> locations_pb2.Location: - """Post-rpc interceptor for get_location - - Override in a subclass to manipulate the response - after it is returned by the Fulfillments server but before - it is returned to user code. - """ - return response - def pre_list_locations( - self, request: locations_pb2.ListLocationsRequest, metadata: Sequence[Tuple[str, str]] - ) -> Tuple[locations_pb2.ListLocationsRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for list_locations - - Override in a subclass to manipulate the request or metadata - before they are sent to the Fulfillments server. - """ - return request, metadata - - def post_list_locations( - self, response: locations_pb2.ListLocationsResponse - ) -> locations_pb2.ListLocationsResponse: - """Post-rpc interceptor for list_locations - - Override in a subclass to manipulate the response - after it is returned by the Fulfillments server but before - it is returned to user code. - """ - return response - def pre_cancel_operation( - self, request: operations_pb2.CancelOperationRequest, metadata: Sequence[Tuple[str, str]] - ) -> Tuple[operations_pb2.CancelOperationRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for cancel_operation - - Override in a subclass to manipulate the request or metadata - before they are sent to the Fulfillments server. - """ - return request, metadata - - def post_cancel_operation( - self, response: None - ) -> None: - """Post-rpc interceptor for cancel_operation - - Override in a subclass to manipulate the response - after it is returned by the Fulfillments server but before - it is returned to user code. - """ - return response - def pre_get_operation( - self, request: operations_pb2.GetOperationRequest, metadata: Sequence[Tuple[str, str]] - ) -> Tuple[operations_pb2.GetOperationRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for get_operation - - Override in a subclass to manipulate the request or metadata - before they are sent to the Fulfillments server. - """ - return request, metadata - - def post_get_operation( - self, response: operations_pb2.Operation - ) -> operations_pb2.Operation: - """Post-rpc interceptor for get_operation - - Override in a subclass to manipulate the response - after it is returned by the Fulfillments server but before - it is returned to user code. - """ - return response - def pre_list_operations( - self, request: operations_pb2.ListOperationsRequest, metadata: Sequence[Tuple[str, str]] - ) -> Tuple[operations_pb2.ListOperationsRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for list_operations - - Override in a subclass to manipulate the request or metadata - before they are sent to the Fulfillments server. - """ - return request, metadata - - def post_list_operations( - self, response: operations_pb2.ListOperationsResponse - ) -> operations_pb2.ListOperationsResponse: - """Post-rpc interceptor for list_operations - - Override in a subclass to manipulate the response - after it is returned by the Fulfillments server but before - it is returned to user code. - """ - return response - - -@dataclasses.dataclass -class FulfillmentsRestStub: - _session: AuthorizedSession - _host: str - _interceptor: FulfillmentsRestInterceptor - - -class FulfillmentsRestTransport(FulfillmentsTransport): - """REST 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 JSON representations of protocol buffers over HTTP/1.1 - - """ - - def __init__(self, *, - host: str = 'dialogflow.googleapis.com', - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - client_cert_source_for_mtls: Optional[Callable[[ - ], Tuple[bytes, bytes]]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - url_scheme: str = 'https', - interceptor: Optional[FulfillmentsRestInterceptor] = None, - api_audience: Optional[str] = None, - ) -> 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 ignored if ``channel`` is provided. - scopes (Optional(Sequence[str])): A list of scopes. This argument is - ignored if ``channel`` is provided. - client_cert_source_for_mtls (Callable[[], Tuple[bytes, bytes]]): Client - certificate to configure mutual TLS HTTP channel. It is ignored - if ``channel`` is provided. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you are developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - url_scheme: the protocol scheme for the API endpoint. Normally - "https", but for testing or local servers, - "http" can be specified. - """ - # Run the base constructor - # TODO(yon-mg): resolve other ctor params i.e. scopes, quota, etc. - # TODO: When custom host (api_endpoint) is set, `scopes` must *also* be set on the - # credentials object - maybe_url_match = re.match("^(?Phttp(?:s)?://)?(?P.*)$", host) - if maybe_url_match is None: - raise ValueError(f"Unexpected hostname structure: {host}") # pragma: NO COVER - - url_match_items = maybe_url_match.groupdict() - - host = f"{url_scheme}://{host}" if not url_match_items["scheme"] else host - - super().__init__( - host=host, - credentials=credentials, - client_info=client_info, - always_use_jwt_access=always_use_jwt_access, - api_audience=api_audience - ) - self._session = AuthorizedSession( - self._credentials, default_host=self.DEFAULT_HOST) - if client_cert_source_for_mtls: - self._session.configure_mtls_channel(client_cert_source_for_mtls) - self._interceptor = interceptor or FulfillmentsRestInterceptor() - self._prep_wrapped_messages(client_info) - - class _GetFulfillment(FulfillmentsRestStub): - def __hash__(self): - return hash("GetFulfillment") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: fulfillment.GetFulfillmentRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> fulfillment.Fulfillment: - r"""Call the get fulfillment method over HTTP. - - Args: - request (~.fulfillment.GetFulfillmentRequest): - The request object. The request message for - [Fulfillments.GetFulfillment][google.cloud.dialogflow.v2.Fulfillments.GetFulfillment]. - 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: - ~.fulfillment.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 `__. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v2/{name=projects/*/agent/fulfillment}', - }, -{ - 'method': 'get', - 'uri': '/v2/{name=projects/*/locations/*/agent/fulfillment}', - }, - ] - request, metadata = self._interceptor.pre_get_fulfillment(request, metadata) - pb_request = fulfillment.GetFulfillmentRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - including_default_value_fields=False, - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = fulfillment.Fulfillment() - pb_resp = fulfillment.Fulfillment.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_get_fulfillment(resp) - return resp - - class _UpdateFulfillment(FulfillmentsRestStub): - def __hash__(self): - return hash("UpdateFulfillment") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - "updateMask" : {}, } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: gcd_fulfillment.UpdateFulfillmentRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> gcd_fulfillment.Fulfillment: - r"""Call the update fulfillment method over HTTP. - - Args: - request (~.gcd_fulfillment.UpdateFulfillmentRequest): - The request object. The request message for - [Fulfillments.UpdateFulfillment][google.cloud.dialogflow.v2.Fulfillments.UpdateFulfillment]. - 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: - ~.gcd_fulfillment.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 `__. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'patch', - 'uri': '/v2/{fulfillment.name=projects/*/agent/fulfillment}', - 'body': 'fulfillment', - }, -{ - 'method': 'patch', - 'uri': '/v2/{fulfillment.name=projects/*/locations/*/agent/fulfillment}', - 'body': 'fulfillment', - }, - ] - request, metadata = self._interceptor.pre_update_fulfillment(request, metadata) - pb_request = gcd_fulfillment.UpdateFulfillmentRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request['body'], - including_default_value_fields=False, - use_integers_for_enums=True - ) - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - including_default_value_fields=False, - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = gcd_fulfillment.Fulfillment() - pb_resp = gcd_fulfillment.Fulfillment.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_update_fulfillment(resp) - return resp - - @property - def get_fulfillment(self) -> Callable[ - [fulfillment.GetFulfillmentRequest], - fulfillment.Fulfillment]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._GetFulfillment(self._session, self._host, self._interceptor) # type: ignore - - @property - def update_fulfillment(self) -> Callable[ - [gcd_fulfillment.UpdateFulfillmentRequest], - gcd_fulfillment.Fulfillment]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._UpdateFulfillment(self._session, self._host, self._interceptor) # type: ignore - - @property - def get_location(self): - return self._GetLocation(self._session, self._host, self._interceptor) # type: ignore - - class _GetLocation(FulfillmentsRestStub): - def __call__(self, - request: locations_pb2.GetLocationRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> locations_pb2.Location: - - r"""Call the get location method over HTTP. - - Args: - request (locations_pb2.GetLocationRequest): - The request object for GetLocation method. - 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: - locations_pb2.Location: Response from GetLocation method. - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v2/{name=projects/*/locations/*}', - }, - ] - - request, metadata = self._interceptor.pre_get_location(request, metadata) - request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode( - http_options, **request_kwargs) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json.dumps(transcoded_request['query_params'])) - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - resp = locations_pb2.Location() - resp = json_format.Parse(response.content.decode("utf-8"), resp) - resp = self._interceptor.post_get_location(resp) - return resp - - @property - def list_locations(self): - return self._ListLocations(self._session, self._host, self._interceptor) # type: ignore - - class _ListLocations(FulfillmentsRestStub): - def __call__(self, - request: locations_pb2.ListLocationsRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> locations_pb2.ListLocationsResponse: - - r"""Call the list locations method over HTTP. - - Args: - request (locations_pb2.ListLocationsRequest): - The request object for ListLocations method. - 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: - locations_pb2.ListLocationsResponse: Response from ListLocations method. - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v2/{name=projects/*}/locations', - }, - ] - - request, metadata = self._interceptor.pre_list_locations(request, metadata) - request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode( - http_options, **request_kwargs) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json.dumps(transcoded_request['query_params'])) - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - resp = locations_pb2.ListLocationsResponse() - resp = json_format.Parse(response.content.decode("utf-8"), resp) - resp = self._interceptor.post_list_locations(resp) - return resp - - @property - def cancel_operation(self): - return self._CancelOperation(self._session, self._host, self._interceptor) # type: ignore - - class _CancelOperation(FulfillmentsRestStub): - def __call__(self, - request: operations_pb2.CancelOperationRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> None: - - r"""Call the cancel operation method over HTTP. - - Args: - request (operations_pb2.CancelOperationRequest): - The request object for CancelOperation method. - 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. - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'post', - 'uri': '/v2/{name=projects/*/operations/*}:cancel', - }, -{ - 'method': 'post', - 'uri': '/v2/{name=projects/*/locations/*/operations/*}:cancel', - }, - ] - - request, metadata = self._interceptor.pre_cancel_operation(request, metadata) - request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode( - http_options, **request_kwargs) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json.dumps(transcoded_request['query_params'])) - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - return self._interceptor.post_cancel_operation(None) - - @property - def get_operation(self): - return self._GetOperation(self._session, self._host, self._interceptor) # type: ignore - - class _GetOperation(FulfillmentsRestStub): - def __call__(self, - request: operations_pb2.GetOperationRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> operations_pb2.Operation: - - r"""Call the get operation method over HTTP. - - Args: - request (operations_pb2.GetOperationRequest): - The request object for GetOperation method. - 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: - operations_pb2.Operation: Response from GetOperation method. - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v2/{name=projects/*/operations/*}', - }, -{ - 'method': 'get', - 'uri': '/v2/{name=projects/*/locations/*/operations/*}', - }, - ] - - request, metadata = self._interceptor.pre_get_operation(request, metadata) - request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode( - http_options, **request_kwargs) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json.dumps(transcoded_request['query_params'])) - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - resp = operations_pb2.Operation() - resp = json_format.Parse(response.content.decode("utf-8"), resp) - resp = self._interceptor.post_get_operation(resp) - return resp - - @property - def list_operations(self): - return self._ListOperations(self._session, self._host, self._interceptor) # type: ignore - - class _ListOperations(FulfillmentsRestStub): - def __call__(self, - request: operations_pb2.ListOperationsRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> operations_pb2.ListOperationsResponse: - - r"""Call the list operations method over HTTP. - - Args: - request (operations_pb2.ListOperationsRequest): - The request object for ListOperations method. - 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: - operations_pb2.ListOperationsResponse: Response from ListOperations method. - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v2/{name=projects/*}/operations', - }, -{ - 'method': 'get', - 'uri': '/v2/{name=projects/*/locations/*}/operations', - }, - ] - - request, metadata = self._interceptor.pre_list_operations(request, metadata) - request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode( - http_options, **request_kwargs) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json.dumps(transcoded_request['query_params'])) - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - resp = operations_pb2.ListOperationsResponse() - resp = json_format.Parse(response.content.decode("utf-8"), resp) - resp = self._interceptor.post_list_operations(resp) - return resp - - @property - def kind(self) -> str: - return "rest" - - def close(self): - self._session.close() - - -__all__=( - 'FulfillmentsRestTransport', -) diff --git a/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/intents/__init__.py b/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/intents/__init__.py deleted file mode 100644 index 536f6a0a2..000000000 --- a/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/intents/__init__.py +++ /dev/null @@ -1,22 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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 IntentsClient -from .async_client import IntentsAsyncClient - -__all__ = ( - 'IntentsClient', - 'IntentsAsyncClient', -) diff --git a/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/intents/async_client.py b/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/intents/async_client.py deleted file mode 100644 index 1935d1fbf..000000000 --- a/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/intents/async_client.py +++ /dev/null @@ -1,1400 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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, Mapping, MutableMapping, MutableSequence, Optional, Sequence, Tuple, Type, Union - -from google.cloud.dialogflow_v2 import gapic_version as package_version - -from google.api_core.client_options import ClientOptions -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import retry as retries -from google.auth import credentials as ga_credentials # type: ignore -from google.oauth2 import service_account # type: ignore - -try: - OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] -except AttributeError: # pragma: NO COVER - OptionalRetry = Union[retries.Retry, object] # type: ignore - -from google.api_core import operation # type: ignore -from google.api_core import operation_async # type: ignore -from google.cloud.dialogflow_v2.services.intents import pagers -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.cloud.location import locations_pb2 # type: ignore -from google.longrunning import operations_pb2 -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 - - -class IntentsAsyncClient: - """Service for managing [Intents][google.cloud.dialogflow.v2.Intent].""" - - _client: IntentsClient - - DEFAULT_ENDPOINT = IntentsClient.DEFAULT_ENDPOINT - DEFAULT_MTLS_ENDPOINT = IntentsClient.DEFAULT_MTLS_ENDPOINT - - context_path = staticmethod(IntentsClient.context_path) - 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) - - @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: - IntentsAsyncClient: The constructed client. - """ - return IntentsClient.from_service_account_info.__func__(IntentsAsyncClient, 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: - IntentsAsyncClient: The constructed client. - """ - return IntentsClient.from_service_account_file.__func__(IntentsAsyncClient, filename, *args, **kwargs) # type: ignore - - from_service_account_json = from_service_account_file - - @classmethod - def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[ClientOptions] = None): - """Return the API endpoint and client cert source for mutual TLS. - - The client cert source is determined in the following order: - (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the - client cert source is None. - (2) if `client_options.client_cert_source` is provided, use the provided one; if the - default client cert source exists, use the default one; otherwise the client cert - source is None. - - The API endpoint is determined in the following order: - (1) if `client_options.api_endpoint` if provided, use the provided one. - (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the - default mTLS endpoint; if the environment variable is "never", use the default API - endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise - use the default API endpoint. - - More details can be found at https://google.aip.dev/auth/4114. - - Args: - client_options (google.api_core.client_options.ClientOptions): Custom options for the - client. Only the `api_endpoint` and `client_cert_source` properties may be used - in this method. - - Returns: - Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the - client cert source to use. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If any errors happen. - """ - return IntentsClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore - - @property - def transport(self) -> IntentsTransport: - """Returns the transport used by the client instance. - - Returns: - IntentsTransport: The transport used by the client instance. - """ - return self._client.transport - - get_transport_class = functools.partial(type(IntentsClient).get_transport_class, type(IntentsClient)) - - def __init__(self, *, - credentials: Optional[ga_credentials.Credentials] = None, - transport: Union[str, IntentsTransport] = "grpc_asyncio", - client_options: Optional[ClientOptions] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the intents 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, ~.IntentsTransport]): 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 = IntentsClient( - credentials=credentials, - transport=transport, - client_options=client_options, - client_info=client_info, - - ) - - async def list_intents(self, - request: Optional[Union[intent.ListIntentsRequest, dict]] = None, - *, - parent: Optional[str] = None, - language_code: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListIntentsAsyncPager: - r"""Returns the list of all intents in the specified - agent. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import dialogflow_v2 - - async def sample_list_intents(): - # Create a client - client = dialogflow_v2.IntentsAsyncClient() - - # Initialize request argument(s) - request = dialogflow_v2.ListIntentsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_intents(request=request) - - # Handle the response - async for response in page_result: - print(response) - - Args: - request (Optional[Union[google.cloud.dialogflow_v2.types.ListIntentsRequest, dict]]): - The request object. The request message for - [Intents.ListIntents][google.cloud.dialogflow.v2.Intents.ListIntents]. - parent (:class:`str`): - Required. The agent to list all intents from. Format: - ``projects//agent`` or - ``projects//locations//agent``. - - Alternatively, you can specify the environment to list - intents for. Format: - ``projects//agent/environments/`` - or - ``projects//locations//agent/environments/``. - Note: training phrases of the intents will not be - returned for non-draft environment. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - language_code (:class:`str`): - Optional. The language used to access language-specific - data. If not specified, the agent's default language is - used. For more information, see `Multilingual intent and - entity - data `__. - - 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. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.dialogflow_v2.services.intents.pagers.ListIntentsAsyncPager: - The response message for - [Intents.ListIntents][google.cloud.dialogflow.v2.Intents.ListIntents]. - - Iterating over this object will yield results and - resolve additional pages automatically. - - """ - # Create or coerce a protobuf request object. - # Quick 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, language_code]) - 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 = 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: - request.language_code = language_code - - # 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_intents, - 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.ListIntentsAsyncPager( - method=rpc, - request=request, - response=response, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def get_intent(self, - request: Optional[Union[intent.GetIntentRequest, dict]] = None, - *, - name: Optional[str] = None, - language_code: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> intent.Intent: - r"""Retrieves the specified intent. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import dialogflow_v2 - - async def sample_get_intent(): - # Create a client - client = dialogflow_v2.IntentsAsyncClient() - - # Initialize request argument(s) - request = dialogflow_v2.GetIntentRequest( - name="name_value", - ) - - # Make the request - response = await client.get_intent(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.dialogflow_v2.types.GetIntentRequest, dict]]): - The request object. The request message for - [Intents.GetIntent][google.cloud.dialogflow.v2.Intents.GetIntent]. - name (:class:`str`): - Required. The name of the intent. Format: - ``projects//agent/intents/``. - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - language_code (:class:`str`): - Optional. The language used to access language-specific - data. If not specified, the agent's default language is - used. For more information, see `Multilingual intent and - entity - data `__. - - 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. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.dialogflow_v2.types.Intent: - An intent categorizes an end-user's intention for one conversation turn. For - each agent, you define many intents, where your - combined intents can handle a complete conversation. - When an end-user writes or says something, referred - to as an end-user expression or end-user input, - Dialogflow matches the end-user input to the best - intent in your agent. Matching an intent is also - known as intent classification. - - For more information, see the [intent - guide](\ https://cloud.google.com/dialogflow/docs/intents-overview). - - """ - # Create or coerce a protobuf request object. - # Quick 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, language_code]) - 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 = 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: - request.language_code = language_code - - # 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_intent, - 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_intent(self, - request: Optional[Union[gcd_intent.CreateIntentRequest, dict]] = None, - *, - parent: Optional[str] = None, - intent: Optional[gcd_intent.Intent] = None, - language_code: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gcd_intent.Intent: - r"""Creates an intent in the specified agent. - - Note: You should always train an agent prior to sending it - queries. See the `training - documentation `__. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import dialogflow_v2 - - async def sample_create_intent(): - # Create a client - client = dialogflow_v2.IntentsAsyncClient() - - # Initialize request argument(s) - intent = dialogflow_v2.Intent() - intent.display_name = "display_name_value" - - request = dialogflow_v2.CreateIntentRequest( - parent="parent_value", - intent=intent, - ) - - # Make the request - response = await client.create_intent(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.dialogflow_v2.types.CreateIntentRequest, dict]]): - The request object. The request message for - [Intents.CreateIntent][google.cloud.dialogflow.v2.Intents.CreateIntent]. - parent (:class:`str`): - Required. The agent to create a intent for. Format: - ``projects//agent``. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - intent (:class:`google.cloud.dialogflow_v2.types.Intent`): - Required. The intent to create. - This corresponds to the ``intent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - language_code (:class:`str`): - Optional. The language used to access language-specific - data. If not specified, the agent's default language is - used. For more information, see `Multilingual intent and - entity - data `__. - - 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. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.dialogflow_v2.types.Intent: - An intent categorizes an end-user's intention for one conversation turn. For - each agent, you define many intents, where your - combined intents can handle a complete conversation. - When an end-user writes or says something, referred - to as an end-user expression or end-user input, - Dialogflow matches the end-user input to the best - intent in your agent. Matching an intent is also - known as intent classification. - - For more information, see the [intent - guide](\ https://cloud.google.com/dialogflow/docs/intents-overview). - - """ - # Create or coerce a protobuf request object. - # Quick 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, intent, language_code]) - 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_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: - request.intent = intent - if language_code is not None: - request.language_code = language_code - - # 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_intent, - 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_intent(self, - request: Optional[Union[gcd_intent.UpdateIntentRequest, dict]] = None, - *, - intent: Optional[gcd_intent.Intent] = None, - language_code: Optional[str] = None, - update_mask: Optional[field_mask_pb2.FieldMask] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gcd_intent.Intent: - r"""Updates the specified intent. - - Note: You should always train an agent prior to sending it - queries. See the `training - documentation `__. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import dialogflow_v2 - - async def sample_update_intent(): - # Create a client - client = dialogflow_v2.IntentsAsyncClient() - - # Initialize request argument(s) - intent = dialogflow_v2.Intent() - intent.display_name = "display_name_value" - - request = dialogflow_v2.UpdateIntentRequest( - intent=intent, - ) - - # Make the request - response = await client.update_intent(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.dialogflow_v2.types.UpdateIntentRequest, dict]]): - The request object. The request message for - [Intents.UpdateIntent][google.cloud.dialogflow.v2.Intents.UpdateIntent]. - intent (:class:`google.cloud.dialogflow_v2.types.Intent`): - Required. The intent to update. - This corresponds to the ``intent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - language_code (:class:`str`): - Optional. The language used to access language-specific - data. If not specified, the agent's default language is - used. For more information, see `Multilingual intent and - entity - data `__. - - This corresponds to the ``language_code`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - update_mask (:class:`google.protobuf.field_mask_pb2.FieldMask`): - Optional. 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.Intent: - An intent categorizes an end-user's intention for one conversation turn. For - each agent, you define many intents, where your - combined intents can handle a complete conversation. - When an end-user writes or says something, referred - to as an end-user expression or end-user input, - Dialogflow matches the end-user input to the best - intent in your agent. Matching an intent is also - known as intent classification. - - For more information, see the [intent - guide](\ https://cloud.google.com/dialogflow/docs/intents-overview). - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([intent, language_code, 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_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: - request.language_code = language_code - 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_intent, - 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(( - ("intent.name", request.intent.name), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def delete_intent(self, - request: Optional[Union[intent.DeleteIntentRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> None: - r"""Deletes the specified intent and its direct or indirect followup - intents. - - Note: You should always train an agent prior to sending it - queries. See the `training - documentation `__. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import dialogflow_v2 - - async def sample_delete_intent(): - # Create a client - client = dialogflow_v2.IntentsAsyncClient() - - # Initialize request argument(s) - request = dialogflow_v2.DeleteIntentRequest( - name="name_value", - ) - - # Make the request - await client.delete_intent(request=request) - - Args: - request (Optional[Union[google.cloud.dialogflow_v2.types.DeleteIntentRequest, dict]]): - The request object. The request message for - [Intents.DeleteIntent][google.cloud.dialogflow.v2.Intents.DeleteIntent]. - name (:class:`str`): - Required. The name of the intent to delete. If this - intent has direct or indirect followup intents, we also - delete them. Format: - ``projects//agent/intents/``. - - 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. - # Quick 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 = intent.DeleteIntentRequest(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_intent, - 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 batch_update_intents(self, - request: Optional[Union[intent.BatchUpdateIntentsRequest, dict]] = None, - *, - parent: Optional[str] = None, - intent_batch_uri: Optional[str] = None, - intent_batch_inline: Optional[intent.IntentBatch] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation_async.AsyncOperation: - r"""Updates/Creates multiple intents in the specified agent. - - This method is a `long-running - operation `__. - The returned ``Operation`` type has the following - method-specific fields: - - - ``metadata``: An empty `Struct - message `__ - - ``response``: - [BatchUpdateIntentsResponse][google.cloud.dialogflow.v2.BatchUpdateIntentsResponse] - - Note: You should always train an agent prior to sending it - queries. See the `training - documentation `__. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import dialogflow_v2 - - async def sample_batch_update_intents(): - # Create a client - client = dialogflow_v2.IntentsAsyncClient() - - # Initialize request argument(s) - request = dialogflow_v2.BatchUpdateIntentsRequest( - intent_batch_uri="intent_batch_uri_value", - parent="parent_value", - ) - - # Make the request - operation = client.batch_update_intents(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.dialogflow_v2.types.BatchUpdateIntentsRequest, dict]]): - The request object. - parent (:class:`str`): - Required. The name of the agent to update or create - intents in. Format: ``projects//agent``. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - intent_batch_uri (:class:`str`): - The URI to a Google Cloud Storage - file containing intents to update or - create. The file format can either be a - serialized proto (of IntentBatch type) - or JSON object. Note: The URI must start - with "gs://". - - This corresponds to the ``intent_batch_uri`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - intent_batch_inline (:class:`google.cloud.dialogflow_v2.types.IntentBatch`): - The collection of intents to update - or create. - - 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. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.api_core.operation_async.AsyncOperation: - An object representing a long-running operation. - - The result type for the operation will be :class:`google.cloud.dialogflow_v2.types.BatchUpdateIntentsResponse` The response message for - [Intents.BatchUpdateIntents][google.cloud.dialogflow.v2.Intents.BatchUpdateIntents]. - - """ - # Create or coerce a protobuf request object. - # Quick 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, intent_batch_uri, intent_batch_inline]) - 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 = 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: - request.intent_batch_uri = intent_batch_uri - if intent_batch_inline is not None: - request.intent_batch_inline = intent_batch_inline - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.batch_update_intents, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Wrap the response in an operation future. - response = operation_async.from_gapic( - response, - self._client._transport.operations_client, - intent.BatchUpdateIntentsResponse, - metadata_type=struct_pb2.Struct, - ) - - # Done; return the response. - return response - - async def batch_delete_intents(self, - request: Optional[Union[intent.BatchDeleteIntentsRequest, dict]] = None, - *, - parent: Optional[str] = None, - intents: Optional[MutableSequence[intent.Intent]] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation_async.AsyncOperation: - r"""Deletes intents in the specified agent. - - This method is a `long-running - operation `__. - The returned ``Operation`` type has the following - method-specific fields: - - - ``metadata``: An empty `Struct - message `__ - - ``response``: An `Empty - message `__ - - Note: You should always train an agent prior to sending it - queries. See the `training - documentation `__. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import dialogflow_v2 - - async def sample_batch_delete_intents(): - # Create a client - client = dialogflow_v2.IntentsAsyncClient() - - # Initialize request argument(s) - intents = dialogflow_v2.Intent() - intents.display_name = "display_name_value" - - request = dialogflow_v2.BatchDeleteIntentsRequest( - parent="parent_value", - intents=intents, - ) - - # Make the request - operation = client.batch_delete_intents(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.dialogflow_v2.types.BatchDeleteIntentsRequest, dict]]): - The request object. The request message for - [Intents.BatchDeleteIntents][google.cloud.dialogflow.v2.Intents.BatchDeleteIntents]. - parent (:class:`str`): - Required. The name of the agent to delete all entities - types for. Format: ``projects//agent``. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - intents (:class:`MutableSequence[google.cloud.dialogflow_v2.types.Intent]`): - Required. The collection of intents to delete. Only - intent ``name`` must be filled in. - - 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. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.api_core.operation_async.AsyncOperation: - An object representing a long-running operation. - - The result type for the operation will be :class:`google.protobuf.empty_pb2.Empty` A generic empty message that you can re-use to avoid defining duplicated - empty messages in your APIs. A typical example is to - use it as the request or the response type of an API - method. For instance: - - service Foo { - rpc Bar(google.protobuf.Empty) returns - (google.protobuf.Empty); - - } - - """ - # Create or coerce a protobuf request object. - # Quick 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, intents]) - 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 = 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: - request.intents.extend(intents) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.batch_delete_intents, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Wrap the response in an operation future. - response = operation_async.from_gapic( - response, - self._client._transport.operations_client, - empty_pb2.Empty, - metadata_type=struct_pb2.Struct, - ) - - # Done; return the response. - return response - - async def list_operations( - self, - request: Optional[operations_pb2.ListOperationsRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operations_pb2.ListOperationsResponse: - r"""Lists operations that match the specified filter in the request. - - Args: - request (:class:`~.operations_pb2.ListOperationsRequest`): - The request object. Request message for - `ListOperations` method. - 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: - ~.operations_pb2.ListOperationsResponse: - Response message for ``ListOperations`` method. - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = operations_pb2.ListOperationsRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._client._transport.list_operations, - 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 get_operation( - self, - request: Optional[operations_pb2.GetOperationRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operations_pb2.Operation: - r"""Gets the latest state of a long-running operation. - - Args: - request (:class:`~.operations_pb2.GetOperationRequest`): - The request object. Request message for - `GetOperation` method. - 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: - ~.operations_pb2.Operation: - An ``Operation`` object. - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = operations_pb2.GetOperationRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._client._transport.get_operation, - 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 cancel_operation( - self, - request: Optional[operations_pb2.CancelOperationRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> None: - r"""Starts asynchronous cancellation on a long-running operation. - - The server makes a best effort to cancel the operation, but success - is not guaranteed. If the server doesn't support this method, it returns - `google.rpc.Code.UNIMPLEMENTED`. - - Args: - request (:class:`~.operations_pb2.CancelOperationRequest`): - The request object. Request message for - `CancelOperation` method. - 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: - None - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = operations_pb2.CancelOperationRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._client._transport.cancel_operation, - 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_location( - self, - request: Optional[locations_pb2.GetLocationRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> locations_pb2.Location: - r"""Gets information about a location. - - Args: - request (:class:`~.location_pb2.GetLocationRequest`): - The request object. Request message for - `GetLocation` method. - 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: - ~.location_pb2.Location: - Location object. - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = locations_pb2.GetLocationRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._client._transport.get_location, - 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 list_locations( - self, - request: Optional[locations_pb2.ListLocationsRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> locations_pb2.ListLocationsResponse: - r"""Lists information about the supported locations for this service. - - Args: - request (:class:`~.location_pb2.ListLocationsRequest`): - The request object. Request message for - `ListLocations` method. - 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: - ~.location_pb2.ListLocationsResponse: - Response message for ``ListLocations`` method. - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = locations_pb2.ListLocationsRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._client._transport.list_locations, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("name", request.name),)), - ) - - # Send the request. - response = await rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - async def __aenter__(self): - return self - - async def __aexit__(self, exc_type, exc, tb): - await self.transport.close() - -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) - - -__all__ = ( - "IntentsAsyncClient", -) diff --git a/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/intents/client.py b/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/intents/client.py deleted file mode 100644 index 897383d1f..000000000 --- a/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/intents/client.py +++ /dev/null @@ -1,1608 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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 os -import re -from typing import Dict, Mapping, MutableMapping, MutableSequence, Optional, Sequence, Tuple, Type, Union, cast - -from google.cloud.dialogflow_v2 import gapic_version as package_version - -from google.api_core import client_options as client_options_lib -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import retry as retries -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 - -try: - OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] -except AttributeError: # pragma: NO COVER - OptionalRetry = Union[retries.Retry, object] # type: ignore - -from google.api_core import operation # type: ignore -from google.api_core import operation_async # type: ignore -from google.cloud.dialogflow_v2.services.intents import pagers -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.cloud.location import locations_pb2 # type: ignore -from google.longrunning import operations_pb2 -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 -from .transports.rest import IntentsRestTransport - - -class IntentsClientMeta(type): - """Metaclass for the Intents 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[IntentsTransport]] - _transport_registry["grpc"] = IntentsGrpcTransport - _transport_registry["grpc_asyncio"] = IntentsGrpcAsyncIOTransport - _transport_registry["rest"] = IntentsRestTransport - - def get_transport_class(cls, - label: Optional[str] = None, - ) -> Type[IntentsTransport]: - """Returns an appropriate transport class. - - Args: - label: The name of the desired transport. If none is - provided, then the first transport in the registry is used. - - Returns: - The transport class to use. - """ - # If a specific transport is requested, return that one. - if label: - return cls._transport_registry[label] - - # No transport is requested; return the default (that is, the first one - # in the dictionary). - return next(iter(cls._transport_registry.values())) - - -class IntentsClient(metaclass=IntentsClientMeta): - """Service for managing [Intents][google.cloud.dialogflow.v2.Intent].""" - - @staticmethod - def _get_default_mtls_endpoint(api_endpoint): - """Converts api endpoint to mTLS endpoint. - - Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to - "*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively. - Args: - api_endpoint (Optional[str]): the api endpoint to convert. - Returns: - str: converted mTLS api endpoint. - """ - if not api_endpoint: - return api_endpoint - - mtls_endpoint_re = re.compile( - r"(?P[^.]+)(?P\.mtls)?(?P\.sandbox)?(?P\.googleapis\.com)?" - ) - - m = mtls_endpoint_re.match(api_endpoint) - name, mtls, sandbox, googledomain = m.groups() - if mtls or not googledomain: - return api_endpoint - - if sandbox: - return api_endpoint.replace( - "sandbox.googleapis.com", "mtls.sandbox.googleapis.com" - ) - - return api_endpoint.replace(".googleapis.com", ".mtls.googleapis.com") - - DEFAULT_ENDPOINT = "dialogflow.googleapis.com" - DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore - DEFAULT_ENDPOINT - ) - - @classmethod - def from_service_account_info(cls, info: dict, *args, **kwargs): - """Creates an instance of this client using the provided credentials - info. - - Args: - info (dict): The service account private key info. - args: Additional arguments to pass to the constructor. - kwargs: Additional arguments to pass to the constructor. - - Returns: - IntentsClient: 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: - IntentsClient: 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) -> IntentsTransport: - """Returns the transport used by the client instance. - - Returns: - IntentsTransport: The transport used by the client - instance. - """ - return self._transport - - @staticmethod - def context_path(project: str,session: str,context: str,) -> str: - """Returns a fully-qualified context string.""" - return "projects/{project}/agent/sessions/{session}/contexts/{context}".format(project=project, session=session, context=context, ) - - @staticmethod - def parse_context_path(path: str) -> Dict[str,str]: - """Parses a context path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/agent/sessions/(?P.+?)/contexts/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def intent_path(project: str,intent: str,) -> str: - """Returns a fully-qualified intent string.""" - return "projects/{project}/agent/intents/{intent}".format(project=project, intent=intent, ) - - @staticmethod - def parse_intent_path(path: str) -> Dict[str,str]: - """Parses a intent path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/agent/intents/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_billing_account_path(billing_account: str, ) -> str: - """Returns a fully-qualified billing_account string.""" - return "billingAccounts/{billing_account}".format(billing_account=billing_account, ) - - @staticmethod - def parse_common_billing_account_path(path: str) -> Dict[str,str]: - """Parse a billing_account path into its component segments.""" - m = re.match(r"^billingAccounts/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_folder_path(folder: str, ) -> str: - """Returns a fully-qualified folder string.""" - return "folders/{folder}".format(folder=folder, ) - - @staticmethod - def parse_common_folder_path(path: str) -> Dict[str,str]: - """Parse a folder path into its component segments.""" - m = re.match(r"^folders/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_organization_path(organization: str, ) -> str: - """Returns a fully-qualified organization string.""" - return "organizations/{organization}".format(organization=organization, ) - - @staticmethod - def parse_common_organization_path(path: str) -> Dict[str,str]: - """Parse a organization path into its component segments.""" - m = re.match(r"^organizations/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_project_path(project: str, ) -> str: - """Returns a fully-qualified project string.""" - return "projects/{project}".format(project=project, ) - - @staticmethod - def parse_common_project_path(path: str) -> Dict[str,str]: - """Parse a project path into its component segments.""" - m = re.match(r"^projects/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_location_path(project: str, location: str, ) -> str: - """Returns a fully-qualified location string.""" - return "projects/{project}/locations/{location}".format(project=project, location=location, ) - - @staticmethod - def parse_common_location_path(path: str) -> Dict[str,str]: - """Parse a location path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)$", path) - return m.groupdict() if m else {} - - @classmethod - def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[client_options_lib.ClientOptions] = None): - """Return the API endpoint and client cert source for mutual TLS. - - The client cert source is determined in the following order: - (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the - client cert source is None. - (2) if `client_options.client_cert_source` is provided, use the provided one; if the - default client cert source exists, use the default one; otherwise the client cert - source is None. - - The API endpoint is determined in the following order: - (1) if `client_options.api_endpoint` if provided, use the provided one. - (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the - default mTLS endpoint; if the environment variable is "never", use the default API - endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise - use the default API endpoint. - - More details can be found at https://google.aip.dev/auth/4114. - - Args: - client_options (google.api_core.client_options.ClientOptions): Custom options for the - client. Only the `api_endpoint` and `client_cert_source` properties may be used - in this method. - - Returns: - Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the - client cert source to use. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If any errors happen. - """ - if client_options is None: - client_options = client_options_lib.ClientOptions() - use_client_cert = os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false") - use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") - if use_client_cert not in ("true", "false"): - raise ValueError("Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`") - if use_mtls_endpoint not in ("auto", "never", "always"): - raise MutualTLSChannelError("Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`") - - # Figure out the client cert source to use. - client_cert_source = None - if use_client_cert == "true": - if client_options.client_cert_source: - client_cert_source = client_options.client_cert_source - elif mtls.has_default_client_cert_source(): - client_cert_source = mtls.default_client_cert_source() - - # Figure out which api endpoint to use. - if client_options.api_endpoint is not None: - api_endpoint = client_options.api_endpoint - elif use_mtls_endpoint == "always" or (use_mtls_endpoint == "auto" and client_cert_source): - api_endpoint = cls.DEFAULT_MTLS_ENDPOINT - else: - api_endpoint = cls.DEFAULT_ENDPOINT - - return api_endpoint, client_cert_source - - def __init__(self, *, - credentials: Optional[ga_credentials.Credentials] = None, - transport: Optional[Union[str, IntentsTransport]] = None, - client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the intents 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, IntentsTransport]): The - transport to use. If set to None, a transport is chosen - automatically. - client_options (Optional[Union[google.api_core.client_options.ClientOptions, dict]]): 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() - client_options = cast(client_options_lib.ClientOptions, client_options) - - api_endpoint, client_cert_source_func = self.get_mtls_endpoint_and_cert_source(client_options) - - api_key_value = getattr(client_options, "api_key", None) - if api_key_value and credentials: - raise ValueError("client_options.api_key and credentials are mutually exclusive") - - # 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, IntentsTransport): - # transport is a IntentsTransport instance. - if credentials or client_options.credentials_file or api_key_value: - 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: - import google.auth._default # type: ignore - - if api_key_value and hasattr(google.auth._default, "get_api_key_credentials"): - credentials = google.auth._default.get_api_key_credentials(api_key_value) - - Transport = type(self).get_transport_class(transport) - self._transport = Transport( - credentials=credentials, - credentials_file=client_options.credentials_file, - host=api_endpoint, - scopes=client_options.scopes, - client_cert_source_for_mtls=client_cert_source_func, - quota_project_id=client_options.quota_project_id, - client_info=client_info, - always_use_jwt_access=True, - api_audience=client_options.api_audience, - ) - - def list_intents(self, - request: Optional[Union[intent.ListIntentsRequest, dict]] = None, - *, - parent: Optional[str] = None, - language_code: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListIntentsPager: - r"""Returns the list of all intents in the specified - agent. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import dialogflow_v2 - - def sample_list_intents(): - # Create a client - client = dialogflow_v2.IntentsClient() - - # Initialize request argument(s) - request = dialogflow_v2.ListIntentsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_intents(request=request) - - # Handle the response - for response in page_result: - print(response) - - Args: - request (Union[google.cloud.dialogflow_v2.types.ListIntentsRequest, dict]): - The request object. The request message for - [Intents.ListIntents][google.cloud.dialogflow.v2.Intents.ListIntents]. - parent (str): - Required. The agent to list all intents from. Format: - ``projects//agent`` or - ``projects//locations//agent``. - - Alternatively, you can specify the environment to list - intents for. Format: - ``projects//agent/environments/`` - or - ``projects//locations//agent/environments/``. - Note: training phrases of the intents will not be - returned for non-draft environment. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - language_code (str): - Optional. The language used to access language-specific - data. If not specified, the agent's default language is - used. For more information, see `Multilingual intent and - entity - data `__. - - 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. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.dialogflow_v2.services.intents.pagers.ListIntentsPager: - The response message for - [Intents.ListIntents][google.cloud.dialogflow.v2.Intents.ListIntents]. - - Iterating over this object will yield results and - resolve additional pages automatically. - - """ - # Create or coerce a protobuf request object. - # Quick 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, language_code]) - 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 intent.ListIntentsRequest. - # There's no risk of modifying the input as we've already verified - # 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: - request.language_code = language_code - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.list_intents] - - # 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.ListIntentsPager( - method=rpc, - request=request, - response=response, - metadata=metadata, - ) - - # Done; return the response. - return response - - def get_intent(self, - request: Optional[Union[intent.GetIntentRequest, dict]] = None, - *, - name: Optional[str] = None, - language_code: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> intent.Intent: - r"""Retrieves the specified intent. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import dialogflow_v2 - - def sample_get_intent(): - # Create a client - client = dialogflow_v2.IntentsClient() - - # Initialize request argument(s) - request = dialogflow_v2.GetIntentRequest( - name="name_value", - ) - - # Make the request - response = client.get_intent(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.dialogflow_v2.types.GetIntentRequest, dict]): - The request object. The request message for - [Intents.GetIntent][google.cloud.dialogflow.v2.Intents.GetIntent]. - name (str): - Required. The name of the intent. Format: - ``projects//agent/intents/``. - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - language_code (str): - Optional. The language used to access language-specific - data. If not specified, the agent's default language is - used. For more information, see `Multilingual intent and - entity - data `__. - - 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. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.dialogflow_v2.types.Intent: - An intent categorizes an end-user's intention for one conversation turn. For - each agent, you define many intents, where your - combined intents can handle a complete conversation. - When an end-user writes or says something, referred - to as an end-user expression or end-user input, - Dialogflow matches the end-user input to the best - intent in your agent. Matching an intent is also - known as intent classification. - - For more information, see the [intent - guide](\ https://cloud.google.com/dialogflow/docs/intents-overview). - - """ - # Create or coerce a protobuf request object. - # Quick 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, language_code]) - 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 intent.GetIntentRequest. - # There's no risk of modifying the input as we've already verified - # 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: - request.language_code = language_code - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.get_intent] - - # 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_intent(self, - request: Optional[Union[gcd_intent.CreateIntentRequest, dict]] = None, - *, - parent: Optional[str] = None, - intent: Optional[gcd_intent.Intent] = None, - language_code: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gcd_intent.Intent: - r"""Creates an intent in the specified agent. - - Note: You should always train an agent prior to sending it - queries. See the `training - documentation `__. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import dialogflow_v2 - - def sample_create_intent(): - # Create a client - client = dialogflow_v2.IntentsClient() - - # Initialize request argument(s) - intent = dialogflow_v2.Intent() - intent.display_name = "display_name_value" - - request = dialogflow_v2.CreateIntentRequest( - parent="parent_value", - intent=intent, - ) - - # Make the request - response = client.create_intent(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.dialogflow_v2.types.CreateIntentRequest, dict]): - The request object. The request message for - [Intents.CreateIntent][google.cloud.dialogflow.v2.Intents.CreateIntent]. - parent (str): - Required. The agent to create a intent for. Format: - ``projects//agent``. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - intent (google.cloud.dialogflow_v2.types.Intent): - Required. The intent to create. - This corresponds to the ``intent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - language_code (str): - Optional. The language used to access language-specific - data. If not specified, the agent's default language is - used. For more information, see `Multilingual intent and - entity - data `__. - - 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. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.dialogflow_v2.types.Intent: - An intent categorizes an end-user's intention for one conversation turn. For - each agent, you define many intents, where your - combined intents can handle a complete conversation. - When an end-user writes or says something, referred - to as an end-user expression or end-user input, - Dialogflow matches the end-user input to the best - intent in your agent. Matching an intent is also - known as intent classification. - - For more information, see the [intent - guide](\ https://cloud.google.com/dialogflow/docs/intents-overview). - - """ - # Create or coerce a protobuf request object. - # Quick 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, intent, language_code]) - 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_intent.CreateIntentRequest. - # There's no risk of modifying the input as we've already verified - # 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: - request.intent = intent - if language_code is not None: - request.language_code = language_code - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.create_intent] - - # 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_intent(self, - request: Optional[Union[gcd_intent.UpdateIntentRequest, dict]] = None, - *, - intent: Optional[gcd_intent.Intent] = None, - language_code: Optional[str] = None, - update_mask: Optional[field_mask_pb2.FieldMask] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gcd_intent.Intent: - r"""Updates the specified intent. - - Note: You should always train an agent prior to sending it - queries. See the `training - documentation `__. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import dialogflow_v2 - - def sample_update_intent(): - # Create a client - client = dialogflow_v2.IntentsClient() - - # Initialize request argument(s) - intent = dialogflow_v2.Intent() - intent.display_name = "display_name_value" - - request = dialogflow_v2.UpdateIntentRequest( - intent=intent, - ) - - # Make the request - response = client.update_intent(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.dialogflow_v2.types.UpdateIntentRequest, dict]): - The request object. The request message for - [Intents.UpdateIntent][google.cloud.dialogflow.v2.Intents.UpdateIntent]. - intent (google.cloud.dialogflow_v2.types.Intent): - Required. The intent to update. - This corresponds to the ``intent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - language_code (str): - Optional. The language used to access language-specific - data. If not specified, the agent's default language is - used. For more information, see `Multilingual intent and - entity - data `__. - - This corresponds to the ``language_code`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - update_mask (google.protobuf.field_mask_pb2.FieldMask): - Optional. 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.Intent: - An intent categorizes an end-user's intention for one conversation turn. For - each agent, you define many intents, where your - combined intents can handle a complete conversation. - When an end-user writes or says something, referred - to as an end-user expression or end-user input, - Dialogflow matches the end-user input to the best - intent in your agent. Matching an intent is also - known as intent classification. - - For more information, see the [intent - guide](\ https://cloud.google.com/dialogflow/docs/intents-overview). - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([intent, language_code, 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_intent.UpdateIntentRequest. - # There's no risk of modifying the input as we've already verified - # 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: - request.language_code = language_code - 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_intent] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("intent.name", request.intent.name), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def delete_intent(self, - request: Optional[Union[intent.DeleteIntentRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> None: - r"""Deletes the specified intent and its direct or indirect followup - intents. - - Note: You should always train an agent prior to sending it - queries. See the `training - documentation `__. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import dialogflow_v2 - - def sample_delete_intent(): - # Create a client - client = dialogflow_v2.IntentsClient() - - # Initialize request argument(s) - request = dialogflow_v2.DeleteIntentRequest( - name="name_value", - ) - - # Make the request - client.delete_intent(request=request) - - Args: - request (Union[google.cloud.dialogflow_v2.types.DeleteIntentRequest, dict]): - The request object. The request message for - [Intents.DeleteIntent][google.cloud.dialogflow.v2.Intents.DeleteIntent]. - name (str): - Required. The name of the intent to delete. If this - intent has direct or indirect followup intents, we also - delete them. Format: - ``projects//agent/intents/``. - - 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. - # Quick 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 intent.DeleteIntentRequest. - # There's no risk of modifying the input as we've already verified - # 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 - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.delete_intent] - - # 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 batch_update_intents(self, - request: Optional[Union[intent.BatchUpdateIntentsRequest, dict]] = None, - *, - parent: Optional[str] = None, - intent_batch_uri: Optional[str] = None, - intent_batch_inline: Optional[intent.IntentBatch] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation.Operation: - r"""Updates/Creates multiple intents in the specified agent. - - This method is a `long-running - operation `__. - The returned ``Operation`` type has the following - method-specific fields: - - - ``metadata``: An empty `Struct - message `__ - - ``response``: - [BatchUpdateIntentsResponse][google.cloud.dialogflow.v2.BatchUpdateIntentsResponse] - - Note: You should always train an agent prior to sending it - queries. See the `training - documentation `__. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import dialogflow_v2 - - def sample_batch_update_intents(): - # Create a client - client = dialogflow_v2.IntentsClient() - - # Initialize request argument(s) - request = dialogflow_v2.BatchUpdateIntentsRequest( - intent_batch_uri="intent_batch_uri_value", - parent="parent_value", - ) - - # Make the request - operation = client.batch_update_intents(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.dialogflow_v2.types.BatchUpdateIntentsRequest, dict]): - The request object. - parent (str): - Required. The name of the agent to update or create - intents in. Format: ``projects//agent``. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - intent_batch_uri (str): - The URI to a Google Cloud Storage - file containing intents to update or - create. The file format can either be a - serialized proto (of IntentBatch type) - or JSON object. Note: The URI must start - with "gs://". - - This corresponds to the ``intent_batch_uri`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - intent_batch_inline (google.cloud.dialogflow_v2.types.IntentBatch): - The collection of intents to update - or create. - - 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. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.api_core.operation.Operation: - An object representing a long-running operation. - - The result type for the operation will be :class:`google.cloud.dialogflow_v2.types.BatchUpdateIntentsResponse` The response message for - [Intents.BatchUpdateIntents][google.cloud.dialogflow.v2.Intents.BatchUpdateIntents]. - - """ - # Create or coerce a protobuf request object. - # Quick 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, intent_batch_uri, intent_batch_inline]) - 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 intent.BatchUpdateIntentsRequest. - # There's no risk of modifying the input as we've already verified - # 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: - request.intent_batch_uri = intent_batch_uri - if intent_batch_inline is not None: - request.intent_batch_inline = intent_batch_inline - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.batch_update_intents] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Wrap the response in an operation future. - response = operation.from_gapic( - response, - self._transport.operations_client, - intent.BatchUpdateIntentsResponse, - metadata_type=struct_pb2.Struct, - ) - - # Done; return the response. - return response - - def batch_delete_intents(self, - request: Optional[Union[intent.BatchDeleteIntentsRequest, dict]] = None, - *, - parent: Optional[str] = None, - intents: Optional[MutableSequence[intent.Intent]] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation.Operation: - r"""Deletes intents in the specified agent. - - This method is a `long-running - operation `__. - The returned ``Operation`` type has the following - method-specific fields: - - - ``metadata``: An empty `Struct - message `__ - - ``response``: An `Empty - message `__ - - Note: You should always train an agent prior to sending it - queries. See the `training - documentation `__. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import dialogflow_v2 - - def sample_batch_delete_intents(): - # Create a client - client = dialogflow_v2.IntentsClient() - - # Initialize request argument(s) - intents = dialogflow_v2.Intent() - intents.display_name = "display_name_value" - - request = dialogflow_v2.BatchDeleteIntentsRequest( - parent="parent_value", - intents=intents, - ) - - # Make the request - operation = client.batch_delete_intents(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.dialogflow_v2.types.BatchDeleteIntentsRequest, dict]): - The request object. The request message for - [Intents.BatchDeleteIntents][google.cloud.dialogflow.v2.Intents.BatchDeleteIntents]. - parent (str): - Required. The name of the agent to delete all entities - types for. Format: ``projects//agent``. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - intents (MutableSequence[google.cloud.dialogflow_v2.types.Intent]): - Required. The collection of intents to delete. Only - intent ``name`` must be filled in. - - 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. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.api_core.operation.Operation: - An object representing a long-running operation. - - The result type for the operation will be :class:`google.protobuf.empty_pb2.Empty` A generic empty message that you can re-use to avoid defining duplicated - empty messages in your APIs. A typical example is to - use it as the request or the response type of an API - method. For instance: - - service Foo { - rpc Bar(google.protobuf.Empty) returns - (google.protobuf.Empty); - - } - - """ - # Create or coerce a protobuf request object. - # Quick 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, intents]) - 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 intent.BatchDeleteIntentsRequest. - # There's no risk of modifying the input as we've already verified - # 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: - request.intents = intents - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.batch_delete_intents] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Wrap the response in an operation future. - response = operation.from_gapic( - response, - self._transport.operations_client, - empty_pb2.Empty, - metadata_type=struct_pb2.Struct, - ) - - # Done; return the response. - return response - - def __enter__(self) -> "IntentsClient": - return self - - def __exit__(self, type, value, traceback): - """Releases underlying transport's resources. - - .. warning:: - ONLY use as a context manager if the transport is NOT shared - with other clients! Exiting the with block will CLOSE the transport - and may cause errors in other clients! - """ - self.transport.close() - - def list_operations( - self, - request: Optional[operations_pb2.ListOperationsRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operations_pb2.ListOperationsResponse: - r"""Lists operations that match the specified filter in the request. - - Args: - request (:class:`~.operations_pb2.ListOperationsRequest`): - The request object. Request message for - `ListOperations` method. - 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: - ~.operations_pb2.ListOperationsResponse: - Response message for ``ListOperations`` method. - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = operations_pb2.ListOperationsRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._transport.list_operations, - 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 = rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - def get_operation( - self, - request: Optional[operations_pb2.GetOperationRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operations_pb2.Operation: - r"""Gets the latest state of a long-running operation. - - Args: - request (:class:`~.operations_pb2.GetOperationRequest`): - The request object. Request message for - `GetOperation` method. - 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: - ~.operations_pb2.Operation: - An ``Operation`` object. - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = operations_pb2.GetOperationRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._transport.get_operation, - 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 = rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - def cancel_operation( - self, - request: Optional[operations_pb2.CancelOperationRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> None: - r"""Starts asynchronous cancellation on a long-running operation. - - The server makes a best effort to cancel the operation, but success - is not guaranteed. If the server doesn't support this method, it returns - `google.rpc.Code.UNIMPLEMENTED`. - - Args: - request (:class:`~.operations_pb2.CancelOperationRequest`): - The request object. Request message for - `CancelOperation` method. - 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: - None - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = operations_pb2.CancelOperationRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._transport.cancel_operation, - 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. - rpc(request, retry=retry, timeout=timeout, metadata=metadata,) - - def get_location( - self, - request: Optional[locations_pb2.GetLocationRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> locations_pb2.Location: - r"""Gets information about a location. - - Args: - request (:class:`~.location_pb2.GetLocationRequest`): - The request object. Request message for - `GetLocation` method. - 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: - ~.location_pb2.Location: - Location object. - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = locations_pb2.GetLocationRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._transport.get_location, - 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 = rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - def list_locations( - self, - request: Optional[locations_pb2.ListLocationsRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> locations_pb2.ListLocationsResponse: - r"""Lists information about the supported locations for this service. - - Args: - request (:class:`~.location_pb2.ListLocationsRequest`): - The request object. Request message for - `ListLocations` method. - 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: - ~.location_pb2.ListLocationsResponse: - Response message for ``ListLocations`` method. - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = locations_pb2.ListLocationsRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._transport.list_locations, - 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 = rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) - - -__all__ = ( - "IntentsClient", -) diff --git a/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/intents/pagers.py b/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/intents/pagers.py deleted file mode 100644 index 3938f12dd..000000000 --- a/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/intents/pagers.py +++ /dev/null @@ -1,139 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from typing import Any, AsyncIterator, Awaitable, Callable, Sequence, Tuple, Optional, Iterator - -from google.cloud.dialogflow_v2.types import intent - - -class ListIntentsPager: - """A pager for iterating through ``list_intents`` requests. - - This class thinly wraps an initial - :class:`google.cloud.dialogflow_v2.types.ListIntentsResponse` object, and - provides an ``__iter__`` method to iterate through its - ``intents`` field. - - If there are more pages, the ``__iter__`` method will make additional - ``ListIntents`` requests and continue to iterate - through the ``intents`` field on the - corresponding responses. - - All the usual :class:`google.cloud.dialogflow_v2.types.ListIntentsResponse` - 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[..., intent.ListIntentsResponse], - request: intent.ListIntentsRequest, - response: intent.ListIntentsResponse, - *, - 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.ListIntentsRequest): - The initial request object. - response (google.cloud.dialogflow_v2.types.ListIntentsResponse): - 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 = intent.ListIntentsRequest(request) - self._response = response - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - def pages(self) -> Iterator[intent.ListIntentsResponse]: - yield self._response - while self._response.next_page_token: - self._request.page_token = self._response.next_page_token - self._response = self._method(self._request, metadata=self._metadata) - yield self._response - - def __iter__(self) -> Iterator[intent.Intent]: - for page in self.pages: - yield from page.intents - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListIntentsAsyncPager: - """A pager for iterating through ``list_intents`` requests. - - This class thinly wraps an initial - :class:`google.cloud.dialogflow_v2.types.ListIntentsResponse` object, and - provides an ``__aiter__`` method to iterate through its - ``intents`` field. - - If there are more pages, the ``__aiter__`` method will make additional - ``ListIntents`` requests and continue to iterate - through the ``intents`` field on the - corresponding responses. - - All the usual :class:`google.cloud.dialogflow_v2.types.ListIntentsResponse` - 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[intent.ListIntentsResponse]], - request: intent.ListIntentsRequest, - response: intent.ListIntentsResponse, - *, - metadata: Sequence[Tuple[str, str]] = ()): - """Instantiates the pager. - - Args: - method (Callable): The method that was originally called, and - which instantiated this pager. - request (google.cloud.dialogflow_v2.types.ListIntentsRequest): - The initial request object. - response (google.cloud.dialogflow_v2.types.ListIntentsResponse): - 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 = intent.ListIntentsRequest(request) - self._response = response - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - async def pages(self) -> AsyncIterator[intent.ListIntentsResponse]: - yield self._response - while self._response.next_page_token: - self._request.page_token = self._response.next_page_token - self._response = await self._method(self._request, metadata=self._metadata) - yield self._response - def __aiter__(self) -> AsyncIterator[intent.Intent]: - async def async_generator(): - async for page in self.pages: - for response in page.intents: - yield response - - return async_generator() - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) diff --git a/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/intents/transports/__init__.py b/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/intents/transports/__init__.py deleted file mode 100644 index 97fdd7315..000000000 --- a/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/intents/transports/__init__.py +++ /dev/null @@ -1,38 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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 IntentsTransport -from .grpc import IntentsGrpcTransport -from .grpc_asyncio import IntentsGrpcAsyncIOTransport -from .rest import IntentsRestTransport -from .rest import IntentsRestInterceptor - - -# Compile a registry of transports. -_transport_registry = OrderedDict() # type: Dict[str, Type[IntentsTransport]] -_transport_registry['grpc'] = IntentsGrpcTransport -_transport_registry['grpc_asyncio'] = IntentsGrpcAsyncIOTransport -_transport_registry['rest'] = IntentsRestTransport - -__all__ = ( - 'IntentsTransport', - 'IntentsGrpcTransport', - 'IntentsGrpcAsyncIOTransport', - 'IntentsRestTransport', - 'IntentsRestInterceptor', -) diff --git a/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/intents/transports/base.py b/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/intents/transports/base.py deleted file mode 100644 index b524cdb09..000000000 --- a/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/intents/transports/base.py +++ /dev/null @@ -1,287 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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 - -from google.cloud.dialogflow_v2 import gapic_version as package_version - -import google.auth # type: ignore -import google.api_core -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import retry as retries -from google.api_core import operations_v1 -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 intent -from google.cloud.dialogflow_v2.types import intent as gcd_intent -from google.cloud.location import locations_pb2 # type: ignore -from google.longrunning import operations_pb2 -from google.longrunning import operations_pb2 # type: ignore -from google.protobuf import empty_pb2 # type: ignore - -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) - - -class IntentsTransport(abc.ABC): - """Abstract transport class for Intents.""" - - 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: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - api_audience: Optional[str] = None, - **kwargs, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. - scopes (Optional[Sequence[str]]): A list of scopes. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - """ - - scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} - - # Save the scopes. - self._scopes = scopes - - # If no credentials are provided, then determine the appropriate - # defaults. - if credentials and credentials_file: - raise core_exceptions.DuplicateCredentialArgs("'credentials_file' and 'credentials' are mutually exclusive") - - if credentials_file is not None: - credentials, _ = google.auth.load_credentials_from_file( - credentials_file, - **scopes_kwargs, - quota_project_id=quota_project_id - ) - elif credentials is None: - credentials, _ = google.auth.default(**scopes_kwargs, quota_project_id=quota_project_id) - # Don't apply audience if the credentials file passed from user. - if hasattr(credentials, "with_gdch_audience"): - credentials = credentials.with_gdch_audience(api_audience if api_audience else host) - - # If the credentials are service account credentials, then always try to use self signed JWT. - if always_use_jwt_access and isinstance(credentials, service_account.Credentials) and hasattr(service_account.Credentials, "with_always_use_jwt_access"): - credentials = credentials.with_always_use_jwt_access(True) - - # Save the credentials. - self._credentials = credentials - - # Save the hostname. Default to port 443 (HTTPS) if none is specified. - if ':' not in host: - host += ':443' - self._host = host - - def _prep_wrapped_messages(self, client_info): - # Precompute the wrapped methods. - self._wrapped_methods = { - self.list_intents: gapic_v1.method.wrap_method( - self.list_intents, - default_timeout=None, - client_info=client_info, - ), - self.get_intent: gapic_v1.method.wrap_method( - self.get_intent, - default_timeout=None, - client_info=client_info, - ), - self.create_intent: gapic_v1.method.wrap_method( - self.create_intent, - default_timeout=None, - client_info=client_info, - ), - self.update_intent: gapic_v1.method.wrap_method( - self.update_intent, - default_timeout=None, - client_info=client_info, - ), - self.delete_intent: gapic_v1.method.wrap_method( - self.delete_intent, - default_timeout=None, - client_info=client_info, - ), - self.batch_update_intents: gapic_v1.method.wrap_method( - self.batch_update_intents, - default_timeout=None, - client_info=client_info, - ), - self.batch_delete_intents: gapic_v1.method.wrap_method( - self.batch_delete_intents, - default_timeout=None, - client_info=client_info, - ), - } - - def close(self): - """Closes resources associated with the transport. - - .. warning:: - Only call this method if the transport is NOT shared - with other clients - this may cause errors in other clients! - """ - raise NotImplementedError() - - @property - def operations_client(self): - """Return the client designed to process long-running operations.""" - raise NotImplementedError() - - @property - def list_intents(self) -> Callable[ - [intent.ListIntentsRequest], - Union[ - intent.ListIntentsResponse, - Awaitable[intent.ListIntentsResponse] - ]]: - raise NotImplementedError() - - @property - def get_intent(self) -> Callable[ - [intent.GetIntentRequest], - Union[ - intent.Intent, - Awaitable[intent.Intent] - ]]: - raise NotImplementedError() - - @property - def create_intent(self) -> Callable[ - [gcd_intent.CreateIntentRequest], - Union[ - gcd_intent.Intent, - Awaitable[gcd_intent.Intent] - ]]: - raise NotImplementedError() - - @property - def update_intent(self) -> Callable[ - [gcd_intent.UpdateIntentRequest], - Union[ - gcd_intent.Intent, - Awaitable[gcd_intent.Intent] - ]]: - raise NotImplementedError() - - @property - def delete_intent(self) -> Callable[ - [intent.DeleteIntentRequest], - Union[ - empty_pb2.Empty, - Awaitable[empty_pb2.Empty] - ]]: - raise NotImplementedError() - - @property - def batch_update_intents(self) -> Callable[ - [intent.BatchUpdateIntentsRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: - raise NotImplementedError() - - @property - def batch_delete_intents(self) -> Callable[ - [intent.BatchDeleteIntentsRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: - raise NotImplementedError() - - @property - def list_operations( - self, - ) -> Callable[ - [operations_pb2.ListOperationsRequest], - Union[operations_pb2.ListOperationsResponse, Awaitable[operations_pb2.ListOperationsResponse]], - ]: - raise NotImplementedError() - - @property - def get_operation( - self, - ) -> Callable[ - [operations_pb2.GetOperationRequest], - Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], - ]: - raise NotImplementedError() - - @property - def cancel_operation( - self, - ) -> Callable[ - [operations_pb2.CancelOperationRequest], - None, - ]: - raise NotImplementedError() - - @property - def get_location(self, - ) -> Callable[ - [locations_pb2.GetLocationRequest], - Union[locations_pb2.Location, Awaitable[locations_pb2.Location]], - ]: - raise NotImplementedError() - - @property - def list_locations(self, - ) -> Callable[ - [locations_pb2.ListLocationsRequest], - Union[locations_pb2.ListLocationsResponse, Awaitable[locations_pb2.ListLocationsResponse]], - ]: - raise NotImplementedError() - - @property - def kind(self) -> str: - raise NotImplementedError() - - -__all__ = ( - 'IntentsTransport', -) diff --git a/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/intents/transports/grpc.py b/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/intents/transports/grpc.py deleted file mode 100644 index 1dc959be3..000000000 --- a/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/intents/transports/grpc.py +++ /dev/null @@ -1,575 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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 -from google.api_core import operations_v1 -from google.api_core import gapic_v1 -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.cloud.location import locations_pb2 # type: ignore -from google.longrunning import operations_pb2 -from google.longrunning import operations_pb2 # type: ignore -from google.protobuf import empty_pb2 # type: ignore -from .base import IntentsTransport, DEFAULT_CLIENT_INFO - - -class IntentsGrpcTransport(IntentsTransport): - """gRPC backend transport for Intents. - - Service for managing [Intents][google.cloud.dialogflow.v2.Intent]. - - 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: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - channel: Optional[grpc.Channel] = None, - api_mtls_endpoint: Optional[str] = None, - client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, - ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, - client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - api_audience: Optional[str] = None, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - This argument is ignored if ``channel`` is provided. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional(Sequence[str])): A list of scopes. This argument is - ignored if ``channel`` is provided. - channel (Optional[grpc.Channel]): A ``Channel`` instance through - which to make calls. - api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. - If provided, it overrides the ``host`` argument and tries to create - a mutual TLS channel with client SSL credentials from - ``client_cert_source`` or application default SSL credentials. - client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): - Deprecated. A callback to provide client SSL certificate bytes and - private key bytes, both in PEM format. It is ignored if - ``api_mtls_endpoint`` is None. - ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials - for the grpc channel. It is ignored if ``channel`` is provided. - client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): - A callback to provide client certificate bytes and private key bytes, - both in PEM format. It is used to configure a mutual TLS channel. It is - ignored if ``channel`` or ``ssl_channel_credentials`` is provided. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport - creation failed for any reason. - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - self._grpc_channel = None - self._ssl_channel_credentials = ssl_channel_credentials - self._stubs: Dict[str, Callable] = {} - self._operations_client: Optional[operations_v1.OperationsClient] = None - - if api_mtls_endpoint: - warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) - if client_cert_source: - warnings.warn("client_cert_source is deprecated", DeprecationWarning) - - if channel: - # Ignore credentials if a channel was passed. - credentials = False - # If a channel was explicitly provided, set it. - self._grpc_channel = channel - self._ssl_channel_credentials = None - - else: - if api_mtls_endpoint: - host = api_mtls_endpoint - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - self._ssl_channel_credentials = SslCredentials().ssl_credentials - - else: - if client_cert_source_for_mtls and not ssl_channel_credentials: - cert, key = client_cert_source_for_mtls() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - - # The base transport sets the host, credentials and scopes - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes, - quota_project_id=quota_project_id, - client_info=client_info, - always_use_jwt_access=always_use_jwt_access, - api_audience=api_audience, - ) - - if not self._grpc_channel: - self._grpc_channel = type(self).create_channel( - self._host, - # use the credentials which are saved - credentials=self._credentials, - # Set ``credentials_file`` to ``None`` here as - # the credentials that we saved earlier should be used. - credentials_file=None, - 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: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - **kwargs) -> grpc.Channel: - """Create and return a gRPC channel object. - Args: - host (Optional[str]): The host for the channel to use. - credentials (Optional[~.Credentials]): The - authorization credentials to attach to requests. These - credentials identify this application to the service. If - none are specified, the client will attempt to ascertain - the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - kwargs (Optional[dict]): Keyword arguments, which are passed to the - channel creation. - Returns: - grpc.Channel: A gRPC channel object. - - Raises: - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - - return grpc_helpers.create_channel( - host, - credentials=credentials, - credentials_file=credentials_file, - quota_project_id=quota_project_id, - default_scopes=cls.AUTH_SCOPES, - scopes=scopes, - default_host=cls.DEFAULT_HOST, - **kwargs - ) - - @property - def grpc_channel(self) -> grpc.Channel: - """Return the channel designed to connect to this service. - """ - return self._grpc_channel - - @property - def operations_client(self) -> operations_v1.OperationsClient: - """Create the client designed to process long-running operations. - - This property caches on the instance; repeated calls return the same - client. - """ - # Quick check: Only create a new client if we do not already have one. - if self._operations_client is None: - self._operations_client = operations_v1.OperationsClient( - self.grpc_channel - ) - - # Return the client from cache. - return self._operations_client - - @property - def list_intents(self) -> Callable[ - [intent.ListIntentsRequest], - intent.ListIntentsResponse]: - r"""Return a callable for the list intents method over gRPC. - - Returns the list of all intents in the specified - agent. - - Returns: - Callable[[~.ListIntentsRequest], - ~.ListIntentsResponse]: - 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_intents' not in self._stubs: - self._stubs['list_intents'] = self.grpc_channel.unary_unary( - '/google.cloud.dialogflow.v2.Intents/ListIntents', - request_serializer=intent.ListIntentsRequest.serialize, - response_deserializer=intent.ListIntentsResponse.deserialize, - ) - return self._stubs['list_intents'] - - @property - def get_intent(self) -> Callable[ - [intent.GetIntentRequest], - intent.Intent]: - r"""Return a callable for the get intent method over gRPC. - - Retrieves the specified intent. - - Returns: - Callable[[~.GetIntentRequest], - ~.Intent]: - 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_intent' not in self._stubs: - self._stubs['get_intent'] = self.grpc_channel.unary_unary( - '/google.cloud.dialogflow.v2.Intents/GetIntent', - request_serializer=intent.GetIntentRequest.serialize, - response_deserializer=intent.Intent.deserialize, - ) - return self._stubs['get_intent'] - - @property - def create_intent(self) -> Callable[ - [gcd_intent.CreateIntentRequest], - gcd_intent.Intent]: - r"""Return a callable for the create intent method over gRPC. - - Creates an intent in the specified agent. - - Note: You should always train an agent prior to sending it - queries. See the `training - documentation `__. - - Returns: - Callable[[~.CreateIntentRequest], - ~.Intent]: - 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_intent' not in self._stubs: - self._stubs['create_intent'] = self.grpc_channel.unary_unary( - '/google.cloud.dialogflow.v2.Intents/CreateIntent', - request_serializer=gcd_intent.CreateIntentRequest.serialize, - response_deserializer=gcd_intent.Intent.deserialize, - ) - return self._stubs['create_intent'] - - @property - def update_intent(self) -> Callable[ - [gcd_intent.UpdateIntentRequest], - gcd_intent.Intent]: - r"""Return a callable for the update intent method over gRPC. - - Updates the specified intent. - - Note: You should always train an agent prior to sending it - queries. See the `training - documentation `__. - - Returns: - Callable[[~.UpdateIntentRequest], - ~.Intent]: - 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_intent' not in self._stubs: - self._stubs['update_intent'] = self.grpc_channel.unary_unary( - '/google.cloud.dialogflow.v2.Intents/UpdateIntent', - request_serializer=gcd_intent.UpdateIntentRequest.serialize, - response_deserializer=gcd_intent.Intent.deserialize, - ) - return self._stubs['update_intent'] - - @property - 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 indirect followup - intents. - - Note: You should always train an agent prior to sending it - queries. See the `training - documentation `__. - - Returns: - Callable[[~.DeleteIntentRequest], - ~.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_intent' not in self._stubs: - self._stubs['delete_intent'] = self.grpc_channel.unary_unary( - '/google.cloud.dialogflow.v2.Intents/DeleteIntent', - request_serializer=intent.DeleteIntentRequest.serialize, - response_deserializer=empty_pb2.Empty.FromString, - ) - return self._stubs['delete_intent'] - - @property - def batch_update_intents(self) -> 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. - - This method is a `long-running - operation `__. - The returned ``Operation`` type has the following - method-specific fields: - - - ``metadata``: An empty `Struct - message `__ - - ``response``: - [BatchUpdateIntentsResponse][google.cloud.dialogflow.v2.BatchUpdateIntentsResponse] - - Note: You should always train an agent prior to sending it - queries. See the `training - documentation `__. - - Returns: - Callable[[~.BatchUpdateIntentsRequest], - ~.Operation]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'batch_update_intents' not in self._stubs: - self._stubs['batch_update_intents'] = self.grpc_channel.unary_unary( - '/google.cloud.dialogflow.v2.Intents/BatchUpdateIntents', - request_serializer=intent.BatchUpdateIntentsRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['batch_update_intents'] - - @property - def batch_delete_intents(self) -> Callable[ - [intent.BatchDeleteIntentsRequest], - operations_pb2.Operation]: - r"""Return a callable for the batch delete intents method over gRPC. - - Deletes intents in the specified agent. - - This method is a `long-running - operation `__. - The returned ``Operation`` type has the following - method-specific fields: - - - ``metadata``: An empty `Struct - message `__ - - ``response``: An `Empty - message `__ - - Note: You should always train an agent prior to sending it - queries. See the `training - documentation `__. - - Returns: - Callable[[~.BatchDeleteIntentsRequest], - ~.Operation]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'batch_delete_intents' not in self._stubs: - self._stubs['batch_delete_intents'] = self.grpc_channel.unary_unary( - '/google.cloud.dialogflow.v2.Intents/BatchDeleteIntents', - request_serializer=intent.BatchDeleteIntentsRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['batch_delete_intents'] - - def close(self): - self.grpc_channel.close() - - @property - def cancel_operation( - self, - ) -> Callable[[operations_pb2.CancelOperationRequest], None]: - r"""Return a callable for the cancel_operation method over gRPC. - """ - # 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 "cancel_operation" not in self._stubs: - self._stubs["cancel_operation"] = self.grpc_channel.unary_unary( - "/google.longrunning.Operations/CancelOperation", - request_serializer=operations_pb2.CancelOperationRequest.SerializeToString, - response_deserializer=None, - ) - return self._stubs["cancel_operation"] - - @property - def get_operation( - self, - ) -> Callable[[operations_pb2.GetOperationRequest], operations_pb2.Operation]: - r"""Return a callable for the get_operation method over gRPC. - """ - # 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_operation" not in self._stubs: - self._stubs["get_operation"] = self.grpc_channel.unary_unary( - "/google.longrunning.Operations/GetOperation", - request_serializer=operations_pb2.GetOperationRequest.SerializeToString, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs["get_operation"] - - @property - def list_operations( - self, - ) -> Callable[[operations_pb2.ListOperationsRequest], operations_pb2.ListOperationsResponse]: - r"""Return a callable for the list_operations method over gRPC. - """ - # 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_operations" not in self._stubs: - self._stubs["list_operations"] = self.grpc_channel.unary_unary( - "/google.longrunning.Operations/ListOperations", - request_serializer=operations_pb2.ListOperationsRequest.SerializeToString, - response_deserializer=operations_pb2.ListOperationsResponse.FromString, - ) - return self._stubs["list_operations"] - - @property - def list_locations( - self, - ) -> Callable[[locations_pb2.ListLocationsRequest], locations_pb2.ListLocationsResponse]: - r"""Return a callable for the list locations method over gRPC. - """ - # 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_locations" not in self._stubs: - self._stubs["list_locations"] = self.grpc_channel.unary_unary( - "/google.cloud.location.Locations/ListLocations", - request_serializer=locations_pb2.ListLocationsRequest.SerializeToString, - response_deserializer=locations_pb2.ListLocationsResponse.FromString, - ) - return self._stubs["list_locations"] - - @property - def get_location( - self, - ) -> Callable[[locations_pb2.GetLocationRequest], locations_pb2.Location]: - r"""Return a callable for the list locations method over gRPC. - """ - # 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_location" not in self._stubs: - self._stubs["get_location"] = self.grpc_channel.unary_unary( - "/google.cloud.location.Locations/GetLocation", - request_serializer=locations_pb2.GetLocationRequest.SerializeToString, - response_deserializer=locations_pb2.Location.FromString, - ) - return self._stubs["get_location"] - - @property - def kind(self) -> str: - return "grpc" - - -__all__ = ( - 'IntentsGrpcTransport', -) diff --git a/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/intents/transports/grpc_asyncio.py b/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/intents/transports/grpc_asyncio.py deleted file mode 100644 index e84af095a..000000000 --- a/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/intents/transports/grpc_asyncio.py +++ /dev/null @@ -1,574 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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 -from google.api_core import grpc_helpers_async -from google.api_core import operations_v1 -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore - -import grpc # type: ignore -from grpc.experimental import aio # type: ignore - -from google.cloud.dialogflow_v2.types import intent -from google.cloud.dialogflow_v2.types import intent as gcd_intent -from google.cloud.location import locations_pb2 # type: ignore -from google.longrunning import operations_pb2 -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 - - -class IntentsGrpcAsyncIOTransport(IntentsTransport): - """gRPC AsyncIO backend transport for Intents. - - Service for managing [Intents][google.cloud.dialogflow.v2.Intent]. - - 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: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - **kwargs) -> aio.Channel: - """Create and return a gRPC AsyncIO channel object. - Args: - host (Optional[str]): The host for the channel to use. - credentials (Optional[~.Credentials]): The - authorization credentials to attach to requests. These - credentials identify this application to the service. If - none are specified, the client will attempt to ascertain - the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - kwargs (Optional[dict]): Keyword arguments, which are passed to the - channel creation. - Returns: - aio.Channel: A gRPC AsyncIO channel object. - """ - - return grpc_helpers_async.create_channel( - host, - credentials=credentials, - credentials_file=credentials_file, - quota_project_id=quota_project_id, - default_scopes=cls.AUTH_SCOPES, - scopes=scopes, - default_host=cls.DEFAULT_HOST, - **kwargs - ) - - def __init__(self, *, - host: str = 'dialogflow.googleapis.com', - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - channel: Optional[aio.Channel] = None, - api_mtls_endpoint: Optional[str] = None, - client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, - ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, - client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - api_audience: Optional[str] = None, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - This argument is ignored if ``channel`` is provided. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - channel (Optional[aio.Channel]): A ``Channel`` instance through - which to make calls. - api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. - If provided, it overrides the ``host`` argument and tries to create - a mutual TLS channel with client SSL credentials from - ``client_cert_source`` or application default SSL credentials. - client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): - Deprecated. A callback to provide client SSL certificate bytes and - private key bytes, both in PEM format. It is ignored if - ``api_mtls_endpoint`` is None. - ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials - for the grpc channel. It is ignored if ``channel`` is provided. - client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): - A callback to provide client certificate bytes and private key bytes, - both in PEM format. It is used to configure a mutual TLS channel. It is - ignored if ``channel`` or ``ssl_channel_credentials`` is provided. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - - Raises: - google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport - creation failed for any reason. - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - self._grpc_channel = None - self._ssl_channel_credentials = ssl_channel_credentials - self._stubs: Dict[str, Callable] = {} - self._operations_client: Optional[operations_v1.OperationsAsyncClient] = None - - if api_mtls_endpoint: - warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) - if client_cert_source: - warnings.warn("client_cert_source is deprecated", DeprecationWarning) - - if channel: - # Ignore credentials if a channel was passed. - credentials = False - # If a channel was explicitly provided, set it. - self._grpc_channel = channel - self._ssl_channel_credentials = None - else: - if api_mtls_endpoint: - host = api_mtls_endpoint - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - self._ssl_channel_credentials = SslCredentials().ssl_credentials - - else: - if client_cert_source_for_mtls and not ssl_channel_credentials: - cert, key = client_cert_source_for_mtls() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - - # The base transport sets the host, credentials and scopes - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes, - quota_project_id=quota_project_id, - client_info=client_info, - always_use_jwt_access=always_use_jwt_access, - api_audience=api_audience, - ) - - if not self._grpc_channel: - self._grpc_channel = type(self).create_channel( - self._host, - # use the credentials which are saved - credentials=self._credentials, - # Set ``credentials_file`` to ``None`` here as - # the credentials that we saved earlier should be used. - credentials_file=None, - 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 operations_client(self) -> operations_v1.OperationsAsyncClient: - """Create the client designed to process long-running operations. - - This property caches on the instance; repeated calls return the same - client. - """ - # Quick check: Only create a new client if we do not already have one. - if self._operations_client is None: - self._operations_client = operations_v1.OperationsAsyncClient( - self.grpc_channel - ) - - # Return the client from cache. - return self._operations_client - - @property - def list_intents(self) -> Callable[ - [intent.ListIntentsRequest], - Awaitable[intent.ListIntentsResponse]]: - r"""Return a callable for the list intents method over gRPC. - - Returns the list of all intents in the specified - agent. - - Returns: - Callable[[~.ListIntentsRequest], - Awaitable[~.ListIntentsResponse]]: - 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_intents' not in self._stubs: - self._stubs['list_intents'] = self.grpc_channel.unary_unary( - '/google.cloud.dialogflow.v2.Intents/ListIntents', - request_serializer=intent.ListIntentsRequest.serialize, - response_deserializer=intent.ListIntentsResponse.deserialize, - ) - return self._stubs['list_intents'] - - @property - def get_intent(self) -> Callable[ - [intent.GetIntentRequest], - Awaitable[intent.Intent]]: - r"""Return a callable for the get intent method over gRPC. - - Retrieves the specified intent. - - Returns: - Callable[[~.GetIntentRequest], - Awaitable[~.Intent]]: - 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_intent' not in self._stubs: - self._stubs['get_intent'] = self.grpc_channel.unary_unary( - '/google.cloud.dialogflow.v2.Intents/GetIntent', - request_serializer=intent.GetIntentRequest.serialize, - response_deserializer=intent.Intent.deserialize, - ) - return self._stubs['get_intent'] - - @property - def create_intent(self) -> Callable[ - [gcd_intent.CreateIntentRequest], - Awaitable[gcd_intent.Intent]]: - r"""Return a callable for the create intent method over gRPC. - - Creates an intent in the specified agent. - - Note: You should always train an agent prior to sending it - queries. See the `training - documentation `__. - - Returns: - Callable[[~.CreateIntentRequest], - Awaitable[~.Intent]]: - 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_intent' not in self._stubs: - self._stubs['create_intent'] = self.grpc_channel.unary_unary( - '/google.cloud.dialogflow.v2.Intents/CreateIntent', - request_serializer=gcd_intent.CreateIntentRequest.serialize, - response_deserializer=gcd_intent.Intent.deserialize, - ) - return self._stubs['create_intent'] - - @property - def update_intent(self) -> Callable[ - [gcd_intent.UpdateIntentRequest], - Awaitable[gcd_intent.Intent]]: - r"""Return a callable for the update intent method over gRPC. - - Updates the specified intent. - - Note: You should always train an agent prior to sending it - queries. See the `training - documentation `__. - - Returns: - Callable[[~.UpdateIntentRequest], - Awaitable[~.Intent]]: - 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_intent' not in self._stubs: - self._stubs['update_intent'] = self.grpc_channel.unary_unary( - '/google.cloud.dialogflow.v2.Intents/UpdateIntent', - request_serializer=gcd_intent.UpdateIntentRequest.serialize, - response_deserializer=gcd_intent.Intent.deserialize, - ) - return self._stubs['update_intent'] - - @property - def delete_intent(self) -> 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 indirect followup - intents. - - Note: You should always train an agent prior to sending it - queries. See the `training - documentation `__. - - Returns: - Callable[[~.DeleteIntentRequest], - 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_intent' not in self._stubs: - self._stubs['delete_intent'] = self.grpc_channel.unary_unary( - '/google.cloud.dialogflow.v2.Intents/DeleteIntent', - request_serializer=intent.DeleteIntentRequest.serialize, - response_deserializer=empty_pb2.Empty.FromString, - ) - return self._stubs['delete_intent'] - - @property - def batch_update_intents(self) -> 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. - - This method is a `long-running - operation `__. - The returned ``Operation`` type has the following - method-specific fields: - - - ``metadata``: An empty `Struct - message `__ - - ``response``: - [BatchUpdateIntentsResponse][google.cloud.dialogflow.v2.BatchUpdateIntentsResponse] - - Note: You should always train an agent prior to sending it - queries. See the `training - documentation `__. - - Returns: - Callable[[~.BatchUpdateIntentsRequest], - Awaitable[~.Operation]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'batch_update_intents' not in self._stubs: - self._stubs['batch_update_intents'] = self.grpc_channel.unary_unary( - '/google.cloud.dialogflow.v2.Intents/BatchUpdateIntents', - request_serializer=intent.BatchUpdateIntentsRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['batch_update_intents'] - - @property - def batch_delete_intents(self) -> 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. - - This method is a `long-running - operation `__. - The returned ``Operation`` type has the following - method-specific fields: - - - ``metadata``: An empty `Struct - message `__ - - ``response``: An `Empty - message `__ - - Note: You should always train an agent prior to sending it - queries. See the `training - documentation `__. - - Returns: - Callable[[~.BatchDeleteIntentsRequest], - Awaitable[~.Operation]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'batch_delete_intents' not in self._stubs: - self._stubs['batch_delete_intents'] = self.grpc_channel.unary_unary( - '/google.cloud.dialogflow.v2.Intents/BatchDeleteIntents', - request_serializer=intent.BatchDeleteIntentsRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['batch_delete_intents'] - - def close(self): - return self.grpc_channel.close() - - @property - def cancel_operation( - self, - ) -> Callable[[operations_pb2.CancelOperationRequest], None]: - r"""Return a callable for the cancel_operation method over gRPC. - """ - # 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 "cancel_operation" not in self._stubs: - self._stubs["cancel_operation"] = self.grpc_channel.unary_unary( - "/google.longrunning.Operations/CancelOperation", - request_serializer=operations_pb2.CancelOperationRequest.SerializeToString, - response_deserializer=None, - ) - return self._stubs["cancel_operation"] - - @property - def get_operation( - self, - ) -> Callable[[operations_pb2.GetOperationRequest], operations_pb2.Operation]: - r"""Return a callable for the get_operation method over gRPC. - """ - # 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_operation" not in self._stubs: - self._stubs["get_operation"] = self.grpc_channel.unary_unary( - "/google.longrunning.Operations/GetOperation", - request_serializer=operations_pb2.GetOperationRequest.SerializeToString, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs["get_operation"] - - @property - def list_operations( - self, - ) -> Callable[[operations_pb2.ListOperationsRequest], operations_pb2.ListOperationsResponse]: - r"""Return a callable for the list_operations method over gRPC. - """ - # 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_operations" not in self._stubs: - self._stubs["list_operations"] = self.grpc_channel.unary_unary( - "/google.longrunning.Operations/ListOperations", - request_serializer=operations_pb2.ListOperationsRequest.SerializeToString, - response_deserializer=operations_pb2.ListOperationsResponse.FromString, - ) - return self._stubs["list_operations"] - - @property - def list_locations( - self, - ) -> Callable[[locations_pb2.ListLocationsRequest], locations_pb2.ListLocationsResponse]: - r"""Return a callable for the list locations method over gRPC. - """ - # 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_locations" not in self._stubs: - self._stubs["list_locations"] = self.grpc_channel.unary_unary( - "/google.cloud.location.Locations/ListLocations", - request_serializer=locations_pb2.ListLocationsRequest.SerializeToString, - response_deserializer=locations_pb2.ListLocationsResponse.FromString, - ) - return self._stubs["list_locations"] - - @property - def get_location( - self, - ) -> Callable[[locations_pb2.GetLocationRequest], locations_pb2.Location]: - r"""Return a callable for the list locations method over gRPC. - """ - # 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_location" not in self._stubs: - self._stubs["get_location"] = self.grpc_channel.unary_unary( - "/google.cloud.location.Locations/GetLocation", - request_serializer=locations_pb2.GetLocationRequest.SerializeToString, - response_deserializer=locations_pb2.Location.FromString, - ) - return self._stubs["get_location"] - - -__all__ = ( - 'IntentsGrpcAsyncIOTransport', -) diff --git a/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/intents/transports/rest.py b/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/intents/transports/rest.py deleted file mode 100644 index 90b68a6cb..000000000 --- a/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/intents/transports/rest.py +++ /dev/null @@ -1,1537 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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 google.auth.transport.requests import AuthorizedSession # type: ignore -import json # type: ignore -import grpc # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore -from google.auth import credentials as ga_credentials # type: ignore -from google.api_core import exceptions as core_exceptions -from google.api_core import retry as retries -from google.api_core import rest_helpers -from google.api_core import rest_streaming -from google.api_core import path_template -from google.api_core import gapic_v1 - -from google.protobuf import json_format -from google.api_core import operations_v1 -from google.cloud.location import locations_pb2 # type: ignore -from google.longrunning import operations_pb2 -from requests import __version__ as requests_version -import dataclasses -import re -from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union -import warnings - -try: - OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] -except AttributeError: # pragma: NO COVER - OptionalRetry = Union[retries.Retry, object] # 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 # type: ignore -from google.protobuf import empty_pb2 # type: ignore - -from .base import IntentsTransport, DEFAULT_CLIENT_INFO as BASE_DEFAULT_CLIENT_INFO - - -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=BASE_DEFAULT_CLIENT_INFO.gapic_version, - grpc_version=None, - rest_version=requests_version, -) - - -class IntentsRestInterceptor: - """Interceptor for Intents. - - Interceptors are used to manipulate requests, request metadata, and responses - in arbitrary ways. - Example use cases include: - * Logging - * Verifying requests according to service or custom semantics - * Stripping extraneous information from responses - - These use cases and more can be enabled by injecting an - instance of a custom subclass when constructing the IntentsRestTransport. - - .. code-block:: python - class MyCustomIntentsInterceptor(IntentsRestInterceptor): - def pre_batch_delete_intents(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_batch_delete_intents(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_batch_update_intents(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_batch_update_intents(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_create_intent(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_create_intent(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_delete_intent(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def pre_get_intent(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_get_intent(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_list_intents(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_list_intents(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_update_intent(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_update_intent(self, response): - logging.log(f"Received response: {response}") - return response - - transport = IntentsRestTransport(interceptor=MyCustomIntentsInterceptor()) - client = IntentsClient(transport=transport) - - - """ - def pre_batch_delete_intents(self, request: intent.BatchDeleteIntentsRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[intent.BatchDeleteIntentsRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for batch_delete_intents - - Override in a subclass to manipulate the request or metadata - before they are sent to the Intents server. - """ - return request, metadata - - def post_batch_delete_intents(self, response: operations_pb2.Operation) -> operations_pb2.Operation: - """Post-rpc interceptor for batch_delete_intents - - Override in a subclass to manipulate the response - after it is returned by the Intents server but before - it is returned to user code. - """ - return response - def pre_batch_update_intents(self, request: intent.BatchUpdateIntentsRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[intent.BatchUpdateIntentsRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for batch_update_intents - - Override in a subclass to manipulate the request or metadata - before they are sent to the Intents server. - """ - return request, metadata - - def post_batch_update_intents(self, response: operations_pb2.Operation) -> operations_pb2.Operation: - """Post-rpc interceptor for batch_update_intents - - Override in a subclass to manipulate the response - after it is returned by the Intents server but before - it is returned to user code. - """ - return response - def pre_create_intent(self, request: gcd_intent.CreateIntentRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[gcd_intent.CreateIntentRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for create_intent - - Override in a subclass to manipulate the request or metadata - before they are sent to the Intents server. - """ - return request, metadata - - def post_create_intent(self, response: gcd_intent.Intent) -> gcd_intent.Intent: - """Post-rpc interceptor for create_intent - - Override in a subclass to manipulate the response - after it is returned by the Intents server but before - it is returned to user code. - """ - return response - def pre_delete_intent(self, request: intent.DeleteIntentRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[intent.DeleteIntentRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for delete_intent - - Override in a subclass to manipulate the request or metadata - before they are sent to the Intents server. - """ - return request, metadata - - def pre_get_intent(self, request: intent.GetIntentRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[intent.GetIntentRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for get_intent - - Override in a subclass to manipulate the request or metadata - before they are sent to the Intents server. - """ - return request, metadata - - def post_get_intent(self, response: intent.Intent) -> intent.Intent: - """Post-rpc interceptor for get_intent - - Override in a subclass to manipulate the response - after it is returned by the Intents server but before - it is returned to user code. - """ - return response - def pre_list_intents(self, request: intent.ListIntentsRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[intent.ListIntentsRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for list_intents - - Override in a subclass to manipulate the request or metadata - before they are sent to the Intents server. - """ - return request, metadata - - def post_list_intents(self, response: intent.ListIntentsResponse) -> intent.ListIntentsResponse: - """Post-rpc interceptor for list_intents - - Override in a subclass to manipulate the response - after it is returned by the Intents server but before - it is returned to user code. - """ - return response - def pre_update_intent(self, request: gcd_intent.UpdateIntentRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[gcd_intent.UpdateIntentRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for update_intent - - Override in a subclass to manipulate the request or metadata - before they are sent to the Intents server. - """ - return request, metadata - - def post_update_intent(self, response: gcd_intent.Intent) -> gcd_intent.Intent: - """Post-rpc interceptor for update_intent - - Override in a subclass to manipulate the response - after it is returned by the Intents server but before - it is returned to user code. - """ - return response - - def pre_get_location( - self, request: locations_pb2.GetLocationRequest, metadata: Sequence[Tuple[str, str]] - ) -> Tuple[locations_pb2.GetLocationRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for get_location - - Override in a subclass to manipulate the request or metadata - before they are sent to the Intents server. - """ - return request, metadata - - def post_get_location( - self, response: locations_pb2.Location - ) -> locations_pb2.Location: - """Post-rpc interceptor for get_location - - Override in a subclass to manipulate the response - after it is returned by the Intents server but before - it is returned to user code. - """ - return response - def pre_list_locations( - self, request: locations_pb2.ListLocationsRequest, metadata: Sequence[Tuple[str, str]] - ) -> Tuple[locations_pb2.ListLocationsRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for list_locations - - Override in a subclass to manipulate the request or metadata - before they are sent to the Intents server. - """ - return request, metadata - - def post_list_locations( - self, response: locations_pb2.ListLocationsResponse - ) -> locations_pb2.ListLocationsResponse: - """Post-rpc interceptor for list_locations - - Override in a subclass to manipulate the response - after it is returned by the Intents server but before - it is returned to user code. - """ - return response - def pre_cancel_operation( - self, request: operations_pb2.CancelOperationRequest, metadata: Sequence[Tuple[str, str]] - ) -> Tuple[operations_pb2.CancelOperationRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for cancel_operation - - Override in a subclass to manipulate the request or metadata - before they are sent to the Intents server. - """ - return request, metadata - - def post_cancel_operation( - self, response: None - ) -> None: - """Post-rpc interceptor for cancel_operation - - Override in a subclass to manipulate the response - after it is returned by the Intents server but before - it is returned to user code. - """ - return response - def pre_get_operation( - self, request: operations_pb2.GetOperationRequest, metadata: Sequence[Tuple[str, str]] - ) -> Tuple[operations_pb2.GetOperationRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for get_operation - - Override in a subclass to manipulate the request or metadata - before they are sent to the Intents server. - """ - return request, metadata - - def post_get_operation( - self, response: operations_pb2.Operation - ) -> operations_pb2.Operation: - """Post-rpc interceptor for get_operation - - Override in a subclass to manipulate the response - after it is returned by the Intents server but before - it is returned to user code. - """ - return response - def pre_list_operations( - self, request: operations_pb2.ListOperationsRequest, metadata: Sequence[Tuple[str, str]] - ) -> Tuple[operations_pb2.ListOperationsRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for list_operations - - Override in a subclass to manipulate the request or metadata - before they are sent to the Intents server. - """ - return request, metadata - - def post_list_operations( - self, response: operations_pb2.ListOperationsResponse - ) -> operations_pb2.ListOperationsResponse: - """Post-rpc interceptor for list_operations - - Override in a subclass to manipulate the response - after it is returned by the Intents server but before - it is returned to user code. - """ - return response - - -@dataclasses.dataclass -class IntentsRestStub: - _session: AuthorizedSession - _host: str - _interceptor: IntentsRestInterceptor - - -class IntentsRestTransport(IntentsTransport): - """REST backend transport for Intents. - - Service for managing [Intents][google.cloud.dialogflow.v2.Intent]. - - 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 JSON representations of protocol buffers over HTTP/1.1 - - """ - - def __init__(self, *, - host: str = 'dialogflow.googleapis.com', - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - client_cert_source_for_mtls: Optional[Callable[[ - ], Tuple[bytes, bytes]]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - url_scheme: str = 'https', - interceptor: Optional[IntentsRestInterceptor] = None, - api_audience: Optional[str] = None, - ) -> 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 ignored if ``channel`` is provided. - scopes (Optional(Sequence[str])): A list of scopes. This argument is - ignored if ``channel`` is provided. - client_cert_source_for_mtls (Callable[[], Tuple[bytes, bytes]]): Client - certificate to configure mutual TLS HTTP channel. It is ignored - if ``channel`` is provided. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you are developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - url_scheme: the protocol scheme for the API endpoint. Normally - "https", but for testing or local servers, - "http" can be specified. - """ - # Run the base constructor - # TODO(yon-mg): resolve other ctor params i.e. scopes, quota, etc. - # TODO: When custom host (api_endpoint) is set, `scopes` must *also* be set on the - # credentials object - maybe_url_match = re.match("^(?Phttp(?:s)?://)?(?P.*)$", host) - if maybe_url_match is None: - raise ValueError(f"Unexpected hostname structure: {host}") # pragma: NO COVER - - url_match_items = maybe_url_match.groupdict() - - host = f"{url_scheme}://{host}" if not url_match_items["scheme"] else host - - super().__init__( - host=host, - credentials=credentials, - client_info=client_info, - always_use_jwt_access=always_use_jwt_access, - api_audience=api_audience - ) - self._session = AuthorizedSession( - self._credentials, default_host=self.DEFAULT_HOST) - self._operations_client: Optional[operations_v1.AbstractOperationsClient] = None - if client_cert_source_for_mtls: - self._session.configure_mtls_channel(client_cert_source_for_mtls) - self._interceptor = interceptor or IntentsRestInterceptor() - self._prep_wrapped_messages(client_info) - - @property - def operations_client(self) -> operations_v1.AbstractOperationsClient: - """Create the client designed to process long-running operations. - - This property caches on the instance; repeated calls return the same - client. - """ - # Only create a new client if we do not already have one. - if self._operations_client is None: - http_options: Dict[str, List[Dict[str, str]]] = { - 'google.longrunning.Operations.CancelOperation': [ - { - 'method': 'post', - 'uri': '/v2/{name=projects/*/operations/*}:cancel', - }, - { - 'method': 'post', - 'uri': '/v2/{name=projects/*/locations/*/operations/*}:cancel', - }, - ], - 'google.longrunning.Operations.GetOperation': [ - { - 'method': 'get', - 'uri': '/v2/{name=projects/*/operations/*}', - }, - { - 'method': 'get', - 'uri': '/v2/{name=projects/*/locations/*/operations/*}', - }, - ], - 'google.longrunning.Operations.ListOperations': [ - { - 'method': 'get', - 'uri': '/v2/{name=projects/*}/operations', - }, - { - 'method': 'get', - 'uri': '/v2/{name=projects/*/locations/*}/operations', - }, - ], - } - - rest_transport = operations_v1.OperationsRestTransport( - host=self._host, - # use the credentials which are saved - credentials=self._credentials, - scopes=self._scopes, - http_options=http_options, - path_prefix="v2") - - self._operations_client = operations_v1.AbstractOperationsClient(transport=rest_transport) - - # Return the client from cache. - return self._operations_client - - class _BatchDeleteIntents(IntentsRestStub): - def __hash__(self): - return hash("BatchDeleteIntents") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: intent.BatchDeleteIntentsRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> operations_pb2.Operation: - r"""Call the batch delete intents method over HTTP. - - Args: - request (~.intent.BatchDeleteIntentsRequest): - The request object. The request message for - [Intents.BatchDeleteIntents][google.cloud.dialogflow.v2.Intents.BatchDeleteIntents]. - 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: - ~.operations_pb2.Operation: - This resource represents a - long-running operation that is the - result of a network API call. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'post', - 'uri': '/v2/{parent=projects/*/agent}/intents:batchDelete', - 'body': '*', - }, -{ - 'method': 'post', - 'uri': '/v2/{parent=projects/*/locations/*/agent}/intents:batchDelete', - 'body': '*', - }, - ] - request, metadata = self._interceptor.pre_batch_delete_intents(request, metadata) - pb_request = intent.BatchDeleteIntentsRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request['body'], - including_default_value_fields=False, - use_integers_for_enums=True - ) - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - including_default_value_fields=False, - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = operations_pb2.Operation() - json_format.Parse(response.content, resp, ignore_unknown_fields=True) - resp = self._interceptor.post_batch_delete_intents(resp) - return resp - - class _BatchUpdateIntents(IntentsRestStub): - def __hash__(self): - return hash("BatchUpdateIntents") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: intent.BatchUpdateIntentsRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> operations_pb2.Operation: - r"""Call the batch update intents method over HTTP. - - Args: - request (~.intent.BatchUpdateIntentsRequest): - The request object. - 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: - ~.operations_pb2.Operation: - This resource represents a - long-running operation that is the - result of a network API call. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'post', - 'uri': '/v2/{parent=projects/*/agent}/intents:batchUpdate', - 'body': '*', - }, -{ - 'method': 'post', - 'uri': '/v2/{parent=projects/*/locations/*/agent}/intents:batchUpdate', - 'body': '*', - }, - ] - request, metadata = self._interceptor.pre_batch_update_intents(request, metadata) - pb_request = intent.BatchUpdateIntentsRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request['body'], - including_default_value_fields=False, - use_integers_for_enums=True - ) - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - including_default_value_fields=False, - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = operations_pb2.Operation() - json_format.Parse(response.content, resp, ignore_unknown_fields=True) - resp = self._interceptor.post_batch_update_intents(resp) - return resp - - class _CreateIntent(IntentsRestStub): - def __hash__(self): - return hash("CreateIntent") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: gcd_intent.CreateIntentRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> gcd_intent.Intent: - r"""Call the create intent method over HTTP. - - Args: - request (~.gcd_intent.CreateIntentRequest): - The request object. The request message for - [Intents.CreateIntent][google.cloud.dialogflow.v2.Intents.CreateIntent]. - 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: - ~.gcd_intent.Intent: - An intent categorizes an end-user's intention for one - conversation turn. For each agent, you define many - intents, where your combined intents can handle a - complete conversation. When an end-user writes or says - something, referred to as an end-user expression or - end-user input, Dialogflow matches the end-user input to - the best intent in your agent. Matching an intent is - also known as intent classification. - - For more information, see the `intent - guide `__. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'post', - 'uri': '/v2/{parent=projects/*/agent}/intents', - 'body': 'intent', - }, -{ - 'method': 'post', - 'uri': '/v2/{parent=projects/*/locations/*/agent}/intents', - 'body': 'intent', - }, - ] - request, metadata = self._interceptor.pre_create_intent(request, metadata) - pb_request = gcd_intent.CreateIntentRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request['body'], - including_default_value_fields=False, - use_integers_for_enums=True - ) - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - including_default_value_fields=False, - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = gcd_intent.Intent() - pb_resp = gcd_intent.Intent.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_create_intent(resp) - return resp - - class _DeleteIntent(IntentsRestStub): - def __hash__(self): - return hash("DeleteIntent") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: intent.DeleteIntentRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ): - r"""Call the delete intent method over HTTP. - - Args: - request (~.intent.DeleteIntentRequest): - The request object. The request message for - [Intents.DeleteIntent][google.cloud.dialogflow.v2.Intents.DeleteIntent]. - 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. - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'delete', - 'uri': '/v2/{name=projects/*/agent/intents/*}', - }, -{ - 'method': 'delete', - 'uri': '/v2/{name=projects/*/locations/*/agent/intents/*}', - }, - ] - request, metadata = self._interceptor.pre_delete_intent(request, metadata) - pb_request = intent.DeleteIntentRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - including_default_value_fields=False, - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - class _GetIntent(IntentsRestStub): - def __hash__(self): - return hash("GetIntent") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: intent.GetIntentRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> intent.Intent: - r"""Call the get intent method over HTTP. - - Args: - request (~.intent.GetIntentRequest): - The request object. The request message for - [Intents.GetIntent][google.cloud.dialogflow.v2.Intents.GetIntent]. - 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: - ~.intent.Intent: - An intent categorizes an end-user's intention for one - conversation turn. For each agent, you define many - intents, where your combined intents can handle a - complete conversation. When an end-user writes or says - something, referred to as an end-user expression or - end-user input, Dialogflow matches the end-user input to - the best intent in your agent. Matching an intent is - also known as intent classification. - - For more information, see the `intent - guide `__. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v2/{name=projects/*/agent/intents/*}', - }, -{ - 'method': 'get', - 'uri': '/v2/{name=projects/*/locations/*/agent/intents/*}', - }, - ] - request, metadata = self._interceptor.pre_get_intent(request, metadata) - pb_request = intent.GetIntentRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - including_default_value_fields=False, - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = intent.Intent() - pb_resp = intent.Intent.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_get_intent(resp) - return resp - - class _ListIntents(IntentsRestStub): - def __hash__(self): - return hash("ListIntents") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: intent.ListIntentsRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> intent.ListIntentsResponse: - r"""Call the list intents method over HTTP. - - Args: - request (~.intent.ListIntentsRequest): - The request object. The request message for - [Intents.ListIntents][google.cloud.dialogflow.v2.Intents.ListIntents]. - 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: - ~.intent.ListIntentsResponse: - The response message for - [Intents.ListIntents][google.cloud.dialogflow.v2.Intents.ListIntents]. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v2/{parent=projects/*/agent}/intents', - }, -{ - 'method': 'get', - 'uri': '/v2/{parent=projects/*/locations/*/agent}/intents', - }, -{ - 'method': 'get', - 'uri': '/v2/{parent=projects/*/agent/environments/*}/intents', - }, -{ - 'method': 'get', - 'uri': '/v2/{parent=projects/*/locations/*/agent/environments/*}/intents', - }, - ] - request, metadata = self._interceptor.pre_list_intents(request, metadata) - pb_request = intent.ListIntentsRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - including_default_value_fields=False, - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = intent.ListIntentsResponse() - pb_resp = intent.ListIntentsResponse.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_list_intents(resp) - return resp - - class _UpdateIntent(IntentsRestStub): - def __hash__(self): - return hash("UpdateIntent") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: gcd_intent.UpdateIntentRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> gcd_intent.Intent: - r"""Call the update intent method over HTTP. - - Args: - request (~.gcd_intent.UpdateIntentRequest): - The request object. The request message for - [Intents.UpdateIntent][google.cloud.dialogflow.v2.Intents.UpdateIntent]. - 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: - ~.gcd_intent.Intent: - An intent categorizes an end-user's intention for one - conversation turn. For each agent, you define many - intents, where your combined intents can handle a - complete conversation. When an end-user writes or says - something, referred to as an end-user expression or - end-user input, Dialogflow matches the end-user input to - the best intent in your agent. Matching an intent is - also known as intent classification. - - For more information, see the `intent - guide `__. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'patch', - 'uri': '/v2/{intent.name=projects/*/agent/intents/*}', - 'body': 'intent', - }, -{ - 'method': 'patch', - 'uri': '/v2/{intent.name=projects/*/locations/*/agent/intents/*}', - 'body': 'intent', - }, - ] - request, metadata = self._interceptor.pre_update_intent(request, metadata) - pb_request = gcd_intent.UpdateIntentRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request['body'], - including_default_value_fields=False, - use_integers_for_enums=True - ) - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - including_default_value_fields=False, - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = gcd_intent.Intent() - pb_resp = gcd_intent.Intent.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_update_intent(resp) - return resp - - @property - def batch_delete_intents(self) -> Callable[ - [intent.BatchDeleteIntentsRequest], - operations_pb2.Operation]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._BatchDeleteIntents(self._session, self._host, self._interceptor) # type: ignore - - @property - def batch_update_intents(self) -> Callable[ - [intent.BatchUpdateIntentsRequest], - operations_pb2.Operation]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._BatchUpdateIntents(self._session, self._host, self._interceptor) # type: ignore - - @property - def create_intent(self) -> Callable[ - [gcd_intent.CreateIntentRequest], - gcd_intent.Intent]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._CreateIntent(self._session, self._host, self._interceptor) # type: ignore - - @property - def delete_intent(self) -> Callable[ - [intent.DeleteIntentRequest], - empty_pb2.Empty]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._DeleteIntent(self._session, self._host, self._interceptor) # type: ignore - - @property - def get_intent(self) -> Callable[ - [intent.GetIntentRequest], - intent.Intent]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._GetIntent(self._session, self._host, self._interceptor) # type: ignore - - @property - def list_intents(self) -> Callable[ - [intent.ListIntentsRequest], - intent.ListIntentsResponse]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._ListIntents(self._session, self._host, self._interceptor) # type: ignore - - @property - def update_intent(self) -> Callable[ - [gcd_intent.UpdateIntentRequest], - gcd_intent.Intent]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._UpdateIntent(self._session, self._host, self._interceptor) # type: ignore - - @property - def get_location(self): - return self._GetLocation(self._session, self._host, self._interceptor) # type: ignore - - class _GetLocation(IntentsRestStub): - def __call__(self, - request: locations_pb2.GetLocationRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> locations_pb2.Location: - - r"""Call the get location method over HTTP. - - Args: - request (locations_pb2.GetLocationRequest): - The request object for GetLocation method. - 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: - locations_pb2.Location: Response from GetLocation method. - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v2/{name=projects/*/locations/*}', - }, - ] - - request, metadata = self._interceptor.pre_get_location(request, metadata) - request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode( - http_options, **request_kwargs) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json.dumps(transcoded_request['query_params'])) - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - resp = locations_pb2.Location() - resp = json_format.Parse(response.content.decode("utf-8"), resp) - resp = self._interceptor.post_get_location(resp) - return resp - - @property - def list_locations(self): - return self._ListLocations(self._session, self._host, self._interceptor) # type: ignore - - class _ListLocations(IntentsRestStub): - def __call__(self, - request: locations_pb2.ListLocationsRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> locations_pb2.ListLocationsResponse: - - r"""Call the list locations method over HTTP. - - Args: - request (locations_pb2.ListLocationsRequest): - The request object for ListLocations method. - 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: - locations_pb2.ListLocationsResponse: Response from ListLocations method. - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v2/{name=projects/*}/locations', - }, - ] - - request, metadata = self._interceptor.pre_list_locations(request, metadata) - request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode( - http_options, **request_kwargs) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json.dumps(transcoded_request['query_params'])) - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - resp = locations_pb2.ListLocationsResponse() - resp = json_format.Parse(response.content.decode("utf-8"), resp) - resp = self._interceptor.post_list_locations(resp) - return resp - - @property - def cancel_operation(self): - return self._CancelOperation(self._session, self._host, self._interceptor) # type: ignore - - class _CancelOperation(IntentsRestStub): - def __call__(self, - request: operations_pb2.CancelOperationRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> None: - - r"""Call the cancel operation method over HTTP. - - Args: - request (operations_pb2.CancelOperationRequest): - The request object for CancelOperation method. - 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. - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'post', - 'uri': '/v2/{name=projects/*/operations/*}:cancel', - }, -{ - 'method': 'post', - 'uri': '/v2/{name=projects/*/locations/*/operations/*}:cancel', - }, - ] - - request, metadata = self._interceptor.pre_cancel_operation(request, metadata) - request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode( - http_options, **request_kwargs) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json.dumps(transcoded_request['query_params'])) - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - return self._interceptor.post_cancel_operation(None) - - @property - def get_operation(self): - return self._GetOperation(self._session, self._host, self._interceptor) # type: ignore - - class _GetOperation(IntentsRestStub): - def __call__(self, - request: operations_pb2.GetOperationRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> operations_pb2.Operation: - - r"""Call the get operation method over HTTP. - - Args: - request (operations_pb2.GetOperationRequest): - The request object for GetOperation method. - 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: - operations_pb2.Operation: Response from GetOperation method. - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v2/{name=projects/*/operations/*}', - }, -{ - 'method': 'get', - 'uri': '/v2/{name=projects/*/locations/*/operations/*}', - }, - ] - - request, metadata = self._interceptor.pre_get_operation(request, metadata) - request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode( - http_options, **request_kwargs) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json.dumps(transcoded_request['query_params'])) - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - resp = operations_pb2.Operation() - resp = json_format.Parse(response.content.decode("utf-8"), resp) - resp = self._interceptor.post_get_operation(resp) - return resp - - @property - def list_operations(self): - return self._ListOperations(self._session, self._host, self._interceptor) # type: ignore - - class _ListOperations(IntentsRestStub): - def __call__(self, - request: operations_pb2.ListOperationsRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> operations_pb2.ListOperationsResponse: - - r"""Call the list operations method over HTTP. - - Args: - request (operations_pb2.ListOperationsRequest): - The request object for ListOperations method. - 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: - operations_pb2.ListOperationsResponse: Response from ListOperations method. - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v2/{name=projects/*}/operations', - }, -{ - 'method': 'get', - 'uri': '/v2/{name=projects/*/locations/*}/operations', - }, - ] - - request, metadata = self._interceptor.pre_list_operations(request, metadata) - request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode( - http_options, **request_kwargs) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json.dumps(transcoded_request['query_params'])) - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - resp = operations_pb2.ListOperationsResponse() - resp = json_format.Parse(response.content.decode("utf-8"), resp) - resp = self._interceptor.post_list_operations(resp) - return resp - - @property - def kind(self) -> str: - return "rest" - - def close(self): - self._session.close() - - -__all__=( - 'IntentsRestTransport', -) diff --git a/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/knowledge_bases/__init__.py b/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/knowledge_bases/__init__.py deleted file mode 100644 index 9dd82d2fd..000000000 --- a/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/knowledge_bases/__init__.py +++ /dev/null @@ -1,22 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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 KnowledgeBasesClient -from .async_client import KnowledgeBasesAsyncClient - -__all__ = ( - 'KnowledgeBasesClient', - 'KnowledgeBasesAsyncClient', -) diff --git a/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/knowledge_bases/async_client.py b/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/knowledge_bases/async_client.py deleted file mode 100644 index 8adfec3c1..000000000 --- a/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/knowledge_bases/async_client.py +++ /dev/null @@ -1,1027 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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, Mapping, MutableMapping, MutableSequence, Optional, Sequence, Tuple, Type, Union - -from google.cloud.dialogflow_v2 import gapic_version as package_version - -from google.api_core.client_options import ClientOptions -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import retry as retries -from google.auth import credentials as ga_credentials # type: ignore -from google.oauth2 import service_account # type: ignore - -try: - OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] -except AttributeError: # pragma: NO COVER - OptionalRetry = Union[retries.Retry, object] # 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.cloud.location import locations_pb2 # type: ignore -from google.longrunning import operations_pb2 -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 - - -class KnowledgeBasesAsyncClient: - """Service for managing - [KnowledgeBases][google.cloud.dialogflow.v2.KnowledgeBase]. - """ - - _client: KnowledgeBasesClient - - DEFAULT_ENDPOINT = KnowledgeBasesClient.DEFAULT_ENDPOINT - DEFAULT_MTLS_ENDPOINT = KnowledgeBasesClient.DEFAULT_MTLS_ENDPOINT - - knowledge_base_path = staticmethod(KnowledgeBasesClient.knowledge_base_path) - 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) - - @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: - KnowledgeBasesAsyncClient: The constructed client. - """ - return KnowledgeBasesClient.from_service_account_info.__func__(KnowledgeBasesAsyncClient, 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: - KnowledgeBasesAsyncClient: The constructed client. - """ - return KnowledgeBasesClient.from_service_account_file.__func__(KnowledgeBasesAsyncClient, filename, *args, **kwargs) # type: ignore - - from_service_account_json = from_service_account_file - - @classmethod - def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[ClientOptions] = None): - """Return the API endpoint and client cert source for mutual TLS. - - The client cert source is determined in the following order: - (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the - client cert source is None. - (2) if `client_options.client_cert_source` is provided, use the provided one; if the - default client cert source exists, use the default one; otherwise the client cert - source is None. - - The API endpoint is determined in the following order: - (1) if `client_options.api_endpoint` if provided, use the provided one. - (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the - default mTLS endpoint; if the environment variable is "never", use the default API - endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise - use the default API endpoint. - - More details can be found at https://google.aip.dev/auth/4114. - - Args: - client_options (google.api_core.client_options.ClientOptions): Custom options for the - client. Only the `api_endpoint` and `client_cert_source` properties may be used - in this method. - - Returns: - Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the - client cert source to use. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If any errors happen. - """ - return KnowledgeBasesClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore - - @property - def transport(self) -> KnowledgeBasesTransport: - """Returns the transport used by the client instance. - - Returns: - KnowledgeBasesTransport: The transport used by the client instance. - """ - return self._client.transport - - get_transport_class = functools.partial(type(KnowledgeBasesClient).get_transport_class, type(KnowledgeBasesClient)) - - def __init__(self, *, - credentials: Optional[ga_credentials.Credentials] = None, - transport: Union[str, KnowledgeBasesTransport] = "grpc_asyncio", - client_options: Optional[ClientOptions] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the knowledge bases 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, ~.KnowledgeBasesTransport]): 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 = KnowledgeBasesClient( - credentials=credentials, - transport=transport, - client_options=client_options, - client_info=client_info, - - ) - - async def list_knowledge_bases(self, - request: Optional[Union[knowledge_base.ListKnowledgeBasesRequest, dict]] = None, - *, - parent: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListKnowledgeBasesAsyncPager: - r"""Returns the list of all knowledge bases of the - specified agent. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import dialogflow_v2 - - async def sample_list_knowledge_bases(): - # Create a client - client = dialogflow_v2.KnowledgeBasesAsyncClient() - - # Initialize request argument(s) - request = dialogflow_v2.ListKnowledgeBasesRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_knowledge_bases(request=request) - - # Handle the response - async for response in page_result: - print(response) - - Args: - request (Optional[Union[google.cloud.dialogflow_v2.types.ListKnowledgeBasesRequest, dict]]): - The request object. Request message for - [KnowledgeBases.ListKnowledgeBases][google.cloud.dialogflow.v2.KnowledgeBases.ListKnowledgeBases]. - parent (:class:`str`): - Required. The project to list of knowledge bases for. - Format: - ``projects//locations/``. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.dialogflow_v2.services.knowledge_bases.pagers.ListKnowledgeBasesAsyncPager: - Response message for - [KnowledgeBases.ListKnowledgeBases][google.cloud.dialogflow.v2.KnowledgeBases.ListKnowledgeBases]. - - Iterating over this object will yield results and - resolve additional pages automatically. - - """ - # Create or coerce a protobuf request object. - # Quick 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 = 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 - - # 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_knowledge_bases, - 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.ListKnowledgeBasesAsyncPager( - method=rpc, - request=request, - response=response, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def get_knowledge_base(self, - request: Optional[Union[knowledge_base.GetKnowledgeBaseRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> knowledge_base.KnowledgeBase: - r"""Retrieves the specified knowledge base. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import dialogflow_v2 - - async def sample_get_knowledge_base(): - # Create a client - client = dialogflow_v2.KnowledgeBasesAsyncClient() - - # Initialize request argument(s) - request = dialogflow_v2.GetKnowledgeBaseRequest( - name="name_value", - ) - - # Make the request - response = await client.get_knowledge_base(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.dialogflow_v2.types.GetKnowledgeBaseRequest, dict]]): - The request object. Request message for - [KnowledgeBases.GetKnowledgeBase][google.cloud.dialogflow.v2.KnowledgeBases.GetKnowledgeBase]. - name (:class:`str`): - Required. The name of the knowledge base to retrieve. - Format - ``projects//locations//knowledgeBases/``. - - 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.KnowledgeBase: - A knowledge base represents a collection of knowledge documents that you - provide to Dialogflow. Your knowledge documents - contain information that may be useful during - conversations with end-users. Some Dialogflow - features use knowledge bases when looking for a - response to an end-user input. - - For more information, see the [knowledge base - guide](\ https://cloud.google.com/dialogflow/docs/how/knowledge-bases). - - Note: The projects.agent.knowledgeBases resource is - deprecated; only use projects.knowledgeBases. - - """ - # Create or coerce a protobuf request object. - # Quick 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 = 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 - - # 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_knowledge_base, - 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_knowledge_base(self, - request: Optional[Union[gcd_knowledge_base.CreateKnowledgeBaseRequest, dict]] = None, - *, - parent: Optional[str] = None, - knowledge_base: Optional[gcd_knowledge_base.KnowledgeBase] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gcd_knowledge_base.KnowledgeBase: - r"""Creates a knowledge base. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import dialogflow_v2 - - async def sample_create_knowledge_base(): - # Create a client - client = dialogflow_v2.KnowledgeBasesAsyncClient() - - # Initialize request argument(s) - knowledge_base = dialogflow_v2.KnowledgeBase() - knowledge_base.display_name = "display_name_value" - - request = dialogflow_v2.CreateKnowledgeBaseRequest( - parent="parent_value", - knowledge_base=knowledge_base, - ) - - # Make the request - response = await client.create_knowledge_base(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.dialogflow_v2.types.CreateKnowledgeBaseRequest, dict]]): - The request object. Request message for - [KnowledgeBases.CreateKnowledgeBase][google.cloud.dialogflow.v2.KnowledgeBases.CreateKnowledgeBase]. - parent (:class:`str`): - Required. The project to create a knowledge base for. - Format: - ``projects//locations/``. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - knowledge_base (:class:`google.cloud.dialogflow_v2.types.KnowledgeBase`): - Required. The knowledge base to - create. - - 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. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.dialogflow_v2.types.KnowledgeBase: - A knowledge base represents a collection of knowledge documents that you - provide to Dialogflow. Your knowledge documents - contain information that may be useful during - conversations with end-users. Some Dialogflow - features use knowledge bases when looking for a - response to an end-user input. - - For more information, see the [knowledge base - guide](\ https://cloud.google.com/dialogflow/docs/how/knowledge-bases). - - Note: The projects.agent.knowledgeBases resource is - deprecated; only use projects.knowledgeBases. - - """ - # Create or coerce a protobuf request object. - # Quick 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, knowledge_base]) - 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_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: - request.knowledge_base = knowledge_base - - # 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_knowledge_base, - 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 delete_knowledge_base(self, - request: Optional[Union[knowledge_base.DeleteKnowledgeBaseRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> None: - r"""Deletes the specified knowledge base. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import dialogflow_v2 - - async def sample_delete_knowledge_base(): - # Create a client - client = dialogflow_v2.KnowledgeBasesAsyncClient() - - # Initialize request argument(s) - request = dialogflow_v2.DeleteKnowledgeBaseRequest( - name="name_value", - ) - - # Make the request - await client.delete_knowledge_base(request=request) - - Args: - request (Optional[Union[google.cloud.dialogflow_v2.types.DeleteKnowledgeBaseRequest, dict]]): - The request object. Request message for - [KnowledgeBases.DeleteKnowledgeBase][google.cloud.dialogflow.v2.KnowledgeBases.DeleteKnowledgeBase]. - name (:class:`str`): - Required. The name of the knowledge base to delete. - Format: - ``projects//locations//knowledgeBases/``. - - 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. - # Quick 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 = 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 - - # 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_knowledge_base, - 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 update_knowledge_base(self, - request: Optional[Union[gcd_knowledge_base.UpdateKnowledgeBaseRequest, dict]] = None, - *, - knowledge_base: Optional[gcd_knowledge_base.KnowledgeBase] = None, - update_mask: Optional[field_mask_pb2.FieldMask] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gcd_knowledge_base.KnowledgeBase: - r"""Updates the specified knowledge base. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import dialogflow_v2 - - async def sample_update_knowledge_base(): - # Create a client - client = dialogflow_v2.KnowledgeBasesAsyncClient() - - # Initialize request argument(s) - knowledge_base = dialogflow_v2.KnowledgeBase() - knowledge_base.display_name = "display_name_value" - - request = dialogflow_v2.UpdateKnowledgeBaseRequest( - knowledge_base=knowledge_base, - ) - - # Make the request - response = await client.update_knowledge_base(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.dialogflow_v2.types.UpdateKnowledgeBaseRequest, dict]]): - The request object. Request message for - [KnowledgeBases.UpdateKnowledgeBase][google.cloud.dialogflow.v2.KnowledgeBases.UpdateKnowledgeBase]. - knowledge_base (:class:`google.cloud.dialogflow_v2.types.KnowledgeBase`): - Required. The knowledge base to - update. - - This corresponds to the ``knowledge_base`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - update_mask (:class:`google.protobuf.field_mask_pb2.FieldMask`): - Optional. Not specified means ``update all``. Currently, - only ``display_name`` can be updated, an InvalidArgument - will be returned for attempting to update other fields. - - 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.KnowledgeBase: - A knowledge base represents a collection of knowledge documents that you - provide to Dialogflow. Your knowledge documents - contain information that may be useful during - conversations with end-users. Some Dialogflow - features use knowledge bases when looking for a - response to an end-user input. - - For more information, see the [knowledge base - guide](\ https://cloud.google.com/dialogflow/docs/how/knowledge-bases). - - Note: The projects.agent.knowledgeBases resource is - deprecated; only use projects.knowledgeBases. - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([knowledge_base, 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_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: - 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_knowledge_base, - 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(( - ("knowledge_base.name", request.knowledge_base.name), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def list_operations( - self, - request: Optional[operations_pb2.ListOperationsRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operations_pb2.ListOperationsResponse: - r"""Lists operations that match the specified filter in the request. - - Args: - request (:class:`~.operations_pb2.ListOperationsRequest`): - The request object. Request message for - `ListOperations` method. - 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: - ~.operations_pb2.ListOperationsResponse: - Response message for ``ListOperations`` method. - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = operations_pb2.ListOperationsRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._client._transport.list_operations, - 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 get_operation( - self, - request: Optional[operations_pb2.GetOperationRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operations_pb2.Operation: - r"""Gets the latest state of a long-running operation. - - Args: - request (:class:`~.operations_pb2.GetOperationRequest`): - The request object. Request message for - `GetOperation` method. - 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: - ~.operations_pb2.Operation: - An ``Operation`` object. - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = operations_pb2.GetOperationRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._client._transport.get_operation, - 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 cancel_operation( - self, - request: Optional[operations_pb2.CancelOperationRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> None: - r"""Starts asynchronous cancellation on a long-running operation. - - The server makes a best effort to cancel the operation, but success - is not guaranteed. If the server doesn't support this method, it returns - `google.rpc.Code.UNIMPLEMENTED`. - - Args: - request (:class:`~.operations_pb2.CancelOperationRequest`): - The request object. Request message for - `CancelOperation` method. - 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: - None - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = operations_pb2.CancelOperationRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._client._transport.cancel_operation, - 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_location( - self, - request: Optional[locations_pb2.GetLocationRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> locations_pb2.Location: - r"""Gets information about a location. - - Args: - request (:class:`~.location_pb2.GetLocationRequest`): - The request object. Request message for - `GetLocation` method. - 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: - ~.location_pb2.Location: - Location object. - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = locations_pb2.GetLocationRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._client._transport.get_location, - 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 list_locations( - self, - request: Optional[locations_pb2.ListLocationsRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> locations_pb2.ListLocationsResponse: - r"""Lists information about the supported locations for this service. - - Args: - request (:class:`~.location_pb2.ListLocationsRequest`): - The request object. Request message for - `ListLocations` method. - 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: - ~.location_pb2.ListLocationsResponse: - Response message for ``ListLocations`` method. - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = locations_pb2.ListLocationsRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._client._transport.list_locations, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("name", request.name),)), - ) - - # Send the request. - response = await rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - async def __aenter__(self): - return self - - async def __aexit__(self, exc_type, exc, tb): - await self.transport.close() - -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) - - -__all__ = ( - "KnowledgeBasesAsyncClient", -) diff --git a/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/knowledge_bases/client.py b/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/knowledge_bases/client.py deleted file mode 100644 index c807760bf..000000000 --- a/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/knowledge_bases/client.py +++ /dev/null @@ -1,1226 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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 os -import re -from typing import Dict, Mapping, MutableMapping, MutableSequence, Optional, Sequence, Tuple, Type, Union, cast - -from google.cloud.dialogflow_v2 import gapic_version as package_version - -from google.api_core import client_options as client_options_lib -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import retry as retries -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 - -try: - OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] -except AttributeError: # pragma: NO COVER - OptionalRetry = Union[retries.Retry, object] # 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.cloud.location import locations_pb2 # type: ignore -from google.longrunning import operations_pb2 -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 -from .transports.rest import KnowledgeBasesRestTransport - - -class KnowledgeBasesClientMeta(type): - """Metaclass for the KnowledgeBases 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[KnowledgeBasesTransport]] - _transport_registry["grpc"] = KnowledgeBasesGrpcTransport - _transport_registry["grpc_asyncio"] = KnowledgeBasesGrpcAsyncIOTransport - _transport_registry["rest"] = KnowledgeBasesRestTransport - - def get_transport_class(cls, - label: Optional[str] = None, - ) -> Type[KnowledgeBasesTransport]: - """Returns an appropriate transport class. - - Args: - label: The name of the desired transport. If none is - provided, then the first transport in the registry is used. - - Returns: - The transport class to use. - """ - # If a specific transport is requested, return that one. - if label: - return cls._transport_registry[label] - - # No transport is requested; return the default (that is, the first one - # in the dictionary). - return next(iter(cls._transport_registry.values())) - - -class KnowledgeBasesClient(metaclass=KnowledgeBasesClientMeta): - """Service for managing - [KnowledgeBases][google.cloud.dialogflow.v2.KnowledgeBase]. - """ - - @staticmethod - def _get_default_mtls_endpoint(api_endpoint): - """Converts api endpoint to mTLS endpoint. - - Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to - "*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively. - Args: - api_endpoint (Optional[str]): the api endpoint to convert. - Returns: - str: converted mTLS api endpoint. - """ - if not api_endpoint: - return api_endpoint - - mtls_endpoint_re = re.compile( - r"(?P[^.]+)(?P\.mtls)?(?P\.sandbox)?(?P\.googleapis\.com)?" - ) - - m = mtls_endpoint_re.match(api_endpoint) - name, mtls, sandbox, googledomain = m.groups() - if mtls or not googledomain: - return api_endpoint - - if sandbox: - return api_endpoint.replace( - "sandbox.googleapis.com", "mtls.sandbox.googleapis.com" - ) - - return api_endpoint.replace(".googleapis.com", ".mtls.googleapis.com") - - DEFAULT_ENDPOINT = "dialogflow.googleapis.com" - DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore - DEFAULT_ENDPOINT - ) - - @classmethod - def from_service_account_info(cls, info: dict, *args, **kwargs): - """Creates an instance of this client using the provided credentials - info. - - Args: - info (dict): The service account private key info. - args: Additional arguments to pass to the constructor. - kwargs: Additional arguments to pass to the constructor. - - Returns: - KnowledgeBasesClient: 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: - KnowledgeBasesClient: 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) -> KnowledgeBasesTransport: - """Returns the transport used by the client instance. - - Returns: - KnowledgeBasesTransport: The transport used by the client - instance. - """ - return self._transport - - @staticmethod - def knowledge_base_path(project: str,knowledge_base: str,) -> str: - """Returns a fully-qualified knowledge_base string.""" - return "projects/{project}/knowledgeBases/{knowledge_base}".format(project=project, knowledge_base=knowledge_base, ) - - @staticmethod - def parse_knowledge_base_path(path: str) -> Dict[str,str]: - """Parses a knowledge_base path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/knowledgeBases/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_billing_account_path(billing_account: str, ) -> str: - """Returns a fully-qualified billing_account string.""" - return "billingAccounts/{billing_account}".format(billing_account=billing_account, ) - - @staticmethod - def parse_common_billing_account_path(path: str) -> Dict[str,str]: - """Parse a billing_account path into its component segments.""" - m = re.match(r"^billingAccounts/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_folder_path(folder: str, ) -> str: - """Returns a fully-qualified folder string.""" - return "folders/{folder}".format(folder=folder, ) - - @staticmethod - def parse_common_folder_path(path: str) -> Dict[str,str]: - """Parse a folder path into its component segments.""" - m = re.match(r"^folders/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_organization_path(organization: str, ) -> str: - """Returns a fully-qualified organization string.""" - return "organizations/{organization}".format(organization=organization, ) - - @staticmethod - def parse_common_organization_path(path: str) -> Dict[str,str]: - """Parse a organization path into its component segments.""" - m = re.match(r"^organizations/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_project_path(project: str, ) -> str: - """Returns a fully-qualified project string.""" - return "projects/{project}".format(project=project, ) - - @staticmethod - def parse_common_project_path(path: str) -> Dict[str,str]: - """Parse a project path into its component segments.""" - m = re.match(r"^projects/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_location_path(project: str, location: str, ) -> str: - """Returns a fully-qualified location string.""" - return "projects/{project}/locations/{location}".format(project=project, location=location, ) - - @staticmethod - def parse_common_location_path(path: str) -> Dict[str,str]: - """Parse a location path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)$", path) - return m.groupdict() if m else {} - - @classmethod - def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[client_options_lib.ClientOptions] = None): - """Return the API endpoint and client cert source for mutual TLS. - - The client cert source is determined in the following order: - (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the - client cert source is None. - (2) if `client_options.client_cert_source` is provided, use the provided one; if the - default client cert source exists, use the default one; otherwise the client cert - source is None. - - The API endpoint is determined in the following order: - (1) if `client_options.api_endpoint` if provided, use the provided one. - (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the - default mTLS endpoint; if the environment variable is "never", use the default API - endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise - use the default API endpoint. - - More details can be found at https://google.aip.dev/auth/4114. - - Args: - client_options (google.api_core.client_options.ClientOptions): Custom options for the - client. Only the `api_endpoint` and `client_cert_source` properties may be used - in this method. - - Returns: - Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the - client cert source to use. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If any errors happen. - """ - if client_options is None: - client_options = client_options_lib.ClientOptions() - use_client_cert = os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false") - use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") - if use_client_cert not in ("true", "false"): - raise ValueError("Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`") - if use_mtls_endpoint not in ("auto", "never", "always"): - raise MutualTLSChannelError("Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`") - - # Figure out the client cert source to use. - client_cert_source = None - if use_client_cert == "true": - if client_options.client_cert_source: - client_cert_source = client_options.client_cert_source - elif mtls.has_default_client_cert_source(): - client_cert_source = mtls.default_client_cert_source() - - # Figure out which api endpoint to use. - if client_options.api_endpoint is not None: - api_endpoint = client_options.api_endpoint - elif use_mtls_endpoint == "always" or (use_mtls_endpoint == "auto" and client_cert_source): - api_endpoint = cls.DEFAULT_MTLS_ENDPOINT - else: - api_endpoint = cls.DEFAULT_ENDPOINT - - return api_endpoint, client_cert_source - - def __init__(self, *, - credentials: Optional[ga_credentials.Credentials] = None, - transport: Optional[Union[str, KnowledgeBasesTransport]] = None, - client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the knowledge bases 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, KnowledgeBasesTransport]): The - transport to use. If set to None, a transport is chosen - automatically. - client_options (Optional[Union[google.api_core.client_options.ClientOptions, dict]]): 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() - client_options = cast(client_options_lib.ClientOptions, client_options) - - api_endpoint, client_cert_source_func = self.get_mtls_endpoint_and_cert_source(client_options) - - api_key_value = getattr(client_options, "api_key", None) - if api_key_value and credentials: - raise ValueError("client_options.api_key and credentials are mutually exclusive") - - # 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, KnowledgeBasesTransport): - # transport is a KnowledgeBasesTransport instance. - if credentials or client_options.credentials_file or api_key_value: - 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: - import google.auth._default # type: ignore - - if api_key_value and hasattr(google.auth._default, "get_api_key_credentials"): - credentials = google.auth._default.get_api_key_credentials(api_key_value) - - Transport = type(self).get_transport_class(transport) - self._transport = Transport( - credentials=credentials, - credentials_file=client_options.credentials_file, - host=api_endpoint, - scopes=client_options.scopes, - client_cert_source_for_mtls=client_cert_source_func, - quota_project_id=client_options.quota_project_id, - client_info=client_info, - always_use_jwt_access=True, - api_audience=client_options.api_audience, - ) - - def list_knowledge_bases(self, - request: Optional[Union[knowledge_base.ListKnowledgeBasesRequest, dict]] = None, - *, - parent: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListKnowledgeBasesPager: - r"""Returns the list of all knowledge bases of the - specified agent. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import dialogflow_v2 - - def sample_list_knowledge_bases(): - # Create a client - client = dialogflow_v2.KnowledgeBasesClient() - - # Initialize request argument(s) - request = dialogflow_v2.ListKnowledgeBasesRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_knowledge_bases(request=request) - - # Handle the response - for response in page_result: - print(response) - - Args: - request (Union[google.cloud.dialogflow_v2.types.ListKnowledgeBasesRequest, dict]): - The request object. Request message for - [KnowledgeBases.ListKnowledgeBases][google.cloud.dialogflow.v2.KnowledgeBases.ListKnowledgeBases]. - parent (str): - Required. The project to list of knowledge bases for. - Format: - ``projects//locations/``. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.dialogflow_v2.services.knowledge_bases.pagers.ListKnowledgeBasesPager: - Response message for - [KnowledgeBases.ListKnowledgeBases][google.cloud.dialogflow.v2.KnowledgeBases.ListKnowledgeBases]. - - Iterating over this object will yield results and - resolve additional pages automatically. - - """ - # Create or coerce a protobuf request object. - # Quick 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 knowledge_base.ListKnowledgeBasesRequest. - # There's no risk of modifying the input as we've already verified - # 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 - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.list_knowledge_bases] - - # 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.ListKnowledgeBasesPager( - method=rpc, - request=request, - response=response, - metadata=metadata, - ) - - # Done; return the response. - return response - - def get_knowledge_base(self, - request: Optional[Union[knowledge_base.GetKnowledgeBaseRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> knowledge_base.KnowledgeBase: - r"""Retrieves the specified knowledge base. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import dialogflow_v2 - - def sample_get_knowledge_base(): - # Create a client - client = dialogflow_v2.KnowledgeBasesClient() - - # Initialize request argument(s) - request = dialogflow_v2.GetKnowledgeBaseRequest( - name="name_value", - ) - - # Make the request - response = client.get_knowledge_base(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.dialogflow_v2.types.GetKnowledgeBaseRequest, dict]): - The request object. Request message for - [KnowledgeBases.GetKnowledgeBase][google.cloud.dialogflow.v2.KnowledgeBases.GetKnowledgeBase]. - name (str): - Required. The name of the knowledge base to retrieve. - Format - ``projects//locations//knowledgeBases/``. - - 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.KnowledgeBase: - A knowledge base represents a collection of knowledge documents that you - provide to Dialogflow. Your knowledge documents - contain information that may be useful during - conversations with end-users. Some Dialogflow - features use knowledge bases when looking for a - response to an end-user input. - - For more information, see the [knowledge base - guide](\ https://cloud.google.com/dialogflow/docs/how/knowledge-bases). - - Note: The projects.agent.knowledgeBases resource is - deprecated; only use projects.knowledgeBases. - - """ - # Create or coerce a protobuf request object. - # Quick 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 knowledge_base.GetKnowledgeBaseRequest. - # There's no risk of modifying the input as we've already verified - # 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 - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.get_knowledge_base] - - # 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_knowledge_base(self, - request: Optional[Union[gcd_knowledge_base.CreateKnowledgeBaseRequest, dict]] = None, - *, - parent: Optional[str] = None, - knowledge_base: Optional[gcd_knowledge_base.KnowledgeBase] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gcd_knowledge_base.KnowledgeBase: - r"""Creates a knowledge base. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import dialogflow_v2 - - def sample_create_knowledge_base(): - # Create a client - client = dialogflow_v2.KnowledgeBasesClient() - - # Initialize request argument(s) - knowledge_base = dialogflow_v2.KnowledgeBase() - knowledge_base.display_name = "display_name_value" - - request = dialogflow_v2.CreateKnowledgeBaseRequest( - parent="parent_value", - knowledge_base=knowledge_base, - ) - - # Make the request - response = client.create_knowledge_base(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.dialogflow_v2.types.CreateKnowledgeBaseRequest, dict]): - The request object. Request message for - [KnowledgeBases.CreateKnowledgeBase][google.cloud.dialogflow.v2.KnowledgeBases.CreateKnowledgeBase]. - parent (str): - Required. The project to create a knowledge base for. - Format: - ``projects//locations/``. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - knowledge_base (google.cloud.dialogflow_v2.types.KnowledgeBase): - Required. The knowledge base to - create. - - 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. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.dialogflow_v2.types.KnowledgeBase: - A knowledge base represents a collection of knowledge documents that you - provide to Dialogflow. Your knowledge documents - contain information that may be useful during - conversations with end-users. Some Dialogflow - features use knowledge bases when looking for a - response to an end-user input. - - For more information, see the [knowledge base - guide](\ https://cloud.google.com/dialogflow/docs/how/knowledge-bases). - - Note: The projects.agent.knowledgeBases resource is - deprecated; only use projects.knowledgeBases. - - """ - # Create or coerce a protobuf request object. - # Quick 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, knowledge_base]) - 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_knowledge_base.CreateKnowledgeBaseRequest. - # There's no risk of modifying the input as we've already verified - # 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: - request.knowledge_base = knowledge_base - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.create_knowledge_base] - - # 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 delete_knowledge_base(self, - request: Optional[Union[knowledge_base.DeleteKnowledgeBaseRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> None: - r"""Deletes the specified knowledge base. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import dialogflow_v2 - - def sample_delete_knowledge_base(): - # Create a client - client = dialogflow_v2.KnowledgeBasesClient() - - # Initialize request argument(s) - request = dialogflow_v2.DeleteKnowledgeBaseRequest( - name="name_value", - ) - - # Make the request - client.delete_knowledge_base(request=request) - - Args: - request (Union[google.cloud.dialogflow_v2.types.DeleteKnowledgeBaseRequest, dict]): - The request object. Request message for - [KnowledgeBases.DeleteKnowledgeBase][google.cloud.dialogflow.v2.KnowledgeBases.DeleteKnowledgeBase]. - name (str): - Required. The name of the knowledge base to delete. - Format: - ``projects//locations//knowledgeBases/``. - - 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. - # Quick 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 knowledge_base.DeleteKnowledgeBaseRequest. - # There's no risk of modifying the input as we've already verified - # 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 - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.delete_knowledge_base] - - # 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 update_knowledge_base(self, - request: Optional[Union[gcd_knowledge_base.UpdateKnowledgeBaseRequest, dict]] = None, - *, - knowledge_base: Optional[gcd_knowledge_base.KnowledgeBase] = None, - update_mask: Optional[field_mask_pb2.FieldMask] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gcd_knowledge_base.KnowledgeBase: - r"""Updates the specified knowledge base. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import dialogflow_v2 - - def sample_update_knowledge_base(): - # Create a client - client = dialogflow_v2.KnowledgeBasesClient() - - # Initialize request argument(s) - knowledge_base = dialogflow_v2.KnowledgeBase() - knowledge_base.display_name = "display_name_value" - - request = dialogflow_v2.UpdateKnowledgeBaseRequest( - knowledge_base=knowledge_base, - ) - - # Make the request - response = client.update_knowledge_base(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.dialogflow_v2.types.UpdateKnowledgeBaseRequest, dict]): - The request object. Request message for - [KnowledgeBases.UpdateKnowledgeBase][google.cloud.dialogflow.v2.KnowledgeBases.UpdateKnowledgeBase]. - knowledge_base (google.cloud.dialogflow_v2.types.KnowledgeBase): - Required. The knowledge base to - update. - - This corresponds to the ``knowledge_base`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - update_mask (google.protobuf.field_mask_pb2.FieldMask): - Optional. Not specified means ``update all``. Currently, - only ``display_name`` can be updated, an InvalidArgument - will be returned for attempting to update other fields. - - 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.KnowledgeBase: - A knowledge base represents a collection of knowledge documents that you - provide to Dialogflow. Your knowledge documents - contain information that may be useful during - conversations with end-users. Some Dialogflow - features use knowledge bases when looking for a - response to an end-user input. - - For more information, see the [knowledge base - guide](\ https://cloud.google.com/dialogflow/docs/how/knowledge-bases). - - Note: The projects.agent.knowledgeBases resource is - deprecated; only use projects.knowledgeBases. - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([knowledge_base, 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_knowledge_base.UpdateKnowledgeBaseRequest. - # There's no risk of modifying the input as we've already verified - # 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: - 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_knowledge_base] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("knowledge_base.name", request.knowledge_base.name), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def __enter__(self) -> "KnowledgeBasesClient": - return self - - def __exit__(self, type, value, traceback): - """Releases underlying transport's resources. - - .. warning:: - ONLY use as a context manager if the transport is NOT shared - with other clients! Exiting the with block will CLOSE the transport - and may cause errors in other clients! - """ - self.transport.close() - - def list_operations( - self, - request: Optional[operations_pb2.ListOperationsRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operations_pb2.ListOperationsResponse: - r"""Lists operations that match the specified filter in the request. - - Args: - request (:class:`~.operations_pb2.ListOperationsRequest`): - The request object. Request message for - `ListOperations` method. - 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: - ~.operations_pb2.ListOperationsResponse: - Response message for ``ListOperations`` method. - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = operations_pb2.ListOperationsRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._transport.list_operations, - 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 = rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - def get_operation( - self, - request: Optional[operations_pb2.GetOperationRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operations_pb2.Operation: - r"""Gets the latest state of a long-running operation. - - Args: - request (:class:`~.operations_pb2.GetOperationRequest`): - The request object. Request message for - `GetOperation` method. - 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: - ~.operations_pb2.Operation: - An ``Operation`` object. - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = operations_pb2.GetOperationRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._transport.get_operation, - 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 = rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - def cancel_operation( - self, - request: Optional[operations_pb2.CancelOperationRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> None: - r"""Starts asynchronous cancellation on a long-running operation. - - The server makes a best effort to cancel the operation, but success - is not guaranteed. If the server doesn't support this method, it returns - `google.rpc.Code.UNIMPLEMENTED`. - - Args: - request (:class:`~.operations_pb2.CancelOperationRequest`): - The request object. Request message for - `CancelOperation` method. - 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: - None - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = operations_pb2.CancelOperationRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._transport.cancel_operation, - 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. - rpc(request, retry=retry, timeout=timeout, metadata=metadata,) - - def get_location( - self, - request: Optional[locations_pb2.GetLocationRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> locations_pb2.Location: - r"""Gets information about a location. - - Args: - request (:class:`~.location_pb2.GetLocationRequest`): - The request object. Request message for - `GetLocation` method. - 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: - ~.location_pb2.Location: - Location object. - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = locations_pb2.GetLocationRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._transport.get_location, - 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 = rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - def list_locations( - self, - request: Optional[locations_pb2.ListLocationsRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> locations_pb2.ListLocationsResponse: - r"""Lists information about the supported locations for this service. - - Args: - request (:class:`~.location_pb2.ListLocationsRequest`): - The request object. Request message for - `ListLocations` method. - 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: - ~.location_pb2.ListLocationsResponse: - Response message for ``ListLocations`` method. - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = locations_pb2.ListLocationsRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._transport.list_locations, - 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 = rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) - - -__all__ = ( - "KnowledgeBasesClient", -) diff --git a/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/knowledge_bases/pagers.py b/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/knowledge_bases/pagers.py deleted file mode 100644 index eec84b93d..000000000 --- a/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/knowledge_bases/pagers.py +++ /dev/null @@ -1,139 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from typing import Any, AsyncIterator, Awaitable, Callable, Sequence, Tuple, Optional, Iterator - -from google.cloud.dialogflow_v2.types import knowledge_base - - -class ListKnowledgeBasesPager: - """A pager for iterating through ``list_knowledge_bases`` requests. - - This class thinly wraps an initial - :class:`google.cloud.dialogflow_v2.types.ListKnowledgeBasesResponse` object, and - provides an ``__iter__`` method to iterate through its - ``knowledge_bases`` field. - - If there are more pages, the ``__iter__`` method will make additional - ``ListKnowledgeBases`` requests and continue to iterate - through the ``knowledge_bases`` field on the - corresponding responses. - - All the usual :class:`google.cloud.dialogflow_v2.types.ListKnowledgeBasesResponse` - 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[..., knowledge_base.ListKnowledgeBasesResponse], - request: knowledge_base.ListKnowledgeBasesRequest, - response: knowledge_base.ListKnowledgeBasesResponse, - *, - 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.ListKnowledgeBasesRequest): - The initial request object. - response (google.cloud.dialogflow_v2.types.ListKnowledgeBasesResponse): - 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 = knowledge_base.ListKnowledgeBasesRequest(request) - self._response = response - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - def pages(self) -> Iterator[knowledge_base.ListKnowledgeBasesResponse]: - yield self._response - while self._response.next_page_token: - self._request.page_token = self._response.next_page_token - self._response = self._method(self._request, metadata=self._metadata) - yield self._response - - def __iter__(self) -> Iterator[knowledge_base.KnowledgeBase]: - for page in self.pages: - yield from page.knowledge_bases - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListKnowledgeBasesAsyncPager: - """A pager for iterating through ``list_knowledge_bases`` requests. - - This class thinly wraps an initial - :class:`google.cloud.dialogflow_v2.types.ListKnowledgeBasesResponse` object, and - provides an ``__aiter__`` method to iterate through its - ``knowledge_bases`` field. - - If there are more pages, the ``__aiter__`` method will make additional - ``ListKnowledgeBases`` requests and continue to iterate - through the ``knowledge_bases`` field on the - corresponding responses. - - All the usual :class:`google.cloud.dialogflow_v2.types.ListKnowledgeBasesResponse` - 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[knowledge_base.ListKnowledgeBasesResponse]], - request: knowledge_base.ListKnowledgeBasesRequest, - response: knowledge_base.ListKnowledgeBasesResponse, - *, - metadata: Sequence[Tuple[str, str]] = ()): - """Instantiates the pager. - - Args: - method (Callable): The method that was originally called, and - which instantiated this pager. - request (google.cloud.dialogflow_v2.types.ListKnowledgeBasesRequest): - The initial request object. - response (google.cloud.dialogflow_v2.types.ListKnowledgeBasesResponse): - 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 = knowledge_base.ListKnowledgeBasesRequest(request) - self._response = response - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - async def pages(self) -> AsyncIterator[knowledge_base.ListKnowledgeBasesResponse]: - yield self._response - while self._response.next_page_token: - self._request.page_token = self._response.next_page_token - self._response = await self._method(self._request, metadata=self._metadata) - yield self._response - def __aiter__(self) -> AsyncIterator[knowledge_base.KnowledgeBase]: - async def async_generator(): - async for page in self.pages: - for response in page.knowledge_bases: - yield response - - return async_generator() - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) diff --git a/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/knowledge_bases/transports/__init__.py b/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/knowledge_bases/transports/__init__.py deleted file mode 100644 index bcb1968b6..000000000 --- a/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/knowledge_bases/transports/__init__.py +++ /dev/null @@ -1,38 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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 KnowledgeBasesTransport -from .grpc import KnowledgeBasesGrpcTransport -from .grpc_asyncio import KnowledgeBasesGrpcAsyncIOTransport -from .rest import KnowledgeBasesRestTransport -from .rest import KnowledgeBasesRestInterceptor - - -# Compile a registry of transports. -_transport_registry = OrderedDict() # type: Dict[str, Type[KnowledgeBasesTransport]] -_transport_registry['grpc'] = KnowledgeBasesGrpcTransport -_transport_registry['grpc_asyncio'] = KnowledgeBasesGrpcAsyncIOTransport -_transport_registry['rest'] = KnowledgeBasesRestTransport - -__all__ = ( - 'KnowledgeBasesTransport', - 'KnowledgeBasesGrpcTransport', - 'KnowledgeBasesGrpcAsyncIOTransport', - 'KnowledgeBasesRestTransport', - 'KnowledgeBasesRestInterceptor', -) diff --git a/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/knowledge_bases/transports/base.py b/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/knowledge_bases/transports/base.py deleted file mode 100644 index 49156d6dd..000000000 --- a/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/knowledge_bases/transports/base.py +++ /dev/null @@ -1,252 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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 - -from google.cloud.dialogflow_v2 import gapic_version as package_version - -import google.auth # type: ignore -import google.api_core -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import retry as retries -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 knowledge_base -from google.cloud.dialogflow_v2.types import knowledge_base as gcd_knowledge_base -from google.cloud.location import locations_pb2 # type: ignore -from google.longrunning import operations_pb2 -from google.protobuf import empty_pb2 # type: ignore - -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) - - -class KnowledgeBasesTransport(abc.ABC): - """Abstract transport class for KnowledgeBases.""" - - 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: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - api_audience: Optional[str] = None, - **kwargs, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. - scopes (Optional[Sequence[str]]): A list of scopes. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - """ - - scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} - - # Save the scopes. - self._scopes = scopes - - # If no credentials are provided, then determine the appropriate - # defaults. - if credentials and credentials_file: - raise core_exceptions.DuplicateCredentialArgs("'credentials_file' and 'credentials' are mutually exclusive") - - if credentials_file is not None: - credentials, _ = google.auth.load_credentials_from_file( - credentials_file, - **scopes_kwargs, - quota_project_id=quota_project_id - ) - elif credentials is None: - credentials, _ = google.auth.default(**scopes_kwargs, quota_project_id=quota_project_id) - # Don't apply audience if the credentials file passed from user. - if hasattr(credentials, "with_gdch_audience"): - credentials = credentials.with_gdch_audience(api_audience if api_audience else host) - - # If the credentials are service account credentials, then always try to use self signed JWT. - if always_use_jwt_access and isinstance(credentials, service_account.Credentials) and hasattr(service_account.Credentials, "with_always_use_jwt_access"): - credentials = credentials.with_always_use_jwt_access(True) - - # Save the credentials. - self._credentials = credentials - - # Save the hostname. Default to port 443 (HTTPS) if none is specified. - if ':' not in host: - host += ':443' - self._host = host - - def _prep_wrapped_messages(self, client_info): - # Precompute the wrapped methods. - self._wrapped_methods = { - self.list_knowledge_bases: gapic_v1.method.wrap_method( - self.list_knowledge_bases, - default_timeout=None, - client_info=client_info, - ), - self.get_knowledge_base: gapic_v1.method.wrap_method( - self.get_knowledge_base, - default_timeout=None, - client_info=client_info, - ), - self.create_knowledge_base: gapic_v1.method.wrap_method( - self.create_knowledge_base, - default_timeout=None, - client_info=client_info, - ), - self.delete_knowledge_base: gapic_v1.method.wrap_method( - self.delete_knowledge_base, - default_timeout=None, - client_info=client_info, - ), - self.update_knowledge_base: gapic_v1.method.wrap_method( - self.update_knowledge_base, - default_timeout=None, - client_info=client_info, - ), - } - - def close(self): - """Closes resources associated with the transport. - - .. warning:: - Only call this method if the transport is NOT shared - with other clients - this may cause errors in other clients! - """ - raise NotImplementedError() - - @property - def list_knowledge_bases(self) -> Callable[ - [knowledge_base.ListKnowledgeBasesRequest], - Union[ - knowledge_base.ListKnowledgeBasesResponse, - Awaitable[knowledge_base.ListKnowledgeBasesResponse] - ]]: - raise NotImplementedError() - - @property - def get_knowledge_base(self) -> Callable[ - [knowledge_base.GetKnowledgeBaseRequest], - Union[ - knowledge_base.KnowledgeBase, - Awaitable[knowledge_base.KnowledgeBase] - ]]: - raise NotImplementedError() - - @property - def create_knowledge_base(self) -> Callable[ - [gcd_knowledge_base.CreateKnowledgeBaseRequest], - Union[ - gcd_knowledge_base.KnowledgeBase, - Awaitable[gcd_knowledge_base.KnowledgeBase] - ]]: - raise NotImplementedError() - - @property - def delete_knowledge_base(self) -> Callable[ - [knowledge_base.DeleteKnowledgeBaseRequest], - Union[ - empty_pb2.Empty, - Awaitable[empty_pb2.Empty] - ]]: - raise NotImplementedError() - - @property - def update_knowledge_base(self) -> Callable[ - [gcd_knowledge_base.UpdateKnowledgeBaseRequest], - Union[ - gcd_knowledge_base.KnowledgeBase, - Awaitable[gcd_knowledge_base.KnowledgeBase] - ]]: - raise NotImplementedError() - - @property - def list_operations( - self, - ) -> Callable[ - [operations_pb2.ListOperationsRequest], - Union[operations_pb2.ListOperationsResponse, Awaitable[operations_pb2.ListOperationsResponse]], - ]: - raise NotImplementedError() - - @property - def get_operation( - self, - ) -> Callable[ - [operations_pb2.GetOperationRequest], - Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], - ]: - raise NotImplementedError() - - @property - def cancel_operation( - self, - ) -> Callable[ - [operations_pb2.CancelOperationRequest], - None, - ]: - raise NotImplementedError() - - @property - def get_location(self, - ) -> Callable[ - [locations_pb2.GetLocationRequest], - Union[locations_pb2.Location, Awaitable[locations_pb2.Location]], - ]: - raise NotImplementedError() - - @property - def list_locations(self, - ) -> Callable[ - [locations_pb2.ListLocationsRequest], - Union[locations_pb2.ListLocationsResponse, Awaitable[locations_pb2.ListLocationsResponse]], - ]: - raise NotImplementedError() - - @property - def kind(self) -> str: - raise NotImplementedError() - - -__all__ = ( - 'KnowledgeBasesTransport', -) diff --git a/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/knowledge_bases/transports/grpc.py b/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/knowledge_bases/transports/grpc.py deleted file mode 100644 index 0e84c4c3a..000000000 --- a/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/knowledge_bases/transports/grpc.py +++ /dev/null @@ -1,464 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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 -from google.api_core import gapic_v1 -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.cloud.location import locations_pb2 # type: ignore -from google.longrunning import operations_pb2 -from google.protobuf import empty_pb2 # type: ignore -from .base import KnowledgeBasesTransport, DEFAULT_CLIENT_INFO - - -class KnowledgeBasesGrpcTransport(KnowledgeBasesTransport): - """gRPC backend transport for KnowledgeBases. - - Service for managing - [KnowledgeBases][google.cloud.dialogflow.v2.KnowledgeBase]. - - 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: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - channel: Optional[grpc.Channel] = None, - api_mtls_endpoint: Optional[str] = None, - client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, - ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, - client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - api_audience: Optional[str] = None, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - This argument is ignored if ``channel`` is provided. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional(Sequence[str])): A list of scopes. This argument is - ignored if ``channel`` is provided. - channel (Optional[grpc.Channel]): A ``Channel`` instance through - which to make calls. - api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. - If provided, it overrides the ``host`` argument and tries to create - a mutual TLS channel with client SSL credentials from - ``client_cert_source`` or application default SSL credentials. - client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): - Deprecated. A callback to provide client SSL certificate bytes and - private key bytes, both in PEM format. It is ignored if - ``api_mtls_endpoint`` is None. - ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials - for the grpc channel. It is ignored if ``channel`` is provided. - client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): - A callback to provide client certificate bytes and private key bytes, - both in PEM format. It is used to configure a mutual TLS channel. It is - ignored if ``channel`` or ``ssl_channel_credentials`` is provided. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport - creation failed for any reason. - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - self._grpc_channel = None - self._ssl_channel_credentials = ssl_channel_credentials - self._stubs: Dict[str, Callable] = {} - - if api_mtls_endpoint: - warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) - if client_cert_source: - warnings.warn("client_cert_source is deprecated", DeprecationWarning) - - if channel: - # Ignore credentials if a channel was passed. - credentials = False - # If a channel was explicitly provided, set it. - self._grpc_channel = channel - self._ssl_channel_credentials = None - - else: - if api_mtls_endpoint: - host = api_mtls_endpoint - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - self._ssl_channel_credentials = SslCredentials().ssl_credentials - - else: - if client_cert_source_for_mtls and not ssl_channel_credentials: - cert, key = client_cert_source_for_mtls() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - - # The base transport sets the host, credentials and scopes - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes, - quota_project_id=quota_project_id, - client_info=client_info, - always_use_jwt_access=always_use_jwt_access, - api_audience=api_audience, - ) - - if not self._grpc_channel: - self._grpc_channel = type(self).create_channel( - self._host, - # use the credentials which are saved - credentials=self._credentials, - # Set ``credentials_file`` to ``None`` here as - # the credentials that we saved earlier should be used. - credentials_file=None, - 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: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - **kwargs) -> grpc.Channel: - """Create and return a gRPC channel object. - Args: - host (Optional[str]): The host for the channel to use. - credentials (Optional[~.Credentials]): The - authorization credentials to attach to requests. These - credentials identify this application to the service. If - none are specified, the client will attempt to ascertain - the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - kwargs (Optional[dict]): Keyword arguments, which are passed to the - channel creation. - Returns: - grpc.Channel: A gRPC channel object. - - Raises: - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - - return grpc_helpers.create_channel( - host, - credentials=credentials, - credentials_file=credentials_file, - quota_project_id=quota_project_id, - default_scopes=cls.AUTH_SCOPES, - scopes=scopes, - default_host=cls.DEFAULT_HOST, - **kwargs - ) - - @property - def grpc_channel(self) -> grpc.Channel: - """Return the channel designed to connect to this service. - """ - return self._grpc_channel - - @property - def list_knowledge_bases(self) -> Callable[ - [knowledge_base.ListKnowledgeBasesRequest], - knowledge_base.ListKnowledgeBasesResponse]: - r"""Return a callable for the list knowledge bases method over gRPC. - - Returns the list of all knowledge bases of the - specified agent. - - Returns: - Callable[[~.ListKnowledgeBasesRequest], - ~.ListKnowledgeBasesResponse]: - 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_knowledge_bases' not in self._stubs: - self._stubs['list_knowledge_bases'] = self.grpc_channel.unary_unary( - '/google.cloud.dialogflow.v2.KnowledgeBases/ListKnowledgeBases', - request_serializer=knowledge_base.ListKnowledgeBasesRequest.serialize, - response_deserializer=knowledge_base.ListKnowledgeBasesResponse.deserialize, - ) - return self._stubs['list_knowledge_bases'] - - @property - def get_knowledge_base(self) -> Callable[ - [knowledge_base.GetKnowledgeBaseRequest], - knowledge_base.KnowledgeBase]: - r"""Return a callable for the get knowledge base method over gRPC. - - Retrieves the specified knowledge base. - - Returns: - Callable[[~.GetKnowledgeBaseRequest], - ~.KnowledgeBase]: - 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_knowledge_base' not in self._stubs: - self._stubs['get_knowledge_base'] = self.grpc_channel.unary_unary( - '/google.cloud.dialogflow.v2.KnowledgeBases/GetKnowledgeBase', - request_serializer=knowledge_base.GetKnowledgeBaseRequest.serialize, - response_deserializer=knowledge_base.KnowledgeBase.deserialize, - ) - return self._stubs['get_knowledge_base'] - - @property - def create_knowledge_base(self) -> Callable[ - [gcd_knowledge_base.CreateKnowledgeBaseRequest], - gcd_knowledge_base.KnowledgeBase]: - r"""Return a callable for the create knowledge base method over gRPC. - - Creates a knowledge base. - - Returns: - Callable[[~.CreateKnowledgeBaseRequest], - ~.KnowledgeBase]: - 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_knowledge_base' not in self._stubs: - self._stubs['create_knowledge_base'] = self.grpc_channel.unary_unary( - '/google.cloud.dialogflow.v2.KnowledgeBases/CreateKnowledgeBase', - request_serializer=gcd_knowledge_base.CreateKnowledgeBaseRequest.serialize, - response_deserializer=gcd_knowledge_base.KnowledgeBase.deserialize, - ) - return self._stubs['create_knowledge_base'] - - @property - def delete_knowledge_base(self) -> Callable[ - [knowledge_base.DeleteKnowledgeBaseRequest], - empty_pb2.Empty]: - r"""Return a callable for the delete knowledge base method over gRPC. - - Deletes the specified knowledge base. - - Returns: - Callable[[~.DeleteKnowledgeBaseRequest], - ~.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_knowledge_base' not in self._stubs: - 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_pb2.Empty.FromString, - ) - return self._stubs['delete_knowledge_base'] - - @property - def update_knowledge_base(self) -> Callable[ - [gcd_knowledge_base.UpdateKnowledgeBaseRequest], - gcd_knowledge_base.KnowledgeBase]: - r"""Return a callable for the update knowledge base method over gRPC. - - Updates the specified knowledge base. - - Returns: - Callable[[~.UpdateKnowledgeBaseRequest], - ~.KnowledgeBase]: - 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_knowledge_base' not in self._stubs: - self._stubs['update_knowledge_base'] = self.grpc_channel.unary_unary( - '/google.cloud.dialogflow.v2.KnowledgeBases/UpdateKnowledgeBase', - request_serializer=gcd_knowledge_base.UpdateKnowledgeBaseRequest.serialize, - response_deserializer=gcd_knowledge_base.KnowledgeBase.deserialize, - ) - return self._stubs['update_knowledge_base'] - - def close(self): - self.grpc_channel.close() - - @property - def cancel_operation( - self, - ) -> Callable[[operations_pb2.CancelOperationRequest], None]: - r"""Return a callable for the cancel_operation method over gRPC. - """ - # 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 "cancel_operation" not in self._stubs: - self._stubs["cancel_operation"] = self.grpc_channel.unary_unary( - "/google.longrunning.Operations/CancelOperation", - request_serializer=operations_pb2.CancelOperationRequest.SerializeToString, - response_deserializer=None, - ) - return self._stubs["cancel_operation"] - - @property - def get_operation( - self, - ) -> Callable[[operations_pb2.GetOperationRequest], operations_pb2.Operation]: - r"""Return a callable for the get_operation method over gRPC. - """ - # 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_operation" not in self._stubs: - self._stubs["get_operation"] = self.grpc_channel.unary_unary( - "/google.longrunning.Operations/GetOperation", - request_serializer=operations_pb2.GetOperationRequest.SerializeToString, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs["get_operation"] - - @property - def list_operations( - self, - ) -> Callable[[operations_pb2.ListOperationsRequest], operations_pb2.ListOperationsResponse]: - r"""Return a callable for the list_operations method over gRPC. - """ - # 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_operations" not in self._stubs: - self._stubs["list_operations"] = self.grpc_channel.unary_unary( - "/google.longrunning.Operations/ListOperations", - request_serializer=operations_pb2.ListOperationsRequest.SerializeToString, - response_deserializer=operations_pb2.ListOperationsResponse.FromString, - ) - return self._stubs["list_operations"] - - @property - def list_locations( - self, - ) -> Callable[[locations_pb2.ListLocationsRequest], locations_pb2.ListLocationsResponse]: - r"""Return a callable for the list locations method over gRPC. - """ - # 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_locations" not in self._stubs: - self._stubs["list_locations"] = self.grpc_channel.unary_unary( - "/google.cloud.location.Locations/ListLocations", - request_serializer=locations_pb2.ListLocationsRequest.SerializeToString, - response_deserializer=locations_pb2.ListLocationsResponse.FromString, - ) - return self._stubs["list_locations"] - - @property - def get_location( - self, - ) -> Callable[[locations_pb2.GetLocationRequest], locations_pb2.Location]: - r"""Return a callable for the list locations method over gRPC. - """ - # 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_location" not in self._stubs: - self._stubs["get_location"] = self.grpc_channel.unary_unary( - "/google.cloud.location.Locations/GetLocation", - request_serializer=locations_pb2.GetLocationRequest.SerializeToString, - response_deserializer=locations_pb2.Location.FromString, - ) - return self._stubs["get_location"] - - @property - def kind(self) -> str: - return "grpc" - - -__all__ = ( - 'KnowledgeBasesGrpcTransport', -) diff --git a/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/knowledge_bases/transports/grpc_asyncio.py b/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/knowledge_bases/transports/grpc_asyncio.py deleted file mode 100644 index 2df794fc3..000000000 --- a/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/knowledge_bases/transports/grpc_asyncio.py +++ /dev/null @@ -1,463 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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 -from google.api_core import grpc_helpers_async -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore - -import grpc # type: ignore -from grpc.experimental import aio # type: ignore - -from google.cloud.dialogflow_v2.types import knowledge_base -from google.cloud.dialogflow_v2.types import knowledge_base as gcd_knowledge_base -from google.cloud.location import locations_pb2 # type: ignore -from google.longrunning import operations_pb2 -from google.protobuf import empty_pb2 # type: ignore -from .base import KnowledgeBasesTransport, DEFAULT_CLIENT_INFO -from .grpc import KnowledgeBasesGrpcTransport - - -class KnowledgeBasesGrpcAsyncIOTransport(KnowledgeBasesTransport): - """gRPC AsyncIO backend transport for KnowledgeBases. - - Service for managing - [KnowledgeBases][google.cloud.dialogflow.v2.KnowledgeBase]. - - 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: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - **kwargs) -> aio.Channel: - """Create and return a gRPC AsyncIO channel object. - Args: - host (Optional[str]): The host for the channel to use. - credentials (Optional[~.Credentials]): The - authorization credentials to attach to requests. These - credentials identify this application to the service. If - none are specified, the client will attempt to ascertain - the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - kwargs (Optional[dict]): Keyword arguments, which are passed to the - channel creation. - Returns: - aio.Channel: A gRPC AsyncIO channel object. - """ - - return grpc_helpers_async.create_channel( - host, - credentials=credentials, - credentials_file=credentials_file, - quota_project_id=quota_project_id, - default_scopes=cls.AUTH_SCOPES, - scopes=scopes, - default_host=cls.DEFAULT_HOST, - **kwargs - ) - - def __init__(self, *, - host: str = 'dialogflow.googleapis.com', - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - channel: Optional[aio.Channel] = None, - api_mtls_endpoint: Optional[str] = None, - client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, - ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, - client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - api_audience: Optional[str] = None, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - This argument is ignored if ``channel`` is provided. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - channel (Optional[aio.Channel]): A ``Channel`` instance through - which to make calls. - api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. - If provided, it overrides the ``host`` argument and tries to create - a mutual TLS channel with client SSL credentials from - ``client_cert_source`` or application default SSL credentials. - client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): - Deprecated. A callback to provide client SSL certificate bytes and - private key bytes, both in PEM format. It is ignored if - ``api_mtls_endpoint`` is None. - ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials - for the grpc channel. It is ignored if ``channel`` is provided. - client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): - A callback to provide client certificate bytes and private key bytes, - both in PEM format. It is used to configure a mutual TLS channel. It is - ignored if ``channel`` or ``ssl_channel_credentials`` is provided. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - - Raises: - google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport - creation failed for any reason. - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - self._grpc_channel = None - self._ssl_channel_credentials = ssl_channel_credentials - self._stubs: Dict[str, Callable] = {} - - if api_mtls_endpoint: - warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) - if client_cert_source: - warnings.warn("client_cert_source is deprecated", DeprecationWarning) - - if channel: - # Ignore credentials if a channel was passed. - credentials = False - # If a channel was explicitly provided, set it. - self._grpc_channel = channel - self._ssl_channel_credentials = None - else: - if api_mtls_endpoint: - host = api_mtls_endpoint - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - self._ssl_channel_credentials = SslCredentials().ssl_credentials - - else: - if client_cert_source_for_mtls and not ssl_channel_credentials: - cert, key = client_cert_source_for_mtls() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - - # The base transport sets the host, credentials and scopes - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes, - quota_project_id=quota_project_id, - client_info=client_info, - always_use_jwt_access=always_use_jwt_access, - api_audience=api_audience, - ) - - if not self._grpc_channel: - self._grpc_channel = type(self).create_channel( - self._host, - # use the credentials which are saved - credentials=self._credentials, - # Set ``credentials_file`` to ``None`` here as - # the credentials that we saved earlier should be used. - credentials_file=None, - 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_knowledge_bases(self) -> Callable[ - [knowledge_base.ListKnowledgeBasesRequest], - Awaitable[knowledge_base.ListKnowledgeBasesResponse]]: - r"""Return a callable for the list knowledge bases method over gRPC. - - Returns the list of all knowledge bases of the - specified agent. - - Returns: - Callable[[~.ListKnowledgeBasesRequest], - Awaitable[~.ListKnowledgeBasesResponse]]: - 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_knowledge_bases' not in self._stubs: - self._stubs['list_knowledge_bases'] = self.grpc_channel.unary_unary( - '/google.cloud.dialogflow.v2.KnowledgeBases/ListKnowledgeBases', - request_serializer=knowledge_base.ListKnowledgeBasesRequest.serialize, - response_deserializer=knowledge_base.ListKnowledgeBasesResponse.deserialize, - ) - return self._stubs['list_knowledge_bases'] - - @property - def get_knowledge_base(self) -> Callable[ - [knowledge_base.GetKnowledgeBaseRequest], - Awaitable[knowledge_base.KnowledgeBase]]: - r"""Return a callable for the get knowledge base method over gRPC. - - Retrieves the specified knowledge base. - - Returns: - Callable[[~.GetKnowledgeBaseRequest], - Awaitable[~.KnowledgeBase]]: - 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_knowledge_base' not in self._stubs: - self._stubs['get_knowledge_base'] = self.grpc_channel.unary_unary( - '/google.cloud.dialogflow.v2.KnowledgeBases/GetKnowledgeBase', - request_serializer=knowledge_base.GetKnowledgeBaseRequest.serialize, - response_deserializer=knowledge_base.KnowledgeBase.deserialize, - ) - return self._stubs['get_knowledge_base'] - - @property - def create_knowledge_base(self) -> Callable[ - [gcd_knowledge_base.CreateKnowledgeBaseRequest], - Awaitable[gcd_knowledge_base.KnowledgeBase]]: - r"""Return a callable for the create knowledge base method over gRPC. - - Creates a knowledge base. - - Returns: - Callable[[~.CreateKnowledgeBaseRequest], - Awaitable[~.KnowledgeBase]]: - 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_knowledge_base' not in self._stubs: - self._stubs['create_knowledge_base'] = self.grpc_channel.unary_unary( - '/google.cloud.dialogflow.v2.KnowledgeBases/CreateKnowledgeBase', - request_serializer=gcd_knowledge_base.CreateKnowledgeBaseRequest.serialize, - response_deserializer=gcd_knowledge_base.KnowledgeBase.deserialize, - ) - return self._stubs['create_knowledge_base'] - - @property - def delete_knowledge_base(self) -> 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. - - Returns: - Callable[[~.DeleteKnowledgeBaseRequest], - 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_knowledge_base' not in self._stubs: - 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_pb2.Empty.FromString, - ) - return self._stubs['delete_knowledge_base'] - - @property - def update_knowledge_base(self) -> Callable[ - [gcd_knowledge_base.UpdateKnowledgeBaseRequest], - Awaitable[gcd_knowledge_base.KnowledgeBase]]: - r"""Return a callable for the update knowledge base method over gRPC. - - Updates the specified knowledge base. - - Returns: - Callable[[~.UpdateKnowledgeBaseRequest], - Awaitable[~.KnowledgeBase]]: - 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_knowledge_base' not in self._stubs: - self._stubs['update_knowledge_base'] = self.grpc_channel.unary_unary( - '/google.cloud.dialogflow.v2.KnowledgeBases/UpdateKnowledgeBase', - request_serializer=gcd_knowledge_base.UpdateKnowledgeBaseRequest.serialize, - response_deserializer=gcd_knowledge_base.KnowledgeBase.deserialize, - ) - return self._stubs['update_knowledge_base'] - - def close(self): - return self.grpc_channel.close() - - @property - def cancel_operation( - self, - ) -> Callable[[operations_pb2.CancelOperationRequest], None]: - r"""Return a callable for the cancel_operation method over gRPC. - """ - # 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 "cancel_operation" not in self._stubs: - self._stubs["cancel_operation"] = self.grpc_channel.unary_unary( - "/google.longrunning.Operations/CancelOperation", - request_serializer=operations_pb2.CancelOperationRequest.SerializeToString, - response_deserializer=None, - ) - return self._stubs["cancel_operation"] - - @property - def get_operation( - self, - ) -> Callable[[operations_pb2.GetOperationRequest], operations_pb2.Operation]: - r"""Return a callable for the get_operation method over gRPC. - """ - # 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_operation" not in self._stubs: - self._stubs["get_operation"] = self.grpc_channel.unary_unary( - "/google.longrunning.Operations/GetOperation", - request_serializer=operations_pb2.GetOperationRequest.SerializeToString, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs["get_operation"] - - @property - def list_operations( - self, - ) -> Callable[[operations_pb2.ListOperationsRequest], operations_pb2.ListOperationsResponse]: - r"""Return a callable for the list_operations method over gRPC. - """ - # 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_operations" not in self._stubs: - self._stubs["list_operations"] = self.grpc_channel.unary_unary( - "/google.longrunning.Operations/ListOperations", - request_serializer=operations_pb2.ListOperationsRequest.SerializeToString, - response_deserializer=operations_pb2.ListOperationsResponse.FromString, - ) - return self._stubs["list_operations"] - - @property - def list_locations( - self, - ) -> Callable[[locations_pb2.ListLocationsRequest], locations_pb2.ListLocationsResponse]: - r"""Return a callable for the list locations method over gRPC. - """ - # 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_locations" not in self._stubs: - self._stubs["list_locations"] = self.grpc_channel.unary_unary( - "/google.cloud.location.Locations/ListLocations", - request_serializer=locations_pb2.ListLocationsRequest.SerializeToString, - response_deserializer=locations_pb2.ListLocationsResponse.FromString, - ) - return self._stubs["list_locations"] - - @property - def get_location( - self, - ) -> Callable[[locations_pb2.GetLocationRequest], locations_pb2.Location]: - r"""Return a callable for the list locations method over gRPC. - """ - # 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_location" not in self._stubs: - self._stubs["get_location"] = self.grpc_channel.unary_unary( - "/google.cloud.location.Locations/GetLocation", - request_serializer=locations_pb2.GetLocationRequest.SerializeToString, - response_deserializer=locations_pb2.Location.FromString, - ) - return self._stubs["get_location"] - - -__all__ = ( - 'KnowledgeBasesGrpcAsyncIOTransport', -) diff --git a/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/knowledge_bases/transports/rest.py b/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/knowledge_bases/transports/rest.py deleted file mode 100644 index 5ef429c6a..000000000 --- a/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/knowledge_bases/transports/rest.py +++ /dev/null @@ -1,1246 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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 google.auth.transport.requests import AuthorizedSession # type: ignore -import json # type: ignore -import grpc # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore -from google.auth import credentials as ga_credentials # type: ignore -from google.api_core import exceptions as core_exceptions -from google.api_core import retry as retries -from google.api_core import rest_helpers -from google.api_core import rest_streaming -from google.api_core import path_template -from google.api_core import gapic_v1 - -from google.protobuf import json_format -from google.cloud.location import locations_pb2 # type: ignore -from google.longrunning import operations_pb2 -from requests import __version__ as requests_version -import dataclasses -import re -from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union -import warnings - -try: - OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] -except AttributeError: # pragma: NO COVER - OptionalRetry = Union[retries.Retry, object] # 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 # type: ignore - -from .base import KnowledgeBasesTransport, DEFAULT_CLIENT_INFO as BASE_DEFAULT_CLIENT_INFO - - -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=BASE_DEFAULT_CLIENT_INFO.gapic_version, - grpc_version=None, - rest_version=requests_version, -) - - -class KnowledgeBasesRestInterceptor: - """Interceptor for KnowledgeBases. - - Interceptors are used to manipulate requests, request metadata, and responses - in arbitrary ways. - Example use cases include: - * Logging - * Verifying requests according to service or custom semantics - * Stripping extraneous information from responses - - These use cases and more can be enabled by injecting an - instance of a custom subclass when constructing the KnowledgeBasesRestTransport. - - .. code-block:: python - class MyCustomKnowledgeBasesInterceptor(KnowledgeBasesRestInterceptor): - def pre_create_knowledge_base(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_create_knowledge_base(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_delete_knowledge_base(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def pre_get_knowledge_base(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_get_knowledge_base(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_list_knowledge_bases(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_list_knowledge_bases(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_update_knowledge_base(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_update_knowledge_base(self, response): - logging.log(f"Received response: {response}") - return response - - transport = KnowledgeBasesRestTransport(interceptor=MyCustomKnowledgeBasesInterceptor()) - client = KnowledgeBasesClient(transport=transport) - - - """ - def pre_create_knowledge_base(self, request: gcd_knowledge_base.CreateKnowledgeBaseRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[gcd_knowledge_base.CreateKnowledgeBaseRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for create_knowledge_base - - Override in a subclass to manipulate the request or metadata - before they are sent to the KnowledgeBases server. - """ - return request, metadata - - def post_create_knowledge_base(self, response: gcd_knowledge_base.KnowledgeBase) -> gcd_knowledge_base.KnowledgeBase: - """Post-rpc interceptor for create_knowledge_base - - Override in a subclass to manipulate the response - after it is returned by the KnowledgeBases server but before - it is returned to user code. - """ - return response - def pre_delete_knowledge_base(self, request: knowledge_base.DeleteKnowledgeBaseRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[knowledge_base.DeleteKnowledgeBaseRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for delete_knowledge_base - - Override in a subclass to manipulate the request or metadata - before they are sent to the KnowledgeBases server. - """ - return request, metadata - - def pre_get_knowledge_base(self, request: knowledge_base.GetKnowledgeBaseRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[knowledge_base.GetKnowledgeBaseRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for get_knowledge_base - - Override in a subclass to manipulate the request or metadata - before they are sent to the KnowledgeBases server. - """ - return request, metadata - - def post_get_knowledge_base(self, response: knowledge_base.KnowledgeBase) -> knowledge_base.KnowledgeBase: - """Post-rpc interceptor for get_knowledge_base - - Override in a subclass to manipulate the response - after it is returned by the KnowledgeBases server but before - it is returned to user code. - """ - return response - def pre_list_knowledge_bases(self, request: knowledge_base.ListKnowledgeBasesRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[knowledge_base.ListKnowledgeBasesRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for list_knowledge_bases - - Override in a subclass to manipulate the request or metadata - before they are sent to the KnowledgeBases server. - """ - return request, metadata - - def post_list_knowledge_bases(self, response: knowledge_base.ListKnowledgeBasesResponse) -> knowledge_base.ListKnowledgeBasesResponse: - """Post-rpc interceptor for list_knowledge_bases - - Override in a subclass to manipulate the response - after it is returned by the KnowledgeBases server but before - it is returned to user code. - """ - return response - def pre_update_knowledge_base(self, request: gcd_knowledge_base.UpdateKnowledgeBaseRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[gcd_knowledge_base.UpdateKnowledgeBaseRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for update_knowledge_base - - Override in a subclass to manipulate the request or metadata - before they are sent to the KnowledgeBases server. - """ - return request, metadata - - def post_update_knowledge_base(self, response: gcd_knowledge_base.KnowledgeBase) -> gcd_knowledge_base.KnowledgeBase: - """Post-rpc interceptor for update_knowledge_base - - Override in a subclass to manipulate the response - after it is returned by the KnowledgeBases server but before - it is returned to user code. - """ - return response - - def pre_get_location( - self, request: locations_pb2.GetLocationRequest, metadata: Sequence[Tuple[str, str]] - ) -> Tuple[locations_pb2.GetLocationRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for get_location - - Override in a subclass to manipulate the request or metadata - before they are sent to the KnowledgeBases server. - """ - return request, metadata - - def post_get_location( - self, response: locations_pb2.Location - ) -> locations_pb2.Location: - """Post-rpc interceptor for get_location - - Override in a subclass to manipulate the response - after it is returned by the KnowledgeBases server but before - it is returned to user code. - """ - return response - def pre_list_locations( - self, request: locations_pb2.ListLocationsRequest, metadata: Sequence[Tuple[str, str]] - ) -> Tuple[locations_pb2.ListLocationsRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for list_locations - - Override in a subclass to manipulate the request or metadata - before they are sent to the KnowledgeBases server. - """ - return request, metadata - - def post_list_locations( - self, response: locations_pb2.ListLocationsResponse - ) -> locations_pb2.ListLocationsResponse: - """Post-rpc interceptor for list_locations - - Override in a subclass to manipulate the response - after it is returned by the KnowledgeBases server but before - it is returned to user code. - """ - return response - def pre_cancel_operation( - self, request: operations_pb2.CancelOperationRequest, metadata: Sequence[Tuple[str, str]] - ) -> Tuple[operations_pb2.CancelOperationRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for cancel_operation - - Override in a subclass to manipulate the request or metadata - before they are sent to the KnowledgeBases server. - """ - return request, metadata - - def post_cancel_operation( - self, response: None - ) -> None: - """Post-rpc interceptor for cancel_operation - - Override in a subclass to manipulate the response - after it is returned by the KnowledgeBases server but before - it is returned to user code. - """ - return response - def pre_get_operation( - self, request: operations_pb2.GetOperationRequest, metadata: Sequence[Tuple[str, str]] - ) -> Tuple[operations_pb2.GetOperationRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for get_operation - - Override in a subclass to manipulate the request or metadata - before they are sent to the KnowledgeBases server. - """ - return request, metadata - - def post_get_operation( - self, response: operations_pb2.Operation - ) -> operations_pb2.Operation: - """Post-rpc interceptor for get_operation - - Override in a subclass to manipulate the response - after it is returned by the KnowledgeBases server but before - it is returned to user code. - """ - return response - def pre_list_operations( - self, request: operations_pb2.ListOperationsRequest, metadata: Sequence[Tuple[str, str]] - ) -> Tuple[operations_pb2.ListOperationsRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for list_operations - - Override in a subclass to manipulate the request or metadata - before they are sent to the KnowledgeBases server. - """ - return request, metadata - - def post_list_operations( - self, response: operations_pb2.ListOperationsResponse - ) -> operations_pb2.ListOperationsResponse: - """Post-rpc interceptor for list_operations - - Override in a subclass to manipulate the response - after it is returned by the KnowledgeBases server but before - it is returned to user code. - """ - return response - - -@dataclasses.dataclass -class KnowledgeBasesRestStub: - _session: AuthorizedSession - _host: str - _interceptor: KnowledgeBasesRestInterceptor - - -class KnowledgeBasesRestTransport(KnowledgeBasesTransport): - """REST backend transport for KnowledgeBases. - - Service for managing - [KnowledgeBases][google.cloud.dialogflow.v2.KnowledgeBase]. - - 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 JSON representations of protocol buffers over HTTP/1.1 - - """ - - def __init__(self, *, - host: str = 'dialogflow.googleapis.com', - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - client_cert_source_for_mtls: Optional[Callable[[ - ], Tuple[bytes, bytes]]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - url_scheme: str = 'https', - interceptor: Optional[KnowledgeBasesRestInterceptor] = None, - api_audience: Optional[str] = None, - ) -> 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 ignored if ``channel`` is provided. - scopes (Optional(Sequence[str])): A list of scopes. This argument is - ignored if ``channel`` is provided. - client_cert_source_for_mtls (Callable[[], Tuple[bytes, bytes]]): Client - certificate to configure mutual TLS HTTP channel. It is ignored - if ``channel`` is provided. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you are developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - url_scheme: the protocol scheme for the API endpoint. Normally - "https", but for testing or local servers, - "http" can be specified. - """ - # Run the base constructor - # TODO(yon-mg): resolve other ctor params i.e. scopes, quota, etc. - # TODO: When custom host (api_endpoint) is set, `scopes` must *also* be set on the - # credentials object - maybe_url_match = re.match("^(?Phttp(?:s)?://)?(?P.*)$", host) - if maybe_url_match is None: - raise ValueError(f"Unexpected hostname structure: {host}") # pragma: NO COVER - - url_match_items = maybe_url_match.groupdict() - - host = f"{url_scheme}://{host}" if not url_match_items["scheme"] else host - - super().__init__( - host=host, - credentials=credentials, - client_info=client_info, - always_use_jwt_access=always_use_jwt_access, - api_audience=api_audience - ) - self._session = AuthorizedSession( - self._credentials, default_host=self.DEFAULT_HOST) - if client_cert_source_for_mtls: - self._session.configure_mtls_channel(client_cert_source_for_mtls) - self._interceptor = interceptor or KnowledgeBasesRestInterceptor() - self._prep_wrapped_messages(client_info) - - class _CreateKnowledgeBase(KnowledgeBasesRestStub): - def __hash__(self): - return hash("CreateKnowledgeBase") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: gcd_knowledge_base.CreateKnowledgeBaseRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> gcd_knowledge_base.KnowledgeBase: - r"""Call the create knowledge base method over HTTP. - - Args: - request (~.gcd_knowledge_base.CreateKnowledgeBaseRequest): - The request object. Request message for - [KnowledgeBases.CreateKnowledgeBase][google.cloud.dialogflow.v2.KnowledgeBases.CreateKnowledgeBase]. - 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: - ~.gcd_knowledge_base.KnowledgeBase: - A knowledge base represents a collection of knowledge - documents that you provide to Dialogflow. Your knowledge - documents contain information that may be useful during - conversations with end-users. Some Dialogflow features - use knowledge bases when looking for a response to an - end-user input. - - For more information, see the `knowledge base - guide `__. - - Note: The ``projects.agent.knowledgeBases`` resource is - deprecated; only use ``projects.knowledgeBases``. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'post', - 'uri': '/v2/{parent=projects/*}/knowledgeBases', - 'body': 'knowledge_base', - }, -{ - 'method': 'post', - 'uri': '/v2/{parent=projects/*/locations/*}/knowledgeBases', - 'body': 'knowledge_base', - }, -{ - 'method': 'post', - 'uri': '/v2/{parent=projects/*/agent}/knowledgeBases', - 'body': 'knowledge_base', - }, - ] - request, metadata = self._interceptor.pre_create_knowledge_base(request, metadata) - pb_request = gcd_knowledge_base.CreateKnowledgeBaseRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request['body'], - including_default_value_fields=False, - use_integers_for_enums=True - ) - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - including_default_value_fields=False, - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = gcd_knowledge_base.KnowledgeBase() - pb_resp = gcd_knowledge_base.KnowledgeBase.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_create_knowledge_base(resp) - return resp - - class _DeleteKnowledgeBase(KnowledgeBasesRestStub): - def __hash__(self): - return hash("DeleteKnowledgeBase") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: knowledge_base.DeleteKnowledgeBaseRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ): - r"""Call the delete knowledge base method over HTTP. - - Args: - request (~.knowledge_base.DeleteKnowledgeBaseRequest): - The request object. Request message for - [KnowledgeBases.DeleteKnowledgeBase][google.cloud.dialogflow.v2.KnowledgeBases.DeleteKnowledgeBase]. - 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. - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'delete', - 'uri': '/v2/{name=projects/*/knowledgeBases/*}', - }, -{ - 'method': 'delete', - 'uri': '/v2/{name=projects/*/locations/*/knowledgeBases/*}', - }, -{ - 'method': 'delete', - 'uri': '/v2/{name=projects/*/agent/knowledgeBases/*}', - }, - ] - request, metadata = self._interceptor.pre_delete_knowledge_base(request, metadata) - pb_request = knowledge_base.DeleteKnowledgeBaseRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - including_default_value_fields=False, - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - class _GetKnowledgeBase(KnowledgeBasesRestStub): - def __hash__(self): - return hash("GetKnowledgeBase") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: knowledge_base.GetKnowledgeBaseRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> knowledge_base.KnowledgeBase: - r"""Call the get knowledge base method over HTTP. - - Args: - request (~.knowledge_base.GetKnowledgeBaseRequest): - The request object. Request message for - [KnowledgeBases.GetKnowledgeBase][google.cloud.dialogflow.v2.KnowledgeBases.GetKnowledgeBase]. - 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: - ~.knowledge_base.KnowledgeBase: - A knowledge base represents a collection of knowledge - documents that you provide to Dialogflow. Your knowledge - documents contain information that may be useful during - conversations with end-users. Some Dialogflow features - use knowledge bases when looking for a response to an - end-user input. - - For more information, see the `knowledge base - guide `__. - - Note: The ``projects.agent.knowledgeBases`` resource is - deprecated; only use ``projects.knowledgeBases``. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v2/{name=projects/*/knowledgeBases/*}', - }, -{ - 'method': 'get', - 'uri': '/v2/{name=projects/*/locations/*/knowledgeBases/*}', - }, -{ - 'method': 'get', - 'uri': '/v2/{name=projects/*/agent/knowledgeBases/*}', - }, - ] - request, metadata = self._interceptor.pre_get_knowledge_base(request, metadata) - pb_request = knowledge_base.GetKnowledgeBaseRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - including_default_value_fields=False, - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = knowledge_base.KnowledgeBase() - pb_resp = knowledge_base.KnowledgeBase.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_get_knowledge_base(resp) - return resp - - class _ListKnowledgeBases(KnowledgeBasesRestStub): - def __hash__(self): - return hash("ListKnowledgeBases") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: knowledge_base.ListKnowledgeBasesRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> knowledge_base.ListKnowledgeBasesResponse: - r"""Call the list knowledge bases method over HTTP. - - Args: - request (~.knowledge_base.ListKnowledgeBasesRequest): - The request object. Request message for - [KnowledgeBases.ListKnowledgeBases][google.cloud.dialogflow.v2.KnowledgeBases.ListKnowledgeBases]. - 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: - ~.knowledge_base.ListKnowledgeBasesResponse: - Response message for - [KnowledgeBases.ListKnowledgeBases][google.cloud.dialogflow.v2.KnowledgeBases.ListKnowledgeBases]. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v2/{parent=projects/*}/knowledgeBases', - }, -{ - 'method': 'get', - 'uri': '/v2/{parent=projects/*/locations/*}/knowledgeBases', - }, -{ - 'method': 'get', - 'uri': '/v2/{parent=projects/*/agent}/knowledgeBases', - }, - ] - request, metadata = self._interceptor.pre_list_knowledge_bases(request, metadata) - pb_request = knowledge_base.ListKnowledgeBasesRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - including_default_value_fields=False, - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = knowledge_base.ListKnowledgeBasesResponse() - pb_resp = knowledge_base.ListKnowledgeBasesResponse.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_list_knowledge_bases(resp) - return resp - - class _UpdateKnowledgeBase(KnowledgeBasesRestStub): - def __hash__(self): - return hash("UpdateKnowledgeBase") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: gcd_knowledge_base.UpdateKnowledgeBaseRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> gcd_knowledge_base.KnowledgeBase: - r"""Call the update knowledge base method over HTTP. - - Args: - request (~.gcd_knowledge_base.UpdateKnowledgeBaseRequest): - The request object. Request message for - [KnowledgeBases.UpdateKnowledgeBase][google.cloud.dialogflow.v2.KnowledgeBases.UpdateKnowledgeBase]. - 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: - ~.gcd_knowledge_base.KnowledgeBase: - A knowledge base represents a collection of knowledge - documents that you provide to Dialogflow. Your knowledge - documents contain information that may be useful during - conversations with end-users. Some Dialogflow features - use knowledge bases when looking for a response to an - end-user input. - - For more information, see the `knowledge base - guide `__. - - Note: The ``projects.agent.knowledgeBases`` resource is - deprecated; only use ``projects.knowledgeBases``. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'patch', - 'uri': '/v2/{knowledge_base.name=projects/*/knowledgeBases/*}', - 'body': 'knowledge_base', - }, -{ - 'method': 'patch', - 'uri': '/v2/{knowledge_base.name=projects/*/locations/*/knowledgeBases/*}', - 'body': 'knowledge_base', - }, -{ - 'method': 'patch', - 'uri': '/v2/{knowledge_base.name=projects/*/agent/knowledgeBases/*}', - 'body': 'knowledge_base', - }, - ] - request, metadata = self._interceptor.pre_update_knowledge_base(request, metadata) - pb_request = gcd_knowledge_base.UpdateKnowledgeBaseRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request['body'], - including_default_value_fields=False, - use_integers_for_enums=True - ) - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - including_default_value_fields=False, - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = gcd_knowledge_base.KnowledgeBase() - pb_resp = gcd_knowledge_base.KnowledgeBase.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_update_knowledge_base(resp) - return resp - - @property - def create_knowledge_base(self) -> Callable[ - [gcd_knowledge_base.CreateKnowledgeBaseRequest], - gcd_knowledge_base.KnowledgeBase]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._CreateKnowledgeBase(self._session, self._host, self._interceptor) # type: ignore - - @property - def delete_knowledge_base(self) -> Callable[ - [knowledge_base.DeleteKnowledgeBaseRequest], - empty_pb2.Empty]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._DeleteKnowledgeBase(self._session, self._host, self._interceptor) # type: ignore - - @property - def get_knowledge_base(self) -> Callable[ - [knowledge_base.GetKnowledgeBaseRequest], - knowledge_base.KnowledgeBase]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._GetKnowledgeBase(self._session, self._host, self._interceptor) # type: ignore - - @property - def list_knowledge_bases(self) -> Callable[ - [knowledge_base.ListKnowledgeBasesRequest], - knowledge_base.ListKnowledgeBasesResponse]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._ListKnowledgeBases(self._session, self._host, self._interceptor) # type: ignore - - @property - def update_knowledge_base(self) -> Callable[ - [gcd_knowledge_base.UpdateKnowledgeBaseRequest], - gcd_knowledge_base.KnowledgeBase]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._UpdateKnowledgeBase(self._session, self._host, self._interceptor) # type: ignore - - @property - def get_location(self): - return self._GetLocation(self._session, self._host, self._interceptor) # type: ignore - - class _GetLocation(KnowledgeBasesRestStub): - def __call__(self, - request: locations_pb2.GetLocationRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> locations_pb2.Location: - - r"""Call the get location method over HTTP. - - Args: - request (locations_pb2.GetLocationRequest): - The request object for GetLocation method. - 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: - locations_pb2.Location: Response from GetLocation method. - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v2/{name=projects/*/locations/*}', - }, - ] - - request, metadata = self._interceptor.pre_get_location(request, metadata) - request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode( - http_options, **request_kwargs) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json.dumps(transcoded_request['query_params'])) - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - resp = locations_pb2.Location() - resp = json_format.Parse(response.content.decode("utf-8"), resp) - resp = self._interceptor.post_get_location(resp) - return resp - - @property - def list_locations(self): - return self._ListLocations(self._session, self._host, self._interceptor) # type: ignore - - class _ListLocations(KnowledgeBasesRestStub): - def __call__(self, - request: locations_pb2.ListLocationsRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> locations_pb2.ListLocationsResponse: - - r"""Call the list locations method over HTTP. - - Args: - request (locations_pb2.ListLocationsRequest): - The request object for ListLocations method. - 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: - locations_pb2.ListLocationsResponse: Response from ListLocations method. - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v2/{name=projects/*}/locations', - }, - ] - - request, metadata = self._interceptor.pre_list_locations(request, metadata) - request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode( - http_options, **request_kwargs) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json.dumps(transcoded_request['query_params'])) - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - resp = locations_pb2.ListLocationsResponse() - resp = json_format.Parse(response.content.decode("utf-8"), resp) - resp = self._interceptor.post_list_locations(resp) - return resp - - @property - def cancel_operation(self): - return self._CancelOperation(self._session, self._host, self._interceptor) # type: ignore - - class _CancelOperation(KnowledgeBasesRestStub): - def __call__(self, - request: operations_pb2.CancelOperationRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> None: - - r"""Call the cancel operation method over HTTP. - - Args: - request (operations_pb2.CancelOperationRequest): - The request object for CancelOperation method. - 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. - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'post', - 'uri': '/v2/{name=projects/*/operations/*}:cancel', - }, -{ - 'method': 'post', - 'uri': '/v2/{name=projects/*/locations/*/operations/*}:cancel', - }, - ] - - request, metadata = self._interceptor.pre_cancel_operation(request, metadata) - request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode( - http_options, **request_kwargs) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json.dumps(transcoded_request['query_params'])) - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - return self._interceptor.post_cancel_operation(None) - - @property - def get_operation(self): - return self._GetOperation(self._session, self._host, self._interceptor) # type: ignore - - class _GetOperation(KnowledgeBasesRestStub): - def __call__(self, - request: operations_pb2.GetOperationRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> operations_pb2.Operation: - - r"""Call the get operation method over HTTP. - - Args: - request (operations_pb2.GetOperationRequest): - The request object for GetOperation method. - 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: - operations_pb2.Operation: Response from GetOperation method. - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v2/{name=projects/*/operations/*}', - }, -{ - 'method': 'get', - 'uri': '/v2/{name=projects/*/locations/*/operations/*}', - }, - ] - - request, metadata = self._interceptor.pre_get_operation(request, metadata) - request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode( - http_options, **request_kwargs) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json.dumps(transcoded_request['query_params'])) - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - resp = operations_pb2.Operation() - resp = json_format.Parse(response.content.decode("utf-8"), resp) - resp = self._interceptor.post_get_operation(resp) - return resp - - @property - def list_operations(self): - return self._ListOperations(self._session, self._host, self._interceptor) # type: ignore - - class _ListOperations(KnowledgeBasesRestStub): - def __call__(self, - request: operations_pb2.ListOperationsRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> operations_pb2.ListOperationsResponse: - - r"""Call the list operations method over HTTP. - - Args: - request (operations_pb2.ListOperationsRequest): - The request object for ListOperations method. - 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: - operations_pb2.ListOperationsResponse: Response from ListOperations method. - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v2/{name=projects/*}/operations', - }, -{ - 'method': 'get', - 'uri': '/v2/{name=projects/*/locations/*}/operations', - }, - ] - - request, metadata = self._interceptor.pre_list_operations(request, metadata) - request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode( - http_options, **request_kwargs) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json.dumps(transcoded_request['query_params'])) - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - resp = operations_pb2.ListOperationsResponse() - resp = json_format.Parse(response.content.decode("utf-8"), resp) - resp = self._interceptor.post_list_operations(resp) - return resp - - @property - def kind(self) -> str: - return "rest" - - def close(self): - self._session.close() - - -__all__=( - 'KnowledgeBasesRestTransport', -) diff --git a/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/participants/__init__.py b/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/participants/__init__.py deleted file mode 100644 index f97cdb2aa..000000000 --- a/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/participants/__init__.py +++ /dev/null @@ -1,22 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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 ParticipantsClient -from .async_client import ParticipantsAsyncClient - -__all__ = ( - 'ParticipantsClient', - 'ParticipantsAsyncClient', -) diff --git a/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/participants/async_client.py b/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/participants/async_client.py deleted file mode 100644 index cf3d3362e..000000000 --- a/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/participants/async_client.py +++ /dev/null @@ -1,1509 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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, Mapping, MutableMapping, MutableSequence, Optional, AsyncIterable, Awaitable, AsyncIterator, Sequence, Tuple, Type, Union - -from google.cloud.dialogflow_v2 import gapic_version as package_version - -from google.api_core.client_options import ClientOptions -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import retry as retries -from google.auth import credentials as ga_credentials # type: ignore -from google.oauth2 import service_account # type: ignore - -try: - OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] -except AttributeError: # pragma: NO COVER - OptionalRetry = Union[retries.Retry, object] # 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.cloud.location import locations_pb2 # type: ignore -from google.longrunning import operations_pb2 -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 - - -class ParticipantsAsyncClient: - """Service for managing - [Participants][google.cloud.dialogflow.v2.Participant]. - """ - - _client: ParticipantsClient - - DEFAULT_ENDPOINT = ParticipantsClient.DEFAULT_ENDPOINT - DEFAULT_MTLS_ENDPOINT = ParticipantsClient.DEFAULT_MTLS_ENDPOINT - - answer_record_path = staticmethod(ParticipantsClient.answer_record_path) - parse_answer_record_path = staticmethod(ParticipantsClient.parse_answer_record_path) - context_path = staticmethod(ParticipantsClient.context_path) - parse_context_path = staticmethod(ParticipantsClient.parse_context_path) - intent_path = staticmethod(ParticipantsClient.intent_path) - parse_intent_path = staticmethod(ParticipantsClient.parse_intent_path) - message_path = staticmethod(ParticipantsClient.message_path) - parse_message_path = staticmethod(ParticipantsClient.parse_message_path) - participant_path = staticmethod(ParticipantsClient.participant_path) - parse_participant_path = staticmethod(ParticipantsClient.parse_participant_path) - session_entity_type_path = staticmethod(ParticipantsClient.session_entity_type_path) - 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) - - @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: - ParticipantsAsyncClient: The constructed client. - """ - return ParticipantsClient.from_service_account_info.__func__(ParticipantsAsyncClient, 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: - ParticipantsAsyncClient: The constructed client. - """ - return ParticipantsClient.from_service_account_file.__func__(ParticipantsAsyncClient, filename, *args, **kwargs) # type: ignore - - from_service_account_json = from_service_account_file - - @classmethod - def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[ClientOptions] = None): - """Return the API endpoint and client cert source for mutual TLS. - - The client cert source is determined in the following order: - (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the - client cert source is None. - (2) if `client_options.client_cert_source` is provided, use the provided one; if the - default client cert source exists, use the default one; otherwise the client cert - source is None. - - The API endpoint is determined in the following order: - (1) if `client_options.api_endpoint` if provided, use the provided one. - (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the - default mTLS endpoint; if the environment variable is "never", use the default API - endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise - use the default API endpoint. - - More details can be found at https://google.aip.dev/auth/4114. - - Args: - client_options (google.api_core.client_options.ClientOptions): Custom options for the - client. Only the `api_endpoint` and `client_cert_source` properties may be used - in this method. - - Returns: - Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the - client cert source to use. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If any errors happen. - """ - return ParticipantsClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore - - @property - def transport(self) -> ParticipantsTransport: - """Returns the transport used by the client instance. - - Returns: - ParticipantsTransport: The transport used by the client instance. - """ - return self._client.transport - - get_transport_class = functools.partial(type(ParticipantsClient).get_transport_class, type(ParticipantsClient)) - - def __init__(self, *, - credentials: Optional[ga_credentials.Credentials] = None, - transport: Union[str, ParticipantsTransport] = "grpc_asyncio", - client_options: Optional[ClientOptions] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the participants 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, ~.ParticipantsTransport]): 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 = ParticipantsClient( - credentials=credentials, - transport=transport, - client_options=client_options, - client_info=client_info, - - ) - - async def create_participant(self, - request: Optional[Union[gcd_participant.CreateParticipantRequest, dict]] = None, - *, - parent: Optional[str] = None, - participant: Optional[gcd_participant.Participant] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gcd_participant.Participant: - r"""Creates a new participant in a conversation. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import dialogflow_v2 - - async def sample_create_participant(): - # Create a client - client = dialogflow_v2.ParticipantsAsyncClient() - - # Initialize request argument(s) - request = dialogflow_v2.CreateParticipantRequest( - parent="parent_value", - ) - - # Make the request - response = await client.create_participant(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.dialogflow_v2.types.CreateParticipantRequest, dict]]): - The request object. The request message for - [Participants.CreateParticipant][google.cloud.dialogflow.v2.Participants.CreateParticipant]. - parent (:class:`str`): - Required. Resource identifier of the conversation adding - the participant. Format: - ``projects//locations//conversations/``. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - participant (:class:`google.cloud.dialogflow_v2.types.Participant`): - Required. The participant to create. - 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. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.dialogflow_v2.types.Participant: - Represents a conversation participant - (human agent, virtual agent, end-user). - - """ - # Create or coerce a protobuf request object. - # Quick 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, participant]) - 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_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: - request.participant = participant - - # 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_participant, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def get_participant(self, - request: Optional[Union[participant.GetParticipantRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> participant.Participant: - r"""Retrieves a conversation participant. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import dialogflow_v2 - - async def sample_get_participant(): - # Create a client - client = dialogflow_v2.ParticipantsAsyncClient() - - # Initialize request argument(s) - request = dialogflow_v2.GetParticipantRequest( - name="name_value", - ) - - # Make the request - response = await client.get_participant(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.dialogflow_v2.types.GetParticipantRequest, dict]]): - The request object. The request message for - [Participants.GetParticipant][google.cloud.dialogflow.v2.Participants.GetParticipant]. - name (:class:`str`): - Required. The name of the participant. Format: - ``projects//locations//conversations//participants/``. - - 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.Participant: - Represents a conversation participant - (human agent, virtual agent, end-user). - - """ - # Create or coerce a protobuf request object. - # Quick 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 = participant.GetParticipantRequest(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_participant, - 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 list_participants(self, - request: Optional[Union[participant.ListParticipantsRequest, dict]] = None, - *, - parent: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListParticipantsAsyncPager: - r"""Returns the list of all participants in the specified - conversation. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import dialogflow_v2 - - async def sample_list_participants(): - # Create a client - client = dialogflow_v2.ParticipantsAsyncClient() - - # Initialize request argument(s) - request = dialogflow_v2.ListParticipantsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_participants(request=request) - - # Handle the response - async for response in page_result: - print(response) - - Args: - request (Optional[Union[google.cloud.dialogflow_v2.types.ListParticipantsRequest, dict]]): - The request object. The request message for - [Participants.ListParticipants][google.cloud.dialogflow.v2.Participants.ListParticipants]. - parent (:class:`str`): - Required. The conversation to list all participants - from. Format: - ``projects//locations//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. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.dialogflow_v2.services.participants.pagers.ListParticipantsAsyncPager: - The response message for - [Participants.ListParticipants][google.cloud.dialogflow.v2.Participants.ListParticipants]. - - Iterating over this object will yield results and - resolve additional pages automatically. - - """ - # Create or coerce a protobuf request object. - # Quick 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 = participant.ListParticipantsRequest(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_participants, - 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.ListParticipantsAsyncPager( - method=rpc, - request=request, - response=response, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def update_participant(self, - request: Optional[Union[gcd_participant.UpdateParticipantRequest, dict]] = None, - *, - participant: Optional[gcd_participant.Participant] = None, - update_mask: Optional[field_mask_pb2.FieldMask] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gcd_participant.Participant: - r"""Updates the specified participant. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import dialogflow_v2 - - async def sample_update_participant(): - # Create a client - client = dialogflow_v2.ParticipantsAsyncClient() - - # Initialize request argument(s) - request = dialogflow_v2.UpdateParticipantRequest( - ) - - # Make the request - response = await client.update_participant(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.dialogflow_v2.types.UpdateParticipantRequest, dict]]): - The request object. The request message for - [Participants.UpdateParticipant][google.cloud.dialogflow.v2.Participants.UpdateParticipant]. - participant (:class:`google.cloud.dialogflow_v2.types.Participant`): - Required. The participant to update. - This corresponds to the ``participant`` 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 specify which - fields to update. - - 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.Participant: - Represents a conversation participant - (human agent, virtual agent, end-user). - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([participant, 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_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: - 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_participant, - 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(( - ("participant.name", request.participant.name), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def analyze_content(self, - request: Optional[Union[gcd_participant.AnalyzeContentRequest, dict]] = None, - *, - participant: Optional[str] = None, - text_input: Optional[session.TextInput] = None, - event_input: Optional[session.EventInput] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gcd_participant.AnalyzeContentResponse: - r"""Adds a text (chat, for example), or audio (phone recording, for - example) message from a participant into the conversation. - - Note: Always use agent versions for production traffic sent to - virtual agents. See `Versions and - environments `__. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import dialogflow_v2 - - async def sample_analyze_content(): - # Create a client - client = dialogflow_v2.ParticipantsAsyncClient() - - # Initialize request argument(s) - text_input = dialogflow_v2.TextInput() - text_input.text = "text_value" - text_input.language_code = "language_code_value" - - request = dialogflow_v2.AnalyzeContentRequest( - text_input=text_input, - participant="participant_value", - ) - - # Make the request - response = await client.analyze_content(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.dialogflow_v2.types.AnalyzeContentRequest, dict]]): - The request object. The request message for - [Participants.AnalyzeContent][google.cloud.dialogflow.v2.Participants.AnalyzeContent]. - participant (:class:`str`): - Required. The name of the participant this text comes - from. Format: - ``projects//locations//conversations//participants/``. - - This corresponds to the ``participant`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - text_input (:class:`google.cloud.dialogflow_v2.types.TextInput`): - The natural language text to be - processed. - - This corresponds to the ``text_input`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - event_input (:class:`google.cloud.dialogflow_v2.types.EventInput`): - An input event to send to Dialogflow. - 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. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.dialogflow_v2.types.AnalyzeContentResponse: - The response message for - [Participants.AnalyzeContent][google.cloud.dialogflow.v2.Participants.AnalyzeContent]. - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([participant, text_input, event_input]) - 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_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: - request.text_input = text_input - if event_input is not None: - request.event_input = event_input - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.analyze_content, - default_retry=retries.Retry( -initial=0.1,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( - core_exceptions.ServiceUnavailable, - ), - deadline=220.0, - ), - default_timeout=220.0, - 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(( - ("participant", request.participant), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def streaming_analyze_content(self, - requests: Optional[AsyncIterator[participant.StreamingAnalyzeContentRequest]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> Awaitable[AsyncIterable[participant.StreamingAnalyzeContentResponse]]: - r"""Adds a text (chat, for example), or audio (phone recording, for - example) message from a participant into the conversation. Note: - This method is only available through the gRPC API (not REST). - - The top-level message sent to the client by the server is - ``StreamingAnalyzeContentResponse``. Multiple response messages - can be returned in order. The first one or more messages contain - the ``recognition_result`` field. Each result represents a more - complete transcript of what the user said. The next message - contains the ``reply_text`` field and potentially the - ``reply_audio`` field. The message can also contain the - ``automated_agent_reply`` field. - - Note: Always use agent versions for production traffic sent to - virtual agents. See `Versions and - environments `__. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import dialogflow_v2 - - async def sample_streaming_analyze_content(): - # Create a client - client = dialogflow_v2.ParticipantsAsyncClient() - - # Initialize request argument(s) - request = dialogflow_v2.StreamingAnalyzeContentRequest( - input_audio=b'input_audio_blob', - participant="participant_value", - ) - - # This method expects an iterator which contains - # 'dialogflow_v2.StreamingAnalyzeContentRequest' objects - # Here we create a generator that yields a single `request` for - # demonstrative purposes. - requests = [request] - - def request_generator(): - for request in requests: - yield request - - # Make the request - stream = await client.streaming_analyze_content(requests=request_generator()) - - # Handle the response - async for response in stream: - print(response) - - Args: - requests (AsyncIterator[`google.cloud.dialogflow_v2.types.StreamingAnalyzeContentRequest`]): - The request object AsyncIterator. The top-level message sent by the client to the - [Participants.StreamingAnalyzeContent][google.cloud.dialogflow.v2.Participants.StreamingAnalyzeContent] - method. - - Multiple request messages should be sent in order: - - 1. The first message must contain - [participant][google.cloud.dialogflow.v2.StreamingAnalyzeContentRequest.participant], - [config][google.cloud.dialogflow.v2.StreamingAnalyzeContentRequest.config] - and optionally - [query_params][google.cloud.dialogflow.v2.StreamingAnalyzeContentRequest.query_params]. - If you want to receive an audio response, it should - also contain - [reply_audio_config][google.cloud.dialogflow.v2.StreamingAnalyzeContentRequest.reply_audio_config]. - The message must not contain - [input][google.cloud.dialogflow.v2.StreamingAnalyzeContentRequest.input]. - - 2. If - [config][google.cloud.dialogflow.v2.StreamingAnalyzeContentRequest.config] - in the first message was set to - [audio_config][google.cloud.dialogflow.v2.StreamingAnalyzeContentRequest.audio_config], - all subsequent messages must contain - [input_audio][google.cloud.dialogflow.v2.StreamingAnalyzeContentRequest.input_audio] - to continue with Speech recognition. However, note - that: - - - Dialogflow will bill you for the audio so far. - - Dialogflow discards all Speech recognition results - in favor of the text input. - - 3. If - [StreamingAnalyzeContentRequest.config][google.cloud.dialogflow.v2.StreamingAnalyzeContentRequest.config] - in the first message was set to - [StreamingAnalyzeContentRequest.text_config][google.cloud.dialogflow.v2.StreamingAnalyzeContentRequest.text_config], - then the second message must contain only - [input_text][google.cloud.dialogflow.v2.StreamingAnalyzeContentRequest.input_text]. - Moreover, you must not send more than two messages. - - After you sent all input, you must half-close or abort - the request stream. - 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: - AsyncIterable[google.cloud.dialogflow_v2.types.StreamingAnalyzeContentResponse]: - The top-level message returned from the - StreamingAnalyzeContent method. - - Multiple response messages can be returned in order: - - 1. If the input was set to streaming audio, the first - one or more messages contain recognition_result. - Each recognition_result represents a more complete - transcript of what the user said. The last - recognition_result has is_final set to true. - 2. In virtual agent stage: if - enable_partial_automated_agent_reply is true, the - following N (currently 1 <= N <= 4) messages - contain automated_agent_reply and optionally - reply_audio returned by the virtual agent. The - first (N-1) automated_agent_replys will have - automated_agent_reply_type set to PARTIAL. The - last automated_agent_reply has - automated_agent_reply_type set to FINAL. If - enable_partial_automated_agent_reply is not - enabled, response stream only contains the final - reply. - - In human assist stage: the following N (N >= 1) - messages contain human_agent_suggestion_results, - end_user_suggestion_results or message. - - """ - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.streaming_analyze_content, - default_timeout=220.0, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Send the request. - response = rpc( - requests, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def suggest_articles(self, - request: Optional[Union[participant.SuggestArticlesRequest, dict]] = None, - *, - parent: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> participant.SuggestArticlesResponse: - r"""Gets suggested articles for a participant based on - specific historical messages. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import dialogflow_v2 - - async def sample_suggest_articles(): - # Create a client - client = dialogflow_v2.ParticipantsAsyncClient() - - # Initialize request argument(s) - request = dialogflow_v2.SuggestArticlesRequest( - parent="parent_value", - ) - - # Make the request - response = await client.suggest_articles(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.dialogflow_v2.types.SuggestArticlesRequest, dict]]): - The request object. The request message for - [Participants.SuggestArticles][google.cloud.dialogflow.v2.Participants.SuggestArticles]. - parent (:class:`str`): - Required. The name of the participant to fetch - suggestion for. Format: - ``projects//locations//conversations//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. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.dialogflow_v2.types.SuggestArticlesResponse: - The response message for - [Participants.SuggestArticles][google.cloud.dialogflow.v2.Participants.SuggestArticles]. - - """ - # Create or coerce a protobuf request object. - # Quick 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 = participant.SuggestArticlesRequest(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.suggest_articles, - 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 suggest_faq_answers(self, - request: Optional[Union[participant.SuggestFaqAnswersRequest, dict]] = None, - *, - parent: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> participant.SuggestFaqAnswersResponse: - r"""Gets suggested faq answers for a participant based on - specific historical messages. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import dialogflow_v2 - - async def sample_suggest_faq_answers(): - # Create a client - client = dialogflow_v2.ParticipantsAsyncClient() - - # Initialize request argument(s) - request = dialogflow_v2.SuggestFaqAnswersRequest( - parent="parent_value", - ) - - # Make the request - response = await client.suggest_faq_answers(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.dialogflow_v2.types.SuggestFaqAnswersRequest, dict]]): - The request object. The request message for - [Participants.SuggestFaqAnswers][google.cloud.dialogflow.v2.Participants.SuggestFaqAnswers]. - parent (:class:`str`): - Required. The name of the participant to fetch - suggestion for. Format: - ``projects//locations//conversations//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. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.dialogflow_v2.types.SuggestFaqAnswersResponse: - The request message for - [Participants.SuggestFaqAnswers][google.cloud.dialogflow.v2.Participants.SuggestFaqAnswers]. - - """ - # Create or coerce a protobuf request object. - # Quick 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 = participant.SuggestFaqAnswersRequest(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.suggest_faq_answers, - 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 suggest_smart_replies(self, - request: Optional[Union[participant.SuggestSmartRepliesRequest, dict]] = None, - *, - parent: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> participant.SuggestSmartRepliesResponse: - r"""Gets smart replies for a participant based on - specific historical messages. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import dialogflow_v2 - - async def sample_suggest_smart_replies(): - # Create a client - client = dialogflow_v2.ParticipantsAsyncClient() - - # Initialize request argument(s) - request = dialogflow_v2.SuggestSmartRepliesRequest( - parent="parent_value", - ) - - # Make the request - response = await client.suggest_smart_replies(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.dialogflow_v2.types.SuggestSmartRepliesRequest, dict]]): - The request object. The request message for - [Participants.SuggestSmartReplies][google.cloud.dialogflow.v2.Participants.SuggestSmartReplies]. - parent (:class:`str`): - Required. The name of the participant to fetch - suggestion for. Format: - ``projects//locations//conversations//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. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.dialogflow_v2.types.SuggestSmartRepliesResponse: - The response message for - [Participants.SuggestSmartReplies][google.cloud.dialogflow.v2.Participants.SuggestSmartReplies]. - - """ - # Create or coerce a protobuf request object. - # Quick 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 = participant.SuggestSmartRepliesRequest(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.suggest_smart_replies, - 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 list_operations( - self, - request: Optional[operations_pb2.ListOperationsRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operations_pb2.ListOperationsResponse: - r"""Lists operations that match the specified filter in the request. - - Args: - request (:class:`~.operations_pb2.ListOperationsRequest`): - The request object. Request message for - `ListOperations` method. - 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: - ~.operations_pb2.ListOperationsResponse: - Response message for ``ListOperations`` method. - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = operations_pb2.ListOperationsRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._client._transport.list_operations, - 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 get_operation( - self, - request: Optional[operations_pb2.GetOperationRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operations_pb2.Operation: - r"""Gets the latest state of a long-running operation. - - Args: - request (:class:`~.operations_pb2.GetOperationRequest`): - The request object. Request message for - `GetOperation` method. - 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: - ~.operations_pb2.Operation: - An ``Operation`` object. - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = operations_pb2.GetOperationRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._client._transport.get_operation, - 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 cancel_operation( - self, - request: Optional[operations_pb2.CancelOperationRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> None: - r"""Starts asynchronous cancellation on a long-running operation. - - The server makes a best effort to cancel the operation, but success - is not guaranteed. If the server doesn't support this method, it returns - `google.rpc.Code.UNIMPLEMENTED`. - - Args: - request (:class:`~.operations_pb2.CancelOperationRequest`): - The request object. Request message for - `CancelOperation` method. - 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: - None - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = operations_pb2.CancelOperationRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._client._transport.cancel_operation, - 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_location( - self, - request: Optional[locations_pb2.GetLocationRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> locations_pb2.Location: - r"""Gets information about a location. - - Args: - request (:class:`~.location_pb2.GetLocationRequest`): - The request object. Request message for - `GetLocation` method. - 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: - ~.location_pb2.Location: - Location object. - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = locations_pb2.GetLocationRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._client._transport.get_location, - 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 list_locations( - self, - request: Optional[locations_pb2.ListLocationsRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> locations_pb2.ListLocationsResponse: - r"""Lists information about the supported locations for this service. - - Args: - request (:class:`~.location_pb2.ListLocationsRequest`): - The request object. Request message for - `ListLocations` method. - 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: - ~.location_pb2.ListLocationsResponse: - Response message for ``ListLocations`` method. - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = locations_pb2.ListLocationsRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._client._transport.list_locations, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("name", request.name),)), - ) - - # Send the request. - response = await rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - async def __aenter__(self): - return self - - async def __aexit__(self, exc_type, exc, tb): - await self.transport.close() - -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) - - -__all__ = ( - "ParticipantsAsyncClient", -) diff --git a/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/participants/client.py b/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/participants/client.py deleted file mode 100644 index b4bda6937..000000000 --- a/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/participants/client.py +++ /dev/null @@ -1,1743 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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 os -import re -from typing import Dict, Mapping, MutableMapping, MutableSequence, Optional, Iterable, Iterator, Sequence, Tuple, Type, Union, cast - -from google.cloud.dialogflow_v2 import gapic_version as package_version - -from google.api_core import client_options as client_options_lib -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import retry as retries -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 - -try: - OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] -except AttributeError: # pragma: NO COVER - OptionalRetry = Union[retries.Retry, object] # 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.cloud.location import locations_pb2 # type: ignore -from google.longrunning import operations_pb2 -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 -from .transports.rest import ParticipantsRestTransport - - -class ParticipantsClientMeta(type): - """Metaclass for the Participants 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[ParticipantsTransport]] - _transport_registry["grpc"] = ParticipantsGrpcTransport - _transport_registry["grpc_asyncio"] = ParticipantsGrpcAsyncIOTransport - _transport_registry["rest"] = ParticipantsRestTransport - - def get_transport_class(cls, - label: Optional[str] = None, - ) -> Type[ParticipantsTransport]: - """Returns an appropriate transport class. - - Args: - label: The name of the desired transport. If none is - provided, then the first transport in the registry is used. - - Returns: - The transport class to use. - """ - # If a specific transport is requested, return that one. - if label: - return cls._transport_registry[label] - - # No transport is requested; return the default (that is, the first one - # in the dictionary). - return next(iter(cls._transport_registry.values())) - - -class ParticipantsClient(metaclass=ParticipantsClientMeta): - """Service for managing - [Participants][google.cloud.dialogflow.v2.Participant]. - """ - - @staticmethod - def _get_default_mtls_endpoint(api_endpoint): - """Converts api endpoint to mTLS endpoint. - - Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to - "*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively. - Args: - api_endpoint (Optional[str]): the api endpoint to convert. - Returns: - str: converted mTLS api endpoint. - """ - if not api_endpoint: - return api_endpoint - - mtls_endpoint_re = re.compile( - r"(?P[^.]+)(?P\.mtls)?(?P\.sandbox)?(?P\.googleapis\.com)?" - ) - - m = mtls_endpoint_re.match(api_endpoint) - name, mtls, sandbox, googledomain = m.groups() - if mtls or not googledomain: - return api_endpoint - - if sandbox: - return api_endpoint.replace( - "sandbox.googleapis.com", "mtls.sandbox.googleapis.com" - ) - - return api_endpoint.replace(".googleapis.com", ".mtls.googleapis.com") - - DEFAULT_ENDPOINT = "dialogflow.googleapis.com" - DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore - DEFAULT_ENDPOINT - ) - - @classmethod - def from_service_account_info(cls, info: dict, *args, **kwargs): - """Creates an instance of this client using the provided credentials - info. - - Args: - info (dict): The service account private key info. - args: Additional arguments to pass to the constructor. - kwargs: Additional arguments to pass to the constructor. - - Returns: - ParticipantsClient: 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: - ParticipantsClient: 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) -> ParticipantsTransport: - """Returns the transport used by the client instance. - - Returns: - ParticipantsTransport: The transport used by the client - instance. - """ - return self._transport - - @staticmethod - def answer_record_path(project: str,answer_record: str,) -> str: - """Returns a fully-qualified answer_record string.""" - return "projects/{project}/answerRecords/{answer_record}".format(project=project, answer_record=answer_record, ) - - @staticmethod - def parse_answer_record_path(path: str) -> Dict[str,str]: - """Parses a answer_record path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/answerRecords/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def context_path(project: str,session: str,context: str,) -> str: - """Returns a fully-qualified context string.""" - return "projects/{project}/agent/sessions/{session}/contexts/{context}".format(project=project, session=session, context=context, ) - - @staticmethod - def parse_context_path(path: str) -> Dict[str,str]: - """Parses a context path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/agent/sessions/(?P.+?)/contexts/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def intent_path(project: str,intent: str,) -> str: - """Returns a fully-qualified intent string.""" - return "projects/{project}/agent/intents/{intent}".format(project=project, intent=intent, ) - - @staticmethod - def parse_intent_path(path: str) -> Dict[str,str]: - """Parses a intent path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/agent/intents/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def message_path(project: str,conversation: str,message: str,) -> str: - """Returns a fully-qualified message string.""" - return "projects/{project}/conversations/{conversation}/messages/{message}".format(project=project, conversation=conversation, message=message, ) - - @staticmethod - def parse_message_path(path: str) -> Dict[str,str]: - """Parses a message path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/conversations/(?P.+?)/messages/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def participant_path(project: str,conversation: str,participant: str,) -> str: - """Returns a fully-qualified participant string.""" - return "projects/{project}/conversations/{conversation}/participants/{participant}".format(project=project, conversation=conversation, participant=participant, ) - - @staticmethod - def parse_participant_path(path: str) -> Dict[str,str]: - """Parses a participant path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/conversations/(?P.+?)/participants/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def session_entity_type_path(project: str,session: str,entity_type: str,) -> str: - """Returns a fully-qualified session_entity_type string.""" - return "projects/{project}/agent/sessions/{session}/entityTypes/{entity_type}".format(project=project, session=session, entity_type=entity_type, ) - - @staticmethod - def parse_session_entity_type_path(path: str) -> Dict[str,str]: - """Parses a session_entity_type path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/agent/sessions/(?P.+?)/entityTypes/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_billing_account_path(billing_account: str, ) -> str: - """Returns a fully-qualified billing_account string.""" - return "billingAccounts/{billing_account}".format(billing_account=billing_account, ) - - @staticmethod - def parse_common_billing_account_path(path: str) -> Dict[str,str]: - """Parse a billing_account path into its component segments.""" - m = re.match(r"^billingAccounts/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_folder_path(folder: str, ) -> str: - """Returns a fully-qualified folder string.""" - return "folders/{folder}".format(folder=folder, ) - - @staticmethod - def parse_common_folder_path(path: str) -> Dict[str,str]: - """Parse a folder path into its component segments.""" - m = re.match(r"^folders/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_organization_path(organization: str, ) -> str: - """Returns a fully-qualified organization string.""" - return "organizations/{organization}".format(organization=organization, ) - - @staticmethod - def parse_common_organization_path(path: str) -> Dict[str,str]: - """Parse a organization path into its component segments.""" - m = re.match(r"^organizations/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_project_path(project: str, ) -> str: - """Returns a fully-qualified project string.""" - return "projects/{project}".format(project=project, ) - - @staticmethod - def parse_common_project_path(path: str) -> Dict[str,str]: - """Parse a project path into its component segments.""" - m = re.match(r"^projects/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_location_path(project: str, location: str, ) -> str: - """Returns a fully-qualified location string.""" - return "projects/{project}/locations/{location}".format(project=project, location=location, ) - - @staticmethod - def parse_common_location_path(path: str) -> Dict[str,str]: - """Parse a location path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)$", path) - return m.groupdict() if m else {} - - @classmethod - def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[client_options_lib.ClientOptions] = None): - """Return the API endpoint and client cert source for mutual TLS. - - The client cert source is determined in the following order: - (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the - client cert source is None. - (2) if `client_options.client_cert_source` is provided, use the provided one; if the - default client cert source exists, use the default one; otherwise the client cert - source is None. - - The API endpoint is determined in the following order: - (1) if `client_options.api_endpoint` if provided, use the provided one. - (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the - default mTLS endpoint; if the environment variable is "never", use the default API - endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise - use the default API endpoint. - - More details can be found at https://google.aip.dev/auth/4114. - - Args: - client_options (google.api_core.client_options.ClientOptions): Custom options for the - client. Only the `api_endpoint` and `client_cert_source` properties may be used - in this method. - - Returns: - Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the - client cert source to use. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If any errors happen. - """ - if client_options is None: - client_options = client_options_lib.ClientOptions() - use_client_cert = os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false") - use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") - if use_client_cert not in ("true", "false"): - raise ValueError("Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`") - if use_mtls_endpoint not in ("auto", "never", "always"): - raise MutualTLSChannelError("Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`") - - # Figure out the client cert source to use. - client_cert_source = None - if use_client_cert == "true": - if client_options.client_cert_source: - client_cert_source = client_options.client_cert_source - elif mtls.has_default_client_cert_source(): - client_cert_source = mtls.default_client_cert_source() - - # Figure out which api endpoint to use. - if client_options.api_endpoint is not None: - api_endpoint = client_options.api_endpoint - elif use_mtls_endpoint == "always" or (use_mtls_endpoint == "auto" and client_cert_source): - api_endpoint = cls.DEFAULT_MTLS_ENDPOINT - else: - api_endpoint = cls.DEFAULT_ENDPOINT - - return api_endpoint, client_cert_source - - def __init__(self, *, - credentials: Optional[ga_credentials.Credentials] = None, - transport: Optional[Union[str, ParticipantsTransport]] = None, - client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the participants 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, ParticipantsTransport]): The - transport to use. If set to None, a transport is chosen - automatically. - client_options (Optional[Union[google.api_core.client_options.ClientOptions, dict]]): 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() - client_options = cast(client_options_lib.ClientOptions, client_options) - - api_endpoint, client_cert_source_func = self.get_mtls_endpoint_and_cert_source(client_options) - - api_key_value = getattr(client_options, "api_key", None) - if api_key_value and credentials: - raise ValueError("client_options.api_key and credentials are mutually exclusive") - - # 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, ParticipantsTransport): - # transport is a ParticipantsTransport instance. - if credentials or client_options.credentials_file or api_key_value: - 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: - import google.auth._default # type: ignore - - if api_key_value and hasattr(google.auth._default, "get_api_key_credentials"): - credentials = google.auth._default.get_api_key_credentials(api_key_value) - - Transport = type(self).get_transport_class(transport) - self._transport = Transport( - credentials=credentials, - credentials_file=client_options.credentials_file, - host=api_endpoint, - scopes=client_options.scopes, - client_cert_source_for_mtls=client_cert_source_func, - quota_project_id=client_options.quota_project_id, - client_info=client_info, - always_use_jwt_access=True, - api_audience=client_options.api_audience, - ) - - def create_participant(self, - request: Optional[Union[gcd_participant.CreateParticipantRequest, dict]] = None, - *, - parent: Optional[str] = None, - participant: Optional[gcd_participant.Participant] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gcd_participant.Participant: - r"""Creates a new participant in a conversation. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import dialogflow_v2 - - def sample_create_participant(): - # Create a client - client = dialogflow_v2.ParticipantsClient() - - # Initialize request argument(s) - request = dialogflow_v2.CreateParticipantRequest( - parent="parent_value", - ) - - # Make the request - response = client.create_participant(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.dialogflow_v2.types.CreateParticipantRequest, dict]): - The request object. The request message for - [Participants.CreateParticipant][google.cloud.dialogflow.v2.Participants.CreateParticipant]. - parent (str): - Required. Resource identifier of the conversation adding - the participant. Format: - ``projects//locations//conversations/``. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - participant (google.cloud.dialogflow_v2.types.Participant): - Required. The participant to create. - 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. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.dialogflow_v2.types.Participant: - Represents a conversation participant - (human agent, virtual agent, end-user). - - """ - # Create or coerce a protobuf request object. - # Quick 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, participant]) - 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_participant.CreateParticipantRequest. - # There's no risk of modifying the input as we've already verified - # 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: - request.participant = participant - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.create_participant] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def get_participant(self, - request: Optional[Union[participant.GetParticipantRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> participant.Participant: - r"""Retrieves a conversation participant. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import dialogflow_v2 - - def sample_get_participant(): - # Create a client - client = dialogflow_v2.ParticipantsClient() - - # Initialize request argument(s) - request = dialogflow_v2.GetParticipantRequest( - name="name_value", - ) - - # Make the request - response = client.get_participant(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.dialogflow_v2.types.GetParticipantRequest, dict]): - The request object. The request message for - [Participants.GetParticipant][google.cloud.dialogflow.v2.Participants.GetParticipant]. - name (str): - Required. The name of the participant. Format: - ``projects//locations//conversations//participants/``. - - 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.Participant: - Represents a conversation participant - (human agent, virtual agent, end-user). - - """ - # Create or coerce a protobuf request object. - # Quick 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 participant.GetParticipantRequest. - # There's no risk of modifying the input as we've already verified - # 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 - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.get_participant] - - # 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 list_participants(self, - request: Optional[Union[participant.ListParticipantsRequest, dict]] = None, - *, - parent: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListParticipantsPager: - r"""Returns the list of all participants in the specified - conversation. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import dialogflow_v2 - - def sample_list_participants(): - # Create a client - client = dialogflow_v2.ParticipantsClient() - - # Initialize request argument(s) - request = dialogflow_v2.ListParticipantsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_participants(request=request) - - # Handle the response - for response in page_result: - print(response) - - Args: - request (Union[google.cloud.dialogflow_v2.types.ListParticipantsRequest, dict]): - The request object. The request message for - [Participants.ListParticipants][google.cloud.dialogflow.v2.Participants.ListParticipants]. - parent (str): - Required. The conversation to list all participants - from. Format: - ``projects//locations//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. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.dialogflow_v2.services.participants.pagers.ListParticipantsPager: - The response message for - [Participants.ListParticipants][google.cloud.dialogflow.v2.Participants.ListParticipants]. - - Iterating over this object will yield results and - resolve additional pages automatically. - - """ - # Create or coerce a protobuf request object. - # Quick 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 participant.ListParticipantsRequest. - # There's no risk of modifying the input as we've already verified - # 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 - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.list_participants] - - # 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.ListParticipantsPager( - method=rpc, - request=request, - response=response, - metadata=metadata, - ) - - # Done; return the response. - return response - - def update_participant(self, - request: Optional[Union[gcd_participant.UpdateParticipantRequest, dict]] = None, - *, - participant: Optional[gcd_participant.Participant] = None, - update_mask: Optional[field_mask_pb2.FieldMask] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gcd_participant.Participant: - r"""Updates the specified participant. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import dialogflow_v2 - - def sample_update_participant(): - # Create a client - client = dialogflow_v2.ParticipantsClient() - - # Initialize request argument(s) - request = dialogflow_v2.UpdateParticipantRequest( - ) - - # Make the request - response = client.update_participant(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.dialogflow_v2.types.UpdateParticipantRequest, dict]): - The request object. The request message for - [Participants.UpdateParticipant][google.cloud.dialogflow.v2.Participants.UpdateParticipant]. - participant (google.cloud.dialogflow_v2.types.Participant): - Required. The participant to update. - This corresponds to the ``participant`` 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 specify which - fields to update. - - 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.Participant: - Represents a conversation participant - (human agent, virtual agent, end-user). - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([participant, 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_participant.UpdateParticipantRequest. - # There's no risk of modifying the input as we've already verified - # 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: - 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_participant] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("participant.name", request.participant.name), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def analyze_content(self, - request: Optional[Union[gcd_participant.AnalyzeContentRequest, dict]] = None, - *, - participant: Optional[str] = None, - text_input: Optional[session.TextInput] = None, - event_input: Optional[session.EventInput] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gcd_participant.AnalyzeContentResponse: - r"""Adds a text (chat, for example), or audio (phone recording, for - example) message from a participant into the conversation. - - Note: Always use agent versions for production traffic sent to - virtual agents. See `Versions and - environments `__. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import dialogflow_v2 - - def sample_analyze_content(): - # Create a client - client = dialogflow_v2.ParticipantsClient() - - # Initialize request argument(s) - text_input = dialogflow_v2.TextInput() - text_input.text = "text_value" - text_input.language_code = "language_code_value" - - request = dialogflow_v2.AnalyzeContentRequest( - text_input=text_input, - participant="participant_value", - ) - - # Make the request - response = client.analyze_content(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.dialogflow_v2.types.AnalyzeContentRequest, dict]): - The request object. The request message for - [Participants.AnalyzeContent][google.cloud.dialogflow.v2.Participants.AnalyzeContent]. - participant (str): - Required. The name of the participant this text comes - from. Format: - ``projects//locations//conversations//participants/``. - - This corresponds to the ``participant`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - text_input (google.cloud.dialogflow_v2.types.TextInput): - The natural language text to be - processed. - - This corresponds to the ``text_input`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - event_input (google.cloud.dialogflow_v2.types.EventInput): - An input event to send to Dialogflow. - 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. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.dialogflow_v2.types.AnalyzeContentResponse: - The response message for - [Participants.AnalyzeContent][google.cloud.dialogflow.v2.Participants.AnalyzeContent]. - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([participant, text_input, event_input]) - 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_participant.AnalyzeContentRequest. - # There's no risk of modifying the input as we've already verified - # 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: - request.text_input = text_input - if event_input is not None: - request.event_input = event_input - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.analyze_content] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("participant", request.participant), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def streaming_analyze_content(self, - requests: Optional[Iterator[participant.StreamingAnalyzeContentRequest]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> Iterable[participant.StreamingAnalyzeContentResponse]: - r"""Adds a text (chat, for example), or audio (phone recording, for - example) message from a participant into the conversation. Note: - This method is only available through the gRPC API (not REST). - - The top-level message sent to the client by the server is - ``StreamingAnalyzeContentResponse``. Multiple response messages - can be returned in order. The first one or more messages contain - the ``recognition_result`` field. Each result represents a more - complete transcript of what the user said. The next message - contains the ``reply_text`` field and potentially the - ``reply_audio`` field. The message can also contain the - ``automated_agent_reply`` field. - - Note: Always use agent versions for production traffic sent to - virtual agents. See `Versions and - environments `__. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import dialogflow_v2 - - def sample_streaming_analyze_content(): - # Create a client - client = dialogflow_v2.ParticipantsClient() - - # Initialize request argument(s) - request = dialogflow_v2.StreamingAnalyzeContentRequest( - input_audio=b'input_audio_blob', - participant="participant_value", - ) - - # This method expects an iterator which contains - # 'dialogflow_v2.StreamingAnalyzeContentRequest' objects - # Here we create a generator that yields a single `request` for - # demonstrative purposes. - requests = [request] - - def request_generator(): - for request in requests: - yield request - - # Make the request - stream = client.streaming_analyze_content(requests=request_generator()) - - # Handle the response - for response in stream: - print(response) - - Args: - requests (Iterator[google.cloud.dialogflow_v2.types.StreamingAnalyzeContentRequest]): - The request object iterator. The top-level message sent by the client to the - [Participants.StreamingAnalyzeContent][google.cloud.dialogflow.v2.Participants.StreamingAnalyzeContent] - method. - - Multiple request messages should be sent in order: - - 1. The first message must contain - [participant][google.cloud.dialogflow.v2.StreamingAnalyzeContentRequest.participant], - [config][google.cloud.dialogflow.v2.StreamingAnalyzeContentRequest.config] - and optionally - [query_params][google.cloud.dialogflow.v2.StreamingAnalyzeContentRequest.query_params]. - If you want to receive an audio response, it should - also contain - [reply_audio_config][google.cloud.dialogflow.v2.StreamingAnalyzeContentRequest.reply_audio_config]. - The message must not contain - [input][google.cloud.dialogflow.v2.StreamingAnalyzeContentRequest.input]. - - 2. If - [config][google.cloud.dialogflow.v2.StreamingAnalyzeContentRequest.config] - in the first message was set to - [audio_config][google.cloud.dialogflow.v2.StreamingAnalyzeContentRequest.audio_config], - all subsequent messages must contain - [input_audio][google.cloud.dialogflow.v2.StreamingAnalyzeContentRequest.input_audio] - to continue with Speech recognition. However, note - that: - - - Dialogflow will bill you for the audio so far. - - Dialogflow discards all Speech recognition results - in favor of the text input. - - 3. If - [StreamingAnalyzeContentRequest.config][google.cloud.dialogflow.v2.StreamingAnalyzeContentRequest.config] - in the first message was set to - [StreamingAnalyzeContentRequest.text_config][google.cloud.dialogflow.v2.StreamingAnalyzeContentRequest.text_config], - then the second message must contain only - [input_text][google.cloud.dialogflow.v2.StreamingAnalyzeContentRequest.input_text]. - Moreover, you must not send more than two messages. - - After you sent all input, you must half-close or abort - the request stream. - 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: - Iterable[google.cloud.dialogflow_v2.types.StreamingAnalyzeContentResponse]: - The top-level message returned from the - StreamingAnalyzeContent method. - - Multiple response messages can be returned in order: - - 1. If the input was set to streaming audio, the first - one or more messages contain recognition_result. - Each recognition_result represents a more complete - transcript of what the user said. The last - recognition_result has is_final set to true. - 2. In virtual agent stage: if - enable_partial_automated_agent_reply is true, the - following N (currently 1 <= N <= 4) messages - contain automated_agent_reply and optionally - reply_audio returned by the virtual agent. The - first (N-1) automated_agent_replys will have - automated_agent_reply_type set to PARTIAL. The - last automated_agent_reply has - automated_agent_reply_type set to FINAL. If - enable_partial_automated_agent_reply is not - enabled, response stream only contains the final - reply. - - In human assist stage: the following N (N >= 1) - messages contain human_agent_suggestion_results, - end_user_suggestion_results or message. - - """ - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.streaming_analyze_content] - - # Send the request. - response = rpc( - requests, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def suggest_articles(self, - request: Optional[Union[participant.SuggestArticlesRequest, dict]] = None, - *, - parent: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> participant.SuggestArticlesResponse: - r"""Gets suggested articles for a participant based on - specific historical messages. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import dialogflow_v2 - - def sample_suggest_articles(): - # Create a client - client = dialogflow_v2.ParticipantsClient() - - # Initialize request argument(s) - request = dialogflow_v2.SuggestArticlesRequest( - parent="parent_value", - ) - - # Make the request - response = client.suggest_articles(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.dialogflow_v2.types.SuggestArticlesRequest, dict]): - The request object. The request message for - [Participants.SuggestArticles][google.cloud.dialogflow.v2.Participants.SuggestArticles]. - parent (str): - Required. The name of the participant to fetch - suggestion for. Format: - ``projects//locations//conversations//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. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.dialogflow_v2.types.SuggestArticlesResponse: - The response message for - [Participants.SuggestArticles][google.cloud.dialogflow.v2.Participants.SuggestArticles]. - - """ - # Create or coerce a protobuf request object. - # Quick 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 participant.SuggestArticlesRequest. - # There's no risk of modifying the input as we've already verified - # 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 - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.suggest_articles] - - # 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 suggest_faq_answers(self, - request: Optional[Union[participant.SuggestFaqAnswersRequest, dict]] = None, - *, - parent: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> participant.SuggestFaqAnswersResponse: - r"""Gets suggested faq answers for a participant based on - specific historical messages. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import dialogflow_v2 - - def sample_suggest_faq_answers(): - # Create a client - client = dialogflow_v2.ParticipantsClient() - - # Initialize request argument(s) - request = dialogflow_v2.SuggestFaqAnswersRequest( - parent="parent_value", - ) - - # Make the request - response = client.suggest_faq_answers(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.dialogflow_v2.types.SuggestFaqAnswersRequest, dict]): - The request object. The request message for - [Participants.SuggestFaqAnswers][google.cloud.dialogflow.v2.Participants.SuggestFaqAnswers]. - parent (str): - Required. The name of the participant to fetch - suggestion for. Format: - ``projects//locations//conversations//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. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.dialogflow_v2.types.SuggestFaqAnswersResponse: - The request message for - [Participants.SuggestFaqAnswers][google.cloud.dialogflow.v2.Participants.SuggestFaqAnswers]. - - """ - # Create or coerce a protobuf request object. - # Quick 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 participant.SuggestFaqAnswersRequest. - # There's no risk of modifying the input as we've already verified - # 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 - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.suggest_faq_answers] - - # 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 suggest_smart_replies(self, - request: Optional[Union[participant.SuggestSmartRepliesRequest, dict]] = None, - *, - parent: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> participant.SuggestSmartRepliesResponse: - r"""Gets smart replies for a participant based on - specific historical messages. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import dialogflow_v2 - - def sample_suggest_smart_replies(): - # Create a client - client = dialogflow_v2.ParticipantsClient() - - # Initialize request argument(s) - request = dialogflow_v2.SuggestSmartRepliesRequest( - parent="parent_value", - ) - - # Make the request - response = client.suggest_smart_replies(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.dialogflow_v2.types.SuggestSmartRepliesRequest, dict]): - The request object. The request message for - [Participants.SuggestSmartReplies][google.cloud.dialogflow.v2.Participants.SuggestSmartReplies]. - parent (str): - Required. The name of the participant to fetch - suggestion for. Format: - ``projects//locations//conversations//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. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.dialogflow_v2.types.SuggestSmartRepliesResponse: - The response message for - [Participants.SuggestSmartReplies][google.cloud.dialogflow.v2.Participants.SuggestSmartReplies]. - - """ - # Create or coerce a protobuf request object. - # Quick 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 participant.SuggestSmartRepliesRequest. - # There's no risk of modifying the input as we've already verified - # 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 - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.suggest_smart_replies] - - # 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 __enter__(self) -> "ParticipantsClient": - return self - - def __exit__(self, type, value, traceback): - """Releases underlying transport's resources. - - .. warning:: - ONLY use as a context manager if the transport is NOT shared - with other clients! Exiting the with block will CLOSE the transport - and may cause errors in other clients! - """ - self.transport.close() - - def list_operations( - self, - request: Optional[operations_pb2.ListOperationsRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operations_pb2.ListOperationsResponse: - r"""Lists operations that match the specified filter in the request. - - Args: - request (:class:`~.operations_pb2.ListOperationsRequest`): - The request object. Request message for - `ListOperations` method. - 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: - ~.operations_pb2.ListOperationsResponse: - Response message for ``ListOperations`` method. - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = operations_pb2.ListOperationsRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._transport.list_operations, - 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 = rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - def get_operation( - self, - request: Optional[operations_pb2.GetOperationRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operations_pb2.Operation: - r"""Gets the latest state of a long-running operation. - - Args: - request (:class:`~.operations_pb2.GetOperationRequest`): - The request object. Request message for - `GetOperation` method. - 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: - ~.operations_pb2.Operation: - An ``Operation`` object. - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = operations_pb2.GetOperationRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._transport.get_operation, - 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 = rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - def cancel_operation( - self, - request: Optional[operations_pb2.CancelOperationRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> None: - r"""Starts asynchronous cancellation on a long-running operation. - - The server makes a best effort to cancel the operation, but success - is not guaranteed. If the server doesn't support this method, it returns - `google.rpc.Code.UNIMPLEMENTED`. - - Args: - request (:class:`~.operations_pb2.CancelOperationRequest`): - The request object. Request message for - `CancelOperation` method. - 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: - None - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = operations_pb2.CancelOperationRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._transport.cancel_operation, - 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. - rpc(request, retry=retry, timeout=timeout, metadata=metadata,) - - def get_location( - self, - request: Optional[locations_pb2.GetLocationRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> locations_pb2.Location: - r"""Gets information about a location. - - Args: - request (:class:`~.location_pb2.GetLocationRequest`): - The request object. Request message for - `GetLocation` method. - 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: - ~.location_pb2.Location: - Location object. - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = locations_pb2.GetLocationRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._transport.get_location, - 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 = rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - def list_locations( - self, - request: Optional[locations_pb2.ListLocationsRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> locations_pb2.ListLocationsResponse: - r"""Lists information about the supported locations for this service. - - Args: - request (:class:`~.location_pb2.ListLocationsRequest`): - The request object. Request message for - `ListLocations` method. - 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: - ~.location_pb2.ListLocationsResponse: - Response message for ``ListLocations`` method. - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = locations_pb2.ListLocationsRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._transport.list_locations, - 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 = rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) - - -__all__ = ( - "ParticipantsClient", -) diff --git a/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/participants/pagers.py b/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/participants/pagers.py deleted file mode 100644 index a0dc81a72..000000000 --- a/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/participants/pagers.py +++ /dev/null @@ -1,139 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from typing import Any, AsyncIterator, Awaitable, Callable, Sequence, Tuple, Optional, Iterator - -from google.cloud.dialogflow_v2.types import participant - - -class ListParticipantsPager: - """A pager for iterating through ``list_participants`` requests. - - This class thinly wraps an initial - :class:`google.cloud.dialogflow_v2.types.ListParticipantsResponse` object, and - provides an ``__iter__`` method to iterate through its - ``participants`` field. - - If there are more pages, the ``__iter__`` method will make additional - ``ListParticipants`` requests and continue to iterate - through the ``participants`` field on the - corresponding responses. - - All the usual :class:`google.cloud.dialogflow_v2.types.ListParticipantsResponse` - 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[..., participant.ListParticipantsResponse], - request: participant.ListParticipantsRequest, - response: participant.ListParticipantsResponse, - *, - 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.ListParticipantsRequest): - The initial request object. - response (google.cloud.dialogflow_v2.types.ListParticipantsResponse): - 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 = participant.ListParticipantsRequest(request) - self._response = response - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - def pages(self) -> Iterator[participant.ListParticipantsResponse]: - yield self._response - while self._response.next_page_token: - self._request.page_token = self._response.next_page_token - self._response = self._method(self._request, metadata=self._metadata) - yield self._response - - def __iter__(self) -> Iterator[participant.Participant]: - for page in self.pages: - yield from page.participants - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListParticipantsAsyncPager: - """A pager for iterating through ``list_participants`` requests. - - This class thinly wraps an initial - :class:`google.cloud.dialogflow_v2.types.ListParticipantsResponse` object, and - provides an ``__aiter__`` method to iterate through its - ``participants`` field. - - If there are more pages, the ``__aiter__`` method will make additional - ``ListParticipants`` requests and continue to iterate - through the ``participants`` field on the - corresponding responses. - - All the usual :class:`google.cloud.dialogflow_v2.types.ListParticipantsResponse` - 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[participant.ListParticipantsResponse]], - request: participant.ListParticipantsRequest, - response: participant.ListParticipantsResponse, - *, - metadata: Sequence[Tuple[str, str]] = ()): - """Instantiates the pager. - - Args: - method (Callable): The method that was originally called, and - which instantiated this pager. - request (google.cloud.dialogflow_v2.types.ListParticipantsRequest): - The initial request object. - response (google.cloud.dialogflow_v2.types.ListParticipantsResponse): - 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 = participant.ListParticipantsRequest(request) - self._response = response - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - async def pages(self) -> AsyncIterator[participant.ListParticipantsResponse]: - yield self._response - while self._response.next_page_token: - self._request.page_token = self._response.next_page_token - self._response = await self._method(self._request, metadata=self._metadata) - yield self._response - def __aiter__(self) -> AsyncIterator[participant.Participant]: - async def async_generator(): - async for page in self.pages: - for response in page.participants: - yield response - - return async_generator() - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) diff --git a/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/participants/transports/__init__.py b/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/participants/transports/__init__.py deleted file mode 100644 index 7fedc8d5d..000000000 --- a/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/participants/transports/__init__.py +++ /dev/null @@ -1,38 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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 ParticipantsTransport -from .grpc import ParticipantsGrpcTransport -from .grpc_asyncio import ParticipantsGrpcAsyncIOTransport -from .rest import ParticipantsRestTransport -from .rest import ParticipantsRestInterceptor - - -# Compile a registry of transports. -_transport_registry = OrderedDict() # type: Dict[str, Type[ParticipantsTransport]] -_transport_registry['grpc'] = ParticipantsGrpcTransport -_transport_registry['grpc_asyncio'] = ParticipantsGrpcAsyncIOTransport -_transport_registry['rest'] = ParticipantsRestTransport - -__all__ = ( - 'ParticipantsTransport', - 'ParticipantsGrpcTransport', - 'ParticipantsGrpcAsyncIOTransport', - 'ParticipantsRestTransport', - 'ParticipantsRestInterceptor', -) diff --git a/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/participants/transports/base.py b/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/participants/transports/base.py deleted file mode 100644 index 9a3110d03..000000000 --- a/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/participants/transports/base.py +++ /dev/null @@ -1,313 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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 - -from google.cloud.dialogflow_v2 import gapic_version as package_version - -import google.auth # type: ignore -import google.api_core -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import retry as retries -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 participant -from google.cloud.dialogflow_v2.types import participant as gcd_participant -from google.cloud.location import locations_pb2 # type: ignore -from google.longrunning import operations_pb2 - -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) - - -class ParticipantsTransport(abc.ABC): - """Abstract transport class for Participants.""" - - 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: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - api_audience: Optional[str] = None, - **kwargs, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. - scopes (Optional[Sequence[str]]): A list of scopes. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - """ - - scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} - - # Save the scopes. - self._scopes = scopes - - # If no credentials are provided, then determine the appropriate - # defaults. - if credentials and credentials_file: - raise core_exceptions.DuplicateCredentialArgs("'credentials_file' and 'credentials' are mutually exclusive") - - if credentials_file is not None: - credentials, _ = google.auth.load_credentials_from_file( - credentials_file, - **scopes_kwargs, - quota_project_id=quota_project_id - ) - elif credentials is None: - credentials, _ = google.auth.default(**scopes_kwargs, quota_project_id=quota_project_id) - # Don't apply audience if the credentials file passed from user. - if hasattr(credentials, "with_gdch_audience"): - credentials = credentials.with_gdch_audience(api_audience if api_audience else host) - - # If the credentials are service account credentials, then always try to use self signed JWT. - if always_use_jwt_access and isinstance(credentials, service_account.Credentials) and hasattr(service_account.Credentials, "with_always_use_jwt_access"): - credentials = credentials.with_always_use_jwt_access(True) - - # Save the credentials. - self._credentials = credentials - - # Save the hostname. Default to port 443 (HTTPS) if none is specified. - if ':' not in host: - host += ':443' - self._host = host - - def _prep_wrapped_messages(self, client_info): - # Precompute the wrapped methods. - self._wrapped_methods = { - self.create_participant: gapic_v1.method.wrap_method( - self.create_participant, - default_timeout=None, - client_info=client_info, - ), - self.get_participant: gapic_v1.method.wrap_method( - self.get_participant, - default_timeout=None, - client_info=client_info, - ), - self.list_participants: gapic_v1.method.wrap_method( - self.list_participants, - default_timeout=None, - client_info=client_info, - ), - self.update_participant: gapic_v1.method.wrap_method( - self.update_participant, - default_timeout=None, - client_info=client_info, - ), - self.analyze_content: gapic_v1.method.wrap_method( - self.analyze_content, - default_retry=retries.Retry( -initial=0.1,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( - core_exceptions.ServiceUnavailable, - ), - deadline=220.0, - ), - default_timeout=220.0, - client_info=client_info, - ), - self.streaming_analyze_content: gapic_v1.method.wrap_method( - self.streaming_analyze_content, - default_timeout=220.0, - client_info=client_info, - ), - self.suggest_articles: gapic_v1.method.wrap_method( - self.suggest_articles, - default_timeout=None, - client_info=client_info, - ), - self.suggest_faq_answers: gapic_v1.method.wrap_method( - self.suggest_faq_answers, - default_timeout=None, - client_info=client_info, - ), - self.suggest_smart_replies: gapic_v1.method.wrap_method( - self.suggest_smart_replies, - default_timeout=None, - client_info=client_info, - ), - } - - def close(self): - """Closes resources associated with the transport. - - .. warning:: - Only call this method if the transport is NOT shared - with other clients - this may cause errors in other clients! - """ - raise NotImplementedError() - - @property - def create_participant(self) -> Callable[ - [gcd_participant.CreateParticipantRequest], - Union[ - gcd_participant.Participant, - Awaitable[gcd_participant.Participant] - ]]: - raise NotImplementedError() - - @property - def get_participant(self) -> Callable[ - [participant.GetParticipantRequest], - Union[ - participant.Participant, - Awaitable[participant.Participant] - ]]: - raise NotImplementedError() - - @property - def list_participants(self) -> Callable[ - [participant.ListParticipantsRequest], - Union[ - participant.ListParticipantsResponse, - Awaitable[participant.ListParticipantsResponse] - ]]: - raise NotImplementedError() - - @property - def update_participant(self) -> Callable[ - [gcd_participant.UpdateParticipantRequest], - Union[ - gcd_participant.Participant, - Awaitable[gcd_participant.Participant] - ]]: - raise NotImplementedError() - - @property - def analyze_content(self) -> Callable[ - [gcd_participant.AnalyzeContentRequest], - Union[ - gcd_participant.AnalyzeContentResponse, - Awaitable[gcd_participant.AnalyzeContentResponse] - ]]: - raise NotImplementedError() - - @property - def streaming_analyze_content(self) -> Callable[ - [participant.StreamingAnalyzeContentRequest], - Union[ - participant.StreamingAnalyzeContentResponse, - Awaitable[participant.StreamingAnalyzeContentResponse] - ]]: - raise NotImplementedError() - - @property - def suggest_articles(self) -> Callable[ - [participant.SuggestArticlesRequest], - Union[ - participant.SuggestArticlesResponse, - Awaitable[participant.SuggestArticlesResponse] - ]]: - raise NotImplementedError() - - @property - def suggest_faq_answers(self) -> Callable[ - [participant.SuggestFaqAnswersRequest], - Union[ - participant.SuggestFaqAnswersResponse, - Awaitable[participant.SuggestFaqAnswersResponse] - ]]: - raise NotImplementedError() - - @property - def suggest_smart_replies(self) -> Callable[ - [participant.SuggestSmartRepliesRequest], - Union[ - participant.SuggestSmartRepliesResponse, - Awaitable[participant.SuggestSmartRepliesResponse] - ]]: - raise NotImplementedError() - - @property - def list_operations( - self, - ) -> Callable[ - [operations_pb2.ListOperationsRequest], - Union[operations_pb2.ListOperationsResponse, Awaitable[operations_pb2.ListOperationsResponse]], - ]: - raise NotImplementedError() - - @property - def get_operation( - self, - ) -> Callable[ - [operations_pb2.GetOperationRequest], - Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], - ]: - raise NotImplementedError() - - @property - def cancel_operation( - self, - ) -> Callable[ - [operations_pb2.CancelOperationRequest], - None, - ]: - raise NotImplementedError() - - @property - def get_location(self, - ) -> Callable[ - [locations_pb2.GetLocationRequest], - Union[locations_pb2.Location, Awaitable[locations_pb2.Location]], - ]: - raise NotImplementedError() - - @property - def list_locations(self, - ) -> Callable[ - [locations_pb2.ListLocationsRequest], - Union[locations_pb2.ListLocationsResponse, Awaitable[locations_pb2.ListLocationsResponse]], - ]: - raise NotImplementedError() - - @property - def kind(self) -> str: - raise NotImplementedError() - - -__all__ = ( - 'ParticipantsTransport', -) diff --git a/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/participants/transports/grpc.py b/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/participants/transports/grpc.py deleted file mode 100644 index 2e40dda54..000000000 --- a/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/participants/transports/grpc.py +++ /dev/null @@ -1,590 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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 -from google.api_core import gapic_v1 -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 google.cloud.location import locations_pb2 # type: ignore -from google.longrunning import operations_pb2 -from .base import ParticipantsTransport, DEFAULT_CLIENT_INFO - - -class ParticipantsGrpcTransport(ParticipantsTransport): - """gRPC backend transport for Participants. - - Service for managing - [Participants][google.cloud.dialogflow.v2.Participant]. - - 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: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - channel: Optional[grpc.Channel] = None, - api_mtls_endpoint: Optional[str] = None, - client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, - ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, - client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - api_audience: Optional[str] = None, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - This argument is ignored if ``channel`` is provided. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional(Sequence[str])): A list of scopes. This argument is - ignored if ``channel`` is provided. - channel (Optional[grpc.Channel]): A ``Channel`` instance through - which to make calls. - api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. - If provided, it overrides the ``host`` argument and tries to create - a mutual TLS channel with client SSL credentials from - ``client_cert_source`` or application default SSL credentials. - client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): - Deprecated. A callback to provide client SSL certificate bytes and - private key bytes, both in PEM format. It is ignored if - ``api_mtls_endpoint`` is None. - ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials - for the grpc channel. It is ignored if ``channel`` is provided. - client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): - A callback to provide client certificate bytes and private key bytes, - both in PEM format. It is used to configure a mutual TLS channel. It is - ignored if ``channel`` or ``ssl_channel_credentials`` is provided. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport - creation failed for any reason. - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - self._grpc_channel = None - self._ssl_channel_credentials = ssl_channel_credentials - self._stubs: Dict[str, Callable] = {} - - if api_mtls_endpoint: - warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) - if client_cert_source: - warnings.warn("client_cert_source is deprecated", DeprecationWarning) - - if channel: - # Ignore credentials if a channel was passed. - credentials = False - # If a channel was explicitly provided, set it. - self._grpc_channel = channel - self._ssl_channel_credentials = None - - else: - if api_mtls_endpoint: - host = api_mtls_endpoint - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - self._ssl_channel_credentials = SslCredentials().ssl_credentials - - else: - if client_cert_source_for_mtls and not ssl_channel_credentials: - cert, key = client_cert_source_for_mtls() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - - # The base transport sets the host, credentials and scopes - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes, - quota_project_id=quota_project_id, - client_info=client_info, - always_use_jwt_access=always_use_jwt_access, - api_audience=api_audience, - ) - - if not self._grpc_channel: - self._grpc_channel = type(self).create_channel( - self._host, - # use the credentials which are saved - credentials=self._credentials, - # Set ``credentials_file`` to ``None`` here as - # the credentials that we saved earlier should be used. - credentials_file=None, - 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: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - **kwargs) -> grpc.Channel: - """Create and return a gRPC channel object. - Args: - host (Optional[str]): The host for the channel to use. - credentials (Optional[~.Credentials]): The - authorization credentials to attach to requests. These - credentials identify this application to the service. If - none are specified, the client will attempt to ascertain - the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - kwargs (Optional[dict]): Keyword arguments, which are passed to the - channel creation. - Returns: - grpc.Channel: A gRPC channel object. - - Raises: - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - - return grpc_helpers.create_channel( - host, - credentials=credentials, - credentials_file=credentials_file, - quota_project_id=quota_project_id, - default_scopes=cls.AUTH_SCOPES, - scopes=scopes, - default_host=cls.DEFAULT_HOST, - **kwargs - ) - - @property - def grpc_channel(self) -> grpc.Channel: - """Return the channel designed to connect to this service. - """ - return self._grpc_channel - - @property - def create_participant(self) -> Callable[ - [gcd_participant.CreateParticipantRequest], - gcd_participant.Participant]: - r"""Return a callable for the create participant method over gRPC. - - Creates a new participant in a conversation. - - Returns: - Callable[[~.CreateParticipantRequest], - ~.Participant]: - 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_participant' not in self._stubs: - self._stubs['create_participant'] = self.grpc_channel.unary_unary( - '/google.cloud.dialogflow.v2.Participants/CreateParticipant', - request_serializer=gcd_participant.CreateParticipantRequest.serialize, - response_deserializer=gcd_participant.Participant.deserialize, - ) - return self._stubs['create_participant'] - - @property - def get_participant(self) -> Callable[ - [participant.GetParticipantRequest], - participant.Participant]: - r"""Return a callable for the get participant method over gRPC. - - Retrieves a conversation participant. - - Returns: - Callable[[~.GetParticipantRequest], - ~.Participant]: - 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_participant' not in self._stubs: - self._stubs['get_participant'] = self.grpc_channel.unary_unary( - '/google.cloud.dialogflow.v2.Participants/GetParticipant', - request_serializer=participant.GetParticipantRequest.serialize, - response_deserializer=participant.Participant.deserialize, - ) - return self._stubs['get_participant'] - - @property - def list_participants(self) -> Callable[ - [participant.ListParticipantsRequest], - participant.ListParticipantsResponse]: - r"""Return a callable for the list participants method over gRPC. - - Returns the list of all participants in the specified - conversation. - - Returns: - Callable[[~.ListParticipantsRequest], - ~.ListParticipantsResponse]: - 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_participants' not in self._stubs: - self._stubs['list_participants'] = self.grpc_channel.unary_unary( - '/google.cloud.dialogflow.v2.Participants/ListParticipants', - request_serializer=participant.ListParticipantsRequest.serialize, - response_deserializer=participant.ListParticipantsResponse.deserialize, - ) - return self._stubs['list_participants'] - - @property - def update_participant(self) -> Callable[ - [gcd_participant.UpdateParticipantRequest], - gcd_participant.Participant]: - r"""Return a callable for the update participant method over gRPC. - - Updates the specified participant. - - Returns: - Callable[[~.UpdateParticipantRequest], - ~.Participant]: - 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_participant' not in self._stubs: - self._stubs['update_participant'] = self.grpc_channel.unary_unary( - '/google.cloud.dialogflow.v2.Participants/UpdateParticipant', - request_serializer=gcd_participant.UpdateParticipantRequest.serialize, - response_deserializer=gcd_participant.Participant.deserialize, - ) - return self._stubs['update_participant'] - - @property - def analyze_content(self) -> Callable[ - [gcd_participant.AnalyzeContentRequest], - gcd_participant.AnalyzeContentResponse]: - r"""Return a callable for the analyze content method over gRPC. - - Adds a text (chat, for example), or audio (phone recording, for - example) message from a participant into the conversation. - - Note: Always use agent versions for production traffic sent to - virtual agents. See `Versions and - environments `__. - - Returns: - Callable[[~.AnalyzeContentRequest], - ~.AnalyzeContentResponse]: - 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 'analyze_content' not in self._stubs: - self._stubs['analyze_content'] = self.grpc_channel.unary_unary( - '/google.cloud.dialogflow.v2.Participants/AnalyzeContent', - request_serializer=gcd_participant.AnalyzeContentRequest.serialize, - response_deserializer=gcd_participant.AnalyzeContentResponse.deserialize, - ) - return self._stubs['analyze_content'] - - @property - def streaming_analyze_content(self) -> Callable[ - [participant.StreamingAnalyzeContentRequest], - participant.StreamingAnalyzeContentResponse]: - r"""Return a callable for the streaming analyze content method over gRPC. - - Adds a text (chat, for example), or audio (phone recording, for - example) message from a participant into the conversation. Note: - This method is only available through the gRPC API (not REST). - - The top-level message sent to the client by the server is - ``StreamingAnalyzeContentResponse``. Multiple response messages - can be returned in order. The first one or more messages contain - the ``recognition_result`` field. Each result represents a more - complete transcript of what the user said. The next message - contains the ``reply_text`` field and potentially the - ``reply_audio`` field. The message can also contain the - ``automated_agent_reply`` field. - - Note: Always use agent versions for production traffic sent to - virtual agents. See `Versions and - environments `__. - - Returns: - Callable[[~.StreamingAnalyzeContentRequest], - ~.StreamingAnalyzeContentResponse]: - 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 'streaming_analyze_content' not in self._stubs: - self._stubs['streaming_analyze_content'] = self.grpc_channel.stream_stream( - '/google.cloud.dialogflow.v2.Participants/StreamingAnalyzeContent', - request_serializer=participant.StreamingAnalyzeContentRequest.serialize, - response_deserializer=participant.StreamingAnalyzeContentResponse.deserialize, - ) - return self._stubs['streaming_analyze_content'] - - @property - def suggest_articles(self) -> Callable[ - [participant.SuggestArticlesRequest], - participant.SuggestArticlesResponse]: - r"""Return a callable for the suggest articles method over gRPC. - - Gets suggested articles for a participant based on - specific historical messages. - - Returns: - Callable[[~.SuggestArticlesRequest], - ~.SuggestArticlesResponse]: - 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 'suggest_articles' not in self._stubs: - self._stubs['suggest_articles'] = self.grpc_channel.unary_unary( - '/google.cloud.dialogflow.v2.Participants/SuggestArticles', - request_serializer=participant.SuggestArticlesRequest.serialize, - response_deserializer=participant.SuggestArticlesResponse.deserialize, - ) - return self._stubs['suggest_articles'] - - @property - def suggest_faq_answers(self) -> Callable[ - [participant.SuggestFaqAnswersRequest], - participant.SuggestFaqAnswersResponse]: - r"""Return a callable for the suggest faq answers method over gRPC. - - Gets suggested faq answers for a participant based on - specific historical messages. - - Returns: - Callable[[~.SuggestFaqAnswersRequest], - ~.SuggestFaqAnswersResponse]: - 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 'suggest_faq_answers' not in self._stubs: - self._stubs['suggest_faq_answers'] = self.grpc_channel.unary_unary( - '/google.cloud.dialogflow.v2.Participants/SuggestFaqAnswers', - request_serializer=participant.SuggestFaqAnswersRequest.serialize, - response_deserializer=participant.SuggestFaqAnswersResponse.deserialize, - ) - return self._stubs['suggest_faq_answers'] - - @property - def suggest_smart_replies(self) -> Callable[ - [participant.SuggestSmartRepliesRequest], - participant.SuggestSmartRepliesResponse]: - r"""Return a callable for the suggest smart replies method over gRPC. - - Gets smart replies for a participant based on - specific historical messages. - - Returns: - Callable[[~.SuggestSmartRepliesRequest], - ~.SuggestSmartRepliesResponse]: - 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 'suggest_smart_replies' not in self._stubs: - self._stubs['suggest_smart_replies'] = self.grpc_channel.unary_unary( - '/google.cloud.dialogflow.v2.Participants/SuggestSmartReplies', - request_serializer=participant.SuggestSmartRepliesRequest.serialize, - response_deserializer=participant.SuggestSmartRepliesResponse.deserialize, - ) - return self._stubs['suggest_smart_replies'] - - def close(self): - self.grpc_channel.close() - - @property - def cancel_operation( - self, - ) -> Callable[[operations_pb2.CancelOperationRequest], None]: - r"""Return a callable for the cancel_operation method over gRPC. - """ - # 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 "cancel_operation" not in self._stubs: - self._stubs["cancel_operation"] = self.grpc_channel.unary_unary( - "/google.longrunning.Operations/CancelOperation", - request_serializer=operations_pb2.CancelOperationRequest.SerializeToString, - response_deserializer=None, - ) - return self._stubs["cancel_operation"] - - @property - def get_operation( - self, - ) -> Callable[[operations_pb2.GetOperationRequest], operations_pb2.Operation]: - r"""Return a callable for the get_operation method over gRPC. - """ - # 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_operation" not in self._stubs: - self._stubs["get_operation"] = self.grpc_channel.unary_unary( - "/google.longrunning.Operations/GetOperation", - request_serializer=operations_pb2.GetOperationRequest.SerializeToString, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs["get_operation"] - - @property - def list_operations( - self, - ) -> Callable[[operations_pb2.ListOperationsRequest], operations_pb2.ListOperationsResponse]: - r"""Return a callable for the list_operations method over gRPC. - """ - # 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_operations" not in self._stubs: - self._stubs["list_operations"] = self.grpc_channel.unary_unary( - "/google.longrunning.Operations/ListOperations", - request_serializer=operations_pb2.ListOperationsRequest.SerializeToString, - response_deserializer=operations_pb2.ListOperationsResponse.FromString, - ) - return self._stubs["list_operations"] - - @property - def list_locations( - self, - ) -> Callable[[locations_pb2.ListLocationsRequest], locations_pb2.ListLocationsResponse]: - r"""Return a callable for the list locations method over gRPC. - """ - # 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_locations" not in self._stubs: - self._stubs["list_locations"] = self.grpc_channel.unary_unary( - "/google.cloud.location.Locations/ListLocations", - request_serializer=locations_pb2.ListLocationsRequest.SerializeToString, - response_deserializer=locations_pb2.ListLocationsResponse.FromString, - ) - return self._stubs["list_locations"] - - @property - def get_location( - self, - ) -> Callable[[locations_pb2.GetLocationRequest], locations_pb2.Location]: - r"""Return a callable for the list locations method over gRPC. - """ - # 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_location" not in self._stubs: - self._stubs["get_location"] = self.grpc_channel.unary_unary( - "/google.cloud.location.Locations/GetLocation", - request_serializer=locations_pb2.GetLocationRequest.SerializeToString, - response_deserializer=locations_pb2.Location.FromString, - ) - return self._stubs["get_location"] - - @property - def kind(self) -> str: - return "grpc" - - -__all__ = ( - 'ParticipantsGrpcTransport', -) diff --git a/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/participants/transports/grpc_asyncio.py b/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/participants/transports/grpc_asyncio.py deleted file mode 100644 index 7dab30886..000000000 --- a/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/participants/transports/grpc_asyncio.py +++ /dev/null @@ -1,589 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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 -from google.api_core import grpc_helpers_async -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore - -import grpc # type: ignore -from grpc.experimental import aio # type: ignore - -from google.cloud.dialogflow_v2.types import participant -from google.cloud.dialogflow_v2.types import participant as gcd_participant -from google.cloud.location import locations_pb2 # type: ignore -from google.longrunning import operations_pb2 -from .base import ParticipantsTransport, DEFAULT_CLIENT_INFO -from .grpc import ParticipantsGrpcTransport - - -class ParticipantsGrpcAsyncIOTransport(ParticipantsTransport): - """gRPC AsyncIO backend transport for Participants. - - Service for managing - [Participants][google.cloud.dialogflow.v2.Participant]. - - 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: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - **kwargs) -> aio.Channel: - """Create and return a gRPC AsyncIO channel object. - Args: - host (Optional[str]): The host for the channel to use. - credentials (Optional[~.Credentials]): The - authorization credentials to attach to requests. These - credentials identify this application to the service. If - none are specified, the client will attempt to ascertain - the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - kwargs (Optional[dict]): Keyword arguments, which are passed to the - channel creation. - Returns: - aio.Channel: A gRPC AsyncIO channel object. - """ - - return grpc_helpers_async.create_channel( - host, - credentials=credentials, - credentials_file=credentials_file, - quota_project_id=quota_project_id, - default_scopes=cls.AUTH_SCOPES, - scopes=scopes, - default_host=cls.DEFAULT_HOST, - **kwargs - ) - - def __init__(self, *, - host: str = 'dialogflow.googleapis.com', - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - channel: Optional[aio.Channel] = None, - api_mtls_endpoint: Optional[str] = None, - client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, - ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, - client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - api_audience: Optional[str] = None, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - This argument is ignored if ``channel`` is provided. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - channel (Optional[aio.Channel]): A ``Channel`` instance through - which to make calls. - api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. - If provided, it overrides the ``host`` argument and tries to create - a mutual TLS channel with client SSL credentials from - ``client_cert_source`` or application default SSL credentials. - client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): - Deprecated. A callback to provide client SSL certificate bytes and - private key bytes, both in PEM format. It is ignored if - ``api_mtls_endpoint`` is None. - ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials - for the grpc channel. It is ignored if ``channel`` is provided. - client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): - A callback to provide client certificate bytes and private key bytes, - both in PEM format. It is used to configure a mutual TLS channel. It is - ignored if ``channel`` or ``ssl_channel_credentials`` is provided. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - - Raises: - google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport - creation failed for any reason. - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - self._grpc_channel = None - self._ssl_channel_credentials = ssl_channel_credentials - self._stubs: Dict[str, Callable] = {} - - if api_mtls_endpoint: - warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) - if client_cert_source: - warnings.warn("client_cert_source is deprecated", DeprecationWarning) - - if channel: - # Ignore credentials if a channel was passed. - credentials = False - # If a channel was explicitly provided, set it. - self._grpc_channel = channel - self._ssl_channel_credentials = None - else: - if api_mtls_endpoint: - host = api_mtls_endpoint - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - self._ssl_channel_credentials = SslCredentials().ssl_credentials - - else: - if client_cert_source_for_mtls and not ssl_channel_credentials: - cert, key = client_cert_source_for_mtls() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - - # The base transport sets the host, credentials and scopes - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes, - quota_project_id=quota_project_id, - client_info=client_info, - always_use_jwt_access=always_use_jwt_access, - api_audience=api_audience, - ) - - if not self._grpc_channel: - self._grpc_channel = type(self).create_channel( - self._host, - # use the credentials which are saved - credentials=self._credentials, - # Set ``credentials_file`` to ``None`` here as - # the credentials that we saved earlier should be used. - credentials_file=None, - 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 create_participant(self) -> Callable[ - [gcd_participant.CreateParticipantRequest], - Awaitable[gcd_participant.Participant]]: - r"""Return a callable for the create participant method over gRPC. - - Creates a new participant in a conversation. - - Returns: - Callable[[~.CreateParticipantRequest], - Awaitable[~.Participant]]: - 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_participant' not in self._stubs: - self._stubs['create_participant'] = self.grpc_channel.unary_unary( - '/google.cloud.dialogflow.v2.Participants/CreateParticipant', - request_serializer=gcd_participant.CreateParticipantRequest.serialize, - response_deserializer=gcd_participant.Participant.deserialize, - ) - return self._stubs['create_participant'] - - @property - def get_participant(self) -> Callable[ - [participant.GetParticipantRequest], - Awaitable[participant.Participant]]: - r"""Return a callable for the get participant method over gRPC. - - Retrieves a conversation participant. - - Returns: - Callable[[~.GetParticipantRequest], - Awaitable[~.Participant]]: - 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_participant' not in self._stubs: - self._stubs['get_participant'] = self.grpc_channel.unary_unary( - '/google.cloud.dialogflow.v2.Participants/GetParticipant', - request_serializer=participant.GetParticipantRequest.serialize, - response_deserializer=participant.Participant.deserialize, - ) - return self._stubs['get_participant'] - - @property - def list_participants(self) -> Callable[ - [participant.ListParticipantsRequest], - Awaitable[participant.ListParticipantsResponse]]: - r"""Return a callable for the list participants method over gRPC. - - Returns the list of all participants in the specified - conversation. - - Returns: - Callable[[~.ListParticipantsRequest], - Awaitable[~.ListParticipantsResponse]]: - 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_participants' not in self._stubs: - self._stubs['list_participants'] = self.grpc_channel.unary_unary( - '/google.cloud.dialogflow.v2.Participants/ListParticipants', - request_serializer=participant.ListParticipantsRequest.serialize, - response_deserializer=participant.ListParticipantsResponse.deserialize, - ) - return self._stubs['list_participants'] - - @property - def update_participant(self) -> Callable[ - [gcd_participant.UpdateParticipantRequest], - Awaitable[gcd_participant.Participant]]: - r"""Return a callable for the update participant method over gRPC. - - Updates the specified participant. - - Returns: - Callable[[~.UpdateParticipantRequest], - Awaitable[~.Participant]]: - 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_participant' not in self._stubs: - self._stubs['update_participant'] = self.grpc_channel.unary_unary( - '/google.cloud.dialogflow.v2.Participants/UpdateParticipant', - request_serializer=gcd_participant.UpdateParticipantRequest.serialize, - response_deserializer=gcd_participant.Participant.deserialize, - ) - return self._stubs['update_participant'] - - @property - def analyze_content(self) -> Callable[ - [gcd_participant.AnalyzeContentRequest], - Awaitable[gcd_participant.AnalyzeContentResponse]]: - r"""Return a callable for the analyze content method over gRPC. - - Adds a text (chat, for example), or audio (phone recording, for - example) message from a participant into the conversation. - - Note: Always use agent versions for production traffic sent to - virtual agents. See `Versions and - environments `__. - - Returns: - Callable[[~.AnalyzeContentRequest], - Awaitable[~.AnalyzeContentResponse]]: - 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 'analyze_content' not in self._stubs: - self._stubs['analyze_content'] = self.grpc_channel.unary_unary( - '/google.cloud.dialogflow.v2.Participants/AnalyzeContent', - request_serializer=gcd_participant.AnalyzeContentRequest.serialize, - response_deserializer=gcd_participant.AnalyzeContentResponse.deserialize, - ) - return self._stubs['analyze_content'] - - @property - def streaming_analyze_content(self) -> Callable[ - [participant.StreamingAnalyzeContentRequest], - Awaitable[participant.StreamingAnalyzeContentResponse]]: - r"""Return a callable for the streaming analyze content method over gRPC. - - Adds a text (chat, for example), or audio (phone recording, for - example) message from a participant into the conversation. Note: - This method is only available through the gRPC API (not REST). - - The top-level message sent to the client by the server is - ``StreamingAnalyzeContentResponse``. Multiple response messages - can be returned in order. The first one or more messages contain - the ``recognition_result`` field. Each result represents a more - complete transcript of what the user said. The next message - contains the ``reply_text`` field and potentially the - ``reply_audio`` field. The message can also contain the - ``automated_agent_reply`` field. - - Note: Always use agent versions for production traffic sent to - virtual agents. See `Versions and - environments `__. - - Returns: - Callable[[~.StreamingAnalyzeContentRequest], - Awaitable[~.StreamingAnalyzeContentResponse]]: - 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 'streaming_analyze_content' not in self._stubs: - self._stubs['streaming_analyze_content'] = self.grpc_channel.stream_stream( - '/google.cloud.dialogflow.v2.Participants/StreamingAnalyzeContent', - request_serializer=participant.StreamingAnalyzeContentRequest.serialize, - response_deserializer=participant.StreamingAnalyzeContentResponse.deserialize, - ) - return self._stubs['streaming_analyze_content'] - - @property - def suggest_articles(self) -> Callable[ - [participant.SuggestArticlesRequest], - Awaitable[participant.SuggestArticlesResponse]]: - r"""Return a callable for the suggest articles method over gRPC. - - Gets suggested articles for a participant based on - specific historical messages. - - Returns: - Callable[[~.SuggestArticlesRequest], - Awaitable[~.SuggestArticlesResponse]]: - 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 'suggest_articles' not in self._stubs: - self._stubs['suggest_articles'] = self.grpc_channel.unary_unary( - '/google.cloud.dialogflow.v2.Participants/SuggestArticles', - request_serializer=participant.SuggestArticlesRequest.serialize, - response_deserializer=participant.SuggestArticlesResponse.deserialize, - ) - return self._stubs['suggest_articles'] - - @property - def suggest_faq_answers(self) -> Callable[ - [participant.SuggestFaqAnswersRequest], - Awaitable[participant.SuggestFaqAnswersResponse]]: - r"""Return a callable for the suggest faq answers method over gRPC. - - Gets suggested faq answers for a participant based on - specific historical messages. - - Returns: - Callable[[~.SuggestFaqAnswersRequest], - Awaitable[~.SuggestFaqAnswersResponse]]: - 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 'suggest_faq_answers' not in self._stubs: - self._stubs['suggest_faq_answers'] = self.grpc_channel.unary_unary( - '/google.cloud.dialogflow.v2.Participants/SuggestFaqAnswers', - request_serializer=participant.SuggestFaqAnswersRequest.serialize, - response_deserializer=participant.SuggestFaqAnswersResponse.deserialize, - ) - return self._stubs['suggest_faq_answers'] - - @property - def suggest_smart_replies(self) -> Callable[ - [participant.SuggestSmartRepliesRequest], - Awaitable[participant.SuggestSmartRepliesResponse]]: - r"""Return a callable for the suggest smart replies method over gRPC. - - Gets smart replies for a participant based on - specific historical messages. - - Returns: - Callable[[~.SuggestSmartRepliesRequest], - Awaitable[~.SuggestSmartRepliesResponse]]: - 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 'suggest_smart_replies' not in self._stubs: - self._stubs['suggest_smart_replies'] = self.grpc_channel.unary_unary( - '/google.cloud.dialogflow.v2.Participants/SuggestSmartReplies', - request_serializer=participant.SuggestSmartRepliesRequest.serialize, - response_deserializer=participant.SuggestSmartRepliesResponse.deserialize, - ) - return self._stubs['suggest_smart_replies'] - - def close(self): - return self.grpc_channel.close() - - @property - def cancel_operation( - self, - ) -> Callable[[operations_pb2.CancelOperationRequest], None]: - r"""Return a callable for the cancel_operation method over gRPC. - """ - # 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 "cancel_operation" not in self._stubs: - self._stubs["cancel_operation"] = self.grpc_channel.unary_unary( - "/google.longrunning.Operations/CancelOperation", - request_serializer=operations_pb2.CancelOperationRequest.SerializeToString, - response_deserializer=None, - ) - return self._stubs["cancel_operation"] - - @property - def get_operation( - self, - ) -> Callable[[operations_pb2.GetOperationRequest], operations_pb2.Operation]: - r"""Return a callable for the get_operation method over gRPC. - """ - # 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_operation" not in self._stubs: - self._stubs["get_operation"] = self.grpc_channel.unary_unary( - "/google.longrunning.Operations/GetOperation", - request_serializer=operations_pb2.GetOperationRequest.SerializeToString, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs["get_operation"] - - @property - def list_operations( - self, - ) -> Callable[[operations_pb2.ListOperationsRequest], operations_pb2.ListOperationsResponse]: - r"""Return a callable for the list_operations method over gRPC. - """ - # 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_operations" not in self._stubs: - self._stubs["list_operations"] = self.grpc_channel.unary_unary( - "/google.longrunning.Operations/ListOperations", - request_serializer=operations_pb2.ListOperationsRequest.SerializeToString, - response_deserializer=operations_pb2.ListOperationsResponse.FromString, - ) - return self._stubs["list_operations"] - - @property - def list_locations( - self, - ) -> Callable[[locations_pb2.ListLocationsRequest], locations_pb2.ListLocationsResponse]: - r"""Return a callable for the list locations method over gRPC. - """ - # 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_locations" not in self._stubs: - self._stubs["list_locations"] = self.grpc_channel.unary_unary( - "/google.cloud.location.Locations/ListLocations", - request_serializer=locations_pb2.ListLocationsRequest.SerializeToString, - response_deserializer=locations_pb2.ListLocationsResponse.FromString, - ) - return self._stubs["list_locations"] - - @property - def get_location( - self, - ) -> Callable[[locations_pb2.GetLocationRequest], locations_pb2.Location]: - r"""Return a callable for the list locations method over gRPC. - """ - # 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_location" not in self._stubs: - self._stubs["get_location"] = self.grpc_channel.unary_unary( - "/google.cloud.location.Locations/GetLocation", - request_serializer=locations_pb2.GetLocationRequest.SerializeToString, - response_deserializer=locations_pb2.Location.FromString, - ) - return self._stubs["get_location"] - - -__all__ = ( - 'ParticipantsGrpcAsyncIOTransport', -) diff --git a/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/participants/transports/rest.py b/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/participants/transports/rest.py deleted file mode 100644 index bbf9a9f8e..000000000 --- a/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/participants/transports/rest.py +++ /dev/null @@ -1,1631 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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 google.auth.transport.requests import AuthorizedSession # type: ignore -import json # type: ignore -import grpc # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore -from google.auth import credentials as ga_credentials # type: ignore -from google.api_core import exceptions as core_exceptions -from google.api_core import retry as retries -from google.api_core import rest_helpers -from google.api_core import rest_streaming -from google.api_core import path_template -from google.api_core import gapic_v1 - -from google.protobuf import json_format -from google.cloud.location import locations_pb2 # type: ignore -from google.longrunning import operations_pb2 -from requests import __version__ as requests_version -import dataclasses -import re -from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union -import warnings - -try: - OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] -except AttributeError: # pragma: NO COVER - OptionalRetry = Union[retries.Retry, object] # 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 as BASE_DEFAULT_CLIENT_INFO - - -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=BASE_DEFAULT_CLIENT_INFO.gapic_version, - grpc_version=None, - rest_version=requests_version, -) - - -class ParticipantsRestInterceptor: - """Interceptor for Participants. - - Interceptors are used to manipulate requests, request metadata, and responses - in arbitrary ways. - Example use cases include: - * Logging - * Verifying requests according to service or custom semantics - * Stripping extraneous information from responses - - These use cases and more can be enabled by injecting an - instance of a custom subclass when constructing the ParticipantsRestTransport. - - .. code-block:: python - class MyCustomParticipantsInterceptor(ParticipantsRestInterceptor): - def pre_analyze_content(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_analyze_content(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_create_participant(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_create_participant(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_get_participant(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_get_participant(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_list_participants(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_list_participants(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_suggest_articles(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_suggest_articles(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_suggest_faq_answers(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_suggest_faq_answers(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_suggest_smart_replies(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_suggest_smart_replies(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_update_participant(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_update_participant(self, response): - logging.log(f"Received response: {response}") - return response - - transport = ParticipantsRestTransport(interceptor=MyCustomParticipantsInterceptor()) - client = ParticipantsClient(transport=transport) - - - """ - def pre_analyze_content(self, request: gcd_participant.AnalyzeContentRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[gcd_participant.AnalyzeContentRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for analyze_content - - Override in a subclass to manipulate the request or metadata - before they are sent to the Participants server. - """ - return request, metadata - - def post_analyze_content(self, response: gcd_participant.AnalyzeContentResponse) -> gcd_participant.AnalyzeContentResponse: - """Post-rpc interceptor for analyze_content - - Override in a subclass to manipulate the response - after it is returned by the Participants server but before - it is returned to user code. - """ - return response - def pre_create_participant(self, request: gcd_participant.CreateParticipantRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[gcd_participant.CreateParticipantRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for create_participant - - Override in a subclass to manipulate the request or metadata - before they are sent to the Participants server. - """ - return request, metadata - - def post_create_participant(self, response: gcd_participant.Participant) -> gcd_participant.Participant: - """Post-rpc interceptor for create_participant - - Override in a subclass to manipulate the response - after it is returned by the Participants server but before - it is returned to user code. - """ - return response - def pre_get_participant(self, request: participant.GetParticipantRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[participant.GetParticipantRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for get_participant - - Override in a subclass to manipulate the request or metadata - before they are sent to the Participants server. - """ - return request, metadata - - def post_get_participant(self, response: participant.Participant) -> participant.Participant: - """Post-rpc interceptor for get_participant - - Override in a subclass to manipulate the response - after it is returned by the Participants server but before - it is returned to user code. - """ - return response - def pre_list_participants(self, request: participant.ListParticipantsRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[participant.ListParticipantsRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for list_participants - - Override in a subclass to manipulate the request or metadata - before they are sent to the Participants server. - """ - return request, metadata - - def post_list_participants(self, response: participant.ListParticipantsResponse) -> participant.ListParticipantsResponse: - """Post-rpc interceptor for list_participants - - Override in a subclass to manipulate the response - after it is returned by the Participants server but before - it is returned to user code. - """ - return response - def pre_suggest_articles(self, request: participant.SuggestArticlesRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[participant.SuggestArticlesRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for suggest_articles - - Override in a subclass to manipulate the request or metadata - before they are sent to the Participants server. - """ - return request, metadata - - def post_suggest_articles(self, response: participant.SuggestArticlesResponse) -> participant.SuggestArticlesResponse: - """Post-rpc interceptor for suggest_articles - - Override in a subclass to manipulate the response - after it is returned by the Participants server but before - it is returned to user code. - """ - return response - def pre_suggest_faq_answers(self, request: participant.SuggestFaqAnswersRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[participant.SuggestFaqAnswersRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for suggest_faq_answers - - Override in a subclass to manipulate the request or metadata - before they are sent to the Participants server. - """ - return request, metadata - - def post_suggest_faq_answers(self, response: participant.SuggestFaqAnswersResponse) -> participant.SuggestFaqAnswersResponse: - """Post-rpc interceptor for suggest_faq_answers - - Override in a subclass to manipulate the response - after it is returned by the Participants server but before - it is returned to user code. - """ - return response - def pre_suggest_smart_replies(self, request: participant.SuggestSmartRepliesRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[participant.SuggestSmartRepliesRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for suggest_smart_replies - - Override in a subclass to manipulate the request or metadata - before they are sent to the Participants server. - """ - return request, metadata - - def post_suggest_smart_replies(self, response: participant.SuggestSmartRepliesResponse) -> participant.SuggestSmartRepliesResponse: - """Post-rpc interceptor for suggest_smart_replies - - Override in a subclass to manipulate the response - after it is returned by the Participants server but before - it is returned to user code. - """ - return response - def pre_update_participant(self, request: gcd_participant.UpdateParticipantRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[gcd_participant.UpdateParticipantRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for update_participant - - Override in a subclass to manipulate the request or metadata - before they are sent to the Participants server. - """ - return request, metadata - - def post_update_participant(self, response: gcd_participant.Participant) -> gcd_participant.Participant: - """Post-rpc interceptor for update_participant - - Override in a subclass to manipulate the response - after it is returned by the Participants server but before - it is returned to user code. - """ - return response - - def pre_get_location( - self, request: locations_pb2.GetLocationRequest, metadata: Sequence[Tuple[str, str]] - ) -> Tuple[locations_pb2.GetLocationRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for get_location - - Override in a subclass to manipulate the request or metadata - before they are sent to the Participants server. - """ - return request, metadata - - def post_get_location( - self, response: locations_pb2.Location - ) -> locations_pb2.Location: - """Post-rpc interceptor for get_location - - Override in a subclass to manipulate the response - after it is returned by the Participants server but before - it is returned to user code. - """ - return response - def pre_list_locations( - self, request: locations_pb2.ListLocationsRequest, metadata: Sequence[Tuple[str, str]] - ) -> Tuple[locations_pb2.ListLocationsRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for list_locations - - Override in a subclass to manipulate the request or metadata - before they are sent to the Participants server. - """ - return request, metadata - - def post_list_locations( - self, response: locations_pb2.ListLocationsResponse - ) -> locations_pb2.ListLocationsResponse: - """Post-rpc interceptor for list_locations - - Override in a subclass to manipulate the response - after it is returned by the Participants server but before - it is returned to user code. - """ - return response - def pre_cancel_operation( - self, request: operations_pb2.CancelOperationRequest, metadata: Sequence[Tuple[str, str]] - ) -> Tuple[operations_pb2.CancelOperationRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for cancel_operation - - Override in a subclass to manipulate the request or metadata - before they are sent to the Participants server. - """ - return request, metadata - - def post_cancel_operation( - self, response: None - ) -> None: - """Post-rpc interceptor for cancel_operation - - Override in a subclass to manipulate the response - after it is returned by the Participants server but before - it is returned to user code. - """ - return response - def pre_get_operation( - self, request: operations_pb2.GetOperationRequest, metadata: Sequence[Tuple[str, str]] - ) -> Tuple[operations_pb2.GetOperationRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for get_operation - - Override in a subclass to manipulate the request or metadata - before they are sent to the Participants server. - """ - return request, metadata - - def post_get_operation( - self, response: operations_pb2.Operation - ) -> operations_pb2.Operation: - """Post-rpc interceptor for get_operation - - Override in a subclass to manipulate the response - after it is returned by the Participants server but before - it is returned to user code. - """ - return response - def pre_list_operations( - self, request: operations_pb2.ListOperationsRequest, metadata: Sequence[Tuple[str, str]] - ) -> Tuple[operations_pb2.ListOperationsRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for list_operations - - Override in a subclass to manipulate the request or metadata - before they are sent to the Participants server. - """ - return request, metadata - - def post_list_operations( - self, response: operations_pb2.ListOperationsResponse - ) -> operations_pb2.ListOperationsResponse: - """Post-rpc interceptor for list_operations - - Override in a subclass to manipulate the response - after it is returned by the Participants server but before - it is returned to user code. - """ - return response - - -@dataclasses.dataclass -class ParticipantsRestStub: - _session: AuthorizedSession - _host: str - _interceptor: ParticipantsRestInterceptor - - -class ParticipantsRestTransport(ParticipantsTransport): - """REST backend transport for Participants. - - Service for managing - [Participants][google.cloud.dialogflow.v2.Participant]. - - 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 JSON representations of protocol buffers over HTTP/1.1 - - """ - - def __init__(self, *, - host: str = 'dialogflow.googleapis.com', - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - client_cert_source_for_mtls: Optional[Callable[[ - ], Tuple[bytes, bytes]]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - url_scheme: str = 'https', - interceptor: Optional[ParticipantsRestInterceptor] = None, - api_audience: Optional[str] = None, - ) -> 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 ignored if ``channel`` is provided. - scopes (Optional(Sequence[str])): A list of scopes. This argument is - ignored if ``channel`` is provided. - client_cert_source_for_mtls (Callable[[], Tuple[bytes, bytes]]): Client - certificate to configure mutual TLS HTTP channel. It is ignored - if ``channel`` is provided. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you are developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - url_scheme: the protocol scheme for the API endpoint. Normally - "https", but for testing or local servers, - "http" can be specified. - """ - # Run the base constructor - # TODO(yon-mg): resolve other ctor params i.e. scopes, quota, etc. - # TODO: When custom host (api_endpoint) is set, `scopes` must *also* be set on the - # credentials object - maybe_url_match = re.match("^(?Phttp(?:s)?://)?(?P.*)$", host) - if maybe_url_match is None: - raise ValueError(f"Unexpected hostname structure: {host}") # pragma: NO COVER - - url_match_items = maybe_url_match.groupdict() - - host = f"{url_scheme}://{host}" if not url_match_items["scheme"] else host - - super().__init__( - host=host, - credentials=credentials, - client_info=client_info, - always_use_jwt_access=always_use_jwt_access, - api_audience=api_audience - ) - self._session = AuthorizedSession( - self._credentials, default_host=self.DEFAULT_HOST) - if client_cert_source_for_mtls: - self._session.configure_mtls_channel(client_cert_source_for_mtls) - self._interceptor = interceptor or ParticipantsRestInterceptor() - self._prep_wrapped_messages(client_info) - - class _AnalyzeContent(ParticipantsRestStub): - def __hash__(self): - return hash("AnalyzeContent") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: gcd_participant.AnalyzeContentRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> gcd_participant.AnalyzeContentResponse: - r"""Call the analyze content method over HTTP. - - Args: - request (~.gcd_participant.AnalyzeContentRequest): - The request object. The request message for - [Participants.AnalyzeContent][google.cloud.dialogflow.v2.Participants.AnalyzeContent]. - 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: - ~.gcd_participant.AnalyzeContentResponse: - The response message for - [Participants.AnalyzeContent][google.cloud.dialogflow.v2.Participants.AnalyzeContent]. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'post', - 'uri': '/v2/{participant=projects/*/conversations/*/participants/*}:analyzeContent', - 'body': '*', - }, -{ - 'method': 'post', - 'uri': '/v2/{participant=projects/*/locations/*/conversations/*/participants/*}:analyzeContent', - 'body': '*', - }, - ] - request, metadata = self._interceptor.pre_analyze_content(request, metadata) - pb_request = gcd_participant.AnalyzeContentRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request['body'], - including_default_value_fields=False, - use_integers_for_enums=True - ) - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - including_default_value_fields=False, - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = gcd_participant.AnalyzeContentResponse() - pb_resp = gcd_participant.AnalyzeContentResponse.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_analyze_content(resp) - return resp - - class _CreateParticipant(ParticipantsRestStub): - def __hash__(self): - return hash("CreateParticipant") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: gcd_participant.CreateParticipantRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> gcd_participant.Participant: - r"""Call the create participant method over HTTP. - - Args: - request (~.gcd_participant.CreateParticipantRequest): - The request object. The request message for - [Participants.CreateParticipant][google.cloud.dialogflow.v2.Participants.CreateParticipant]. - 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: - ~.gcd_participant.Participant: - Represents a conversation participant - (human agent, virtual agent, end-user). - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'post', - 'uri': '/v2/{parent=projects/*/conversations/*}/participants', - 'body': 'participant', - }, -{ - 'method': 'post', - 'uri': '/v2/{parent=projects/*/locations/*/conversations/*}/participants', - 'body': 'participant', - }, - ] - request, metadata = self._interceptor.pre_create_participant(request, metadata) - pb_request = gcd_participant.CreateParticipantRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request['body'], - including_default_value_fields=False, - use_integers_for_enums=True - ) - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - including_default_value_fields=False, - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = gcd_participant.Participant() - pb_resp = gcd_participant.Participant.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_create_participant(resp) - return resp - - class _GetParticipant(ParticipantsRestStub): - def __hash__(self): - return hash("GetParticipant") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: participant.GetParticipantRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> participant.Participant: - r"""Call the get participant method over HTTP. - - Args: - request (~.participant.GetParticipantRequest): - The request object. The request message for - [Participants.GetParticipant][google.cloud.dialogflow.v2.Participants.GetParticipant]. - 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: - ~.participant.Participant: - Represents a conversation participant - (human agent, virtual agent, end-user). - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v2/{name=projects/*/conversations/*/participants/*}', - }, -{ - 'method': 'get', - 'uri': '/v2/{name=projects/*/locations/*/conversations/*/participants/*}', - }, - ] - request, metadata = self._interceptor.pre_get_participant(request, metadata) - pb_request = participant.GetParticipantRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - including_default_value_fields=False, - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = participant.Participant() - pb_resp = participant.Participant.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_get_participant(resp) - return resp - - class _ListParticipants(ParticipantsRestStub): - def __hash__(self): - return hash("ListParticipants") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: participant.ListParticipantsRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> participant.ListParticipantsResponse: - r"""Call the list participants method over HTTP. - - Args: - request (~.participant.ListParticipantsRequest): - The request object. The request message for - [Participants.ListParticipants][google.cloud.dialogflow.v2.Participants.ListParticipants]. - 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: - ~.participant.ListParticipantsResponse: - The response message for - [Participants.ListParticipants][google.cloud.dialogflow.v2.Participants.ListParticipants]. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v2/{parent=projects/*/conversations/*}/participants', - }, -{ - 'method': 'get', - 'uri': '/v2/{parent=projects/*/locations/*/conversations/*}/participants', - }, - ] - request, metadata = self._interceptor.pre_list_participants(request, metadata) - pb_request = participant.ListParticipantsRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - including_default_value_fields=False, - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = participant.ListParticipantsResponse() - pb_resp = participant.ListParticipantsResponse.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_list_participants(resp) - return resp - - class _StreamingAnalyzeContent(ParticipantsRestStub): - def __hash__(self): - return hash("StreamingAnalyzeContent") - - def __call__(self, - request: participant.StreamingAnalyzeContentRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> rest_streaming.ResponseIterator: - raise NotImplementedError( - "Method StreamingAnalyzeContent is not available over REST transport" - ) - class _SuggestArticles(ParticipantsRestStub): - def __hash__(self): - return hash("SuggestArticles") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: participant.SuggestArticlesRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> participant.SuggestArticlesResponse: - r"""Call the suggest articles method over HTTP. - - Args: - request (~.participant.SuggestArticlesRequest): - The request object. The request message for - [Participants.SuggestArticles][google.cloud.dialogflow.v2.Participants.SuggestArticles]. - 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: - ~.participant.SuggestArticlesResponse: - The response message for - [Participants.SuggestArticles][google.cloud.dialogflow.v2.Participants.SuggestArticles]. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'post', - 'uri': '/v2/{parent=projects/*/conversations/*/participants/*}/suggestions:suggestArticles', - 'body': '*', - }, -{ - 'method': 'post', - 'uri': '/v2/{parent=projects/*/locations/*/conversations/*/participants/*}/suggestions:suggestArticles', - 'body': '*', - }, - ] - request, metadata = self._interceptor.pre_suggest_articles(request, metadata) - pb_request = participant.SuggestArticlesRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request['body'], - including_default_value_fields=False, - use_integers_for_enums=True - ) - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - including_default_value_fields=False, - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = participant.SuggestArticlesResponse() - pb_resp = participant.SuggestArticlesResponse.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_suggest_articles(resp) - return resp - - class _SuggestFaqAnswers(ParticipantsRestStub): - def __hash__(self): - return hash("SuggestFaqAnswers") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: participant.SuggestFaqAnswersRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> participant.SuggestFaqAnswersResponse: - r"""Call the suggest faq answers method over HTTP. - - Args: - request (~.participant.SuggestFaqAnswersRequest): - The request object. The request message for - [Participants.SuggestFaqAnswers][google.cloud.dialogflow.v2.Participants.SuggestFaqAnswers]. - 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: - ~.participant.SuggestFaqAnswersResponse: - The request message for - [Participants.SuggestFaqAnswers][google.cloud.dialogflow.v2.Participants.SuggestFaqAnswers]. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'post', - 'uri': '/v2/{parent=projects/*/conversations/*/participants/*}/suggestions:suggestFaqAnswers', - 'body': '*', - }, -{ - 'method': 'post', - 'uri': '/v2/{parent=projects/*/locations/*/conversations/*/participants/*}/suggestions:suggestFaqAnswers', - 'body': '*', - }, - ] - request, metadata = self._interceptor.pre_suggest_faq_answers(request, metadata) - pb_request = participant.SuggestFaqAnswersRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request['body'], - including_default_value_fields=False, - use_integers_for_enums=True - ) - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - including_default_value_fields=False, - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = participant.SuggestFaqAnswersResponse() - pb_resp = participant.SuggestFaqAnswersResponse.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_suggest_faq_answers(resp) - return resp - - class _SuggestSmartReplies(ParticipantsRestStub): - def __hash__(self): - return hash("SuggestSmartReplies") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: participant.SuggestSmartRepliesRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> participant.SuggestSmartRepliesResponse: - r"""Call the suggest smart replies method over HTTP. - - Args: - request (~.participant.SuggestSmartRepliesRequest): - The request object. The request message for - [Participants.SuggestSmartReplies][google.cloud.dialogflow.v2.Participants.SuggestSmartReplies]. - 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: - ~.participant.SuggestSmartRepliesResponse: - The response message for - [Participants.SuggestSmartReplies][google.cloud.dialogflow.v2.Participants.SuggestSmartReplies]. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'post', - 'uri': '/v2/{parent=projects/*/conversations/*/participants/*}/suggestions:suggestSmartReplies', - 'body': '*', - }, -{ - 'method': 'post', - 'uri': '/v2/{parent=projects/*/locations/*/conversations/*/participants/*}/suggestions:suggestSmartReplies', - 'body': '*', - }, - ] - request, metadata = self._interceptor.pre_suggest_smart_replies(request, metadata) - pb_request = participant.SuggestSmartRepliesRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request['body'], - including_default_value_fields=False, - use_integers_for_enums=True - ) - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - including_default_value_fields=False, - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = participant.SuggestSmartRepliesResponse() - pb_resp = participant.SuggestSmartRepliesResponse.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_suggest_smart_replies(resp) - return resp - - class _UpdateParticipant(ParticipantsRestStub): - def __hash__(self): - return hash("UpdateParticipant") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - "updateMask" : {}, } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: gcd_participant.UpdateParticipantRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> gcd_participant.Participant: - r"""Call the update participant method over HTTP. - - Args: - request (~.gcd_participant.UpdateParticipantRequest): - The request object. The request message for - [Participants.UpdateParticipant][google.cloud.dialogflow.v2.Participants.UpdateParticipant]. - 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: - ~.gcd_participant.Participant: - Represents a conversation participant - (human agent, virtual agent, end-user). - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'patch', - 'uri': '/v2/{participant.name=projects/*/conversations/*/participants/*}', - 'body': 'participant', - }, -{ - 'method': 'patch', - 'uri': '/v2/{participant.name=projects/*/locations/*/conversations/*/participants/*}', - 'body': 'participant', - }, - ] - request, metadata = self._interceptor.pre_update_participant(request, metadata) - pb_request = gcd_participant.UpdateParticipantRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request['body'], - including_default_value_fields=False, - use_integers_for_enums=True - ) - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - including_default_value_fields=False, - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = gcd_participant.Participant() - pb_resp = gcd_participant.Participant.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_update_participant(resp) - return resp - - @property - def analyze_content(self) -> Callable[ - [gcd_participant.AnalyzeContentRequest], - gcd_participant.AnalyzeContentResponse]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._AnalyzeContent(self._session, self._host, self._interceptor) # type: ignore - - @property - def create_participant(self) -> Callable[ - [gcd_participant.CreateParticipantRequest], - gcd_participant.Participant]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._CreateParticipant(self._session, self._host, self._interceptor) # type: ignore - - @property - def get_participant(self) -> Callable[ - [participant.GetParticipantRequest], - participant.Participant]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._GetParticipant(self._session, self._host, self._interceptor) # type: ignore - - @property - def list_participants(self) -> Callable[ - [participant.ListParticipantsRequest], - participant.ListParticipantsResponse]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._ListParticipants(self._session, self._host, self._interceptor) # type: ignore - - @property - def streaming_analyze_content(self) -> Callable[ - [participant.StreamingAnalyzeContentRequest], - participant.StreamingAnalyzeContentResponse]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._StreamingAnalyzeContent(self._session, self._host, self._interceptor) # type: ignore - - @property - def suggest_articles(self) -> Callable[ - [participant.SuggestArticlesRequest], - participant.SuggestArticlesResponse]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._SuggestArticles(self._session, self._host, self._interceptor) # type: ignore - - @property - def suggest_faq_answers(self) -> Callable[ - [participant.SuggestFaqAnswersRequest], - participant.SuggestFaqAnswersResponse]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._SuggestFaqAnswers(self._session, self._host, self._interceptor) # type: ignore - - @property - def suggest_smart_replies(self) -> Callable[ - [participant.SuggestSmartRepliesRequest], - participant.SuggestSmartRepliesResponse]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._SuggestSmartReplies(self._session, self._host, self._interceptor) # type: ignore - - @property - def update_participant(self) -> Callable[ - [gcd_participant.UpdateParticipantRequest], - gcd_participant.Participant]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._UpdateParticipant(self._session, self._host, self._interceptor) # type: ignore - - @property - def get_location(self): - return self._GetLocation(self._session, self._host, self._interceptor) # type: ignore - - class _GetLocation(ParticipantsRestStub): - def __call__(self, - request: locations_pb2.GetLocationRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> locations_pb2.Location: - - r"""Call the get location method over HTTP. - - Args: - request (locations_pb2.GetLocationRequest): - The request object for GetLocation method. - 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: - locations_pb2.Location: Response from GetLocation method. - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v2/{name=projects/*/locations/*}', - }, - ] - - request, metadata = self._interceptor.pre_get_location(request, metadata) - request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode( - http_options, **request_kwargs) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json.dumps(transcoded_request['query_params'])) - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - resp = locations_pb2.Location() - resp = json_format.Parse(response.content.decode("utf-8"), resp) - resp = self._interceptor.post_get_location(resp) - return resp - - @property - def list_locations(self): - return self._ListLocations(self._session, self._host, self._interceptor) # type: ignore - - class _ListLocations(ParticipantsRestStub): - def __call__(self, - request: locations_pb2.ListLocationsRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> locations_pb2.ListLocationsResponse: - - r"""Call the list locations method over HTTP. - - Args: - request (locations_pb2.ListLocationsRequest): - The request object for ListLocations method. - 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: - locations_pb2.ListLocationsResponse: Response from ListLocations method. - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v2/{name=projects/*}/locations', - }, - ] - - request, metadata = self._interceptor.pre_list_locations(request, metadata) - request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode( - http_options, **request_kwargs) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json.dumps(transcoded_request['query_params'])) - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - resp = locations_pb2.ListLocationsResponse() - resp = json_format.Parse(response.content.decode("utf-8"), resp) - resp = self._interceptor.post_list_locations(resp) - return resp - - @property - def cancel_operation(self): - return self._CancelOperation(self._session, self._host, self._interceptor) # type: ignore - - class _CancelOperation(ParticipantsRestStub): - def __call__(self, - request: operations_pb2.CancelOperationRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> None: - - r"""Call the cancel operation method over HTTP. - - Args: - request (operations_pb2.CancelOperationRequest): - The request object for CancelOperation method. - 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. - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'post', - 'uri': '/v2/{name=projects/*/operations/*}:cancel', - }, -{ - 'method': 'post', - 'uri': '/v2/{name=projects/*/locations/*/operations/*}:cancel', - }, - ] - - request, metadata = self._interceptor.pre_cancel_operation(request, metadata) - request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode( - http_options, **request_kwargs) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json.dumps(transcoded_request['query_params'])) - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - return self._interceptor.post_cancel_operation(None) - - @property - def get_operation(self): - return self._GetOperation(self._session, self._host, self._interceptor) # type: ignore - - class _GetOperation(ParticipantsRestStub): - def __call__(self, - request: operations_pb2.GetOperationRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> operations_pb2.Operation: - - r"""Call the get operation method over HTTP. - - Args: - request (operations_pb2.GetOperationRequest): - The request object for GetOperation method. - 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: - operations_pb2.Operation: Response from GetOperation method. - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v2/{name=projects/*/operations/*}', - }, -{ - 'method': 'get', - 'uri': '/v2/{name=projects/*/locations/*/operations/*}', - }, - ] - - request, metadata = self._interceptor.pre_get_operation(request, metadata) - request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode( - http_options, **request_kwargs) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json.dumps(transcoded_request['query_params'])) - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - resp = operations_pb2.Operation() - resp = json_format.Parse(response.content.decode("utf-8"), resp) - resp = self._interceptor.post_get_operation(resp) - return resp - - @property - def list_operations(self): - return self._ListOperations(self._session, self._host, self._interceptor) # type: ignore - - class _ListOperations(ParticipantsRestStub): - def __call__(self, - request: operations_pb2.ListOperationsRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> operations_pb2.ListOperationsResponse: - - r"""Call the list operations method over HTTP. - - Args: - request (operations_pb2.ListOperationsRequest): - The request object for ListOperations method. - 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: - operations_pb2.ListOperationsResponse: Response from ListOperations method. - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v2/{name=projects/*}/operations', - }, -{ - 'method': 'get', - 'uri': '/v2/{name=projects/*/locations/*}/operations', - }, - ] - - request, metadata = self._interceptor.pre_list_operations(request, metadata) - request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode( - http_options, **request_kwargs) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json.dumps(transcoded_request['query_params'])) - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - resp = operations_pb2.ListOperationsResponse() - resp = json_format.Parse(response.content.decode("utf-8"), resp) - resp = self._interceptor.post_list_operations(resp) - return resp - - @property - def kind(self) -> str: - return "rest" - - def close(self): - self._session.close() - - -__all__=( - 'ParticipantsRestTransport', -) diff --git a/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/session_entity_types/__init__.py b/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/session_entity_types/__init__.py deleted file mode 100644 index 1a3f965dd..000000000 --- a/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/session_entity_types/__init__.py +++ /dev/null @@ -1,22 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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 SessionEntityTypesClient -from .async_client import SessionEntityTypesAsyncClient - -__all__ = ( - 'SessionEntityTypesClient', - 'SessionEntityTypesAsyncClient', -) diff --git a/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/session_entity_types/async_client.py b/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/session_entity_types/async_client.py deleted file mode 100644 index e8c315ea8..000000000 --- a/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/session_entity_types/async_client.py +++ /dev/null @@ -1,1061 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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, Mapping, MutableMapping, MutableSequence, Optional, Sequence, Tuple, Type, Union - -from google.cloud.dialogflow_v2 import gapic_version as package_version - -from google.api_core.client_options import ClientOptions -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import retry as retries -from google.auth import credentials as ga_credentials # type: ignore -from google.oauth2 import service_account # type: ignore - -try: - OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] -except AttributeError: # pragma: NO COVER - OptionalRetry = Union[retries.Retry, object] # type: ignore - -from google.cloud.dialogflow_v2.services.session_entity_types import pagers -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.cloud.location import locations_pb2 # type: ignore -from google.longrunning import operations_pb2 -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 - - -class SessionEntityTypesAsyncClient: - """Service for managing - [SessionEntityTypes][google.cloud.dialogflow.v2.SessionEntityType]. - """ - - _client: SessionEntityTypesClient - - DEFAULT_ENDPOINT = SessionEntityTypesClient.DEFAULT_ENDPOINT - DEFAULT_MTLS_ENDPOINT = SessionEntityTypesClient.DEFAULT_MTLS_ENDPOINT - - session_entity_type_path = staticmethod(SessionEntityTypesClient.session_entity_type_path) - 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) - - @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: - SessionEntityTypesAsyncClient: The constructed client. - """ - return SessionEntityTypesClient.from_service_account_info.__func__(SessionEntityTypesAsyncClient, 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: - SessionEntityTypesAsyncClient: The constructed client. - """ - return SessionEntityTypesClient.from_service_account_file.__func__(SessionEntityTypesAsyncClient, filename, *args, **kwargs) # type: ignore - - from_service_account_json = from_service_account_file - - @classmethod - def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[ClientOptions] = None): - """Return the API endpoint and client cert source for mutual TLS. - - The client cert source is determined in the following order: - (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the - client cert source is None. - (2) if `client_options.client_cert_source` is provided, use the provided one; if the - default client cert source exists, use the default one; otherwise the client cert - source is None. - - The API endpoint is determined in the following order: - (1) if `client_options.api_endpoint` if provided, use the provided one. - (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the - default mTLS endpoint; if the environment variable is "never", use the default API - endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise - use the default API endpoint. - - More details can be found at https://google.aip.dev/auth/4114. - - Args: - client_options (google.api_core.client_options.ClientOptions): Custom options for the - client. Only the `api_endpoint` and `client_cert_source` properties may be used - in this method. - - Returns: - Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the - client cert source to use. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If any errors happen. - """ - return SessionEntityTypesClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore - - @property - def transport(self) -> SessionEntityTypesTransport: - """Returns the transport used by the client instance. - - Returns: - SessionEntityTypesTransport: The transport used by the client instance. - """ - return self._client.transport - - get_transport_class = functools.partial(type(SessionEntityTypesClient).get_transport_class, type(SessionEntityTypesClient)) - - def __init__(self, *, - credentials: Optional[ga_credentials.Credentials] = None, - transport: Union[str, SessionEntityTypesTransport] = "grpc_asyncio", - client_options: Optional[ClientOptions] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the session entity types 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, ~.SessionEntityTypesTransport]): 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 = SessionEntityTypesClient( - credentials=credentials, - transport=transport, - client_options=client_options, - client_info=client_info, - - ) - - async def list_session_entity_types(self, - request: Optional[Union[session_entity_type.ListSessionEntityTypesRequest, dict]] = None, - *, - parent: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListSessionEntityTypesAsyncPager: - r"""Returns the list of all session entity types in the - specified session. - This method doesn't work with Google Assistant - integration. Contact Dialogflow support if you need to - use session entities with Google Assistant integration. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import dialogflow_v2 - - async def sample_list_session_entity_types(): - # Create a client - client = dialogflow_v2.SessionEntityTypesAsyncClient() - - # Initialize request argument(s) - request = dialogflow_v2.ListSessionEntityTypesRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_session_entity_types(request=request) - - # Handle the response - async for response in page_result: - print(response) - - Args: - request (Optional[Union[google.cloud.dialogflow_v2.types.ListSessionEntityTypesRequest, dict]]): - The request object. The request message for - [SessionEntityTypes.ListSessionEntityTypes][google.cloud.dialogflow.v2.SessionEntityTypes.ListSessionEntityTypes]. - parent (:class:`str`): - Required. The session to list all session entity types - from. Format: - ``projects//agent/sessions/`` or - ``projects//agent/environments//users// sessions/``. - If ``Environment ID`` is not specified, we assume - default 'draft' environment. If ``User ID`` is not - specified, we assume default '-' user. - - 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.session_entity_types.pagers.ListSessionEntityTypesAsyncPager: - The response message for - [SessionEntityTypes.ListSessionEntityTypes][google.cloud.dialogflow.v2.SessionEntityTypes.ListSessionEntityTypes]. - - Iterating over this object will yield results and - resolve additional pages automatically. - - """ - # Create or coerce a protobuf request object. - # Quick 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 = 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 - - # 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_session_entity_types, - 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.ListSessionEntityTypesAsyncPager( - method=rpc, - request=request, - response=response, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def get_session_entity_type(self, - request: Optional[Union[session_entity_type.GetSessionEntityTypeRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> session_entity_type.SessionEntityType: - r"""Retrieves the specified session entity type. - This method doesn't work with Google Assistant - integration. Contact Dialogflow support if you need to - use session entities with Google Assistant integration. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import dialogflow_v2 - - async def sample_get_session_entity_type(): - # Create a client - client = dialogflow_v2.SessionEntityTypesAsyncClient() - - # Initialize request argument(s) - request = dialogflow_v2.GetSessionEntityTypeRequest( - name="name_value", - ) - - # Make the request - response = await client.get_session_entity_type(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.dialogflow_v2.types.GetSessionEntityTypeRequest, dict]]): - The request object. The request message for - [SessionEntityTypes.GetSessionEntityType][google.cloud.dialogflow.v2.SessionEntityTypes.GetSessionEntityType]. - name (:class:`str`): - Required. The name of the session entity type. Format: - ``projects//agent/sessions//entityTypes/`` - or - ``projects//agent/environments//users//sessions//entityTypes/``. - If ``Environment ID`` is not specified, we assume - default 'draft' environment. If ``User ID`` is not - specified, we assume default '-' user. - - 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.SessionEntityType: - A session represents a conversation between a Dialogflow agent and an - end-user. You can create special entities, called - session entities, during a session. Session entities - can extend or replace custom entity types and only - exist during the session that they were created for. - All session data, including session entities, is - stored by Dialogflow for 20 minutes. - - For more information, see the [session entity - guide](\ https://cloud.google.com/dialogflow/docs/entities-session). - - """ - # Create or coerce a protobuf request object. - # Quick 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 = 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 - - # 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_session_entity_type, - 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_session_entity_type(self, - request: Optional[Union[gcd_session_entity_type.CreateSessionEntityTypeRequest, dict]] = None, - *, - parent: Optional[str] = None, - session_entity_type: Optional[gcd_session_entity_type.SessionEntityType] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gcd_session_entity_type.SessionEntityType: - r"""Creates a session entity type. - If the specified session entity type already exists, - overrides the session entity type. - - This method doesn't work with Google Assistant - integration. Contact Dialogflow support if you need to - use session entities with Google Assistant integration. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import dialogflow_v2 - - async def sample_create_session_entity_type(): - # Create a client - client = dialogflow_v2.SessionEntityTypesAsyncClient() - - # Initialize request argument(s) - session_entity_type = dialogflow_v2.SessionEntityType() - session_entity_type.name = "name_value" - session_entity_type.entity_override_mode = "ENTITY_OVERRIDE_MODE_SUPPLEMENT" - session_entity_type.entities.value = "value_value" - session_entity_type.entities.synonyms = ['synonyms_value1', 'synonyms_value2'] - - request = dialogflow_v2.CreateSessionEntityTypeRequest( - parent="parent_value", - session_entity_type=session_entity_type, - ) - - # Make the request - response = await client.create_session_entity_type(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.dialogflow_v2.types.CreateSessionEntityTypeRequest, dict]]): - The request object. The request message for - [SessionEntityTypes.CreateSessionEntityType][google.cloud.dialogflow.v2.SessionEntityTypes.CreateSessionEntityType]. - parent (:class:`str`): - Required. The session to create a session entity type - for. Format: - ``projects//agent/sessions/`` or - ``projects//agent/environments//users// sessions/``. - If ``Environment ID`` is not specified, we assume - default 'draft' environment. If ``User ID`` is not - specified, we assume default '-' user. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - session_entity_type (:class:`google.cloud.dialogflow_v2.types.SessionEntityType`): - Required. The session entity type to - create. - - 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. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.dialogflow_v2.types.SessionEntityType: - A session represents a conversation between a Dialogflow agent and an - end-user. You can create special entities, called - session entities, during a session. Session entities - can extend or replace custom entity types and only - exist during the session that they were created for. - All session data, including session entities, is - stored by Dialogflow for 20 minutes. - - For more information, see the [session entity - guide](\ https://cloud.google.com/dialogflow/docs/entities-session). - - """ - # Create or coerce a protobuf request object. - # Quick 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, session_entity_type]) - 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_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: - request.session_entity_type = session_entity_type - - # 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_session_entity_type, - 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_session_entity_type(self, - request: Optional[Union[gcd_session_entity_type.UpdateSessionEntityTypeRequest, dict]] = None, - *, - session_entity_type: Optional[gcd_session_entity_type.SessionEntityType] = None, - update_mask: Optional[field_mask_pb2.FieldMask] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gcd_session_entity_type.SessionEntityType: - r"""Updates the specified session entity type. - This method doesn't work with Google Assistant - integration. Contact Dialogflow support if you need to - use session entities with Google Assistant integration. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import dialogflow_v2 - - async def sample_update_session_entity_type(): - # Create a client - client = dialogflow_v2.SessionEntityTypesAsyncClient() - - # Initialize request argument(s) - session_entity_type = dialogflow_v2.SessionEntityType() - session_entity_type.name = "name_value" - session_entity_type.entity_override_mode = "ENTITY_OVERRIDE_MODE_SUPPLEMENT" - session_entity_type.entities.value = "value_value" - session_entity_type.entities.synonyms = ['synonyms_value1', 'synonyms_value2'] - - request = dialogflow_v2.UpdateSessionEntityTypeRequest( - session_entity_type=session_entity_type, - ) - - # Make the request - response = await client.update_session_entity_type(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.dialogflow_v2.types.UpdateSessionEntityTypeRequest, dict]]): - The request object. The request message for - [SessionEntityTypes.UpdateSessionEntityType][google.cloud.dialogflow.v2.SessionEntityTypes.UpdateSessionEntityType]. - session_entity_type (:class:`google.cloud.dialogflow_v2.types.SessionEntityType`): - Required. The session entity type to - update. - - This corresponds to the ``session_entity_type`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - update_mask (:class:`google.protobuf.field_mask_pb2.FieldMask`): - Optional. 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.SessionEntityType: - A session represents a conversation between a Dialogflow agent and an - end-user. You can create special entities, called - session entities, during a session. Session entities - can extend or replace custom entity types and only - exist during the session that they were created for. - All session data, including session entities, is - stored by Dialogflow for 20 minutes. - - For more information, see the [session entity - guide](\ https://cloud.google.com/dialogflow/docs/entities-session). - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([session_entity_type, 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_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: - 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_session_entity_type, - 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(( - ("session_entity_type.name", request.session_entity_type.name), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def delete_session_entity_type(self, - request: Optional[Union[session_entity_type.DeleteSessionEntityTypeRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> None: - r"""Deletes the specified session entity type. - This method doesn't work with Google Assistant - integration. Contact Dialogflow support if you need to - use session entities with Google Assistant integration. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import dialogflow_v2 - - async def sample_delete_session_entity_type(): - # Create a client - client = dialogflow_v2.SessionEntityTypesAsyncClient() - - # Initialize request argument(s) - request = dialogflow_v2.DeleteSessionEntityTypeRequest( - name="name_value", - ) - - # Make the request - await client.delete_session_entity_type(request=request) - - Args: - request (Optional[Union[google.cloud.dialogflow_v2.types.DeleteSessionEntityTypeRequest, dict]]): - The request object. The request message for - [SessionEntityTypes.DeleteSessionEntityType][google.cloud.dialogflow.v2.SessionEntityTypes.DeleteSessionEntityType]. - name (:class:`str`): - Required. The name of the entity type to delete. Format: - ``projects//agent/sessions//entityTypes/`` - or - ``projects//agent/environments//users//sessions//entityTypes/``. - If ``Environment ID`` is not specified, we assume - default 'draft' environment. If ``User ID`` is not - specified, we assume default '-' user. - - 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. - # Quick 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 = 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 - - # 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_session_entity_type, - 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 list_operations( - self, - request: Optional[operations_pb2.ListOperationsRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operations_pb2.ListOperationsResponse: - r"""Lists operations that match the specified filter in the request. - - Args: - request (:class:`~.operations_pb2.ListOperationsRequest`): - The request object. Request message for - `ListOperations` method. - 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: - ~.operations_pb2.ListOperationsResponse: - Response message for ``ListOperations`` method. - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = operations_pb2.ListOperationsRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._client._transport.list_operations, - 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 get_operation( - self, - request: Optional[operations_pb2.GetOperationRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operations_pb2.Operation: - r"""Gets the latest state of a long-running operation. - - Args: - request (:class:`~.operations_pb2.GetOperationRequest`): - The request object. Request message for - `GetOperation` method. - 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: - ~.operations_pb2.Operation: - An ``Operation`` object. - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = operations_pb2.GetOperationRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._client._transport.get_operation, - 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 cancel_operation( - self, - request: Optional[operations_pb2.CancelOperationRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> None: - r"""Starts asynchronous cancellation on a long-running operation. - - The server makes a best effort to cancel the operation, but success - is not guaranteed. If the server doesn't support this method, it returns - `google.rpc.Code.UNIMPLEMENTED`. - - Args: - request (:class:`~.operations_pb2.CancelOperationRequest`): - The request object. Request message for - `CancelOperation` method. - 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: - None - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = operations_pb2.CancelOperationRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._client._transport.cancel_operation, - 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_location( - self, - request: Optional[locations_pb2.GetLocationRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> locations_pb2.Location: - r"""Gets information about a location. - - Args: - request (:class:`~.location_pb2.GetLocationRequest`): - The request object. Request message for - `GetLocation` method. - 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: - ~.location_pb2.Location: - Location object. - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = locations_pb2.GetLocationRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._client._transport.get_location, - 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 list_locations( - self, - request: Optional[locations_pb2.ListLocationsRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> locations_pb2.ListLocationsResponse: - r"""Lists information about the supported locations for this service. - - Args: - request (:class:`~.location_pb2.ListLocationsRequest`): - The request object. Request message for - `ListLocations` method. - 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: - ~.location_pb2.ListLocationsResponse: - Response message for ``ListLocations`` method. - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = locations_pb2.ListLocationsRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._client._transport.list_locations, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("name", request.name),)), - ) - - # Send the request. - response = await rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - async def __aenter__(self): - return self - - async def __aexit__(self, exc_type, exc, tb): - await self.transport.close() - -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) - - -__all__ = ( - "SessionEntityTypesAsyncClient", -) diff --git a/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/session_entity_types/client.py b/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/session_entity_types/client.py deleted file mode 100644 index 709c8e0c5..000000000 --- a/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/session_entity_types/client.py +++ /dev/null @@ -1,1260 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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 os -import re -from typing import Dict, Mapping, MutableMapping, MutableSequence, Optional, Sequence, Tuple, Type, Union, cast - -from google.cloud.dialogflow_v2 import gapic_version as package_version - -from google.api_core import client_options as client_options_lib -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import retry as retries -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 - -try: - OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] -except AttributeError: # pragma: NO COVER - OptionalRetry = Union[retries.Retry, object] # type: ignore - -from google.cloud.dialogflow_v2.services.session_entity_types import pagers -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.cloud.location import locations_pb2 # type: ignore -from google.longrunning import operations_pb2 -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 -from .transports.rest import SessionEntityTypesRestTransport - - -class SessionEntityTypesClientMeta(type): - """Metaclass for the SessionEntityTypes 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[SessionEntityTypesTransport]] - _transport_registry["grpc"] = SessionEntityTypesGrpcTransport - _transport_registry["grpc_asyncio"] = SessionEntityTypesGrpcAsyncIOTransport - _transport_registry["rest"] = SessionEntityTypesRestTransport - - def get_transport_class(cls, - label: Optional[str] = None, - ) -> Type[SessionEntityTypesTransport]: - """Returns an appropriate transport class. - - Args: - label: The name of the desired transport. If none is - provided, then the first transport in the registry is used. - - Returns: - The transport class to use. - """ - # If a specific transport is requested, return that one. - if label: - return cls._transport_registry[label] - - # No transport is requested; return the default (that is, the first one - # in the dictionary). - return next(iter(cls._transport_registry.values())) - - -class SessionEntityTypesClient(metaclass=SessionEntityTypesClientMeta): - """Service for managing - [SessionEntityTypes][google.cloud.dialogflow.v2.SessionEntityType]. - """ - - @staticmethod - def _get_default_mtls_endpoint(api_endpoint): - """Converts api endpoint to mTLS endpoint. - - Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to - "*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively. - Args: - api_endpoint (Optional[str]): the api endpoint to convert. - Returns: - str: converted mTLS api endpoint. - """ - if not api_endpoint: - return api_endpoint - - mtls_endpoint_re = re.compile( - r"(?P[^.]+)(?P\.mtls)?(?P\.sandbox)?(?P\.googleapis\.com)?" - ) - - m = mtls_endpoint_re.match(api_endpoint) - name, mtls, sandbox, googledomain = m.groups() - if mtls or not googledomain: - return api_endpoint - - if sandbox: - return api_endpoint.replace( - "sandbox.googleapis.com", "mtls.sandbox.googleapis.com" - ) - - return api_endpoint.replace(".googleapis.com", ".mtls.googleapis.com") - - DEFAULT_ENDPOINT = "dialogflow.googleapis.com" - DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore - DEFAULT_ENDPOINT - ) - - @classmethod - def from_service_account_info(cls, info: dict, *args, **kwargs): - """Creates an instance of this client using the provided credentials - info. - - Args: - info (dict): The service account private key info. - args: Additional arguments to pass to the constructor. - kwargs: Additional arguments to pass to the constructor. - - Returns: - SessionEntityTypesClient: 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: - SessionEntityTypesClient: 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) -> SessionEntityTypesTransport: - """Returns the transport used by the client instance. - - Returns: - SessionEntityTypesTransport: The transport used by the client - instance. - """ - return self._transport - - @staticmethod - def session_entity_type_path(project: str,session: str,entity_type: str,) -> str: - """Returns a fully-qualified session_entity_type string.""" - return "projects/{project}/agent/sessions/{session}/entityTypes/{entity_type}".format(project=project, session=session, entity_type=entity_type, ) - - @staticmethod - def parse_session_entity_type_path(path: str) -> Dict[str,str]: - """Parses a session_entity_type path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/agent/sessions/(?P.+?)/entityTypes/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_billing_account_path(billing_account: str, ) -> str: - """Returns a fully-qualified billing_account string.""" - return "billingAccounts/{billing_account}".format(billing_account=billing_account, ) - - @staticmethod - def parse_common_billing_account_path(path: str) -> Dict[str,str]: - """Parse a billing_account path into its component segments.""" - m = re.match(r"^billingAccounts/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_folder_path(folder: str, ) -> str: - """Returns a fully-qualified folder string.""" - return "folders/{folder}".format(folder=folder, ) - - @staticmethod - def parse_common_folder_path(path: str) -> Dict[str,str]: - """Parse a folder path into its component segments.""" - m = re.match(r"^folders/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_organization_path(organization: str, ) -> str: - """Returns a fully-qualified organization string.""" - return "organizations/{organization}".format(organization=organization, ) - - @staticmethod - def parse_common_organization_path(path: str) -> Dict[str,str]: - """Parse a organization path into its component segments.""" - m = re.match(r"^organizations/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_project_path(project: str, ) -> str: - """Returns a fully-qualified project string.""" - return "projects/{project}".format(project=project, ) - - @staticmethod - def parse_common_project_path(path: str) -> Dict[str,str]: - """Parse a project path into its component segments.""" - m = re.match(r"^projects/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_location_path(project: str, location: str, ) -> str: - """Returns a fully-qualified location string.""" - return "projects/{project}/locations/{location}".format(project=project, location=location, ) - - @staticmethod - def parse_common_location_path(path: str) -> Dict[str,str]: - """Parse a location path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)$", path) - return m.groupdict() if m else {} - - @classmethod - def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[client_options_lib.ClientOptions] = None): - """Return the API endpoint and client cert source for mutual TLS. - - The client cert source is determined in the following order: - (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the - client cert source is None. - (2) if `client_options.client_cert_source` is provided, use the provided one; if the - default client cert source exists, use the default one; otherwise the client cert - source is None. - - The API endpoint is determined in the following order: - (1) if `client_options.api_endpoint` if provided, use the provided one. - (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the - default mTLS endpoint; if the environment variable is "never", use the default API - endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise - use the default API endpoint. - - More details can be found at https://google.aip.dev/auth/4114. - - Args: - client_options (google.api_core.client_options.ClientOptions): Custom options for the - client. Only the `api_endpoint` and `client_cert_source` properties may be used - in this method. - - Returns: - Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the - client cert source to use. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If any errors happen. - """ - if client_options is None: - client_options = client_options_lib.ClientOptions() - use_client_cert = os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false") - use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") - if use_client_cert not in ("true", "false"): - raise ValueError("Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`") - if use_mtls_endpoint not in ("auto", "never", "always"): - raise MutualTLSChannelError("Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`") - - # Figure out the client cert source to use. - client_cert_source = None - if use_client_cert == "true": - if client_options.client_cert_source: - client_cert_source = client_options.client_cert_source - elif mtls.has_default_client_cert_source(): - client_cert_source = mtls.default_client_cert_source() - - # Figure out which api endpoint to use. - if client_options.api_endpoint is not None: - api_endpoint = client_options.api_endpoint - elif use_mtls_endpoint == "always" or (use_mtls_endpoint == "auto" and client_cert_source): - api_endpoint = cls.DEFAULT_MTLS_ENDPOINT - else: - api_endpoint = cls.DEFAULT_ENDPOINT - - return api_endpoint, client_cert_source - - def __init__(self, *, - credentials: Optional[ga_credentials.Credentials] = None, - transport: Optional[Union[str, SessionEntityTypesTransport]] = None, - client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the session entity types 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, SessionEntityTypesTransport]): The - transport to use. If set to None, a transport is chosen - automatically. - client_options (Optional[Union[google.api_core.client_options.ClientOptions, dict]]): 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() - client_options = cast(client_options_lib.ClientOptions, client_options) - - api_endpoint, client_cert_source_func = self.get_mtls_endpoint_and_cert_source(client_options) - - api_key_value = getattr(client_options, "api_key", None) - if api_key_value and credentials: - raise ValueError("client_options.api_key and credentials are mutually exclusive") - - # 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, SessionEntityTypesTransport): - # transport is a SessionEntityTypesTransport instance. - if credentials or client_options.credentials_file or api_key_value: - 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: - import google.auth._default # type: ignore - - if api_key_value and hasattr(google.auth._default, "get_api_key_credentials"): - credentials = google.auth._default.get_api_key_credentials(api_key_value) - - Transport = type(self).get_transport_class(transport) - self._transport = Transport( - credentials=credentials, - credentials_file=client_options.credentials_file, - host=api_endpoint, - scopes=client_options.scopes, - client_cert_source_for_mtls=client_cert_source_func, - quota_project_id=client_options.quota_project_id, - client_info=client_info, - always_use_jwt_access=True, - api_audience=client_options.api_audience, - ) - - def list_session_entity_types(self, - request: Optional[Union[session_entity_type.ListSessionEntityTypesRequest, dict]] = None, - *, - parent: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListSessionEntityTypesPager: - r"""Returns the list of all session entity types in the - specified session. - This method doesn't work with Google Assistant - integration. Contact Dialogflow support if you need to - use session entities with Google Assistant integration. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import dialogflow_v2 - - def sample_list_session_entity_types(): - # Create a client - client = dialogflow_v2.SessionEntityTypesClient() - - # Initialize request argument(s) - request = dialogflow_v2.ListSessionEntityTypesRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_session_entity_types(request=request) - - # Handle the response - for response in page_result: - print(response) - - Args: - request (Union[google.cloud.dialogflow_v2.types.ListSessionEntityTypesRequest, dict]): - The request object. The request message for - [SessionEntityTypes.ListSessionEntityTypes][google.cloud.dialogflow.v2.SessionEntityTypes.ListSessionEntityTypes]. - parent (str): - Required. The session to list all session entity types - from. Format: - ``projects//agent/sessions/`` or - ``projects//agent/environments//users// sessions/``. - If ``Environment ID`` is not specified, we assume - default 'draft' environment. If ``User ID`` is not - specified, we assume default '-' user. - - 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.session_entity_types.pagers.ListSessionEntityTypesPager: - The response message for - [SessionEntityTypes.ListSessionEntityTypes][google.cloud.dialogflow.v2.SessionEntityTypes.ListSessionEntityTypes]. - - Iterating over this object will yield results and - resolve additional pages automatically. - - """ - # Create or coerce a protobuf request object. - # Quick 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 session_entity_type.ListSessionEntityTypesRequest. - # There's no risk of modifying the input as we've already verified - # 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 - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.list_session_entity_types] - - # 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.ListSessionEntityTypesPager( - method=rpc, - request=request, - response=response, - metadata=metadata, - ) - - # Done; return the response. - return response - - def get_session_entity_type(self, - request: Optional[Union[session_entity_type.GetSessionEntityTypeRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> session_entity_type.SessionEntityType: - r"""Retrieves the specified session entity type. - This method doesn't work with Google Assistant - integration. Contact Dialogflow support if you need to - use session entities with Google Assistant integration. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import dialogflow_v2 - - def sample_get_session_entity_type(): - # Create a client - client = dialogflow_v2.SessionEntityTypesClient() - - # Initialize request argument(s) - request = dialogflow_v2.GetSessionEntityTypeRequest( - name="name_value", - ) - - # Make the request - response = client.get_session_entity_type(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.dialogflow_v2.types.GetSessionEntityTypeRequest, dict]): - The request object. The request message for - [SessionEntityTypes.GetSessionEntityType][google.cloud.dialogflow.v2.SessionEntityTypes.GetSessionEntityType]. - name (str): - Required. The name of the session entity type. Format: - ``projects//agent/sessions//entityTypes/`` - or - ``projects//agent/environments//users//sessions//entityTypes/``. - If ``Environment ID`` is not specified, we assume - default 'draft' environment. If ``User ID`` is not - specified, we assume default '-' user. - - 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.SessionEntityType: - A session represents a conversation between a Dialogflow agent and an - end-user. You can create special entities, called - session entities, during a session. Session entities - can extend or replace custom entity types and only - exist during the session that they were created for. - All session data, including session entities, is - stored by Dialogflow for 20 minutes. - - For more information, see the [session entity - guide](\ https://cloud.google.com/dialogflow/docs/entities-session). - - """ - # Create or coerce a protobuf request object. - # Quick 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 session_entity_type.GetSessionEntityTypeRequest. - # There's no risk of modifying the input as we've already verified - # 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 - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.get_session_entity_type] - - # 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_session_entity_type(self, - request: Optional[Union[gcd_session_entity_type.CreateSessionEntityTypeRequest, dict]] = None, - *, - parent: Optional[str] = None, - session_entity_type: Optional[gcd_session_entity_type.SessionEntityType] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gcd_session_entity_type.SessionEntityType: - r"""Creates a session entity type. - If the specified session entity type already exists, - overrides the session entity type. - - This method doesn't work with Google Assistant - integration. Contact Dialogflow support if you need to - use session entities with Google Assistant integration. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import dialogflow_v2 - - def sample_create_session_entity_type(): - # Create a client - client = dialogflow_v2.SessionEntityTypesClient() - - # Initialize request argument(s) - session_entity_type = dialogflow_v2.SessionEntityType() - session_entity_type.name = "name_value" - session_entity_type.entity_override_mode = "ENTITY_OVERRIDE_MODE_SUPPLEMENT" - session_entity_type.entities.value = "value_value" - session_entity_type.entities.synonyms = ['synonyms_value1', 'synonyms_value2'] - - request = dialogflow_v2.CreateSessionEntityTypeRequest( - parent="parent_value", - session_entity_type=session_entity_type, - ) - - # Make the request - response = client.create_session_entity_type(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.dialogflow_v2.types.CreateSessionEntityTypeRequest, dict]): - The request object. The request message for - [SessionEntityTypes.CreateSessionEntityType][google.cloud.dialogflow.v2.SessionEntityTypes.CreateSessionEntityType]. - parent (str): - Required. The session to create a session entity type - for. Format: - ``projects//agent/sessions/`` or - ``projects//agent/environments//users// sessions/``. - If ``Environment ID`` is not specified, we assume - default 'draft' environment. If ``User ID`` is not - specified, we assume default '-' user. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - session_entity_type (google.cloud.dialogflow_v2.types.SessionEntityType): - Required. The session entity type to - create. - - 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. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.dialogflow_v2.types.SessionEntityType: - A session represents a conversation between a Dialogflow agent and an - end-user. You can create special entities, called - session entities, during a session. Session entities - can extend or replace custom entity types and only - exist during the session that they were created for. - All session data, including session entities, is - stored by Dialogflow for 20 minutes. - - For more information, see the [session entity - guide](\ https://cloud.google.com/dialogflow/docs/entities-session). - - """ - # Create or coerce a protobuf request object. - # Quick 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, session_entity_type]) - 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_session_entity_type.CreateSessionEntityTypeRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(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: - request.session_entity_type = session_entity_type - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.create_session_entity_type] - - # 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_session_entity_type(self, - request: Optional[Union[gcd_session_entity_type.UpdateSessionEntityTypeRequest, dict]] = None, - *, - session_entity_type: Optional[gcd_session_entity_type.SessionEntityType] = None, - update_mask: Optional[field_mask_pb2.FieldMask] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gcd_session_entity_type.SessionEntityType: - r"""Updates the specified session entity type. - This method doesn't work with Google Assistant - integration. Contact Dialogflow support if you need to - use session entities with Google Assistant integration. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import dialogflow_v2 - - def sample_update_session_entity_type(): - # Create a client - client = dialogflow_v2.SessionEntityTypesClient() - - # Initialize request argument(s) - session_entity_type = dialogflow_v2.SessionEntityType() - session_entity_type.name = "name_value" - session_entity_type.entity_override_mode = "ENTITY_OVERRIDE_MODE_SUPPLEMENT" - session_entity_type.entities.value = "value_value" - session_entity_type.entities.synonyms = ['synonyms_value1', 'synonyms_value2'] - - request = dialogflow_v2.UpdateSessionEntityTypeRequest( - session_entity_type=session_entity_type, - ) - - # Make the request - response = client.update_session_entity_type(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.dialogflow_v2.types.UpdateSessionEntityTypeRequest, dict]): - The request object. The request message for - [SessionEntityTypes.UpdateSessionEntityType][google.cloud.dialogflow.v2.SessionEntityTypes.UpdateSessionEntityType]. - session_entity_type (google.cloud.dialogflow_v2.types.SessionEntityType): - Required. The session entity type to - update. - - This corresponds to the ``session_entity_type`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - update_mask (google.protobuf.field_mask_pb2.FieldMask): - Optional. 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.SessionEntityType: - A session represents a conversation between a Dialogflow agent and an - end-user. You can create special entities, called - session entities, during a session. Session entities - can extend or replace custom entity types and only - exist during the session that they were created for. - All session data, including session entities, is - stored by Dialogflow for 20 minutes. - - For more information, see the [session entity - guide](\ https://cloud.google.com/dialogflow/docs/entities-session). - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([session_entity_type, 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_session_entity_type.UpdateSessionEntityTypeRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(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: - 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_session_entity_type] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("session_entity_type.name", request.session_entity_type.name), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def delete_session_entity_type(self, - request: Optional[Union[session_entity_type.DeleteSessionEntityTypeRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> None: - r"""Deletes the specified session entity type. - This method doesn't work with Google Assistant - integration. Contact Dialogflow support if you need to - use session entities with Google Assistant integration. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import dialogflow_v2 - - def sample_delete_session_entity_type(): - # Create a client - client = dialogflow_v2.SessionEntityTypesClient() - - # Initialize request argument(s) - request = dialogflow_v2.DeleteSessionEntityTypeRequest( - name="name_value", - ) - - # Make the request - client.delete_session_entity_type(request=request) - - Args: - request (Union[google.cloud.dialogflow_v2.types.DeleteSessionEntityTypeRequest, dict]): - The request object. The request message for - [SessionEntityTypes.DeleteSessionEntityType][google.cloud.dialogflow.v2.SessionEntityTypes.DeleteSessionEntityType]. - name (str): - Required. The name of the entity type to delete. Format: - ``projects//agent/sessions//entityTypes/`` - or - ``projects//agent/environments//users//sessions//entityTypes/``. - If ``Environment ID`` is not specified, we assume - default 'draft' environment. If ``User ID`` is not - specified, we assume default '-' user. - - 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. - # Quick 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 session_entity_type.DeleteSessionEntityTypeRequest. - # There's no risk of modifying the input as we've already verified - # 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 - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.delete_session_entity_type] - - # 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 __enter__(self) -> "SessionEntityTypesClient": - return self - - def __exit__(self, type, value, traceback): - """Releases underlying transport's resources. - - .. warning:: - ONLY use as a context manager if the transport is NOT shared - with other clients! Exiting the with block will CLOSE the transport - and may cause errors in other clients! - """ - self.transport.close() - - def list_operations( - self, - request: Optional[operations_pb2.ListOperationsRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operations_pb2.ListOperationsResponse: - r"""Lists operations that match the specified filter in the request. - - Args: - request (:class:`~.operations_pb2.ListOperationsRequest`): - The request object. Request message for - `ListOperations` method. - 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: - ~.operations_pb2.ListOperationsResponse: - Response message for ``ListOperations`` method. - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = operations_pb2.ListOperationsRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._transport.list_operations, - 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 = rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - def get_operation( - self, - request: Optional[operations_pb2.GetOperationRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operations_pb2.Operation: - r"""Gets the latest state of a long-running operation. - - Args: - request (:class:`~.operations_pb2.GetOperationRequest`): - The request object. Request message for - `GetOperation` method. - 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: - ~.operations_pb2.Operation: - An ``Operation`` object. - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = operations_pb2.GetOperationRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._transport.get_operation, - 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 = rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - def cancel_operation( - self, - request: Optional[operations_pb2.CancelOperationRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> None: - r"""Starts asynchronous cancellation on a long-running operation. - - The server makes a best effort to cancel the operation, but success - is not guaranteed. If the server doesn't support this method, it returns - `google.rpc.Code.UNIMPLEMENTED`. - - Args: - request (:class:`~.operations_pb2.CancelOperationRequest`): - The request object. Request message for - `CancelOperation` method. - 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: - None - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = operations_pb2.CancelOperationRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._transport.cancel_operation, - 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. - rpc(request, retry=retry, timeout=timeout, metadata=metadata,) - - def get_location( - self, - request: Optional[locations_pb2.GetLocationRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> locations_pb2.Location: - r"""Gets information about a location. - - Args: - request (:class:`~.location_pb2.GetLocationRequest`): - The request object. Request message for - `GetLocation` method. - 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: - ~.location_pb2.Location: - Location object. - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = locations_pb2.GetLocationRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._transport.get_location, - 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 = rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - def list_locations( - self, - request: Optional[locations_pb2.ListLocationsRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> locations_pb2.ListLocationsResponse: - r"""Lists information about the supported locations for this service. - - Args: - request (:class:`~.location_pb2.ListLocationsRequest`): - The request object. Request message for - `ListLocations` method. - 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: - ~.location_pb2.ListLocationsResponse: - Response message for ``ListLocations`` method. - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = locations_pb2.ListLocationsRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._transport.list_locations, - 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 = rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) - - -__all__ = ( - "SessionEntityTypesClient", -) diff --git a/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/session_entity_types/pagers.py b/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/session_entity_types/pagers.py deleted file mode 100644 index 8b16e4663..000000000 --- a/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/session_entity_types/pagers.py +++ /dev/null @@ -1,139 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from typing import Any, AsyncIterator, Awaitable, Callable, Sequence, Tuple, Optional, Iterator - -from google.cloud.dialogflow_v2.types import session_entity_type - - -class ListSessionEntityTypesPager: - """A pager for iterating through ``list_session_entity_types`` requests. - - This class thinly wraps an initial - :class:`google.cloud.dialogflow_v2.types.ListSessionEntityTypesResponse` object, and - provides an ``__iter__`` method to iterate through its - ``session_entity_types`` field. - - If there are more pages, the ``__iter__`` method will make additional - ``ListSessionEntityTypes`` requests and continue to iterate - through the ``session_entity_types`` field on the - corresponding responses. - - All the usual :class:`google.cloud.dialogflow_v2.types.ListSessionEntityTypesResponse` - 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[..., session_entity_type.ListSessionEntityTypesResponse], - request: session_entity_type.ListSessionEntityTypesRequest, - response: session_entity_type.ListSessionEntityTypesResponse, - *, - 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.ListSessionEntityTypesRequest): - The initial request object. - response (google.cloud.dialogflow_v2.types.ListSessionEntityTypesResponse): - 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 = session_entity_type.ListSessionEntityTypesRequest(request) - self._response = response - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - def pages(self) -> Iterator[session_entity_type.ListSessionEntityTypesResponse]: - yield self._response - while self._response.next_page_token: - self._request.page_token = self._response.next_page_token - self._response = self._method(self._request, metadata=self._metadata) - yield self._response - - def __iter__(self) -> Iterator[session_entity_type.SessionEntityType]: - for page in self.pages: - yield from page.session_entity_types - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListSessionEntityTypesAsyncPager: - """A pager for iterating through ``list_session_entity_types`` requests. - - This class thinly wraps an initial - :class:`google.cloud.dialogflow_v2.types.ListSessionEntityTypesResponse` object, and - provides an ``__aiter__`` method to iterate through its - ``session_entity_types`` field. - - If there are more pages, the ``__aiter__`` method will make additional - ``ListSessionEntityTypes`` requests and continue to iterate - through the ``session_entity_types`` field on the - corresponding responses. - - All the usual :class:`google.cloud.dialogflow_v2.types.ListSessionEntityTypesResponse` - 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[session_entity_type.ListSessionEntityTypesResponse]], - request: session_entity_type.ListSessionEntityTypesRequest, - response: session_entity_type.ListSessionEntityTypesResponse, - *, - metadata: Sequence[Tuple[str, str]] = ()): - """Instantiates the pager. - - Args: - method (Callable): The method that was originally called, and - which instantiated this pager. - request (google.cloud.dialogflow_v2.types.ListSessionEntityTypesRequest): - The initial request object. - response (google.cloud.dialogflow_v2.types.ListSessionEntityTypesResponse): - 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 = session_entity_type.ListSessionEntityTypesRequest(request) - self._response = response - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - async def pages(self) -> AsyncIterator[session_entity_type.ListSessionEntityTypesResponse]: - yield self._response - while self._response.next_page_token: - self._request.page_token = self._response.next_page_token - self._response = await self._method(self._request, metadata=self._metadata) - yield self._response - def __aiter__(self) -> AsyncIterator[session_entity_type.SessionEntityType]: - async def async_generator(): - async for page in self.pages: - for response in page.session_entity_types: - yield response - - return async_generator() - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) diff --git a/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/session_entity_types/transports/__init__.py b/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/session_entity_types/transports/__init__.py deleted file mode 100644 index 6971010ce..000000000 --- a/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/session_entity_types/transports/__init__.py +++ /dev/null @@ -1,38 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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 SessionEntityTypesTransport -from .grpc import SessionEntityTypesGrpcTransport -from .grpc_asyncio import SessionEntityTypesGrpcAsyncIOTransport -from .rest import SessionEntityTypesRestTransport -from .rest import SessionEntityTypesRestInterceptor - - -# Compile a registry of transports. -_transport_registry = OrderedDict() # type: Dict[str, Type[SessionEntityTypesTransport]] -_transport_registry['grpc'] = SessionEntityTypesGrpcTransport -_transport_registry['grpc_asyncio'] = SessionEntityTypesGrpcAsyncIOTransport -_transport_registry['rest'] = SessionEntityTypesRestTransport - -__all__ = ( - 'SessionEntityTypesTransport', - 'SessionEntityTypesGrpcTransport', - 'SessionEntityTypesGrpcAsyncIOTransport', - 'SessionEntityTypesRestTransport', - 'SessionEntityTypesRestInterceptor', -) diff --git a/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/session_entity_types/transports/base.py b/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/session_entity_types/transports/base.py deleted file mode 100644 index ae995de05..000000000 --- a/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/session_entity_types/transports/base.py +++ /dev/null @@ -1,252 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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 - -from google.cloud.dialogflow_v2 import gapic_version as package_version - -import google.auth # type: ignore -import google.api_core -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import retry as retries -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 session_entity_type -from google.cloud.dialogflow_v2.types import session_entity_type as gcd_session_entity_type -from google.cloud.location import locations_pb2 # type: ignore -from google.longrunning import operations_pb2 -from google.protobuf import empty_pb2 # type: ignore - -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) - - -class SessionEntityTypesTransport(abc.ABC): - """Abstract transport class for SessionEntityTypes.""" - - 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: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - api_audience: Optional[str] = None, - **kwargs, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. - scopes (Optional[Sequence[str]]): A list of scopes. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - """ - - scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} - - # Save the scopes. - self._scopes = scopes - - # If no credentials are provided, then determine the appropriate - # defaults. - if credentials and credentials_file: - raise core_exceptions.DuplicateCredentialArgs("'credentials_file' and 'credentials' are mutually exclusive") - - if credentials_file is not None: - credentials, _ = google.auth.load_credentials_from_file( - credentials_file, - **scopes_kwargs, - quota_project_id=quota_project_id - ) - elif credentials is None: - credentials, _ = google.auth.default(**scopes_kwargs, quota_project_id=quota_project_id) - # Don't apply audience if the credentials file passed from user. - if hasattr(credentials, "with_gdch_audience"): - credentials = credentials.with_gdch_audience(api_audience if api_audience else host) - - # If the credentials are service account credentials, then always try to use self signed JWT. - if always_use_jwt_access and isinstance(credentials, service_account.Credentials) and hasattr(service_account.Credentials, "with_always_use_jwt_access"): - credentials = credentials.with_always_use_jwt_access(True) - - # Save the credentials. - self._credentials = credentials - - # Save the hostname. Default to port 443 (HTTPS) if none is specified. - if ':' not in host: - host += ':443' - self._host = host - - def _prep_wrapped_messages(self, client_info): - # Precompute the wrapped methods. - self._wrapped_methods = { - self.list_session_entity_types: gapic_v1.method.wrap_method( - self.list_session_entity_types, - default_timeout=None, - client_info=client_info, - ), - self.get_session_entity_type: gapic_v1.method.wrap_method( - self.get_session_entity_type, - default_timeout=None, - client_info=client_info, - ), - self.create_session_entity_type: gapic_v1.method.wrap_method( - self.create_session_entity_type, - default_timeout=None, - client_info=client_info, - ), - self.update_session_entity_type: gapic_v1.method.wrap_method( - self.update_session_entity_type, - default_timeout=None, - client_info=client_info, - ), - self.delete_session_entity_type: gapic_v1.method.wrap_method( - self.delete_session_entity_type, - default_timeout=None, - client_info=client_info, - ), - } - - def close(self): - """Closes resources associated with the transport. - - .. warning:: - Only call this method if the transport is NOT shared - with other clients - this may cause errors in other clients! - """ - raise NotImplementedError() - - @property - def list_session_entity_types(self) -> Callable[ - [session_entity_type.ListSessionEntityTypesRequest], - Union[ - session_entity_type.ListSessionEntityTypesResponse, - Awaitable[session_entity_type.ListSessionEntityTypesResponse] - ]]: - raise NotImplementedError() - - @property - def get_session_entity_type(self) -> Callable[ - [session_entity_type.GetSessionEntityTypeRequest], - Union[ - session_entity_type.SessionEntityType, - Awaitable[session_entity_type.SessionEntityType] - ]]: - raise NotImplementedError() - - @property - def create_session_entity_type(self) -> Callable[ - [gcd_session_entity_type.CreateSessionEntityTypeRequest], - Union[ - gcd_session_entity_type.SessionEntityType, - Awaitable[gcd_session_entity_type.SessionEntityType] - ]]: - raise NotImplementedError() - - @property - def update_session_entity_type(self) -> Callable[ - [gcd_session_entity_type.UpdateSessionEntityTypeRequest], - Union[ - gcd_session_entity_type.SessionEntityType, - Awaitable[gcd_session_entity_type.SessionEntityType] - ]]: - raise NotImplementedError() - - @property - def delete_session_entity_type(self) -> Callable[ - [session_entity_type.DeleteSessionEntityTypeRequest], - Union[ - empty_pb2.Empty, - Awaitable[empty_pb2.Empty] - ]]: - raise NotImplementedError() - - @property - def list_operations( - self, - ) -> Callable[ - [operations_pb2.ListOperationsRequest], - Union[operations_pb2.ListOperationsResponse, Awaitable[operations_pb2.ListOperationsResponse]], - ]: - raise NotImplementedError() - - @property - def get_operation( - self, - ) -> Callable[ - [operations_pb2.GetOperationRequest], - Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], - ]: - raise NotImplementedError() - - @property - def cancel_operation( - self, - ) -> Callable[ - [operations_pb2.CancelOperationRequest], - None, - ]: - raise NotImplementedError() - - @property - def get_location(self, - ) -> Callable[ - [locations_pb2.GetLocationRequest], - Union[locations_pb2.Location, Awaitable[locations_pb2.Location]], - ]: - raise NotImplementedError() - - @property - def list_locations(self, - ) -> Callable[ - [locations_pb2.ListLocationsRequest], - Union[locations_pb2.ListLocationsResponse, Awaitable[locations_pb2.ListLocationsResponse]], - ]: - raise NotImplementedError() - - @property - def kind(self) -> str: - raise NotImplementedError() - - -__all__ = ( - 'SessionEntityTypesTransport', -) diff --git a/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/session_entity_types/transports/grpc.py b/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/session_entity_types/transports/grpc.py deleted file mode 100644 index 9f1aa6d72..000000000 --- a/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/session_entity_types/transports/grpc.py +++ /dev/null @@ -1,482 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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 -from google.api_core import gapic_v1 -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_entity_type -from google.cloud.dialogflow_v2.types import session_entity_type as gcd_session_entity_type -from google.cloud.location import locations_pb2 # type: ignore -from google.longrunning import operations_pb2 -from google.protobuf import empty_pb2 # type: ignore -from .base import SessionEntityTypesTransport, DEFAULT_CLIENT_INFO - - -class SessionEntityTypesGrpcTransport(SessionEntityTypesTransport): - """gRPC backend transport for SessionEntityTypes. - - Service for managing - [SessionEntityTypes][google.cloud.dialogflow.v2.SessionEntityType]. - - 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: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - channel: Optional[grpc.Channel] = None, - api_mtls_endpoint: Optional[str] = None, - client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, - ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, - client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - api_audience: Optional[str] = None, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - This argument is ignored if ``channel`` is provided. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional(Sequence[str])): A list of scopes. This argument is - ignored if ``channel`` is provided. - channel (Optional[grpc.Channel]): A ``Channel`` instance through - which to make calls. - api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. - If provided, it overrides the ``host`` argument and tries to create - a mutual TLS channel with client SSL credentials from - ``client_cert_source`` or application default SSL credentials. - client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): - Deprecated. A callback to provide client SSL certificate bytes and - private key bytes, both in PEM format. It is ignored if - ``api_mtls_endpoint`` is None. - ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials - for the grpc channel. It is ignored if ``channel`` is provided. - client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): - A callback to provide client certificate bytes and private key bytes, - both in PEM format. It is used to configure a mutual TLS channel. It is - ignored if ``channel`` or ``ssl_channel_credentials`` is provided. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport - creation failed for any reason. - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - self._grpc_channel = None - self._ssl_channel_credentials = ssl_channel_credentials - self._stubs: Dict[str, Callable] = {} - - if api_mtls_endpoint: - warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) - if client_cert_source: - warnings.warn("client_cert_source is deprecated", DeprecationWarning) - - if channel: - # Ignore credentials if a channel was passed. - credentials = False - # If a channel was explicitly provided, set it. - self._grpc_channel = channel - self._ssl_channel_credentials = None - - else: - if api_mtls_endpoint: - host = api_mtls_endpoint - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - self._ssl_channel_credentials = SslCredentials().ssl_credentials - - else: - if client_cert_source_for_mtls and not ssl_channel_credentials: - cert, key = client_cert_source_for_mtls() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - - # The base transport sets the host, credentials and scopes - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes, - quota_project_id=quota_project_id, - client_info=client_info, - always_use_jwt_access=always_use_jwt_access, - api_audience=api_audience, - ) - - if not self._grpc_channel: - self._grpc_channel = type(self).create_channel( - self._host, - # use the credentials which are saved - credentials=self._credentials, - # Set ``credentials_file`` to ``None`` here as - # the credentials that we saved earlier should be used. - credentials_file=None, - 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: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - **kwargs) -> grpc.Channel: - """Create and return a gRPC channel object. - Args: - host (Optional[str]): The host for the channel to use. - credentials (Optional[~.Credentials]): The - authorization credentials to attach to requests. These - credentials identify this application to the service. If - none are specified, the client will attempt to ascertain - the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - kwargs (Optional[dict]): Keyword arguments, which are passed to the - channel creation. - Returns: - grpc.Channel: A gRPC channel object. - - Raises: - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - - return grpc_helpers.create_channel( - host, - credentials=credentials, - credentials_file=credentials_file, - quota_project_id=quota_project_id, - default_scopes=cls.AUTH_SCOPES, - scopes=scopes, - default_host=cls.DEFAULT_HOST, - **kwargs - ) - - @property - def grpc_channel(self) -> grpc.Channel: - """Return the channel designed to connect to this service. - """ - return self._grpc_channel - - @property - def list_session_entity_types(self) -> Callable[ - [session_entity_type.ListSessionEntityTypesRequest], - session_entity_type.ListSessionEntityTypesResponse]: - r"""Return a callable for the list session entity types method over gRPC. - - Returns the list of all session entity types in the - specified session. - This method doesn't work with Google Assistant - integration. Contact Dialogflow support if you need to - use session entities with Google Assistant integration. - - Returns: - Callable[[~.ListSessionEntityTypesRequest], - ~.ListSessionEntityTypesResponse]: - 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_session_entity_types' not in self._stubs: - self._stubs['list_session_entity_types'] = self.grpc_channel.unary_unary( - '/google.cloud.dialogflow.v2.SessionEntityTypes/ListSessionEntityTypes', - request_serializer=session_entity_type.ListSessionEntityTypesRequest.serialize, - response_deserializer=session_entity_type.ListSessionEntityTypesResponse.deserialize, - ) - return self._stubs['list_session_entity_types'] - - @property - def get_session_entity_type(self) -> Callable[ - [session_entity_type.GetSessionEntityTypeRequest], - session_entity_type.SessionEntityType]: - r"""Return a callable for the get session entity type method over gRPC. - - Retrieves the specified session entity type. - This method doesn't work with Google Assistant - integration. Contact Dialogflow support if you need to - use session entities with Google Assistant integration. - - Returns: - Callable[[~.GetSessionEntityTypeRequest], - ~.SessionEntityType]: - 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_session_entity_type' not in self._stubs: - self._stubs['get_session_entity_type'] = self.grpc_channel.unary_unary( - '/google.cloud.dialogflow.v2.SessionEntityTypes/GetSessionEntityType', - request_serializer=session_entity_type.GetSessionEntityTypeRequest.serialize, - response_deserializer=session_entity_type.SessionEntityType.deserialize, - ) - return self._stubs['get_session_entity_type'] - - @property - def create_session_entity_type(self) -> Callable[ - [gcd_session_entity_type.CreateSessionEntityTypeRequest], - gcd_session_entity_type.SessionEntityType]: - r"""Return a callable for the create session entity type method over gRPC. - - Creates a session entity type. - If the specified session entity type already exists, - overrides the session entity type. - - This method doesn't work with Google Assistant - integration. Contact Dialogflow support if you need to - use session entities with Google Assistant integration. - - Returns: - Callable[[~.CreateSessionEntityTypeRequest], - ~.SessionEntityType]: - 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_session_entity_type' not in self._stubs: - self._stubs['create_session_entity_type'] = self.grpc_channel.unary_unary( - '/google.cloud.dialogflow.v2.SessionEntityTypes/CreateSessionEntityType', - request_serializer=gcd_session_entity_type.CreateSessionEntityTypeRequest.serialize, - response_deserializer=gcd_session_entity_type.SessionEntityType.deserialize, - ) - return self._stubs['create_session_entity_type'] - - @property - def update_session_entity_type(self) -> Callable[ - [gcd_session_entity_type.UpdateSessionEntityTypeRequest], - gcd_session_entity_type.SessionEntityType]: - r"""Return a callable for the update session entity type method over gRPC. - - Updates the specified session entity type. - This method doesn't work with Google Assistant - integration. Contact Dialogflow support if you need to - use session entities with Google Assistant integration. - - Returns: - Callable[[~.UpdateSessionEntityTypeRequest], - ~.SessionEntityType]: - 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_session_entity_type' not in self._stubs: - self._stubs['update_session_entity_type'] = self.grpc_channel.unary_unary( - '/google.cloud.dialogflow.v2.SessionEntityTypes/UpdateSessionEntityType', - request_serializer=gcd_session_entity_type.UpdateSessionEntityTypeRequest.serialize, - response_deserializer=gcd_session_entity_type.SessionEntityType.deserialize, - ) - return self._stubs['update_session_entity_type'] - - @property - def delete_session_entity_type(self) -> 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. - This method doesn't work with Google Assistant - integration. Contact Dialogflow support if you need to - use session entities with Google Assistant integration. - - Returns: - Callable[[~.DeleteSessionEntityTypeRequest], - ~.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_session_entity_type' not in self._stubs: - 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_pb2.Empty.FromString, - ) - return self._stubs['delete_session_entity_type'] - - def close(self): - self.grpc_channel.close() - - @property - def cancel_operation( - self, - ) -> Callable[[operations_pb2.CancelOperationRequest], None]: - r"""Return a callable for the cancel_operation method over gRPC. - """ - # 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 "cancel_operation" not in self._stubs: - self._stubs["cancel_operation"] = self.grpc_channel.unary_unary( - "/google.longrunning.Operations/CancelOperation", - request_serializer=operations_pb2.CancelOperationRequest.SerializeToString, - response_deserializer=None, - ) - return self._stubs["cancel_operation"] - - @property - def get_operation( - self, - ) -> Callable[[operations_pb2.GetOperationRequest], operations_pb2.Operation]: - r"""Return a callable for the get_operation method over gRPC. - """ - # 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_operation" not in self._stubs: - self._stubs["get_operation"] = self.grpc_channel.unary_unary( - "/google.longrunning.Operations/GetOperation", - request_serializer=operations_pb2.GetOperationRequest.SerializeToString, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs["get_operation"] - - @property - def list_operations( - self, - ) -> Callable[[operations_pb2.ListOperationsRequest], operations_pb2.ListOperationsResponse]: - r"""Return a callable for the list_operations method over gRPC. - """ - # 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_operations" not in self._stubs: - self._stubs["list_operations"] = self.grpc_channel.unary_unary( - "/google.longrunning.Operations/ListOperations", - request_serializer=operations_pb2.ListOperationsRequest.SerializeToString, - response_deserializer=operations_pb2.ListOperationsResponse.FromString, - ) - return self._stubs["list_operations"] - - @property - def list_locations( - self, - ) -> Callable[[locations_pb2.ListLocationsRequest], locations_pb2.ListLocationsResponse]: - r"""Return a callable for the list locations method over gRPC. - """ - # 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_locations" not in self._stubs: - self._stubs["list_locations"] = self.grpc_channel.unary_unary( - "/google.cloud.location.Locations/ListLocations", - request_serializer=locations_pb2.ListLocationsRequest.SerializeToString, - response_deserializer=locations_pb2.ListLocationsResponse.FromString, - ) - return self._stubs["list_locations"] - - @property - def get_location( - self, - ) -> Callable[[locations_pb2.GetLocationRequest], locations_pb2.Location]: - r"""Return a callable for the list locations method over gRPC. - """ - # 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_location" not in self._stubs: - self._stubs["get_location"] = self.grpc_channel.unary_unary( - "/google.cloud.location.Locations/GetLocation", - request_serializer=locations_pb2.GetLocationRequest.SerializeToString, - response_deserializer=locations_pb2.Location.FromString, - ) - return self._stubs["get_location"] - - @property - def kind(self) -> str: - return "grpc" - - -__all__ = ( - 'SessionEntityTypesGrpcTransport', -) diff --git a/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/session_entity_types/transports/grpc_asyncio.py b/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/session_entity_types/transports/grpc_asyncio.py deleted file mode 100644 index 565c9b1ef..000000000 --- a/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/session_entity_types/transports/grpc_asyncio.py +++ /dev/null @@ -1,481 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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 -from google.api_core import grpc_helpers_async -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore - -import grpc # type: ignore -from grpc.experimental import aio # type: ignore - -from google.cloud.dialogflow_v2.types import session_entity_type -from google.cloud.dialogflow_v2.types import session_entity_type as gcd_session_entity_type -from google.cloud.location import locations_pb2 # type: ignore -from google.longrunning import operations_pb2 -from google.protobuf import empty_pb2 # type: ignore -from .base import SessionEntityTypesTransport, DEFAULT_CLIENT_INFO -from .grpc import SessionEntityTypesGrpcTransport - - -class SessionEntityTypesGrpcAsyncIOTransport(SessionEntityTypesTransport): - """gRPC AsyncIO backend transport for SessionEntityTypes. - - Service for managing - [SessionEntityTypes][google.cloud.dialogflow.v2.SessionEntityType]. - - 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: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - **kwargs) -> aio.Channel: - """Create and return a gRPC AsyncIO channel object. - Args: - host (Optional[str]): The host for the channel to use. - credentials (Optional[~.Credentials]): The - authorization credentials to attach to requests. These - credentials identify this application to the service. If - none are specified, the client will attempt to ascertain - the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - kwargs (Optional[dict]): Keyword arguments, which are passed to the - channel creation. - Returns: - aio.Channel: A gRPC AsyncIO channel object. - """ - - return grpc_helpers_async.create_channel( - host, - credentials=credentials, - credentials_file=credentials_file, - quota_project_id=quota_project_id, - default_scopes=cls.AUTH_SCOPES, - scopes=scopes, - default_host=cls.DEFAULT_HOST, - **kwargs - ) - - def __init__(self, *, - host: str = 'dialogflow.googleapis.com', - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - channel: Optional[aio.Channel] = None, - api_mtls_endpoint: Optional[str] = None, - client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, - ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, - client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - api_audience: Optional[str] = None, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - This argument is ignored if ``channel`` is provided. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - channel (Optional[aio.Channel]): A ``Channel`` instance through - which to make calls. - api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. - If provided, it overrides the ``host`` argument and tries to create - a mutual TLS channel with client SSL credentials from - ``client_cert_source`` or application default SSL credentials. - client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): - Deprecated. A callback to provide client SSL certificate bytes and - private key bytes, both in PEM format. It is ignored if - ``api_mtls_endpoint`` is None. - ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials - for the grpc channel. It is ignored if ``channel`` is provided. - client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): - A callback to provide client certificate bytes and private key bytes, - both in PEM format. It is used to configure a mutual TLS channel. It is - ignored if ``channel`` or ``ssl_channel_credentials`` is provided. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - - Raises: - google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport - creation failed for any reason. - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - self._grpc_channel = None - self._ssl_channel_credentials = ssl_channel_credentials - self._stubs: Dict[str, Callable] = {} - - if api_mtls_endpoint: - warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) - if client_cert_source: - warnings.warn("client_cert_source is deprecated", DeprecationWarning) - - if channel: - # Ignore credentials if a channel was passed. - credentials = False - # If a channel was explicitly provided, set it. - self._grpc_channel = channel - self._ssl_channel_credentials = None - else: - if api_mtls_endpoint: - host = api_mtls_endpoint - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - self._ssl_channel_credentials = SslCredentials().ssl_credentials - - else: - if client_cert_source_for_mtls and not ssl_channel_credentials: - cert, key = client_cert_source_for_mtls() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - - # The base transport sets the host, credentials and scopes - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes, - quota_project_id=quota_project_id, - client_info=client_info, - always_use_jwt_access=always_use_jwt_access, - api_audience=api_audience, - ) - - if not self._grpc_channel: - self._grpc_channel = type(self).create_channel( - self._host, - # use the credentials which are saved - credentials=self._credentials, - # Set ``credentials_file`` to ``None`` here as - # the credentials that we saved earlier should be used. - credentials_file=None, - 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_session_entity_types(self) -> Callable[ - [session_entity_type.ListSessionEntityTypesRequest], - Awaitable[session_entity_type.ListSessionEntityTypesResponse]]: - r"""Return a callable for the list session entity types method over gRPC. - - Returns the list of all session entity types in the - specified session. - This method doesn't work with Google Assistant - integration. Contact Dialogflow support if you need to - use session entities with Google Assistant integration. - - Returns: - Callable[[~.ListSessionEntityTypesRequest], - Awaitable[~.ListSessionEntityTypesResponse]]: - 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_session_entity_types' not in self._stubs: - self._stubs['list_session_entity_types'] = self.grpc_channel.unary_unary( - '/google.cloud.dialogflow.v2.SessionEntityTypes/ListSessionEntityTypes', - request_serializer=session_entity_type.ListSessionEntityTypesRequest.serialize, - response_deserializer=session_entity_type.ListSessionEntityTypesResponse.deserialize, - ) - return self._stubs['list_session_entity_types'] - - @property - def get_session_entity_type(self) -> Callable[ - [session_entity_type.GetSessionEntityTypeRequest], - Awaitable[session_entity_type.SessionEntityType]]: - r"""Return a callable for the get session entity type method over gRPC. - - Retrieves the specified session entity type. - This method doesn't work with Google Assistant - integration. Contact Dialogflow support if you need to - use session entities with Google Assistant integration. - - Returns: - Callable[[~.GetSessionEntityTypeRequest], - Awaitable[~.SessionEntityType]]: - 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_session_entity_type' not in self._stubs: - self._stubs['get_session_entity_type'] = self.grpc_channel.unary_unary( - '/google.cloud.dialogflow.v2.SessionEntityTypes/GetSessionEntityType', - request_serializer=session_entity_type.GetSessionEntityTypeRequest.serialize, - response_deserializer=session_entity_type.SessionEntityType.deserialize, - ) - return self._stubs['get_session_entity_type'] - - @property - def create_session_entity_type(self) -> Callable[ - [gcd_session_entity_type.CreateSessionEntityTypeRequest], - Awaitable[gcd_session_entity_type.SessionEntityType]]: - r"""Return a callable for the create session entity type method over gRPC. - - Creates a session entity type. - If the specified session entity type already exists, - overrides the session entity type. - - This method doesn't work with Google Assistant - integration. Contact Dialogflow support if you need to - use session entities with Google Assistant integration. - - Returns: - Callable[[~.CreateSessionEntityTypeRequest], - Awaitable[~.SessionEntityType]]: - 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_session_entity_type' not in self._stubs: - self._stubs['create_session_entity_type'] = self.grpc_channel.unary_unary( - '/google.cloud.dialogflow.v2.SessionEntityTypes/CreateSessionEntityType', - request_serializer=gcd_session_entity_type.CreateSessionEntityTypeRequest.serialize, - response_deserializer=gcd_session_entity_type.SessionEntityType.deserialize, - ) - return self._stubs['create_session_entity_type'] - - @property - def update_session_entity_type(self) -> Callable[ - [gcd_session_entity_type.UpdateSessionEntityTypeRequest], - Awaitable[gcd_session_entity_type.SessionEntityType]]: - r"""Return a callable for the update session entity type method over gRPC. - - Updates the specified session entity type. - This method doesn't work with Google Assistant - integration. Contact Dialogflow support if you need to - use session entities with Google Assistant integration. - - Returns: - Callable[[~.UpdateSessionEntityTypeRequest], - Awaitable[~.SessionEntityType]]: - 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_session_entity_type' not in self._stubs: - self._stubs['update_session_entity_type'] = self.grpc_channel.unary_unary( - '/google.cloud.dialogflow.v2.SessionEntityTypes/UpdateSessionEntityType', - request_serializer=gcd_session_entity_type.UpdateSessionEntityTypeRequest.serialize, - response_deserializer=gcd_session_entity_type.SessionEntityType.deserialize, - ) - return self._stubs['update_session_entity_type'] - - @property - def delete_session_entity_type(self) -> Callable[ - [session_entity_type.DeleteSessionEntityTypeRequest], - Awaitable[empty_pb2.Empty]]: - r"""Return a callable for the delete session entity type method over gRPC. - - Deletes the specified session entity type. - This method doesn't work with Google Assistant - integration. Contact Dialogflow support if you need to - use session entities with Google Assistant integration. - - Returns: - Callable[[~.DeleteSessionEntityTypeRequest], - 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_session_entity_type' not in self._stubs: - 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_pb2.Empty.FromString, - ) - return self._stubs['delete_session_entity_type'] - - def close(self): - return self.grpc_channel.close() - - @property - def cancel_operation( - self, - ) -> Callable[[operations_pb2.CancelOperationRequest], None]: - r"""Return a callable for the cancel_operation method over gRPC. - """ - # 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 "cancel_operation" not in self._stubs: - self._stubs["cancel_operation"] = self.grpc_channel.unary_unary( - "/google.longrunning.Operations/CancelOperation", - request_serializer=operations_pb2.CancelOperationRequest.SerializeToString, - response_deserializer=None, - ) - return self._stubs["cancel_operation"] - - @property - def get_operation( - self, - ) -> Callable[[operations_pb2.GetOperationRequest], operations_pb2.Operation]: - r"""Return a callable for the get_operation method over gRPC. - """ - # 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_operation" not in self._stubs: - self._stubs["get_operation"] = self.grpc_channel.unary_unary( - "/google.longrunning.Operations/GetOperation", - request_serializer=operations_pb2.GetOperationRequest.SerializeToString, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs["get_operation"] - - @property - def list_operations( - self, - ) -> Callable[[operations_pb2.ListOperationsRequest], operations_pb2.ListOperationsResponse]: - r"""Return a callable for the list_operations method over gRPC. - """ - # 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_operations" not in self._stubs: - self._stubs["list_operations"] = self.grpc_channel.unary_unary( - "/google.longrunning.Operations/ListOperations", - request_serializer=operations_pb2.ListOperationsRequest.SerializeToString, - response_deserializer=operations_pb2.ListOperationsResponse.FromString, - ) - return self._stubs["list_operations"] - - @property - def list_locations( - self, - ) -> Callable[[locations_pb2.ListLocationsRequest], locations_pb2.ListLocationsResponse]: - r"""Return a callable for the list locations method over gRPC. - """ - # 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_locations" not in self._stubs: - self._stubs["list_locations"] = self.grpc_channel.unary_unary( - "/google.cloud.location.Locations/ListLocations", - request_serializer=locations_pb2.ListLocationsRequest.SerializeToString, - response_deserializer=locations_pb2.ListLocationsResponse.FromString, - ) - return self._stubs["list_locations"] - - @property - def get_location( - self, - ) -> Callable[[locations_pb2.GetLocationRequest], locations_pb2.Location]: - r"""Return a callable for the list locations method over gRPC. - """ - # 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_location" not in self._stubs: - self._stubs["get_location"] = self.grpc_channel.unary_unary( - "/google.cloud.location.Locations/GetLocation", - request_serializer=locations_pb2.GetLocationRequest.SerializeToString, - response_deserializer=locations_pb2.Location.FromString, - ) - return self._stubs["get_location"] - - -__all__ = ( - 'SessionEntityTypesGrpcAsyncIOTransport', -) diff --git a/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/session_entity_types/transports/rest.py b/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/session_entity_types/transports/rest.py deleted file mode 100644 index 209d24fa8..000000000 --- a/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/session_entity_types/transports/rest.py +++ /dev/null @@ -1,1265 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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 google.auth.transport.requests import AuthorizedSession # type: ignore -import json # type: ignore -import grpc # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore -from google.auth import credentials as ga_credentials # type: ignore -from google.api_core import exceptions as core_exceptions -from google.api_core import retry as retries -from google.api_core import rest_helpers -from google.api_core import rest_streaming -from google.api_core import path_template -from google.api_core import gapic_v1 - -from google.protobuf import json_format -from google.cloud.location import locations_pb2 # type: ignore -from google.longrunning import operations_pb2 -from requests import __version__ as requests_version -import dataclasses -import re -from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union -import warnings - -try: - OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] -except AttributeError: # pragma: NO COVER - OptionalRetry = Union[retries.Retry, object] # 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 # type: ignore - -from .base import SessionEntityTypesTransport, DEFAULT_CLIENT_INFO as BASE_DEFAULT_CLIENT_INFO - - -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=BASE_DEFAULT_CLIENT_INFO.gapic_version, - grpc_version=None, - rest_version=requests_version, -) - - -class SessionEntityTypesRestInterceptor: - """Interceptor for SessionEntityTypes. - - Interceptors are used to manipulate requests, request metadata, and responses - in arbitrary ways. - Example use cases include: - * Logging - * Verifying requests according to service or custom semantics - * Stripping extraneous information from responses - - These use cases and more can be enabled by injecting an - instance of a custom subclass when constructing the SessionEntityTypesRestTransport. - - .. code-block:: python - class MyCustomSessionEntityTypesInterceptor(SessionEntityTypesRestInterceptor): - def pre_create_session_entity_type(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_create_session_entity_type(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_delete_session_entity_type(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def pre_get_session_entity_type(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_get_session_entity_type(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_list_session_entity_types(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_list_session_entity_types(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_update_session_entity_type(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_update_session_entity_type(self, response): - logging.log(f"Received response: {response}") - return response - - transport = SessionEntityTypesRestTransport(interceptor=MyCustomSessionEntityTypesInterceptor()) - client = SessionEntityTypesClient(transport=transport) - - - """ - def pre_create_session_entity_type(self, request: gcd_session_entity_type.CreateSessionEntityTypeRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[gcd_session_entity_type.CreateSessionEntityTypeRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for create_session_entity_type - - Override in a subclass to manipulate the request or metadata - before they are sent to the SessionEntityTypes server. - """ - return request, metadata - - def post_create_session_entity_type(self, response: gcd_session_entity_type.SessionEntityType) -> gcd_session_entity_type.SessionEntityType: - """Post-rpc interceptor for create_session_entity_type - - Override in a subclass to manipulate the response - after it is returned by the SessionEntityTypes server but before - it is returned to user code. - """ - return response - def pre_delete_session_entity_type(self, request: session_entity_type.DeleteSessionEntityTypeRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[session_entity_type.DeleteSessionEntityTypeRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for delete_session_entity_type - - Override in a subclass to manipulate the request or metadata - before they are sent to the SessionEntityTypes server. - """ - return request, metadata - - def pre_get_session_entity_type(self, request: session_entity_type.GetSessionEntityTypeRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[session_entity_type.GetSessionEntityTypeRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for get_session_entity_type - - Override in a subclass to manipulate the request or metadata - before they are sent to the SessionEntityTypes server. - """ - return request, metadata - - def post_get_session_entity_type(self, response: session_entity_type.SessionEntityType) -> session_entity_type.SessionEntityType: - """Post-rpc interceptor for get_session_entity_type - - Override in a subclass to manipulate the response - after it is returned by the SessionEntityTypes server but before - it is returned to user code. - """ - return response - def pre_list_session_entity_types(self, request: session_entity_type.ListSessionEntityTypesRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[session_entity_type.ListSessionEntityTypesRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for list_session_entity_types - - Override in a subclass to manipulate the request or metadata - before they are sent to the SessionEntityTypes server. - """ - return request, metadata - - def post_list_session_entity_types(self, response: session_entity_type.ListSessionEntityTypesResponse) -> session_entity_type.ListSessionEntityTypesResponse: - """Post-rpc interceptor for list_session_entity_types - - Override in a subclass to manipulate the response - after it is returned by the SessionEntityTypes server but before - it is returned to user code. - """ - return response - def pre_update_session_entity_type(self, request: gcd_session_entity_type.UpdateSessionEntityTypeRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[gcd_session_entity_type.UpdateSessionEntityTypeRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for update_session_entity_type - - Override in a subclass to manipulate the request or metadata - before they are sent to the SessionEntityTypes server. - """ - return request, metadata - - def post_update_session_entity_type(self, response: gcd_session_entity_type.SessionEntityType) -> gcd_session_entity_type.SessionEntityType: - """Post-rpc interceptor for update_session_entity_type - - Override in a subclass to manipulate the response - after it is returned by the SessionEntityTypes server but before - it is returned to user code. - """ - return response - - def pre_get_location( - self, request: locations_pb2.GetLocationRequest, metadata: Sequence[Tuple[str, str]] - ) -> Tuple[locations_pb2.GetLocationRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for get_location - - Override in a subclass to manipulate the request or metadata - before they are sent to the SessionEntityTypes server. - """ - return request, metadata - - def post_get_location( - self, response: locations_pb2.Location - ) -> locations_pb2.Location: - """Post-rpc interceptor for get_location - - Override in a subclass to manipulate the response - after it is returned by the SessionEntityTypes server but before - it is returned to user code. - """ - return response - def pre_list_locations( - self, request: locations_pb2.ListLocationsRequest, metadata: Sequence[Tuple[str, str]] - ) -> Tuple[locations_pb2.ListLocationsRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for list_locations - - Override in a subclass to manipulate the request or metadata - before they are sent to the SessionEntityTypes server. - """ - return request, metadata - - def post_list_locations( - self, response: locations_pb2.ListLocationsResponse - ) -> locations_pb2.ListLocationsResponse: - """Post-rpc interceptor for list_locations - - Override in a subclass to manipulate the response - after it is returned by the SessionEntityTypes server but before - it is returned to user code. - """ - return response - def pre_cancel_operation( - self, request: operations_pb2.CancelOperationRequest, metadata: Sequence[Tuple[str, str]] - ) -> Tuple[operations_pb2.CancelOperationRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for cancel_operation - - Override in a subclass to manipulate the request or metadata - before they are sent to the SessionEntityTypes server. - """ - return request, metadata - - def post_cancel_operation( - self, response: None - ) -> None: - """Post-rpc interceptor for cancel_operation - - Override in a subclass to manipulate the response - after it is returned by the SessionEntityTypes server but before - it is returned to user code. - """ - return response - def pre_get_operation( - self, request: operations_pb2.GetOperationRequest, metadata: Sequence[Tuple[str, str]] - ) -> Tuple[operations_pb2.GetOperationRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for get_operation - - Override in a subclass to manipulate the request or metadata - before they are sent to the SessionEntityTypes server. - """ - return request, metadata - - def post_get_operation( - self, response: operations_pb2.Operation - ) -> operations_pb2.Operation: - """Post-rpc interceptor for get_operation - - Override in a subclass to manipulate the response - after it is returned by the SessionEntityTypes server but before - it is returned to user code. - """ - return response - def pre_list_operations( - self, request: operations_pb2.ListOperationsRequest, metadata: Sequence[Tuple[str, str]] - ) -> Tuple[operations_pb2.ListOperationsRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for list_operations - - Override in a subclass to manipulate the request or metadata - before they are sent to the SessionEntityTypes server. - """ - return request, metadata - - def post_list_operations( - self, response: operations_pb2.ListOperationsResponse - ) -> operations_pb2.ListOperationsResponse: - """Post-rpc interceptor for list_operations - - Override in a subclass to manipulate the response - after it is returned by the SessionEntityTypes server but before - it is returned to user code. - """ - return response - - -@dataclasses.dataclass -class SessionEntityTypesRestStub: - _session: AuthorizedSession - _host: str - _interceptor: SessionEntityTypesRestInterceptor - - -class SessionEntityTypesRestTransport(SessionEntityTypesTransport): - """REST backend transport for SessionEntityTypes. - - Service for managing - [SessionEntityTypes][google.cloud.dialogflow.v2.SessionEntityType]. - - 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 JSON representations of protocol buffers over HTTP/1.1 - - """ - - def __init__(self, *, - host: str = 'dialogflow.googleapis.com', - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - client_cert_source_for_mtls: Optional[Callable[[ - ], Tuple[bytes, bytes]]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - url_scheme: str = 'https', - interceptor: Optional[SessionEntityTypesRestInterceptor] = None, - api_audience: Optional[str] = None, - ) -> 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 ignored if ``channel`` is provided. - scopes (Optional(Sequence[str])): A list of scopes. This argument is - ignored if ``channel`` is provided. - client_cert_source_for_mtls (Callable[[], Tuple[bytes, bytes]]): Client - certificate to configure mutual TLS HTTP channel. It is ignored - if ``channel`` is provided. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you are developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - url_scheme: the protocol scheme for the API endpoint. Normally - "https", but for testing or local servers, - "http" can be specified. - """ - # Run the base constructor - # TODO(yon-mg): resolve other ctor params i.e. scopes, quota, etc. - # TODO: When custom host (api_endpoint) is set, `scopes` must *also* be set on the - # credentials object - maybe_url_match = re.match("^(?Phttp(?:s)?://)?(?P.*)$", host) - if maybe_url_match is None: - raise ValueError(f"Unexpected hostname structure: {host}") # pragma: NO COVER - - url_match_items = maybe_url_match.groupdict() - - host = f"{url_scheme}://{host}" if not url_match_items["scheme"] else host - - super().__init__( - host=host, - credentials=credentials, - client_info=client_info, - always_use_jwt_access=always_use_jwt_access, - api_audience=api_audience - ) - self._session = AuthorizedSession( - self._credentials, default_host=self.DEFAULT_HOST) - if client_cert_source_for_mtls: - self._session.configure_mtls_channel(client_cert_source_for_mtls) - self._interceptor = interceptor or SessionEntityTypesRestInterceptor() - self._prep_wrapped_messages(client_info) - - class _CreateSessionEntityType(SessionEntityTypesRestStub): - def __hash__(self): - return hash("CreateSessionEntityType") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: gcd_session_entity_type.CreateSessionEntityTypeRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> gcd_session_entity_type.SessionEntityType: - r"""Call the create session entity - type method over HTTP. - - Args: - request (~.gcd_session_entity_type.CreateSessionEntityTypeRequest): - The request object. The request message for - [SessionEntityTypes.CreateSessionEntityType][google.cloud.dialogflow.v2.SessionEntityTypes.CreateSessionEntityType]. - 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: - ~.gcd_session_entity_type.SessionEntityType: - A session represents a conversation between a Dialogflow - agent and an end-user. You can create special entities, - called session entities, during a session. Session - entities can extend or replace custom entity types and - only exist during the session that they were created - for. All session data, including session entities, is - stored by Dialogflow for 20 minutes. - - For more information, see the `session entity - guide `__. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'post', - 'uri': '/v2/{parent=projects/*/agent/sessions/*}/entityTypes', - 'body': 'session_entity_type', - }, -{ - 'method': 'post', - 'uri': '/v2/{parent=projects/*/agent/environments/*/users/*/sessions/*}/entityTypes', - 'body': 'session_entity_type', - }, -{ - 'method': 'post', - 'uri': '/v2/{parent=projects/*/locations/*/agent/sessions/*}/entityTypes', - 'body': 'session_entity_type', - }, -{ - 'method': 'post', - 'uri': '/v2/{parent=projects/*/locations/*/agent/environments/*/users/*/sessions/*}/entityTypes', - 'body': 'session_entity_type', - }, - ] - request, metadata = self._interceptor.pre_create_session_entity_type(request, metadata) - pb_request = gcd_session_entity_type.CreateSessionEntityTypeRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request['body'], - including_default_value_fields=False, - use_integers_for_enums=True - ) - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - including_default_value_fields=False, - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = gcd_session_entity_type.SessionEntityType() - pb_resp = gcd_session_entity_type.SessionEntityType.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_create_session_entity_type(resp) - return resp - - class _DeleteSessionEntityType(SessionEntityTypesRestStub): - def __hash__(self): - return hash("DeleteSessionEntityType") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: session_entity_type.DeleteSessionEntityTypeRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ): - r"""Call the delete session entity - type method over HTTP. - - Args: - request (~.session_entity_type.DeleteSessionEntityTypeRequest): - The request object. The request message for - [SessionEntityTypes.DeleteSessionEntityType][google.cloud.dialogflow.v2.SessionEntityTypes.DeleteSessionEntityType]. - 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. - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'delete', - 'uri': '/v2/{name=projects/*/agent/sessions/*/entityTypes/*}', - }, -{ - 'method': 'delete', - 'uri': '/v2/{name=projects/*/agent/environments/*/users/*/sessions/*/entityTypes/*}', - }, -{ - 'method': 'delete', - 'uri': '/v2/{name=projects/*/locations/*/agent/sessions/*/entityTypes/*}', - }, -{ - 'method': 'delete', - 'uri': '/v2/{name=projects/*/locations/*/agent/environments/*/users/*/sessions/*/entityTypes/*}', - }, - ] - request, metadata = self._interceptor.pre_delete_session_entity_type(request, metadata) - pb_request = session_entity_type.DeleteSessionEntityTypeRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - including_default_value_fields=False, - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - class _GetSessionEntityType(SessionEntityTypesRestStub): - def __hash__(self): - return hash("GetSessionEntityType") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: session_entity_type.GetSessionEntityTypeRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> session_entity_type.SessionEntityType: - r"""Call the get session entity type method over HTTP. - - Args: - request (~.session_entity_type.GetSessionEntityTypeRequest): - The request object. The request message for - [SessionEntityTypes.GetSessionEntityType][google.cloud.dialogflow.v2.SessionEntityTypes.GetSessionEntityType]. - 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: - ~.session_entity_type.SessionEntityType: - A session represents a conversation between a Dialogflow - agent and an end-user. You can create special entities, - called session entities, during a session. Session - entities can extend or replace custom entity types and - only exist during the session that they were created - for. All session data, including session entities, is - stored by Dialogflow for 20 minutes. - - For more information, see the `session entity - guide `__. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v2/{name=projects/*/agent/sessions/*/entityTypes/*}', - }, -{ - 'method': 'get', - 'uri': '/v2/{name=projects/*/agent/environments/*/users/*/sessions/*/entityTypes/*}', - }, -{ - 'method': 'get', - 'uri': '/v2/{name=projects/*/locations/*/agent/sessions/*/entityTypes/*}', - }, -{ - 'method': 'get', - 'uri': '/v2/{name=projects/*/locations/*/agent/environments/*/users/*/sessions/*/entityTypes/*}', - }, - ] - request, metadata = self._interceptor.pre_get_session_entity_type(request, metadata) - pb_request = session_entity_type.GetSessionEntityTypeRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - including_default_value_fields=False, - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = session_entity_type.SessionEntityType() - pb_resp = session_entity_type.SessionEntityType.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_get_session_entity_type(resp) - return resp - - class _ListSessionEntityTypes(SessionEntityTypesRestStub): - def __hash__(self): - return hash("ListSessionEntityTypes") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: session_entity_type.ListSessionEntityTypesRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> session_entity_type.ListSessionEntityTypesResponse: - r"""Call the list session entity types method over HTTP. - - Args: - request (~.session_entity_type.ListSessionEntityTypesRequest): - The request object. The request message for - [SessionEntityTypes.ListSessionEntityTypes][google.cloud.dialogflow.v2.SessionEntityTypes.ListSessionEntityTypes]. - 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: - ~.session_entity_type.ListSessionEntityTypesResponse: - The response message for - [SessionEntityTypes.ListSessionEntityTypes][google.cloud.dialogflow.v2.SessionEntityTypes.ListSessionEntityTypes]. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v2/{parent=projects/*/agent/sessions/*}/entityTypes', - }, -{ - 'method': 'get', - 'uri': '/v2/{parent=projects/*/agent/environments/*/users/*/sessions/*}/entityTypes', - }, -{ - 'method': 'get', - 'uri': '/v2/{parent=projects/*/locations/*/agent/sessions/*}/entityTypes', - }, -{ - 'method': 'get', - 'uri': '/v2/{parent=projects/*/locations/*/agent/environments/*/users/*/sessions/*}/entityTypes', - }, - ] - request, metadata = self._interceptor.pre_list_session_entity_types(request, metadata) - pb_request = session_entity_type.ListSessionEntityTypesRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - including_default_value_fields=False, - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = session_entity_type.ListSessionEntityTypesResponse() - pb_resp = session_entity_type.ListSessionEntityTypesResponse.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_list_session_entity_types(resp) - return resp - - class _UpdateSessionEntityType(SessionEntityTypesRestStub): - def __hash__(self): - return hash("UpdateSessionEntityType") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: gcd_session_entity_type.UpdateSessionEntityTypeRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> gcd_session_entity_type.SessionEntityType: - r"""Call the update session entity - type method over HTTP. - - Args: - request (~.gcd_session_entity_type.UpdateSessionEntityTypeRequest): - The request object. The request message for - [SessionEntityTypes.UpdateSessionEntityType][google.cloud.dialogflow.v2.SessionEntityTypes.UpdateSessionEntityType]. - 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: - ~.gcd_session_entity_type.SessionEntityType: - A session represents a conversation between a Dialogflow - agent and an end-user. You can create special entities, - called session entities, during a session. Session - entities can extend or replace custom entity types and - only exist during the session that they were created - for. All session data, including session entities, is - stored by Dialogflow for 20 minutes. - - For more information, see the `session entity - guide `__. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'patch', - 'uri': '/v2/{session_entity_type.name=projects/*/agent/sessions/*/entityTypes/*}', - 'body': 'session_entity_type', - }, -{ - 'method': 'patch', - 'uri': '/v2/{session_entity_type.name=projects/*/agent/environments/*/users/*/sessions/*/entityTypes/*}', - 'body': 'session_entity_type', - }, -{ - 'method': 'patch', - 'uri': '/v2/{session_entity_type.name=projects/*/locations/*/agent/sessions/*/entityTypes/*}', - 'body': 'session_entity_type', - }, -{ - 'method': 'patch', - 'uri': '/v2/{session_entity_type.name=projects/*/locations/*/agent/environments/*/users/*/sessions/*/entityTypes/*}', - 'body': 'session_entity_type', - }, - ] - request, metadata = self._interceptor.pre_update_session_entity_type(request, metadata) - pb_request = gcd_session_entity_type.UpdateSessionEntityTypeRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request['body'], - including_default_value_fields=False, - use_integers_for_enums=True - ) - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - including_default_value_fields=False, - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = gcd_session_entity_type.SessionEntityType() - pb_resp = gcd_session_entity_type.SessionEntityType.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_update_session_entity_type(resp) - return resp - - @property - def create_session_entity_type(self) -> Callable[ - [gcd_session_entity_type.CreateSessionEntityTypeRequest], - gcd_session_entity_type.SessionEntityType]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._CreateSessionEntityType(self._session, self._host, self._interceptor) # type: ignore - - @property - def delete_session_entity_type(self) -> Callable[ - [session_entity_type.DeleteSessionEntityTypeRequest], - empty_pb2.Empty]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._DeleteSessionEntityType(self._session, self._host, self._interceptor) # type: ignore - - @property - def get_session_entity_type(self) -> Callable[ - [session_entity_type.GetSessionEntityTypeRequest], - session_entity_type.SessionEntityType]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._GetSessionEntityType(self._session, self._host, self._interceptor) # type: ignore - - @property - def list_session_entity_types(self) -> Callable[ - [session_entity_type.ListSessionEntityTypesRequest], - session_entity_type.ListSessionEntityTypesResponse]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._ListSessionEntityTypes(self._session, self._host, self._interceptor) # type: ignore - - @property - def update_session_entity_type(self) -> Callable[ - [gcd_session_entity_type.UpdateSessionEntityTypeRequest], - gcd_session_entity_type.SessionEntityType]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._UpdateSessionEntityType(self._session, self._host, self._interceptor) # type: ignore - - @property - def get_location(self): - return self._GetLocation(self._session, self._host, self._interceptor) # type: ignore - - class _GetLocation(SessionEntityTypesRestStub): - def __call__(self, - request: locations_pb2.GetLocationRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> locations_pb2.Location: - - r"""Call the get location method over HTTP. - - Args: - request (locations_pb2.GetLocationRequest): - The request object for GetLocation method. - 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: - locations_pb2.Location: Response from GetLocation method. - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v2/{name=projects/*/locations/*}', - }, - ] - - request, metadata = self._interceptor.pre_get_location(request, metadata) - request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode( - http_options, **request_kwargs) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json.dumps(transcoded_request['query_params'])) - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - resp = locations_pb2.Location() - resp = json_format.Parse(response.content.decode("utf-8"), resp) - resp = self._interceptor.post_get_location(resp) - return resp - - @property - def list_locations(self): - return self._ListLocations(self._session, self._host, self._interceptor) # type: ignore - - class _ListLocations(SessionEntityTypesRestStub): - def __call__(self, - request: locations_pb2.ListLocationsRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> locations_pb2.ListLocationsResponse: - - r"""Call the list locations method over HTTP. - - Args: - request (locations_pb2.ListLocationsRequest): - The request object for ListLocations method. - 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: - locations_pb2.ListLocationsResponse: Response from ListLocations method. - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v2/{name=projects/*}/locations', - }, - ] - - request, metadata = self._interceptor.pre_list_locations(request, metadata) - request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode( - http_options, **request_kwargs) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json.dumps(transcoded_request['query_params'])) - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - resp = locations_pb2.ListLocationsResponse() - resp = json_format.Parse(response.content.decode("utf-8"), resp) - resp = self._interceptor.post_list_locations(resp) - return resp - - @property - def cancel_operation(self): - return self._CancelOperation(self._session, self._host, self._interceptor) # type: ignore - - class _CancelOperation(SessionEntityTypesRestStub): - def __call__(self, - request: operations_pb2.CancelOperationRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> None: - - r"""Call the cancel operation method over HTTP. - - Args: - request (operations_pb2.CancelOperationRequest): - The request object for CancelOperation method. - 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. - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'post', - 'uri': '/v2/{name=projects/*/operations/*}:cancel', - }, -{ - 'method': 'post', - 'uri': '/v2/{name=projects/*/locations/*/operations/*}:cancel', - }, - ] - - request, metadata = self._interceptor.pre_cancel_operation(request, metadata) - request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode( - http_options, **request_kwargs) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json.dumps(transcoded_request['query_params'])) - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - return self._interceptor.post_cancel_operation(None) - - @property - def get_operation(self): - return self._GetOperation(self._session, self._host, self._interceptor) # type: ignore - - class _GetOperation(SessionEntityTypesRestStub): - def __call__(self, - request: operations_pb2.GetOperationRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> operations_pb2.Operation: - - r"""Call the get operation method over HTTP. - - Args: - request (operations_pb2.GetOperationRequest): - The request object for GetOperation method. - 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: - operations_pb2.Operation: Response from GetOperation method. - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v2/{name=projects/*/operations/*}', - }, -{ - 'method': 'get', - 'uri': '/v2/{name=projects/*/locations/*/operations/*}', - }, - ] - - request, metadata = self._interceptor.pre_get_operation(request, metadata) - request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode( - http_options, **request_kwargs) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json.dumps(transcoded_request['query_params'])) - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - resp = operations_pb2.Operation() - resp = json_format.Parse(response.content.decode("utf-8"), resp) - resp = self._interceptor.post_get_operation(resp) - return resp - - @property - def list_operations(self): - return self._ListOperations(self._session, self._host, self._interceptor) # type: ignore - - class _ListOperations(SessionEntityTypesRestStub): - def __call__(self, - request: operations_pb2.ListOperationsRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> operations_pb2.ListOperationsResponse: - - r"""Call the list operations method over HTTP. - - Args: - request (operations_pb2.ListOperationsRequest): - The request object for ListOperations method. - 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: - operations_pb2.ListOperationsResponse: Response from ListOperations method. - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v2/{name=projects/*}/operations', - }, -{ - 'method': 'get', - 'uri': '/v2/{name=projects/*/locations/*}/operations', - }, - ] - - request, metadata = self._interceptor.pre_list_operations(request, metadata) - request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode( - http_options, **request_kwargs) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json.dumps(transcoded_request['query_params'])) - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - resp = operations_pb2.ListOperationsResponse() - resp = json_format.Parse(response.content.decode("utf-8"), resp) - resp = self._interceptor.post_list_operations(resp) - return resp - - @property - def kind(self) -> str: - return "rest" - - def close(self): - self._session.close() - - -__all__=( - 'SessionEntityTypesRestTransport', -) diff --git a/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/sessions/__init__.py b/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/sessions/__init__.py deleted file mode 100644 index b1e28f0e8..000000000 --- a/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/sessions/__init__.py +++ /dev/null @@ -1,22 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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 SessionsClient -from .async_client import SessionsAsyncClient - -__all__ = ( - 'SessionsClient', - 'SessionsAsyncClient', -) diff --git a/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/sessions/async_client.py b/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/sessions/async_client.py deleted file mode 100644 index 44eaf4637..000000000 --- a/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/sessions/async_client.py +++ /dev/null @@ -1,770 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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, Mapping, MutableMapping, MutableSequence, Optional, AsyncIterable, Awaitable, AsyncIterator, Sequence, Tuple, Type, Union - -from google.cloud.dialogflow_v2 import gapic_version as package_version - -from google.api_core.client_options import ClientOptions -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import retry as retries -from google.auth import credentials as ga_credentials # type: ignore -from google.oauth2 import service_account # type: ignore - -try: - OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] -except AttributeError: # pragma: NO COVER - OptionalRetry = Union[retries.Retry, object] # 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.cloud.location import locations_pb2 # type: ignore -from google.longrunning import operations_pb2 -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 - - -class SessionsAsyncClient: - """A service used for session interactions. - - For more information, see the `API interactions - guide `__. - """ - - _client: SessionsClient - - DEFAULT_ENDPOINT = SessionsClient.DEFAULT_ENDPOINT - DEFAULT_MTLS_ENDPOINT = SessionsClient.DEFAULT_MTLS_ENDPOINT - - context_path = staticmethod(SessionsClient.context_path) - parse_context_path = staticmethod(SessionsClient.parse_context_path) - intent_path = staticmethod(SessionsClient.intent_path) - parse_intent_path = staticmethod(SessionsClient.parse_intent_path) - session_path = staticmethod(SessionsClient.session_path) - parse_session_path = staticmethod(SessionsClient.parse_session_path) - session_entity_type_path = staticmethod(SessionsClient.session_entity_type_path) - 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) - - @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: - SessionsAsyncClient: The constructed client. - """ - return SessionsClient.from_service_account_info.__func__(SessionsAsyncClient, 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: - SessionsAsyncClient: The constructed client. - """ - return SessionsClient.from_service_account_file.__func__(SessionsAsyncClient, filename, *args, **kwargs) # type: ignore - - from_service_account_json = from_service_account_file - - @classmethod - def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[ClientOptions] = None): - """Return the API endpoint and client cert source for mutual TLS. - - The client cert source is determined in the following order: - (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the - client cert source is None. - (2) if `client_options.client_cert_source` is provided, use the provided one; if the - default client cert source exists, use the default one; otherwise the client cert - source is None. - - The API endpoint is determined in the following order: - (1) if `client_options.api_endpoint` if provided, use the provided one. - (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the - default mTLS endpoint; if the environment variable is "never", use the default API - endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise - use the default API endpoint. - - More details can be found at https://google.aip.dev/auth/4114. - - Args: - client_options (google.api_core.client_options.ClientOptions): Custom options for the - client. Only the `api_endpoint` and `client_cert_source` properties may be used - in this method. - - Returns: - Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the - client cert source to use. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If any errors happen. - """ - return SessionsClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore - - @property - def transport(self) -> SessionsTransport: - """Returns the transport used by the client instance. - - Returns: - SessionsTransport: The transport used by the client instance. - """ - return self._client.transport - - get_transport_class = functools.partial(type(SessionsClient).get_transport_class, type(SessionsClient)) - - def __init__(self, *, - credentials: Optional[ga_credentials.Credentials] = None, - transport: Union[str, SessionsTransport] = "grpc_asyncio", - client_options: Optional[ClientOptions] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the sessions 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, ~.SessionsTransport]): 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 = SessionsClient( - credentials=credentials, - transport=transport, - client_options=client_options, - client_info=client_info, - - ) - - async def detect_intent(self, - request: Optional[Union[gcd_session.DetectIntentRequest, dict]] = None, - *, - session: Optional[str] = None, - query_input: Optional[gcd_session.QueryInput] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gcd_session.DetectIntentResponse: - r"""Processes a natural language query and returns structured, - actionable data as a result. This method is not idempotent, - because it may cause contexts and session entity types to be - updated, which in turn might affect results of future queries. - - If you might use `Agent - Assist `__ or - other CCAI products now or in the future, consider using - [AnalyzeContent][google.cloud.dialogflow.v2.Participants.AnalyzeContent] - instead of ``DetectIntent``. ``AnalyzeContent`` has additional - functionality for Agent Assist and other CCAI products. - - Note: Always use agent versions for production traffic. See - `Versions and - environments `__. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import dialogflow_v2 - - async def sample_detect_intent(): - # Create a client - client = dialogflow_v2.SessionsAsyncClient() - - # Initialize request argument(s) - request = dialogflow_v2.DetectIntentRequest( - session="session_value", - ) - - # Make the request - response = await client.detect_intent(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.dialogflow_v2.types.DetectIntentRequest, dict]]): - The request object. The request to detect user's intent. - session (:class:`str`): - Required. The name of the session this query is sent to. - Format: - ``projects//agent/sessions/``, - or - ``projects//agent/environments//users//sessions/``. - If ``Environment ID`` is not specified, we assume - default 'draft' environment (``Environment ID`` might be - referred to as environment name at some places). If - ``User ID`` is not specified, we are using "-". It's up - to the API caller to choose an appropriate - ``Session ID`` and ``User Id``. They can be a random - number or some type of user and session identifiers - (preferably hashed). The length of the ``Session ID`` - and ``User ID`` must not exceed 36 characters. - - For more information, see the `API interactions - guide `__. - - Note: Always use agent versions for production traffic. - See `Versions and - environments `__. - - This corresponds to the ``session`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - query_input (:class:`google.cloud.dialogflow_v2.types.QueryInput`): - Required. The input specification. It - can be set to: - 1. an audio config - which instructs the speech - recognizer how to process the speech - audio, - 2. a conversational query in the form - of text, or - 3. an event that specifies which intent - to trigger. - - 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. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.dialogflow_v2.types.DetectIntentResponse: - The message returned from the - DetectIntent method. - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([session, query_input]) - 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_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: - request.query_input = query_input - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.detect_intent, - default_retry=retries.Retry( -initial=0.1,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( - core_exceptions.ServiceUnavailable, - ), - deadline=220.0, - ), - default_timeout=220.0, - 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(( - ("session", request.session), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def streaming_detect_intent(self, - requests: Optional[AsyncIterator[session.StreamingDetectIntentRequest]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> Awaitable[AsyncIterable[session.StreamingDetectIntentResponse]]: - r"""Processes a natural language query in audio format in a - streaming fashion and returns structured, actionable data as a - result. This method is only available via the gRPC API (not - REST). - - If you might use `Agent - Assist `__ or - other CCAI products now or in the future, consider using - [StreamingAnalyzeContent][google.cloud.dialogflow.v2.Participants.StreamingAnalyzeContent] - instead of ``StreamingDetectIntent``. - ``StreamingAnalyzeContent`` has additional functionality for - Agent Assist and other CCAI products. - - Note: Always use agent versions for production traffic. See - `Versions and - environments `__. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import dialogflow_v2 - - async def sample_streaming_detect_intent(): - # Create a client - client = dialogflow_v2.SessionsAsyncClient() - - # Initialize request argument(s) - request = dialogflow_v2.StreamingDetectIntentRequest( - session="session_value", - ) - - # This method expects an iterator which contains - # 'dialogflow_v2.StreamingDetectIntentRequest' objects - # Here we create a generator that yields a single `request` for - # demonstrative purposes. - requests = [request] - - def request_generator(): - for request in requests: - yield request - - # Make the request - stream = await client.streaming_detect_intent(requests=request_generator()) - - # Handle the response - async for response in stream: - print(response) - - Args: - requests (AsyncIterator[`google.cloud.dialogflow_v2.types.StreamingDetectIntentRequest`]): - The request object AsyncIterator. The top-level message sent by the client to the - [Sessions.StreamingDetectIntent][google.cloud.dialogflow.v2.Sessions.StreamingDetectIntent] - method. - - Multiple request messages should be sent in order: - - 1. The first message must contain - [session][google.cloud.dialogflow.v2.StreamingDetectIntentRequest.session], - [query_input][google.cloud.dialogflow.v2.StreamingDetectIntentRequest.query_input] - plus optionally - [query_params][google.cloud.dialogflow.v2.StreamingDetectIntentRequest.query_params]. - If the client wants to receive an audio response, it - should also contain - [output_audio_config][google.cloud.dialogflow.v2.StreamingDetectIntentRequest.output_audio_config]. - The message must not contain - [input_audio][google.cloud.dialogflow.v2.StreamingDetectIntentRequest.input_audio]. - - 2. If - [query_input][google.cloud.dialogflow.v2.StreamingDetectIntentRequest.query_input] - was set to - [query_input.audio_config][google.cloud.dialogflow.v2.InputAudioConfig], - all subsequent messages must contain - [input_audio][google.cloud.dialogflow.v2.StreamingDetectIntentRequest.input_audio] - to continue with Speech recognition. If you decide to - rather detect an intent from text input after you - already started Speech recognition, please send a - message with - [query_input.text][google.cloud.dialogflow.v2.QueryInput.text]. - - However, note that: - - - Dialogflow will bill you for the audio duration so - far. - - Dialogflow discards all Speech recognition results - in favor of the input text. - - Dialogflow will use the language code from the - first message. - - After you sent all input, you must half-close or abort - the request stream. - 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: - AsyncIterable[google.cloud.dialogflow_v2.types.StreamingDetectIntentResponse]: - The top-level message returned from the - StreamingDetectIntent method. - - Multiple response messages can be returned in order: - - 1. If the StreamingDetectIntentRequest.input_audio - field was set, the recognition_result field is - populated for one or more messages. See the - [StreamingRecognitionResult][google.cloud.dialogflow.v2.StreamingRecognitionResult] - message for details about the result message - sequence. - 2. The next message contains response_id, - query_result and optionally webhook_status if a - WebHook was called. - - """ - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.streaming_detect_intent, - default_timeout=220.0, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Send the request. - response = rpc( - requests, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def list_operations( - self, - request: Optional[operations_pb2.ListOperationsRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operations_pb2.ListOperationsResponse: - r"""Lists operations that match the specified filter in the request. - - Args: - request (:class:`~.operations_pb2.ListOperationsRequest`): - The request object. Request message for - `ListOperations` method. - 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: - ~.operations_pb2.ListOperationsResponse: - Response message for ``ListOperations`` method. - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = operations_pb2.ListOperationsRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._client._transport.list_operations, - 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 get_operation( - self, - request: Optional[operations_pb2.GetOperationRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operations_pb2.Operation: - r"""Gets the latest state of a long-running operation. - - Args: - request (:class:`~.operations_pb2.GetOperationRequest`): - The request object. Request message for - `GetOperation` method. - 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: - ~.operations_pb2.Operation: - An ``Operation`` object. - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = operations_pb2.GetOperationRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._client._transport.get_operation, - 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 cancel_operation( - self, - request: Optional[operations_pb2.CancelOperationRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> None: - r"""Starts asynchronous cancellation on a long-running operation. - - The server makes a best effort to cancel the operation, but success - is not guaranteed. If the server doesn't support this method, it returns - `google.rpc.Code.UNIMPLEMENTED`. - - Args: - request (:class:`~.operations_pb2.CancelOperationRequest`): - The request object. Request message for - `CancelOperation` method. - 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: - None - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = operations_pb2.CancelOperationRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._client._transport.cancel_operation, - 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_location( - self, - request: Optional[locations_pb2.GetLocationRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> locations_pb2.Location: - r"""Gets information about a location. - - Args: - request (:class:`~.location_pb2.GetLocationRequest`): - The request object. Request message for - `GetLocation` method. - 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: - ~.location_pb2.Location: - Location object. - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = locations_pb2.GetLocationRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._client._transport.get_location, - 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 list_locations( - self, - request: Optional[locations_pb2.ListLocationsRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> locations_pb2.ListLocationsResponse: - r"""Lists information about the supported locations for this service. - - Args: - request (:class:`~.location_pb2.ListLocationsRequest`): - The request object. Request message for - `ListLocations` method. - 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: - ~.location_pb2.ListLocationsResponse: - Response message for ``ListLocations`` method. - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = locations_pb2.ListLocationsRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._client._transport.list_locations, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("name", request.name),)), - ) - - # Send the request. - response = await rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - async def __aenter__(self): - return self - - async def __aexit__(self, exc_type, exc, tb): - await self.transport.close() - -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) - - -__all__ = ( - "SessionsAsyncClient", -) diff --git a/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/sessions/client.py b/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/sessions/client.py deleted file mode 100644 index 875676cdd..000000000 --- a/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/sessions/client.py +++ /dev/null @@ -1,986 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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 os -import re -from typing import Dict, Mapping, MutableMapping, MutableSequence, Optional, Iterable, Iterator, Sequence, Tuple, Type, Union, cast - -from google.cloud.dialogflow_v2 import gapic_version as package_version - -from google.api_core import client_options as client_options_lib -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import retry as retries -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 - -try: - OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] -except AttributeError: # pragma: NO COVER - OptionalRetry = Union[retries.Retry, object] # 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.cloud.location import locations_pb2 # type: ignore -from google.longrunning import operations_pb2 -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 -from .transports.rest import SessionsRestTransport - - -class SessionsClientMeta(type): - """Metaclass for the Sessions 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[SessionsTransport]] - _transport_registry["grpc"] = SessionsGrpcTransport - _transport_registry["grpc_asyncio"] = SessionsGrpcAsyncIOTransport - _transport_registry["rest"] = SessionsRestTransport - - def get_transport_class(cls, - label: Optional[str] = None, - ) -> Type[SessionsTransport]: - """Returns an appropriate transport class. - - Args: - label: The name of the desired transport. If none is - provided, then the first transport in the registry is used. - - Returns: - The transport class to use. - """ - # If a specific transport is requested, return that one. - if label: - return cls._transport_registry[label] - - # No transport is requested; return the default (that is, the first one - # in the dictionary). - return next(iter(cls._transport_registry.values())) - - -class SessionsClient(metaclass=SessionsClientMeta): - """A service used for session interactions. - - For more information, see the `API interactions - guide `__. - """ - - @staticmethod - def _get_default_mtls_endpoint(api_endpoint): - """Converts api endpoint to mTLS endpoint. - - Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to - "*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively. - Args: - api_endpoint (Optional[str]): the api endpoint to convert. - Returns: - str: converted mTLS api endpoint. - """ - if not api_endpoint: - return api_endpoint - - mtls_endpoint_re = re.compile( - r"(?P[^.]+)(?P\.mtls)?(?P\.sandbox)?(?P\.googleapis\.com)?" - ) - - m = mtls_endpoint_re.match(api_endpoint) - name, mtls, sandbox, googledomain = m.groups() - if mtls or not googledomain: - return api_endpoint - - if sandbox: - return api_endpoint.replace( - "sandbox.googleapis.com", "mtls.sandbox.googleapis.com" - ) - - return api_endpoint.replace(".googleapis.com", ".mtls.googleapis.com") - - DEFAULT_ENDPOINT = "dialogflow.googleapis.com" - DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore - DEFAULT_ENDPOINT - ) - - @classmethod - def from_service_account_info(cls, info: dict, *args, **kwargs): - """Creates an instance of this client using the provided credentials - info. - - Args: - info (dict): The service account private key info. - args: Additional arguments to pass to the constructor. - kwargs: Additional arguments to pass to the constructor. - - Returns: - SessionsClient: 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: - SessionsClient: 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) -> SessionsTransport: - """Returns the transport used by the client instance. - - Returns: - SessionsTransport: The transport used by the client - instance. - """ - return self._transport - - @staticmethod - def context_path(project: str,session: str,context: str,) -> str: - """Returns a fully-qualified context string.""" - return "projects/{project}/agent/sessions/{session}/contexts/{context}".format(project=project, session=session, context=context, ) - - @staticmethod - def parse_context_path(path: str) -> Dict[str,str]: - """Parses a context path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/agent/sessions/(?P.+?)/contexts/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def intent_path(project: str,intent: str,) -> str: - """Returns a fully-qualified intent string.""" - return "projects/{project}/agent/intents/{intent}".format(project=project, intent=intent, ) - - @staticmethod - def parse_intent_path(path: str) -> Dict[str,str]: - """Parses a intent path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/agent/intents/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def session_path(project: str,session: str,) -> str: - """Returns a fully-qualified session string.""" - return "projects/{project}/agent/sessions/{session}".format(project=project, session=session, ) - - @staticmethod - def parse_session_path(path: str) -> Dict[str,str]: - """Parses a session path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/agent/sessions/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def session_entity_type_path(project: str,session: str,entity_type: str,) -> str: - """Returns a fully-qualified session_entity_type string.""" - return "projects/{project}/agent/sessions/{session}/entityTypes/{entity_type}".format(project=project, session=session, entity_type=entity_type, ) - - @staticmethod - def parse_session_entity_type_path(path: str) -> Dict[str,str]: - """Parses a session_entity_type path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/agent/sessions/(?P.+?)/entityTypes/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_billing_account_path(billing_account: str, ) -> str: - """Returns a fully-qualified billing_account string.""" - return "billingAccounts/{billing_account}".format(billing_account=billing_account, ) - - @staticmethod - def parse_common_billing_account_path(path: str) -> Dict[str,str]: - """Parse a billing_account path into its component segments.""" - m = re.match(r"^billingAccounts/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_folder_path(folder: str, ) -> str: - """Returns a fully-qualified folder string.""" - return "folders/{folder}".format(folder=folder, ) - - @staticmethod - def parse_common_folder_path(path: str) -> Dict[str,str]: - """Parse a folder path into its component segments.""" - m = re.match(r"^folders/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_organization_path(organization: str, ) -> str: - """Returns a fully-qualified organization string.""" - return "organizations/{organization}".format(organization=organization, ) - - @staticmethod - def parse_common_organization_path(path: str) -> Dict[str,str]: - """Parse a organization path into its component segments.""" - m = re.match(r"^organizations/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_project_path(project: str, ) -> str: - """Returns a fully-qualified project string.""" - return "projects/{project}".format(project=project, ) - - @staticmethod - def parse_common_project_path(path: str) -> Dict[str,str]: - """Parse a project path into its component segments.""" - m = re.match(r"^projects/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_location_path(project: str, location: str, ) -> str: - """Returns a fully-qualified location string.""" - return "projects/{project}/locations/{location}".format(project=project, location=location, ) - - @staticmethod - def parse_common_location_path(path: str) -> Dict[str,str]: - """Parse a location path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)$", path) - return m.groupdict() if m else {} - - @classmethod - def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[client_options_lib.ClientOptions] = None): - """Return the API endpoint and client cert source for mutual TLS. - - The client cert source is determined in the following order: - (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the - client cert source is None. - (2) if `client_options.client_cert_source` is provided, use the provided one; if the - default client cert source exists, use the default one; otherwise the client cert - source is None. - - The API endpoint is determined in the following order: - (1) if `client_options.api_endpoint` if provided, use the provided one. - (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the - default mTLS endpoint; if the environment variable is "never", use the default API - endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise - use the default API endpoint. - - More details can be found at https://google.aip.dev/auth/4114. - - Args: - client_options (google.api_core.client_options.ClientOptions): Custom options for the - client. Only the `api_endpoint` and `client_cert_source` properties may be used - in this method. - - Returns: - Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the - client cert source to use. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If any errors happen. - """ - if client_options is None: - client_options = client_options_lib.ClientOptions() - use_client_cert = os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false") - use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") - if use_client_cert not in ("true", "false"): - raise ValueError("Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`") - if use_mtls_endpoint not in ("auto", "never", "always"): - raise MutualTLSChannelError("Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`") - - # Figure out the client cert source to use. - client_cert_source = None - if use_client_cert == "true": - if client_options.client_cert_source: - client_cert_source = client_options.client_cert_source - elif mtls.has_default_client_cert_source(): - client_cert_source = mtls.default_client_cert_source() - - # Figure out which api endpoint to use. - if client_options.api_endpoint is not None: - api_endpoint = client_options.api_endpoint - elif use_mtls_endpoint == "always" or (use_mtls_endpoint == "auto" and client_cert_source): - api_endpoint = cls.DEFAULT_MTLS_ENDPOINT - else: - api_endpoint = cls.DEFAULT_ENDPOINT - - return api_endpoint, client_cert_source - - def __init__(self, *, - credentials: Optional[ga_credentials.Credentials] = None, - transport: Optional[Union[str, SessionsTransport]] = None, - client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the sessions 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, SessionsTransport]): The - transport to use. If set to None, a transport is chosen - automatically. - client_options (Optional[Union[google.api_core.client_options.ClientOptions, dict]]): 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() - client_options = cast(client_options_lib.ClientOptions, client_options) - - api_endpoint, client_cert_source_func = self.get_mtls_endpoint_and_cert_source(client_options) - - api_key_value = getattr(client_options, "api_key", None) - if api_key_value and credentials: - raise ValueError("client_options.api_key and credentials are mutually exclusive") - - # 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, SessionsTransport): - # transport is a SessionsTransport instance. - if credentials or client_options.credentials_file or api_key_value: - 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: - import google.auth._default # type: ignore - - if api_key_value and hasattr(google.auth._default, "get_api_key_credentials"): - credentials = google.auth._default.get_api_key_credentials(api_key_value) - - Transport = type(self).get_transport_class(transport) - self._transport = Transport( - credentials=credentials, - credentials_file=client_options.credentials_file, - host=api_endpoint, - scopes=client_options.scopes, - client_cert_source_for_mtls=client_cert_source_func, - quota_project_id=client_options.quota_project_id, - client_info=client_info, - always_use_jwt_access=True, - api_audience=client_options.api_audience, - ) - - def detect_intent(self, - request: Optional[Union[gcd_session.DetectIntentRequest, dict]] = None, - *, - session: Optional[str] = None, - query_input: Optional[gcd_session.QueryInput] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gcd_session.DetectIntentResponse: - r"""Processes a natural language query and returns structured, - actionable data as a result. This method is not idempotent, - because it may cause contexts and session entity types to be - updated, which in turn might affect results of future queries. - - If you might use `Agent - Assist `__ or - other CCAI products now or in the future, consider using - [AnalyzeContent][google.cloud.dialogflow.v2.Participants.AnalyzeContent] - instead of ``DetectIntent``. ``AnalyzeContent`` has additional - functionality for Agent Assist and other CCAI products. - - Note: Always use agent versions for production traffic. See - `Versions and - environments `__. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import dialogflow_v2 - - def sample_detect_intent(): - # Create a client - client = dialogflow_v2.SessionsClient() - - # Initialize request argument(s) - request = dialogflow_v2.DetectIntentRequest( - session="session_value", - ) - - # Make the request - response = client.detect_intent(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.dialogflow_v2.types.DetectIntentRequest, dict]): - The request object. The request to detect user's intent. - session (str): - Required. The name of the session this query is sent to. - Format: - ``projects//agent/sessions/``, - or - ``projects//agent/environments//users//sessions/``. - If ``Environment ID`` is not specified, we assume - default 'draft' environment (``Environment ID`` might be - referred to as environment name at some places). If - ``User ID`` is not specified, we are using "-". It's up - to the API caller to choose an appropriate - ``Session ID`` and ``User Id``. They can be a random - number or some type of user and session identifiers - (preferably hashed). The length of the ``Session ID`` - and ``User ID`` must not exceed 36 characters. - - For more information, see the `API interactions - guide `__. - - Note: Always use agent versions for production traffic. - See `Versions and - environments `__. - - This corresponds to the ``session`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - query_input (google.cloud.dialogflow_v2.types.QueryInput): - Required. The input specification. It - can be set to: - 1. an audio config - which instructs the speech - recognizer how to process the speech - audio, - 2. a conversational query in the form - of text, or - 3. an event that specifies which intent - to trigger. - - 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. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.dialogflow_v2.types.DetectIntentResponse: - The message returned from the - DetectIntent method. - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([session, query_input]) - 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_session.DetectIntentRequest. - # There's no risk of modifying the input as we've already verified - # 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: - request.query_input = query_input - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.detect_intent] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("session", request.session), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def streaming_detect_intent(self, - requests: Optional[Iterator[session.StreamingDetectIntentRequest]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> Iterable[session.StreamingDetectIntentResponse]: - r"""Processes a natural language query in audio format in a - streaming fashion and returns structured, actionable data as a - result. This method is only available via the gRPC API (not - REST). - - If you might use `Agent - Assist `__ or - other CCAI products now or in the future, consider using - [StreamingAnalyzeContent][google.cloud.dialogflow.v2.Participants.StreamingAnalyzeContent] - instead of ``StreamingDetectIntent``. - ``StreamingAnalyzeContent`` has additional functionality for - Agent Assist and other CCAI products. - - Note: Always use agent versions for production traffic. See - `Versions and - environments `__. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import dialogflow_v2 - - def sample_streaming_detect_intent(): - # Create a client - client = dialogflow_v2.SessionsClient() - - # Initialize request argument(s) - request = dialogflow_v2.StreamingDetectIntentRequest( - session="session_value", - ) - - # This method expects an iterator which contains - # 'dialogflow_v2.StreamingDetectIntentRequest' objects - # Here we create a generator that yields a single `request` for - # demonstrative purposes. - requests = [request] - - def request_generator(): - for request in requests: - yield request - - # Make the request - stream = client.streaming_detect_intent(requests=request_generator()) - - # Handle the response - for response in stream: - print(response) - - Args: - requests (Iterator[google.cloud.dialogflow_v2.types.StreamingDetectIntentRequest]): - The request object iterator. The top-level message sent by the client to the - [Sessions.StreamingDetectIntent][google.cloud.dialogflow.v2.Sessions.StreamingDetectIntent] - method. - - Multiple request messages should be sent in order: - - 1. The first message must contain - [session][google.cloud.dialogflow.v2.StreamingDetectIntentRequest.session], - [query_input][google.cloud.dialogflow.v2.StreamingDetectIntentRequest.query_input] - plus optionally - [query_params][google.cloud.dialogflow.v2.StreamingDetectIntentRequest.query_params]. - If the client wants to receive an audio response, it - should also contain - [output_audio_config][google.cloud.dialogflow.v2.StreamingDetectIntentRequest.output_audio_config]. - The message must not contain - [input_audio][google.cloud.dialogflow.v2.StreamingDetectIntentRequest.input_audio]. - - 2. If - [query_input][google.cloud.dialogflow.v2.StreamingDetectIntentRequest.query_input] - was set to - [query_input.audio_config][google.cloud.dialogflow.v2.InputAudioConfig], - all subsequent messages must contain - [input_audio][google.cloud.dialogflow.v2.StreamingDetectIntentRequest.input_audio] - to continue with Speech recognition. If you decide to - rather detect an intent from text input after you - already started Speech recognition, please send a - message with - [query_input.text][google.cloud.dialogflow.v2.QueryInput.text]. - - However, note that: - - - Dialogflow will bill you for the audio duration so - far. - - Dialogflow discards all Speech recognition results - in favor of the input text. - - Dialogflow will use the language code from the - first message. - - After you sent all input, you must half-close or abort - the request stream. - 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: - Iterable[google.cloud.dialogflow_v2.types.StreamingDetectIntentResponse]: - The top-level message returned from the - StreamingDetectIntent method. - - Multiple response messages can be returned in order: - - 1. If the StreamingDetectIntentRequest.input_audio - field was set, the recognition_result field is - populated for one or more messages. See the - [StreamingRecognitionResult][google.cloud.dialogflow.v2.StreamingRecognitionResult] - message for details about the result message - sequence. - 2. The next message contains response_id, - query_result and optionally webhook_status if a - WebHook was called. - - """ - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.streaming_detect_intent] - - # Send the request. - response = rpc( - requests, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def __enter__(self) -> "SessionsClient": - return self - - def __exit__(self, type, value, traceback): - """Releases underlying transport's resources. - - .. warning:: - ONLY use as a context manager if the transport is NOT shared - with other clients! Exiting the with block will CLOSE the transport - and may cause errors in other clients! - """ - self.transport.close() - - def list_operations( - self, - request: Optional[operations_pb2.ListOperationsRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operations_pb2.ListOperationsResponse: - r"""Lists operations that match the specified filter in the request. - - Args: - request (:class:`~.operations_pb2.ListOperationsRequest`): - The request object. Request message for - `ListOperations` method. - 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: - ~.operations_pb2.ListOperationsResponse: - Response message for ``ListOperations`` method. - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = operations_pb2.ListOperationsRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._transport.list_operations, - 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 = rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - def get_operation( - self, - request: Optional[operations_pb2.GetOperationRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operations_pb2.Operation: - r"""Gets the latest state of a long-running operation. - - Args: - request (:class:`~.operations_pb2.GetOperationRequest`): - The request object. Request message for - `GetOperation` method. - 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: - ~.operations_pb2.Operation: - An ``Operation`` object. - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = operations_pb2.GetOperationRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._transport.get_operation, - 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 = rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - def cancel_operation( - self, - request: Optional[operations_pb2.CancelOperationRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> None: - r"""Starts asynchronous cancellation on a long-running operation. - - The server makes a best effort to cancel the operation, but success - is not guaranteed. If the server doesn't support this method, it returns - `google.rpc.Code.UNIMPLEMENTED`. - - Args: - request (:class:`~.operations_pb2.CancelOperationRequest`): - The request object. Request message for - `CancelOperation` method. - 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: - None - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = operations_pb2.CancelOperationRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._transport.cancel_operation, - 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. - rpc(request, retry=retry, timeout=timeout, metadata=metadata,) - - def get_location( - self, - request: Optional[locations_pb2.GetLocationRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> locations_pb2.Location: - r"""Gets information about a location. - - Args: - request (:class:`~.location_pb2.GetLocationRequest`): - The request object. Request message for - `GetLocation` method. - 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: - ~.location_pb2.Location: - Location object. - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = locations_pb2.GetLocationRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._transport.get_location, - 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 = rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - def list_locations( - self, - request: Optional[locations_pb2.ListLocationsRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> locations_pb2.ListLocationsResponse: - r"""Lists information about the supported locations for this service. - - Args: - request (:class:`~.location_pb2.ListLocationsRequest`): - The request object. Request message for - `ListLocations` method. - 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: - ~.location_pb2.ListLocationsResponse: - Response message for ``ListLocations`` method. - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = locations_pb2.ListLocationsRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._transport.list_locations, - 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 = rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) - - -__all__ = ( - "SessionsClient", -) diff --git a/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/sessions/transports/__init__.py b/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/sessions/transports/__init__.py deleted file mode 100644 index 62897c27a..000000000 --- a/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/sessions/transports/__init__.py +++ /dev/null @@ -1,38 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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 SessionsTransport -from .grpc import SessionsGrpcTransport -from .grpc_asyncio import SessionsGrpcAsyncIOTransport -from .rest import SessionsRestTransport -from .rest import SessionsRestInterceptor - - -# Compile a registry of transports. -_transport_registry = OrderedDict() # type: Dict[str, Type[SessionsTransport]] -_transport_registry['grpc'] = SessionsGrpcTransport -_transport_registry['grpc_asyncio'] = SessionsGrpcAsyncIOTransport -_transport_registry['rest'] = SessionsRestTransport - -__all__ = ( - 'SessionsTransport', - 'SessionsGrpcTransport', - 'SessionsGrpcAsyncIOTransport', - 'SessionsRestTransport', - 'SessionsRestInterceptor', -) diff --git a/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/sessions/transports/base.py b/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/sessions/transports/base.py deleted file mode 100644 index 61a599012..000000000 --- a/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/sessions/transports/base.py +++ /dev/null @@ -1,215 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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 - -from google.cloud.dialogflow_v2 import gapic_version as package_version - -import google.auth # type: ignore -import google.api_core -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import retry as retries -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 session -from google.cloud.dialogflow_v2.types import session as gcd_session -from google.cloud.location import locations_pb2 # type: ignore -from google.longrunning import operations_pb2 - -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) - - -class SessionsTransport(abc.ABC): - """Abstract transport class for Sessions.""" - - 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: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - api_audience: Optional[str] = None, - **kwargs, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. - scopes (Optional[Sequence[str]]): A list of scopes. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - """ - - scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} - - # Save the scopes. - self._scopes = scopes - - # If no credentials are provided, then determine the appropriate - # defaults. - if credentials and credentials_file: - raise core_exceptions.DuplicateCredentialArgs("'credentials_file' and 'credentials' are mutually exclusive") - - if credentials_file is not None: - credentials, _ = google.auth.load_credentials_from_file( - credentials_file, - **scopes_kwargs, - quota_project_id=quota_project_id - ) - elif credentials is None: - credentials, _ = google.auth.default(**scopes_kwargs, quota_project_id=quota_project_id) - # Don't apply audience if the credentials file passed from user. - if hasattr(credentials, "with_gdch_audience"): - credentials = credentials.with_gdch_audience(api_audience if api_audience else host) - - # If the credentials are service account credentials, then always try to use self signed JWT. - if always_use_jwt_access and isinstance(credentials, service_account.Credentials) and hasattr(service_account.Credentials, "with_always_use_jwt_access"): - credentials = credentials.with_always_use_jwt_access(True) - - # Save the credentials. - self._credentials = credentials - - # Save the hostname. Default to port 443 (HTTPS) if none is specified. - if ':' not in host: - host += ':443' - self._host = host - - def _prep_wrapped_messages(self, client_info): - # Precompute the wrapped methods. - self._wrapped_methods = { - self.detect_intent: gapic_v1.method.wrap_method( - self.detect_intent, - default_retry=retries.Retry( -initial=0.1,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( - core_exceptions.ServiceUnavailable, - ), - deadline=220.0, - ), - default_timeout=220.0, - client_info=client_info, - ), - self.streaming_detect_intent: gapic_v1.method.wrap_method( - self.streaming_detect_intent, - default_timeout=220.0, - client_info=client_info, - ), - } - - def close(self): - """Closes resources associated with the transport. - - .. warning:: - Only call this method if the transport is NOT shared - with other clients - this may cause errors in other clients! - """ - raise NotImplementedError() - - @property - def detect_intent(self) -> Callable[ - [gcd_session.DetectIntentRequest], - Union[ - gcd_session.DetectIntentResponse, - Awaitable[gcd_session.DetectIntentResponse] - ]]: - raise NotImplementedError() - - @property - def streaming_detect_intent(self) -> Callable[ - [session.StreamingDetectIntentRequest], - Union[ - session.StreamingDetectIntentResponse, - Awaitable[session.StreamingDetectIntentResponse] - ]]: - raise NotImplementedError() - - @property - def list_operations( - self, - ) -> Callable[ - [operations_pb2.ListOperationsRequest], - Union[operations_pb2.ListOperationsResponse, Awaitable[operations_pb2.ListOperationsResponse]], - ]: - raise NotImplementedError() - - @property - def get_operation( - self, - ) -> Callable[ - [operations_pb2.GetOperationRequest], - Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], - ]: - raise NotImplementedError() - - @property - def cancel_operation( - self, - ) -> Callable[ - [operations_pb2.CancelOperationRequest], - None, - ]: - raise NotImplementedError() - - @property - def get_location(self, - ) -> Callable[ - [locations_pb2.GetLocationRequest], - Union[locations_pb2.Location, Awaitable[locations_pb2.Location]], - ]: - raise NotImplementedError() - - @property - def list_locations(self, - ) -> Callable[ - [locations_pb2.ListLocationsRequest], - Union[locations_pb2.ListLocationsResponse, Awaitable[locations_pb2.ListLocationsResponse]], - ]: - raise NotImplementedError() - - @property - def kind(self) -> str: - raise NotImplementedError() - - -__all__ = ( - 'SessionsTransport', -) diff --git a/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/sessions/transports/grpc.py b/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/sessions/transports/grpc.py deleted file mode 100644 index 053991e14..000000000 --- a/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/sessions/transports/grpc.py +++ /dev/null @@ -1,415 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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 -from google.api_core import gapic_v1 -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 google.cloud.location import locations_pb2 # type: ignore -from google.longrunning import operations_pb2 -from .base import SessionsTransport, DEFAULT_CLIENT_INFO - - -class SessionsGrpcTransport(SessionsTransport): - """gRPC backend transport for Sessions. - - A service used for session interactions. - - For more information, see the `API interactions - guide `__. - - 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: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - channel: Optional[grpc.Channel] = None, - api_mtls_endpoint: Optional[str] = None, - client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, - ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, - client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - api_audience: Optional[str] = None, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - This argument is ignored if ``channel`` is provided. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional(Sequence[str])): A list of scopes. This argument is - ignored if ``channel`` is provided. - channel (Optional[grpc.Channel]): A ``Channel`` instance through - which to make calls. - api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. - If provided, it overrides the ``host`` argument and tries to create - a mutual TLS channel with client SSL credentials from - ``client_cert_source`` or application default SSL credentials. - client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): - Deprecated. A callback to provide client SSL certificate bytes and - private key bytes, both in PEM format. It is ignored if - ``api_mtls_endpoint`` is None. - ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials - for the grpc channel. It is ignored if ``channel`` is provided. - client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): - A callback to provide client certificate bytes and private key bytes, - both in PEM format. It is used to configure a mutual TLS channel. It is - ignored if ``channel`` or ``ssl_channel_credentials`` is provided. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport - creation failed for any reason. - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - self._grpc_channel = None - self._ssl_channel_credentials = ssl_channel_credentials - self._stubs: Dict[str, Callable] = {} - - if api_mtls_endpoint: - warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) - if client_cert_source: - warnings.warn("client_cert_source is deprecated", DeprecationWarning) - - if channel: - # Ignore credentials if a channel was passed. - credentials = False - # If a channel was explicitly provided, set it. - self._grpc_channel = channel - self._ssl_channel_credentials = None - - else: - if api_mtls_endpoint: - host = api_mtls_endpoint - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - self._ssl_channel_credentials = SslCredentials().ssl_credentials - - else: - if client_cert_source_for_mtls and not ssl_channel_credentials: - cert, key = client_cert_source_for_mtls() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - - # The base transport sets the host, credentials and scopes - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes, - quota_project_id=quota_project_id, - client_info=client_info, - always_use_jwt_access=always_use_jwt_access, - api_audience=api_audience, - ) - - if not self._grpc_channel: - self._grpc_channel = type(self).create_channel( - self._host, - # use the credentials which are saved - credentials=self._credentials, - # Set ``credentials_file`` to ``None`` here as - # the credentials that we saved earlier should be used. - credentials_file=None, - 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: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - **kwargs) -> grpc.Channel: - """Create and return a gRPC channel object. - Args: - host (Optional[str]): The host for the channel to use. - credentials (Optional[~.Credentials]): The - authorization credentials to attach to requests. These - credentials identify this application to the service. If - none are specified, the client will attempt to ascertain - the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - kwargs (Optional[dict]): Keyword arguments, which are passed to the - channel creation. - Returns: - grpc.Channel: A gRPC channel object. - - Raises: - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - - return grpc_helpers.create_channel( - host, - credentials=credentials, - credentials_file=credentials_file, - quota_project_id=quota_project_id, - default_scopes=cls.AUTH_SCOPES, - scopes=scopes, - default_host=cls.DEFAULT_HOST, - **kwargs - ) - - @property - def grpc_channel(self) -> grpc.Channel: - """Return the channel designed to connect to this service. - """ - return self._grpc_channel - - @property - def detect_intent(self) -> Callable[ - [gcd_session.DetectIntentRequest], - gcd_session.DetectIntentResponse]: - r"""Return a callable for the detect intent method over gRPC. - - Processes a natural language query and returns structured, - actionable data as a result. This method is not idempotent, - because it may cause contexts and session entity types to be - updated, which in turn might affect results of future queries. - - If you might use `Agent - Assist `__ or - other CCAI products now or in the future, consider using - [AnalyzeContent][google.cloud.dialogflow.v2.Participants.AnalyzeContent] - instead of ``DetectIntent``. ``AnalyzeContent`` has additional - functionality for Agent Assist and other CCAI products. - - Note: Always use agent versions for production traffic. See - `Versions and - environments `__. - - Returns: - Callable[[~.DetectIntentRequest], - ~.DetectIntentResponse]: - 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 'detect_intent' not in self._stubs: - self._stubs['detect_intent'] = self.grpc_channel.unary_unary( - '/google.cloud.dialogflow.v2.Sessions/DetectIntent', - request_serializer=gcd_session.DetectIntentRequest.serialize, - response_deserializer=gcd_session.DetectIntentResponse.deserialize, - ) - return self._stubs['detect_intent'] - - @property - def streaming_detect_intent(self) -> Callable[ - [session.StreamingDetectIntentRequest], - session.StreamingDetectIntentResponse]: - r"""Return a callable for the streaming detect intent method over gRPC. - - Processes a natural language query in audio format in a - streaming fashion and returns structured, actionable data as a - result. This method is only available via the gRPC API (not - REST). - - If you might use `Agent - Assist `__ or - other CCAI products now or in the future, consider using - [StreamingAnalyzeContent][google.cloud.dialogflow.v2.Participants.StreamingAnalyzeContent] - instead of ``StreamingDetectIntent``. - ``StreamingAnalyzeContent`` has additional functionality for - Agent Assist and other CCAI products. - - Note: Always use agent versions for production traffic. See - `Versions and - environments `__. - - Returns: - Callable[[~.StreamingDetectIntentRequest], - ~.StreamingDetectIntentResponse]: - 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 'streaming_detect_intent' not in self._stubs: - self._stubs['streaming_detect_intent'] = self.grpc_channel.stream_stream( - '/google.cloud.dialogflow.v2.Sessions/StreamingDetectIntent', - request_serializer=session.StreamingDetectIntentRequest.serialize, - response_deserializer=session.StreamingDetectIntentResponse.deserialize, - ) - return self._stubs['streaming_detect_intent'] - - def close(self): - self.grpc_channel.close() - - @property - def cancel_operation( - self, - ) -> Callable[[operations_pb2.CancelOperationRequest], None]: - r"""Return a callable for the cancel_operation method over gRPC. - """ - # 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 "cancel_operation" not in self._stubs: - self._stubs["cancel_operation"] = self.grpc_channel.unary_unary( - "/google.longrunning.Operations/CancelOperation", - request_serializer=operations_pb2.CancelOperationRequest.SerializeToString, - response_deserializer=None, - ) - return self._stubs["cancel_operation"] - - @property - def get_operation( - self, - ) -> Callable[[operations_pb2.GetOperationRequest], operations_pb2.Operation]: - r"""Return a callable for the get_operation method over gRPC. - """ - # 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_operation" not in self._stubs: - self._stubs["get_operation"] = self.grpc_channel.unary_unary( - "/google.longrunning.Operations/GetOperation", - request_serializer=operations_pb2.GetOperationRequest.SerializeToString, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs["get_operation"] - - @property - def list_operations( - self, - ) -> Callable[[operations_pb2.ListOperationsRequest], operations_pb2.ListOperationsResponse]: - r"""Return a callable for the list_operations method over gRPC. - """ - # 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_operations" not in self._stubs: - self._stubs["list_operations"] = self.grpc_channel.unary_unary( - "/google.longrunning.Operations/ListOperations", - request_serializer=operations_pb2.ListOperationsRequest.SerializeToString, - response_deserializer=operations_pb2.ListOperationsResponse.FromString, - ) - return self._stubs["list_operations"] - - @property - def list_locations( - self, - ) -> Callable[[locations_pb2.ListLocationsRequest], locations_pb2.ListLocationsResponse]: - r"""Return a callable for the list locations method over gRPC. - """ - # 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_locations" not in self._stubs: - self._stubs["list_locations"] = self.grpc_channel.unary_unary( - "/google.cloud.location.Locations/ListLocations", - request_serializer=locations_pb2.ListLocationsRequest.SerializeToString, - response_deserializer=locations_pb2.ListLocationsResponse.FromString, - ) - return self._stubs["list_locations"] - - @property - def get_location( - self, - ) -> Callable[[locations_pb2.GetLocationRequest], locations_pb2.Location]: - r"""Return a callable for the list locations method over gRPC. - """ - # 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_location" not in self._stubs: - self._stubs["get_location"] = self.grpc_channel.unary_unary( - "/google.cloud.location.Locations/GetLocation", - request_serializer=locations_pb2.GetLocationRequest.SerializeToString, - response_deserializer=locations_pb2.Location.FromString, - ) - return self._stubs["get_location"] - - @property - def kind(self) -> str: - return "grpc" - - -__all__ = ( - 'SessionsGrpcTransport', -) diff --git a/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/sessions/transports/grpc_asyncio.py b/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/sessions/transports/grpc_asyncio.py deleted file mode 100644 index 140c9f0e4..000000000 --- a/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/sessions/transports/grpc_asyncio.py +++ /dev/null @@ -1,414 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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 -from google.api_core import grpc_helpers_async -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore - -import grpc # type: ignore -from grpc.experimental import aio # type: ignore - -from google.cloud.dialogflow_v2.types import session -from google.cloud.dialogflow_v2.types import session as gcd_session -from google.cloud.location import locations_pb2 # type: ignore -from google.longrunning import operations_pb2 -from .base import SessionsTransport, DEFAULT_CLIENT_INFO -from .grpc import SessionsGrpcTransport - - -class SessionsGrpcAsyncIOTransport(SessionsTransport): - """gRPC AsyncIO backend transport for Sessions. - - A service used for session interactions. - - For more information, see the `API interactions - guide `__. - - 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: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - **kwargs) -> aio.Channel: - """Create and return a gRPC AsyncIO channel object. - Args: - host (Optional[str]): The host for the channel to use. - credentials (Optional[~.Credentials]): The - authorization credentials to attach to requests. These - credentials identify this application to the service. If - none are specified, the client will attempt to ascertain - the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - kwargs (Optional[dict]): Keyword arguments, which are passed to the - channel creation. - Returns: - aio.Channel: A gRPC AsyncIO channel object. - """ - - return grpc_helpers_async.create_channel( - host, - credentials=credentials, - credentials_file=credentials_file, - quota_project_id=quota_project_id, - default_scopes=cls.AUTH_SCOPES, - scopes=scopes, - default_host=cls.DEFAULT_HOST, - **kwargs - ) - - def __init__(self, *, - host: str = 'dialogflow.googleapis.com', - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - channel: Optional[aio.Channel] = None, - api_mtls_endpoint: Optional[str] = None, - client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, - ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, - client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - api_audience: Optional[str] = None, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - This argument is ignored if ``channel`` is provided. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - channel (Optional[aio.Channel]): A ``Channel`` instance through - which to make calls. - api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. - If provided, it overrides the ``host`` argument and tries to create - a mutual TLS channel with client SSL credentials from - ``client_cert_source`` or application default SSL credentials. - client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): - Deprecated. A callback to provide client SSL certificate bytes and - private key bytes, both in PEM format. It is ignored if - ``api_mtls_endpoint`` is None. - ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials - for the grpc channel. It is ignored if ``channel`` is provided. - client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): - A callback to provide client certificate bytes and private key bytes, - both in PEM format. It is used to configure a mutual TLS channel. It is - ignored if ``channel`` or ``ssl_channel_credentials`` is provided. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - - Raises: - google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport - creation failed for any reason. - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - self._grpc_channel = None - self._ssl_channel_credentials = ssl_channel_credentials - self._stubs: Dict[str, Callable] = {} - - if api_mtls_endpoint: - warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) - if client_cert_source: - warnings.warn("client_cert_source is deprecated", DeprecationWarning) - - if channel: - # Ignore credentials if a channel was passed. - credentials = False - # If a channel was explicitly provided, set it. - self._grpc_channel = channel - self._ssl_channel_credentials = None - else: - if api_mtls_endpoint: - host = api_mtls_endpoint - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - self._ssl_channel_credentials = SslCredentials().ssl_credentials - - else: - if client_cert_source_for_mtls and not ssl_channel_credentials: - cert, key = client_cert_source_for_mtls() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - - # The base transport sets the host, credentials and scopes - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes, - quota_project_id=quota_project_id, - client_info=client_info, - always_use_jwt_access=always_use_jwt_access, - api_audience=api_audience, - ) - - if not self._grpc_channel: - self._grpc_channel = type(self).create_channel( - self._host, - # use the credentials which are saved - credentials=self._credentials, - # Set ``credentials_file`` to ``None`` here as - # the credentials that we saved earlier should be used. - credentials_file=None, - 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 detect_intent(self) -> Callable[ - [gcd_session.DetectIntentRequest], - Awaitable[gcd_session.DetectIntentResponse]]: - r"""Return a callable for the detect intent method over gRPC. - - Processes a natural language query and returns structured, - actionable data as a result. This method is not idempotent, - because it may cause contexts and session entity types to be - updated, which in turn might affect results of future queries. - - If you might use `Agent - Assist `__ or - other CCAI products now or in the future, consider using - [AnalyzeContent][google.cloud.dialogflow.v2.Participants.AnalyzeContent] - instead of ``DetectIntent``. ``AnalyzeContent`` has additional - functionality for Agent Assist and other CCAI products. - - Note: Always use agent versions for production traffic. See - `Versions and - environments `__. - - Returns: - Callable[[~.DetectIntentRequest], - Awaitable[~.DetectIntentResponse]]: - 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 'detect_intent' not in self._stubs: - self._stubs['detect_intent'] = self.grpc_channel.unary_unary( - '/google.cloud.dialogflow.v2.Sessions/DetectIntent', - request_serializer=gcd_session.DetectIntentRequest.serialize, - response_deserializer=gcd_session.DetectIntentResponse.deserialize, - ) - return self._stubs['detect_intent'] - - @property - def streaming_detect_intent(self) -> Callable[ - [session.StreamingDetectIntentRequest], - Awaitable[session.StreamingDetectIntentResponse]]: - r"""Return a callable for the streaming detect intent method over gRPC. - - Processes a natural language query in audio format in a - streaming fashion and returns structured, actionable data as a - result. This method is only available via the gRPC API (not - REST). - - If you might use `Agent - Assist `__ or - other CCAI products now or in the future, consider using - [StreamingAnalyzeContent][google.cloud.dialogflow.v2.Participants.StreamingAnalyzeContent] - instead of ``StreamingDetectIntent``. - ``StreamingAnalyzeContent`` has additional functionality for - Agent Assist and other CCAI products. - - Note: Always use agent versions for production traffic. See - `Versions and - environments `__. - - Returns: - Callable[[~.StreamingDetectIntentRequest], - Awaitable[~.StreamingDetectIntentResponse]]: - 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 'streaming_detect_intent' not in self._stubs: - self._stubs['streaming_detect_intent'] = self.grpc_channel.stream_stream( - '/google.cloud.dialogflow.v2.Sessions/StreamingDetectIntent', - request_serializer=session.StreamingDetectIntentRequest.serialize, - response_deserializer=session.StreamingDetectIntentResponse.deserialize, - ) - return self._stubs['streaming_detect_intent'] - - def close(self): - return self.grpc_channel.close() - - @property - def cancel_operation( - self, - ) -> Callable[[operations_pb2.CancelOperationRequest], None]: - r"""Return a callable for the cancel_operation method over gRPC. - """ - # 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 "cancel_operation" not in self._stubs: - self._stubs["cancel_operation"] = self.grpc_channel.unary_unary( - "/google.longrunning.Operations/CancelOperation", - request_serializer=operations_pb2.CancelOperationRequest.SerializeToString, - response_deserializer=None, - ) - return self._stubs["cancel_operation"] - - @property - def get_operation( - self, - ) -> Callable[[operations_pb2.GetOperationRequest], operations_pb2.Operation]: - r"""Return a callable for the get_operation method over gRPC. - """ - # 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_operation" not in self._stubs: - self._stubs["get_operation"] = self.grpc_channel.unary_unary( - "/google.longrunning.Operations/GetOperation", - request_serializer=operations_pb2.GetOperationRequest.SerializeToString, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs["get_operation"] - - @property - def list_operations( - self, - ) -> Callable[[operations_pb2.ListOperationsRequest], operations_pb2.ListOperationsResponse]: - r"""Return a callable for the list_operations method over gRPC. - """ - # 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_operations" not in self._stubs: - self._stubs["list_operations"] = self.grpc_channel.unary_unary( - "/google.longrunning.Operations/ListOperations", - request_serializer=operations_pb2.ListOperationsRequest.SerializeToString, - response_deserializer=operations_pb2.ListOperationsResponse.FromString, - ) - return self._stubs["list_operations"] - - @property - def list_locations( - self, - ) -> Callable[[locations_pb2.ListLocationsRequest], locations_pb2.ListLocationsResponse]: - r"""Return a callable for the list locations method over gRPC. - """ - # 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_locations" not in self._stubs: - self._stubs["list_locations"] = self.grpc_channel.unary_unary( - "/google.cloud.location.Locations/ListLocations", - request_serializer=locations_pb2.ListLocationsRequest.SerializeToString, - response_deserializer=locations_pb2.ListLocationsResponse.FromString, - ) - return self._stubs["list_locations"] - - @property - def get_location( - self, - ) -> Callable[[locations_pb2.GetLocationRequest], locations_pb2.Location]: - r"""Return a callable for the list locations method over gRPC. - """ - # 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_location" not in self._stubs: - self._stubs["get_location"] = self.grpc_channel.unary_unary( - "/google.cloud.location.Locations/GetLocation", - request_serializer=locations_pb2.GetLocationRequest.SerializeToString, - response_deserializer=locations_pb2.Location.FromString, - ) - return self._stubs["get_location"] - - -__all__ = ( - 'SessionsGrpcAsyncIOTransport', -) diff --git a/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/sessions/transports/rest.py b/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/sessions/transports/rest.py deleted file mode 100644 index 37b3e147e..000000000 --- a/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/sessions/transports/rest.py +++ /dev/null @@ -1,774 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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 google.auth.transport.requests import AuthorizedSession # type: ignore -import json # type: ignore -import grpc # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore -from google.auth import credentials as ga_credentials # type: ignore -from google.api_core import exceptions as core_exceptions -from google.api_core import retry as retries -from google.api_core import rest_helpers -from google.api_core import rest_streaming -from google.api_core import path_template -from google.api_core import gapic_v1 - -from google.protobuf import json_format -from google.cloud.location import locations_pb2 # type: ignore -from google.longrunning import operations_pb2 -from requests import __version__ as requests_version -import dataclasses -import re -from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union -import warnings - -try: - OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] -except AttributeError: # pragma: NO COVER - OptionalRetry = Union[retries.Retry, object] # 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 as BASE_DEFAULT_CLIENT_INFO - - -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=BASE_DEFAULT_CLIENT_INFO.gapic_version, - grpc_version=None, - rest_version=requests_version, -) - - -class SessionsRestInterceptor: - """Interceptor for Sessions. - - Interceptors are used to manipulate requests, request metadata, and responses - in arbitrary ways. - Example use cases include: - * Logging - * Verifying requests according to service or custom semantics - * Stripping extraneous information from responses - - These use cases and more can be enabled by injecting an - instance of a custom subclass when constructing the SessionsRestTransport. - - .. code-block:: python - class MyCustomSessionsInterceptor(SessionsRestInterceptor): - def pre_detect_intent(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_detect_intent(self, response): - logging.log(f"Received response: {response}") - return response - - transport = SessionsRestTransport(interceptor=MyCustomSessionsInterceptor()) - client = SessionsClient(transport=transport) - - - """ - def pre_detect_intent(self, request: gcd_session.DetectIntentRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[gcd_session.DetectIntentRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for detect_intent - - Override in a subclass to manipulate the request or metadata - before they are sent to the Sessions server. - """ - return request, metadata - - def post_detect_intent(self, response: gcd_session.DetectIntentResponse) -> gcd_session.DetectIntentResponse: - """Post-rpc interceptor for detect_intent - - Override in a subclass to manipulate the response - after it is returned by the Sessions server but before - it is returned to user code. - """ - return response - - def pre_get_location( - self, request: locations_pb2.GetLocationRequest, metadata: Sequence[Tuple[str, str]] - ) -> Tuple[locations_pb2.GetLocationRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for get_location - - Override in a subclass to manipulate the request or metadata - before they are sent to the Sessions server. - """ - return request, metadata - - def post_get_location( - self, response: locations_pb2.Location - ) -> locations_pb2.Location: - """Post-rpc interceptor for get_location - - Override in a subclass to manipulate the response - after it is returned by the Sessions server but before - it is returned to user code. - """ - return response - def pre_list_locations( - self, request: locations_pb2.ListLocationsRequest, metadata: Sequence[Tuple[str, str]] - ) -> Tuple[locations_pb2.ListLocationsRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for list_locations - - Override in a subclass to manipulate the request or metadata - before they are sent to the Sessions server. - """ - return request, metadata - - def post_list_locations( - self, response: locations_pb2.ListLocationsResponse - ) -> locations_pb2.ListLocationsResponse: - """Post-rpc interceptor for list_locations - - Override in a subclass to manipulate the response - after it is returned by the Sessions server but before - it is returned to user code. - """ - return response - def pre_cancel_operation( - self, request: operations_pb2.CancelOperationRequest, metadata: Sequence[Tuple[str, str]] - ) -> Tuple[operations_pb2.CancelOperationRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for cancel_operation - - Override in a subclass to manipulate the request or metadata - before they are sent to the Sessions server. - """ - return request, metadata - - def post_cancel_operation( - self, response: None - ) -> None: - """Post-rpc interceptor for cancel_operation - - Override in a subclass to manipulate the response - after it is returned by the Sessions server but before - it is returned to user code. - """ - return response - def pre_get_operation( - self, request: operations_pb2.GetOperationRequest, metadata: Sequence[Tuple[str, str]] - ) -> Tuple[operations_pb2.GetOperationRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for get_operation - - Override in a subclass to manipulate the request or metadata - before they are sent to the Sessions server. - """ - return request, metadata - - def post_get_operation( - self, response: operations_pb2.Operation - ) -> operations_pb2.Operation: - """Post-rpc interceptor for get_operation - - Override in a subclass to manipulate the response - after it is returned by the Sessions server but before - it is returned to user code. - """ - return response - def pre_list_operations( - self, request: operations_pb2.ListOperationsRequest, metadata: Sequence[Tuple[str, str]] - ) -> Tuple[operations_pb2.ListOperationsRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for list_operations - - Override in a subclass to manipulate the request or metadata - before they are sent to the Sessions server. - """ - return request, metadata - - def post_list_operations( - self, response: operations_pb2.ListOperationsResponse - ) -> operations_pb2.ListOperationsResponse: - """Post-rpc interceptor for list_operations - - Override in a subclass to manipulate the response - after it is returned by the Sessions server but before - it is returned to user code. - """ - return response - - -@dataclasses.dataclass -class SessionsRestStub: - _session: AuthorizedSession - _host: str - _interceptor: SessionsRestInterceptor - - -class SessionsRestTransport(SessionsTransport): - """REST backend transport for Sessions. - - A service used for session interactions. - - For more information, see the `API interactions - guide `__. - - 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 JSON representations of protocol buffers over HTTP/1.1 - - """ - - def __init__(self, *, - host: str = 'dialogflow.googleapis.com', - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - client_cert_source_for_mtls: Optional[Callable[[ - ], Tuple[bytes, bytes]]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - url_scheme: str = 'https', - interceptor: Optional[SessionsRestInterceptor] = None, - api_audience: Optional[str] = None, - ) -> 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 ignored if ``channel`` is provided. - scopes (Optional(Sequence[str])): A list of scopes. This argument is - ignored if ``channel`` is provided. - client_cert_source_for_mtls (Callable[[], Tuple[bytes, bytes]]): Client - certificate to configure mutual TLS HTTP channel. It is ignored - if ``channel`` is provided. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you are developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - url_scheme: the protocol scheme for the API endpoint. Normally - "https", but for testing or local servers, - "http" can be specified. - """ - # Run the base constructor - # TODO(yon-mg): resolve other ctor params i.e. scopes, quota, etc. - # TODO: When custom host (api_endpoint) is set, `scopes` must *also* be set on the - # credentials object - maybe_url_match = re.match("^(?Phttp(?:s)?://)?(?P.*)$", host) - if maybe_url_match is None: - raise ValueError(f"Unexpected hostname structure: {host}") # pragma: NO COVER - - url_match_items = maybe_url_match.groupdict() - - host = f"{url_scheme}://{host}" if not url_match_items["scheme"] else host - - super().__init__( - host=host, - credentials=credentials, - client_info=client_info, - always_use_jwt_access=always_use_jwt_access, - api_audience=api_audience - ) - self._session = AuthorizedSession( - self._credentials, default_host=self.DEFAULT_HOST) - if client_cert_source_for_mtls: - self._session.configure_mtls_channel(client_cert_source_for_mtls) - self._interceptor = interceptor or SessionsRestInterceptor() - self._prep_wrapped_messages(client_info) - - class _DetectIntent(SessionsRestStub): - def __hash__(self): - return hash("DetectIntent") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: gcd_session.DetectIntentRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> gcd_session.DetectIntentResponse: - r"""Call the detect intent method over HTTP. - - Args: - request (~.gcd_session.DetectIntentRequest): - The request object. The request to detect user's intent. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.gcd_session.DetectIntentResponse: - The message returned from the - DetectIntent method. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'post', - 'uri': '/v2/{session=projects/*/agent/sessions/*}:detectIntent', - 'body': '*', - }, -{ - 'method': 'post', - 'uri': '/v2/{session=projects/*/agent/environments/*/users/*/sessions/*}:detectIntent', - 'body': '*', - }, -{ - 'method': 'post', - 'uri': '/v2/{session=projects/*/locations/*/agent/sessions/*}:detectIntent', - 'body': '*', - }, -{ - 'method': 'post', - 'uri': '/v2/{session=projects/*/locations/*/agent/environments/*/users/*/sessions/*}:detectIntent', - 'body': '*', - }, - ] - request, metadata = self._interceptor.pre_detect_intent(request, metadata) - pb_request = gcd_session.DetectIntentRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request['body'], - including_default_value_fields=False, - use_integers_for_enums=True - ) - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - including_default_value_fields=False, - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = gcd_session.DetectIntentResponse() - pb_resp = gcd_session.DetectIntentResponse.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_detect_intent(resp) - return resp - - class _StreamingDetectIntent(SessionsRestStub): - def __hash__(self): - return hash("StreamingDetectIntent") - - def __call__(self, - request: session.StreamingDetectIntentRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> rest_streaming.ResponseIterator: - raise NotImplementedError( - "Method StreamingDetectIntent is not available over REST transport" - ) - - @property - def detect_intent(self) -> Callable[ - [gcd_session.DetectIntentRequest], - gcd_session.DetectIntentResponse]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._DetectIntent(self._session, self._host, self._interceptor) # type: ignore - - @property - def streaming_detect_intent(self) -> Callable[ - [session.StreamingDetectIntentRequest], - session.StreamingDetectIntentResponse]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._StreamingDetectIntent(self._session, self._host, self._interceptor) # type: ignore - - @property - def get_location(self): - return self._GetLocation(self._session, self._host, self._interceptor) # type: ignore - - class _GetLocation(SessionsRestStub): - def __call__(self, - request: locations_pb2.GetLocationRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> locations_pb2.Location: - - r"""Call the get location method over HTTP. - - Args: - request (locations_pb2.GetLocationRequest): - The request object for GetLocation method. - 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: - locations_pb2.Location: Response from GetLocation method. - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v2/{name=projects/*/locations/*}', - }, - ] - - request, metadata = self._interceptor.pre_get_location(request, metadata) - request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode( - http_options, **request_kwargs) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json.dumps(transcoded_request['query_params'])) - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - resp = locations_pb2.Location() - resp = json_format.Parse(response.content.decode("utf-8"), resp) - resp = self._interceptor.post_get_location(resp) - return resp - - @property - def list_locations(self): - return self._ListLocations(self._session, self._host, self._interceptor) # type: ignore - - class _ListLocations(SessionsRestStub): - def __call__(self, - request: locations_pb2.ListLocationsRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> locations_pb2.ListLocationsResponse: - - r"""Call the list locations method over HTTP. - - Args: - request (locations_pb2.ListLocationsRequest): - The request object for ListLocations method. - 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: - locations_pb2.ListLocationsResponse: Response from ListLocations method. - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v2/{name=projects/*}/locations', - }, - ] - - request, metadata = self._interceptor.pre_list_locations(request, metadata) - request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode( - http_options, **request_kwargs) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json.dumps(transcoded_request['query_params'])) - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - resp = locations_pb2.ListLocationsResponse() - resp = json_format.Parse(response.content.decode("utf-8"), resp) - resp = self._interceptor.post_list_locations(resp) - return resp - - @property - def cancel_operation(self): - return self._CancelOperation(self._session, self._host, self._interceptor) # type: ignore - - class _CancelOperation(SessionsRestStub): - def __call__(self, - request: operations_pb2.CancelOperationRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> None: - - r"""Call the cancel operation method over HTTP. - - Args: - request (operations_pb2.CancelOperationRequest): - The request object for CancelOperation method. - 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. - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'post', - 'uri': '/v2/{name=projects/*/operations/*}:cancel', - }, -{ - 'method': 'post', - 'uri': '/v2/{name=projects/*/locations/*/operations/*}:cancel', - }, - ] - - request, metadata = self._interceptor.pre_cancel_operation(request, metadata) - request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode( - http_options, **request_kwargs) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json.dumps(transcoded_request['query_params'])) - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - return self._interceptor.post_cancel_operation(None) - - @property - def get_operation(self): - return self._GetOperation(self._session, self._host, self._interceptor) # type: ignore - - class _GetOperation(SessionsRestStub): - def __call__(self, - request: operations_pb2.GetOperationRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> operations_pb2.Operation: - - r"""Call the get operation method over HTTP. - - Args: - request (operations_pb2.GetOperationRequest): - The request object for GetOperation method. - 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: - operations_pb2.Operation: Response from GetOperation method. - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v2/{name=projects/*/operations/*}', - }, -{ - 'method': 'get', - 'uri': '/v2/{name=projects/*/locations/*/operations/*}', - }, - ] - - request, metadata = self._interceptor.pre_get_operation(request, metadata) - request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode( - http_options, **request_kwargs) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json.dumps(transcoded_request['query_params'])) - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - resp = operations_pb2.Operation() - resp = json_format.Parse(response.content.decode("utf-8"), resp) - resp = self._interceptor.post_get_operation(resp) - return resp - - @property - def list_operations(self): - return self._ListOperations(self._session, self._host, self._interceptor) # type: ignore - - class _ListOperations(SessionsRestStub): - def __call__(self, - request: operations_pb2.ListOperationsRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> operations_pb2.ListOperationsResponse: - - r"""Call the list operations method over HTTP. - - Args: - request (operations_pb2.ListOperationsRequest): - The request object for ListOperations method. - 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: - operations_pb2.ListOperationsResponse: Response from ListOperations method. - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v2/{name=projects/*}/operations', - }, -{ - 'method': 'get', - 'uri': '/v2/{name=projects/*/locations/*}/operations', - }, - ] - - request, metadata = self._interceptor.pre_list_operations(request, metadata) - request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode( - http_options, **request_kwargs) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json.dumps(transcoded_request['query_params'])) - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - resp = operations_pb2.ListOperationsResponse() - resp = json_format.Parse(response.content.decode("utf-8"), resp) - resp = self._interceptor.post_list_operations(resp) - return resp - - @property - def kind(self) -> str: - return "rest" - - def close(self): - self._session.close() - - -__all__=( - 'SessionsRestTransport', -) diff --git a/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/versions/__init__.py b/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/versions/__init__.py deleted file mode 100644 index 8f339fd03..000000000 --- a/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/versions/__init__.py +++ /dev/null @@ -1,22 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/versions/async_client.py b/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/versions/async_client.py deleted file mode 100644 index eb4220c40..000000000 --- a/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/versions/async_client.py +++ /dev/null @@ -1,1057 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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, Mapping, MutableMapping, MutableSequence, Optional, Sequence, Tuple, Type, Union - -from google.cloud.dialogflow_v2 import gapic_version as package_version - -from google.api_core.client_options import ClientOptions -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import retry as retries -from google.auth import credentials as ga_credentials # type: ignore -from google.oauth2 import service_account # type: ignore - -try: - OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] -except AttributeError: # pragma: NO COVER - OptionalRetry = Union[retries.Retry, object] # 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.cloud.location import locations_pb2 # type: ignore -from google.longrunning import operations_pb2 -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 - - @classmethod - def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[ClientOptions] = None): - """Return the API endpoint and client cert source for mutual TLS. - - The client cert source is determined in the following order: - (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the - client cert source is None. - (2) if `client_options.client_cert_source` is provided, use the provided one; if the - default client cert source exists, use the default one; otherwise the client cert - source is None. - - The API endpoint is determined in the following order: - (1) if `client_options.api_endpoint` if provided, use the provided one. - (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the - default mTLS endpoint; if the environment variable is "never", use the default API - endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise - use the default API endpoint. - - More details can be found at https://google.aip.dev/auth/4114. - - Args: - client_options (google.api_core.client_options.ClientOptions): Custom options for the - client. Only the `api_endpoint` and `client_cert_source` properties may be used - in this method. - - Returns: - Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the - client cert source to use. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If any errors happen. - """ - return VersionsClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore - - @property - def transport(self) -> VersionsTransport: - """Returns 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: Optional[ga_credentials.Credentials] = None, - transport: Union[str, VersionsTransport] = "grpc_asyncio", - client_options: Optional[ClientOptions] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates 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: Optional[Union[version.ListVersionsRequest, dict]] = None, - *, - parent: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListVersionsAsyncPager: - r"""Returns the list of all versions of the specified - agent. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import dialogflow_v2 - - async def sample_list_versions(): - # Create a client - client = dialogflow_v2.VersionsAsyncClient() - - # Initialize request argument(s) - request = dialogflow_v2.ListVersionsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_versions(request=request) - - # Handle the response - async for response in page_result: - print(response) - - Args: - request (Optional[Union[google.cloud.dialogflow_v2.types.ListVersionsRequest, dict]]): - 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. - # Quick 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: Optional[Union[version.GetVersionRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> version.Version: - r"""Retrieves the specified agent version. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import dialogflow_v2 - - async def sample_get_version(): - # Create a client - client = dialogflow_v2.VersionsAsyncClient() - - # Initialize request argument(s) - request = dialogflow_v2.GetVersionRequest( - name="name_value", - ) - - # Make the request - response = await client.get_version(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.dialogflow_v2.types.GetVersionRequest, dict]]): - 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. - # Quick 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: Optional[Union[gcd_version.CreateVersionRequest, dict]] = None, - *, - parent: Optional[str] = None, - version: Optional[gcd_version.Version] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - 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. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import dialogflow_v2 - - async def sample_create_version(): - # Create a client - client = dialogflow_v2.VersionsAsyncClient() - - # Initialize request argument(s) - request = dialogflow_v2.CreateVersionRequest( - parent="parent_value", - ) - - # Make the request - response = await client.create_version(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.dialogflow_v2.types.CreateVersionRequest, dict]]): - 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. - # Quick 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: Optional[Union[gcd_version.UpdateVersionRequest, dict]] = None, - *, - version: Optional[gcd_version.Version] = None, - update_mask: Optional[field_mask_pb2.FieldMask] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - 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. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import dialogflow_v2 - - async def sample_update_version(): - # Create a client - client = dialogflow_v2.VersionsAsyncClient() - - # Initialize request argument(s) - request = dialogflow_v2.UpdateVersionRequest( - ) - - # Make the request - response = await client.update_version(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.dialogflow_v2.types.UpdateVersionRequest, dict]]): - 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. - # Quick 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: Optional[Union[version.DeleteVersionRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> None: - r"""Delete the specified agent version. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import dialogflow_v2 - - async def sample_delete_version(): - # Create a client - client = dialogflow_v2.VersionsAsyncClient() - - # Initialize request argument(s) - request = dialogflow_v2.DeleteVersionRequest( - name="name_value", - ) - - # Make the request - await client.delete_version(request=request) - - Args: - request (Optional[Union[google.cloud.dialogflow_v2.types.DeleteVersionRequest, dict]]): - 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. - # Quick 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, - ) - - async def list_operations( - self, - request: Optional[operations_pb2.ListOperationsRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operations_pb2.ListOperationsResponse: - r"""Lists operations that match the specified filter in the request. - - Args: - request (:class:`~.operations_pb2.ListOperationsRequest`): - The request object. Request message for - `ListOperations` method. - 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: - ~.operations_pb2.ListOperationsResponse: - Response message for ``ListOperations`` method. - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = operations_pb2.ListOperationsRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._client._transport.list_operations, - 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 get_operation( - self, - request: Optional[operations_pb2.GetOperationRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operations_pb2.Operation: - r"""Gets the latest state of a long-running operation. - - Args: - request (:class:`~.operations_pb2.GetOperationRequest`): - The request object. Request message for - `GetOperation` method. - 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: - ~.operations_pb2.Operation: - An ``Operation`` object. - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = operations_pb2.GetOperationRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._client._transport.get_operation, - 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 cancel_operation( - self, - request: Optional[operations_pb2.CancelOperationRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> None: - r"""Starts asynchronous cancellation on a long-running operation. - - The server makes a best effort to cancel the operation, but success - is not guaranteed. If the server doesn't support this method, it returns - `google.rpc.Code.UNIMPLEMENTED`. - - Args: - request (:class:`~.operations_pb2.CancelOperationRequest`): - The request object. Request message for - `CancelOperation` method. - 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: - None - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = operations_pb2.CancelOperationRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._client._transport.cancel_operation, - 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_location( - self, - request: Optional[locations_pb2.GetLocationRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> locations_pb2.Location: - r"""Gets information about a location. - - Args: - request (:class:`~.location_pb2.GetLocationRequest`): - The request object. Request message for - `GetLocation` method. - 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: - ~.location_pb2.Location: - Location object. - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = locations_pb2.GetLocationRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._client._transport.get_location, - 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 list_locations( - self, - request: Optional[locations_pb2.ListLocationsRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> locations_pb2.ListLocationsResponse: - r"""Lists information about the supported locations for this service. - - Args: - request (:class:`~.location_pb2.ListLocationsRequest`): - The request object. Request message for - `ListLocations` method. - 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: - ~.location_pb2.ListLocationsResponse: - Response message for ``ListLocations`` method. - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = locations_pb2.ListLocationsRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._client._transport.list_locations, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("name", request.name),)), - ) - - # Send the request. - response = await rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - async def __aenter__(self): - return self - - async def __aexit__(self, exc_type, exc, tb): - await self.transport.close() - -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) - - -__all__ = ( - "VersionsAsyncClient", -) diff --git a/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/versions/client.py b/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/versions/client.py deleted file mode 100644 index c72cc5c2c..000000000 --- a/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/versions/client.py +++ /dev/null @@ -1,1256 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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 os -import re -from typing import Dict, Mapping, MutableMapping, MutableSequence, Optional, Sequence, Tuple, Type, Union, cast - -from google.cloud.dialogflow_v2 import gapic_version as package_version - -from google.api_core import client_options as client_options_lib -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import retry as retries -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 - -try: - OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] -except AttributeError: # pragma: NO COVER - OptionalRetry = Union[retries.Retry, object] # 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.cloud.location import locations_pb2 # type: ignore -from google.longrunning import operations_pb2 -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 -from .transports.rest import VersionsRestTransport - - -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 - _transport_registry["rest"] = VersionsRestTransport - - def get_transport_class(cls, - label: Optional[str] = None, - ) -> Type[VersionsTransport]: - """Returns an appropriate transport class. - - Args: - label: The name of the desired transport. If none is - provided, then the first transport in the registry is used. - - Returns: - The transport class to use. - """ - # If a specific transport is requested, return that one. - if label: - return cls._transport_registry[label] - - # No transport is requested; return the default (that is, the first one - # in the dictionary). - return next(iter(cls._transport_registry.values())) - - -class VersionsClient(metaclass=VersionsClientMeta): - """Service for managing [Versions][google.cloud.dialogflow.v2.Version].""" - - @staticmethod - def _get_default_mtls_endpoint(api_endpoint): - """Converts api endpoint to mTLS endpoint. - - Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to - "*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively. - Args: - api_endpoint (Optional[str]): the api endpoint to convert. - Returns: - str: converted mTLS api endpoint. - """ - if not api_endpoint: - return api_endpoint - - mtls_endpoint_re = re.compile( - r"(?P[^.]+)(?P\.mtls)?(?P\.sandbox)?(?P\.googleapis\.com)?" - ) - - m = mtls_endpoint_re.match(api_endpoint) - name, mtls, sandbox, googledomain = m.groups() - if mtls or not googledomain: - return api_endpoint - - if sandbox: - return api_endpoint.replace( - "sandbox.googleapis.com", "mtls.sandbox.googleapis.com" - ) - - return api_endpoint.replace(".googleapis.com", ".mtls.googleapis.com") - - DEFAULT_ENDPOINT = "dialogflow.googleapis.com" - DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore - DEFAULT_ENDPOINT - ) - - @classmethod - def from_service_account_info(cls, info: dict, *args, **kwargs): - """Creates an instance of this client using the provided credentials - info. - - Args: - info (dict): The service account private key info. - args: Additional arguments to pass to the constructor. - kwargs: Additional arguments to pass to the constructor. - - Returns: - 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: - """Returns 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: - """Returns 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]: - """Parses 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: - """Returns a fully-qualified billing_account string.""" - return "billingAccounts/{billing_account}".format(billing_account=billing_account, ) - - @staticmethod - def parse_common_billing_account_path(path: str) -> Dict[str,str]: - """Parse a billing_account path into its component segments.""" - m = re.match(r"^billingAccounts/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_folder_path(folder: str, ) -> str: - """Returns a fully-qualified folder string.""" - return "folders/{folder}".format(folder=folder, ) - - @staticmethod - def parse_common_folder_path(path: str) -> Dict[str,str]: - """Parse a folder path into its component segments.""" - m = re.match(r"^folders/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_organization_path(organization: str, ) -> str: - """Returns a fully-qualified organization string.""" - return "organizations/{organization}".format(organization=organization, ) - - @staticmethod - def parse_common_organization_path(path: str) -> Dict[str,str]: - """Parse a organization path into its component segments.""" - m = re.match(r"^organizations/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_project_path(project: str, ) -> str: - """Returns a fully-qualified project string.""" - return "projects/{project}".format(project=project, ) - - @staticmethod - def parse_common_project_path(path: str) -> Dict[str,str]: - """Parse a project path into its component segments.""" - m = re.match(r"^projects/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_location_path(project: str, location: str, ) -> str: - """Returns a fully-qualified location string.""" - return "projects/{project}/locations/{location}".format(project=project, location=location, ) - - @staticmethod - def parse_common_location_path(path: str) -> Dict[str,str]: - """Parse a location path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)$", path) - return m.groupdict() if m else {} - - @classmethod - def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[client_options_lib.ClientOptions] = None): - """Return the API endpoint and client cert source for mutual TLS. - - The client cert source is determined in the following order: - (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the - client cert source is None. - (2) if `client_options.client_cert_source` is provided, use the provided one; if the - default client cert source exists, use the default one; otherwise the client cert - source is None. - - The API endpoint is determined in the following order: - (1) if `client_options.api_endpoint` if provided, use the provided one. - (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the - default mTLS endpoint; if the environment variable is "never", use the default API - endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise - use the default API endpoint. - - More details can be found at https://google.aip.dev/auth/4114. - - Args: - client_options (google.api_core.client_options.ClientOptions): Custom options for the - client. Only the `api_endpoint` and `client_cert_source` properties may be used - in this method. - - Returns: - Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the - client cert source to use. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If any errors happen. - """ - if client_options is None: - client_options = client_options_lib.ClientOptions() - use_client_cert = os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false") - use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") - if use_client_cert not in ("true", "false"): - raise ValueError("Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`") - if use_mtls_endpoint not in ("auto", "never", "always"): - raise MutualTLSChannelError("Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`") - - # Figure out the client cert source to use. - client_cert_source = None - if use_client_cert == "true": - if client_options.client_cert_source: - client_cert_source = client_options.client_cert_source - elif mtls.has_default_client_cert_source(): - client_cert_source = mtls.default_client_cert_source() - - # Figure out which api endpoint to use. - if client_options.api_endpoint is not None: - api_endpoint = client_options.api_endpoint - elif use_mtls_endpoint == "always" or (use_mtls_endpoint == "auto" and client_cert_source): - api_endpoint = cls.DEFAULT_MTLS_ENDPOINT - else: - api_endpoint = cls.DEFAULT_ENDPOINT - - return api_endpoint, client_cert_source - - def __init__(self, *, - credentials: Optional[ga_credentials.Credentials] = None, - transport: Optional[Union[str, VersionsTransport]] = None, - client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates 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 (Optional[Union[google.api_core.client_options.ClientOptions, dict]]): 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() - client_options = cast(client_options_lib.ClientOptions, client_options) - - api_endpoint, client_cert_source_func = self.get_mtls_endpoint_and_cert_source(client_options) - - api_key_value = getattr(client_options, "api_key", None) - if api_key_value and credentials: - raise ValueError("client_options.api_key and credentials are mutually exclusive") - - # 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 or api_key_value: - 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: - import google.auth._default # type: ignore - - if api_key_value and hasattr(google.auth._default, "get_api_key_credentials"): - credentials = google.auth._default.get_api_key_credentials(api_key_value) - - Transport = type(self).get_transport_class(transport) - self._transport = Transport( - credentials=credentials, - credentials_file=client_options.credentials_file, - host=api_endpoint, - scopes=client_options.scopes, - client_cert_source_for_mtls=client_cert_source_func, - quota_project_id=client_options.quota_project_id, - client_info=client_info, - always_use_jwt_access=True, - api_audience=client_options.api_audience, - ) - - def list_versions(self, - request: Optional[Union[version.ListVersionsRequest, dict]] = None, - *, - parent: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListVersionsPager: - r"""Returns the list of all versions of the specified - agent. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import dialogflow_v2 - - def sample_list_versions(): - # Create a client - client = dialogflow_v2.VersionsClient() - - # Initialize request argument(s) - request = dialogflow_v2.ListVersionsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_versions(request=request) - - # Handle the response - for response in page_result: - print(response) - - Args: - request (Union[google.cloud.dialogflow_v2.types.ListVersionsRequest, dict]): - 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. - # Quick 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: Optional[Union[version.GetVersionRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> version.Version: - r"""Retrieves the specified agent version. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import dialogflow_v2 - - def sample_get_version(): - # Create a client - client = dialogflow_v2.VersionsClient() - - # Initialize request argument(s) - request = dialogflow_v2.GetVersionRequest( - name="name_value", - ) - - # Make the request - response = client.get_version(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.dialogflow_v2.types.GetVersionRequest, dict]): - 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. - # Quick 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: Optional[Union[gcd_version.CreateVersionRequest, dict]] = None, - *, - parent: Optional[str] = None, - version: Optional[gcd_version.Version] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - 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. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import dialogflow_v2 - - def sample_create_version(): - # Create a client - client = dialogflow_v2.VersionsClient() - - # Initialize request argument(s) - request = dialogflow_v2.CreateVersionRequest( - parent="parent_value", - ) - - # Make the request - response = client.create_version(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.dialogflow_v2.types.CreateVersionRequest, dict]): - 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. - # Quick 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: Optional[Union[gcd_version.UpdateVersionRequest, dict]] = None, - *, - version: Optional[gcd_version.Version] = None, - update_mask: Optional[field_mask_pb2.FieldMask] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - 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. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import dialogflow_v2 - - def sample_update_version(): - # Create a client - client = dialogflow_v2.VersionsClient() - - # Initialize request argument(s) - request = dialogflow_v2.UpdateVersionRequest( - ) - - # Make the request - response = client.update_version(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.dialogflow_v2.types.UpdateVersionRequest, dict]): - 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. - # Quick 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: Optional[Union[version.DeleteVersionRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> None: - r"""Delete the specified agent version. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import dialogflow_v2 - - def sample_delete_version(): - # Create a client - client = dialogflow_v2.VersionsClient() - - # Initialize request argument(s) - request = dialogflow_v2.DeleteVersionRequest( - name="name_value", - ) - - # Make the request - client.delete_version(request=request) - - Args: - request (Union[google.cloud.dialogflow_v2.types.DeleteVersionRequest, dict]): - 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. - # Quick 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, - ) - - def __enter__(self) -> "VersionsClient": - return self - - def __exit__(self, type, value, traceback): - """Releases underlying transport's resources. - - .. warning:: - ONLY use as a context manager if the transport is NOT shared - with other clients! Exiting the with block will CLOSE the transport - and may cause errors in other clients! - """ - self.transport.close() - - def list_operations( - self, - request: Optional[operations_pb2.ListOperationsRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operations_pb2.ListOperationsResponse: - r"""Lists operations that match the specified filter in the request. - - Args: - request (:class:`~.operations_pb2.ListOperationsRequest`): - The request object. Request message for - `ListOperations` method. - 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: - ~.operations_pb2.ListOperationsResponse: - Response message for ``ListOperations`` method. - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = operations_pb2.ListOperationsRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._transport.list_operations, - 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 = rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - def get_operation( - self, - request: Optional[operations_pb2.GetOperationRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operations_pb2.Operation: - r"""Gets the latest state of a long-running operation. - - Args: - request (:class:`~.operations_pb2.GetOperationRequest`): - The request object. Request message for - `GetOperation` method. - 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: - ~.operations_pb2.Operation: - An ``Operation`` object. - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = operations_pb2.GetOperationRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._transport.get_operation, - 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 = rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - def cancel_operation( - self, - request: Optional[operations_pb2.CancelOperationRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> None: - r"""Starts asynchronous cancellation on a long-running operation. - - The server makes a best effort to cancel the operation, but success - is not guaranteed. If the server doesn't support this method, it returns - `google.rpc.Code.UNIMPLEMENTED`. - - Args: - request (:class:`~.operations_pb2.CancelOperationRequest`): - The request object. Request message for - `CancelOperation` method. - 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: - None - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = operations_pb2.CancelOperationRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._transport.cancel_operation, - 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. - rpc(request, retry=retry, timeout=timeout, metadata=metadata,) - - def get_location( - self, - request: Optional[locations_pb2.GetLocationRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> locations_pb2.Location: - r"""Gets information about a location. - - Args: - request (:class:`~.location_pb2.GetLocationRequest`): - The request object. Request message for - `GetLocation` method. - 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: - ~.location_pb2.Location: - Location object. - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = locations_pb2.GetLocationRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._transport.get_location, - 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 = rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - def list_locations( - self, - request: Optional[locations_pb2.ListLocationsRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> locations_pb2.ListLocationsResponse: - r"""Lists information about the supported locations for this service. - - Args: - request (:class:`~.location_pb2.ListLocationsRequest`): - The request object. Request message for - `ListLocations` method. - 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: - ~.location_pb2.ListLocationsResponse: - Response message for ``ListLocations`` method. - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = locations_pb2.ListLocationsRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._transport.list_locations, - 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 = rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) - - -__all__ = ( - "VersionsClient", -) diff --git a/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/versions/pagers.py b/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/versions/pagers.py deleted file mode 100644 index 03624dde7..000000000 --- a/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/versions/pagers.py +++ /dev/null @@ -1,139 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from typing import Any, AsyncIterator, Awaitable, Callable, Sequence, Tuple, Optional, Iterator - -from google.cloud.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) -> Iterator[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) -> Iterator[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]] = ()): - """Instantiates 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) -> AsyncIterator[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) -> AsyncIterator[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/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/versions/transports/__init__.py b/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/versions/transports/__init__.py deleted file mode 100644 index 778af6195..000000000 --- a/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/versions/transports/__init__.py +++ /dev/null @@ -1,38 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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 -from .rest import VersionsRestTransport -from .rest import VersionsRestInterceptor - - -# Compile a registry of transports. -_transport_registry = OrderedDict() # type: Dict[str, Type[VersionsTransport]] -_transport_registry['grpc'] = VersionsGrpcTransport -_transport_registry['grpc_asyncio'] = VersionsGrpcAsyncIOTransport -_transport_registry['rest'] = VersionsRestTransport - -__all__ = ( - 'VersionsTransport', - 'VersionsGrpcTransport', - 'VersionsGrpcAsyncIOTransport', - 'VersionsRestTransport', - 'VersionsRestInterceptor', -) diff --git a/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/versions/transports/base.py b/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/versions/transports/base.py deleted file mode 100644 index 0256553de..000000000 --- a/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/versions/transports/base.py +++ /dev/null @@ -1,252 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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 - -from google.cloud.dialogflow_v2 import gapic_version as package_version - -import google.auth # type: ignore -import google.api_core -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import retry as retries -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 version -from google.cloud.dialogflow_v2.types import version as gcd_version -from google.cloud.location import locations_pb2 # type: ignore -from google.longrunning import operations_pb2 -from google.protobuf import empty_pb2 # type: ignore - -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__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: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - api_audience: Optional[str] = None, - **kwargs, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. - scopes (Optional[Sequence[str]]): A list of scopes. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - """ - - scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} - - # Save the scopes. - self._scopes = scopes - - # If no credentials are provided, then determine the appropriate - # defaults. - if credentials and credentials_file: - raise core_exceptions.DuplicateCredentialArgs("'credentials_file' and 'credentials' are mutually exclusive") - - if credentials_file is not None: - credentials, _ = google.auth.load_credentials_from_file( - credentials_file, - **scopes_kwargs, - quota_project_id=quota_project_id - ) - elif credentials is None: - credentials, _ = google.auth.default(**scopes_kwargs, quota_project_id=quota_project_id) - # Don't apply audience if the credentials file passed from user. - if hasattr(credentials, "with_gdch_audience"): - credentials = credentials.with_gdch_audience(api_audience if api_audience else host) - - # If the credentials are service account credentials, then always try to use self signed JWT. - if always_use_jwt_access and isinstance(credentials, service_account.Credentials) and hasattr(service_account.Credentials, "with_always_use_jwt_access"): - credentials = credentials.with_always_use_jwt_access(True) - - # Save the credentials. - self._credentials = credentials - - # Save the hostname. Default to port 443 (HTTPS) if none is specified. - if ':' not in host: - host += ':443' - self._host = host - - 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, - ), - } - - def close(self): - """Closes resources associated with the transport. - - .. warning:: - Only call this method if the transport is NOT shared - with other clients - this may cause errors in other clients! - """ - raise NotImplementedError() - - @property - def list_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() - - @property - def list_operations( - self, - ) -> Callable[ - [operations_pb2.ListOperationsRequest], - Union[operations_pb2.ListOperationsResponse, Awaitable[operations_pb2.ListOperationsResponse]], - ]: - raise NotImplementedError() - - @property - def get_operation( - self, - ) -> Callable[ - [operations_pb2.GetOperationRequest], - Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], - ]: - raise NotImplementedError() - - @property - def cancel_operation( - self, - ) -> Callable[ - [operations_pb2.CancelOperationRequest], - None, - ]: - raise NotImplementedError() - - @property - def get_location(self, - ) -> Callable[ - [locations_pb2.GetLocationRequest], - Union[locations_pb2.Location, Awaitable[locations_pb2.Location]], - ]: - raise NotImplementedError() - - @property - def list_locations(self, - ) -> Callable[ - [locations_pb2.ListLocationsRequest], - Union[locations_pb2.ListLocationsResponse, Awaitable[locations_pb2.ListLocationsResponse]], - ]: - raise NotImplementedError() - - @property - def kind(self) -> str: - raise NotImplementedError() - - -__all__ = ( - 'VersionsTransport', -) diff --git a/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/versions/transports/grpc.py b/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/versions/transports/grpc.py deleted file mode 100644 index e07bfb01f..000000000 --- a/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/versions/transports/grpc.py +++ /dev/null @@ -1,469 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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 -from google.api_core import gapic_v1 -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.cloud.location import locations_pb2 # type: ignore -from google.longrunning import operations_pb2 -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: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - channel: Optional[grpc.Channel] = None, - api_mtls_endpoint: Optional[str] = None, - client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, - ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, - client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - api_audience: Optional[str] = None, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - This argument is ignored if ``channel`` is provided. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional(Sequence[str])): A list of scopes. This argument is - ignored if ``channel`` is provided. - channel (Optional[grpc.Channel]): A ``Channel`` instance through - which to make calls. - api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. - If provided, it overrides the ``host`` argument and tries to create - a mutual TLS channel with client SSL credentials from - ``client_cert_source`` or application default SSL credentials. - client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): - Deprecated. A callback to provide client SSL certificate bytes and - private key bytes, both in PEM format. It is ignored if - ``api_mtls_endpoint`` is None. - ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials - for the grpc channel. It is ignored if ``channel`` is provided. - client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): - A callback to provide client certificate bytes and private key bytes, - both in PEM format. It is used to configure a mutual TLS channel. It is - ignored if ``channel`` or ``ssl_channel_credentials`` is provided. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport - creation failed for any reason. - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - self._grpc_channel = None - self._ssl_channel_credentials = ssl_channel_credentials - self._stubs: Dict[str, Callable] = {} - - if api_mtls_endpoint: - warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) - if client_cert_source: - warnings.warn("client_cert_source is deprecated", DeprecationWarning) - - if channel: - # Ignore credentials if a channel was passed. - credentials = False - # If a channel was explicitly provided, set it. - self._grpc_channel = channel - self._ssl_channel_credentials = None - - else: - if api_mtls_endpoint: - host = api_mtls_endpoint - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - self._ssl_channel_credentials = SslCredentials().ssl_credentials - - else: - if client_cert_source_for_mtls and not ssl_channel_credentials: - cert, key = client_cert_source_for_mtls() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - - # The base transport sets the host, credentials and scopes - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes, - quota_project_id=quota_project_id, - client_info=client_info, - always_use_jwt_access=always_use_jwt_access, - api_audience=api_audience, - ) - - if not self._grpc_channel: - self._grpc_channel = type(self).create_channel( - self._host, - # use the credentials which are saved - credentials=self._credentials, - # Set ``credentials_file`` to ``None`` here as - # the credentials that we saved earlier should be used. - credentials_file=None, - 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: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - **kwargs) -> grpc.Channel: - """Create and return a gRPC channel object. - Args: - host (Optional[str]): The host for the channel to use. - credentials (Optional[~.Credentials]): The - authorization credentials to attach to requests. These - credentials identify this application to the service. If - none are specified, the client will attempt to ascertain - the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - kwargs (Optional[dict]): Keyword arguments, which are passed to the - channel creation. - Returns: - grpc.Channel: A gRPC channel object. - - Raises: - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - - return grpc_helpers.create_channel( - host, - credentials=credentials, - credentials_file=credentials_file, - quota_project_id=quota_project_id, - default_scopes=cls.AUTH_SCOPES, - scopes=scopes, - default_host=cls.DEFAULT_HOST, - **kwargs - ) - - @property - def grpc_channel(self) -> grpc.Channel: - """Return the channel designed to connect to this service. - """ - return self._grpc_channel - - @property - def list_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'] - - def close(self): - self.grpc_channel.close() - - @property - def cancel_operation( - self, - ) -> Callable[[operations_pb2.CancelOperationRequest], None]: - r"""Return a callable for the cancel_operation method over gRPC. - """ - # 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 "cancel_operation" not in self._stubs: - self._stubs["cancel_operation"] = self.grpc_channel.unary_unary( - "/google.longrunning.Operations/CancelOperation", - request_serializer=operations_pb2.CancelOperationRequest.SerializeToString, - response_deserializer=None, - ) - return self._stubs["cancel_operation"] - - @property - def get_operation( - self, - ) -> Callable[[operations_pb2.GetOperationRequest], operations_pb2.Operation]: - r"""Return a callable for the get_operation method over gRPC. - """ - # 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_operation" not in self._stubs: - self._stubs["get_operation"] = self.grpc_channel.unary_unary( - "/google.longrunning.Operations/GetOperation", - request_serializer=operations_pb2.GetOperationRequest.SerializeToString, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs["get_operation"] - - @property - def list_operations( - self, - ) -> Callable[[operations_pb2.ListOperationsRequest], operations_pb2.ListOperationsResponse]: - r"""Return a callable for the list_operations method over gRPC. - """ - # 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_operations" not in self._stubs: - self._stubs["list_operations"] = self.grpc_channel.unary_unary( - "/google.longrunning.Operations/ListOperations", - request_serializer=operations_pb2.ListOperationsRequest.SerializeToString, - response_deserializer=operations_pb2.ListOperationsResponse.FromString, - ) - return self._stubs["list_operations"] - - @property - def list_locations( - self, - ) -> Callable[[locations_pb2.ListLocationsRequest], locations_pb2.ListLocationsResponse]: - r"""Return a callable for the list locations method over gRPC. - """ - # 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_locations" not in self._stubs: - self._stubs["list_locations"] = self.grpc_channel.unary_unary( - "/google.cloud.location.Locations/ListLocations", - request_serializer=locations_pb2.ListLocationsRequest.SerializeToString, - response_deserializer=locations_pb2.ListLocationsResponse.FromString, - ) - return self._stubs["list_locations"] - - @property - def get_location( - self, - ) -> Callable[[locations_pb2.GetLocationRequest], locations_pb2.Location]: - r"""Return a callable for the list locations method over gRPC. - """ - # 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_location" not in self._stubs: - self._stubs["get_location"] = self.grpc_channel.unary_unary( - "/google.cloud.location.Locations/GetLocation", - request_serializer=locations_pb2.GetLocationRequest.SerializeToString, - response_deserializer=locations_pb2.Location.FromString, - ) - return self._stubs["get_location"] - - @property - def kind(self) -> str: - return "grpc" - - -__all__ = ( - 'VersionsGrpcTransport', -) diff --git a/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/versions/transports/grpc_asyncio.py b/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/versions/transports/grpc_asyncio.py deleted file mode 100644 index 01df88a75..000000000 --- a/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/versions/transports/grpc_asyncio.py +++ /dev/null @@ -1,468 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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 -from google.api_core import grpc_helpers_async -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore - -import grpc # type: ignore -from grpc.experimental import aio # type: ignore - -from google.cloud.dialogflow_v2.types import version -from google.cloud.dialogflow_v2.types import version as gcd_version -from google.cloud.location import locations_pb2 # type: ignore -from google.longrunning import operations_pb2 -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: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - **kwargs) -> aio.Channel: - """Create and return a gRPC AsyncIO channel object. - Args: - host (Optional[str]): The host for the channel to use. - credentials (Optional[~.Credentials]): The - authorization credentials to attach to requests. These - credentials identify this application to the service. If - none are specified, the client will attempt to ascertain - the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - kwargs (Optional[dict]): Keyword arguments, which are passed to the - channel creation. - Returns: - aio.Channel: A gRPC AsyncIO channel object. - """ - - return grpc_helpers_async.create_channel( - host, - credentials=credentials, - credentials_file=credentials_file, - quota_project_id=quota_project_id, - default_scopes=cls.AUTH_SCOPES, - scopes=scopes, - default_host=cls.DEFAULT_HOST, - **kwargs - ) - - def __init__(self, *, - host: str = 'dialogflow.googleapis.com', - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - channel: Optional[aio.Channel] = None, - api_mtls_endpoint: Optional[str] = None, - client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, - ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, - client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - api_audience: Optional[str] = None, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - This argument is ignored if ``channel`` is provided. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - channel (Optional[aio.Channel]): A ``Channel`` instance through - which to make calls. - api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. - If provided, it overrides the ``host`` argument and tries to create - a mutual TLS channel with client SSL credentials from - ``client_cert_source`` or application default SSL credentials. - client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): - Deprecated. A callback to provide client SSL certificate bytes and - private key bytes, both in PEM format. It is ignored if - ``api_mtls_endpoint`` is None. - ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials - for the grpc channel. It is ignored if ``channel`` is provided. - client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): - A callback to provide client certificate bytes and private key bytes, - both in PEM format. It is used to configure a mutual TLS channel. It is - ignored if ``channel`` or ``ssl_channel_credentials`` is provided. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - - Raises: - google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport - creation failed for any reason. - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - self._grpc_channel = None - self._ssl_channel_credentials = ssl_channel_credentials - self._stubs: Dict[str, Callable] = {} - - if api_mtls_endpoint: - warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) - if client_cert_source: - warnings.warn("client_cert_source is deprecated", DeprecationWarning) - - if channel: - # Ignore credentials if a channel was passed. - credentials = False - # If a channel was explicitly provided, set it. - self._grpc_channel = channel - self._ssl_channel_credentials = None - else: - if api_mtls_endpoint: - host = api_mtls_endpoint - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - self._ssl_channel_credentials = SslCredentials().ssl_credentials - - else: - if client_cert_source_for_mtls and not ssl_channel_credentials: - cert, key = client_cert_source_for_mtls() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - - # The base transport sets the host, credentials and scopes - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes, - quota_project_id=quota_project_id, - client_info=client_info, - always_use_jwt_access=always_use_jwt_access, - api_audience=api_audience, - ) - - if not self._grpc_channel: - self._grpc_channel = type(self).create_channel( - self._host, - # use the credentials which are saved - credentials=self._credentials, - # Set ``credentials_file`` to ``None`` here as - # the credentials that we saved earlier should be used. - credentials_file=None, - 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'] - - def close(self): - return self.grpc_channel.close() - - @property - def cancel_operation( - self, - ) -> Callable[[operations_pb2.CancelOperationRequest], None]: - r"""Return a callable for the cancel_operation method over gRPC. - """ - # 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 "cancel_operation" not in self._stubs: - self._stubs["cancel_operation"] = self.grpc_channel.unary_unary( - "/google.longrunning.Operations/CancelOperation", - request_serializer=operations_pb2.CancelOperationRequest.SerializeToString, - response_deserializer=None, - ) - return self._stubs["cancel_operation"] - - @property - def get_operation( - self, - ) -> Callable[[operations_pb2.GetOperationRequest], operations_pb2.Operation]: - r"""Return a callable for the get_operation method over gRPC. - """ - # 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_operation" not in self._stubs: - self._stubs["get_operation"] = self.grpc_channel.unary_unary( - "/google.longrunning.Operations/GetOperation", - request_serializer=operations_pb2.GetOperationRequest.SerializeToString, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs["get_operation"] - - @property - def list_operations( - self, - ) -> Callable[[operations_pb2.ListOperationsRequest], operations_pb2.ListOperationsResponse]: - r"""Return a callable for the list_operations method over gRPC. - """ - # 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_operations" not in self._stubs: - self._stubs["list_operations"] = self.grpc_channel.unary_unary( - "/google.longrunning.Operations/ListOperations", - request_serializer=operations_pb2.ListOperationsRequest.SerializeToString, - response_deserializer=operations_pb2.ListOperationsResponse.FromString, - ) - return self._stubs["list_operations"] - - @property - def list_locations( - self, - ) -> Callable[[locations_pb2.ListLocationsRequest], locations_pb2.ListLocationsResponse]: - r"""Return a callable for the list locations method over gRPC. - """ - # 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_locations" not in self._stubs: - self._stubs["list_locations"] = self.grpc_channel.unary_unary( - "/google.cloud.location.Locations/ListLocations", - request_serializer=locations_pb2.ListLocationsRequest.SerializeToString, - response_deserializer=locations_pb2.ListLocationsResponse.FromString, - ) - return self._stubs["list_locations"] - - @property - def get_location( - self, - ) -> Callable[[locations_pb2.GetLocationRequest], locations_pb2.Location]: - r"""Return a callable for the list locations method over gRPC. - """ - # 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_location" not in self._stubs: - self._stubs["get_location"] = self.grpc_channel.unary_unary( - "/google.cloud.location.Locations/GetLocation", - request_serializer=locations_pb2.GetLocationRequest.SerializeToString, - response_deserializer=locations_pb2.Location.FromString, - ) - return self._stubs["get_location"] - - -__all__ = ( - 'VersionsGrpcAsyncIOTransport', -) diff --git a/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/versions/transports/rest.py b/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/versions/transports/rest.py deleted file mode 100644 index 6b43bd7e9..000000000 --- a/owl-bot-staging/v2/google/cloud/dialogflow_v2/services/versions/transports/rest.py +++ /dev/null @@ -1,1244 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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 google.auth.transport.requests import AuthorizedSession # type: ignore -import json # type: ignore -import grpc # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore -from google.auth import credentials as ga_credentials # type: ignore -from google.api_core import exceptions as core_exceptions -from google.api_core import retry as retries -from google.api_core import rest_helpers -from google.api_core import rest_streaming -from google.api_core import path_template -from google.api_core import gapic_v1 - -from google.protobuf import json_format -from google.cloud.location import locations_pb2 # type: ignore -from google.longrunning import operations_pb2 -from requests import __version__ as requests_version -import dataclasses -import re -from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union -import warnings - -try: - OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] -except AttributeError: # pragma: NO COVER - OptionalRetry = Union[retries.Retry, object] # 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 as BASE_DEFAULT_CLIENT_INFO - - -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=BASE_DEFAULT_CLIENT_INFO.gapic_version, - grpc_version=None, - rest_version=requests_version, -) - - -class VersionsRestInterceptor: - """Interceptor for Versions. - - Interceptors are used to manipulate requests, request metadata, and responses - in arbitrary ways. - Example use cases include: - * Logging - * Verifying requests according to service or custom semantics - * Stripping extraneous information from responses - - These use cases and more can be enabled by injecting an - instance of a custom subclass when constructing the VersionsRestTransport. - - .. code-block:: python - class MyCustomVersionsInterceptor(VersionsRestInterceptor): - def pre_create_version(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_create_version(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_delete_version(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def pre_get_version(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_get_version(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_list_versions(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_list_versions(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_update_version(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_update_version(self, response): - logging.log(f"Received response: {response}") - return response - - transport = VersionsRestTransport(interceptor=MyCustomVersionsInterceptor()) - client = VersionsClient(transport=transport) - - - """ - def pre_create_version(self, request: gcd_version.CreateVersionRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[gcd_version.CreateVersionRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for create_version - - Override in a subclass to manipulate the request or metadata - before they are sent to the Versions server. - """ - return request, metadata - - def post_create_version(self, response: gcd_version.Version) -> gcd_version.Version: - """Post-rpc interceptor for create_version - - Override in a subclass to manipulate the response - after it is returned by the Versions server but before - it is returned to user code. - """ - return response - def pre_delete_version(self, request: version.DeleteVersionRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[version.DeleteVersionRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for delete_version - - Override in a subclass to manipulate the request or metadata - before they are sent to the Versions server. - """ - return request, metadata - - def pre_get_version(self, request: version.GetVersionRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[version.GetVersionRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for get_version - - Override in a subclass to manipulate the request or metadata - before they are sent to the Versions server. - """ - return request, metadata - - def post_get_version(self, response: version.Version) -> version.Version: - """Post-rpc interceptor for get_version - - Override in a subclass to manipulate the response - after it is returned by the Versions server but before - it is returned to user code. - """ - return response - def pre_list_versions(self, request: version.ListVersionsRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[version.ListVersionsRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for list_versions - - Override in a subclass to manipulate the request or metadata - before they are sent to the Versions server. - """ - return request, metadata - - def post_list_versions(self, response: version.ListVersionsResponse) -> version.ListVersionsResponse: - """Post-rpc interceptor for list_versions - - Override in a subclass to manipulate the response - after it is returned by the Versions server but before - it is returned to user code. - """ - return response - def pre_update_version(self, request: gcd_version.UpdateVersionRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[gcd_version.UpdateVersionRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for update_version - - Override in a subclass to manipulate the request or metadata - before they are sent to the Versions server. - """ - return request, metadata - - def post_update_version(self, response: gcd_version.Version) -> gcd_version.Version: - """Post-rpc interceptor for update_version - - Override in a subclass to manipulate the response - after it is returned by the Versions server but before - it is returned to user code. - """ - return response - - def pre_get_location( - self, request: locations_pb2.GetLocationRequest, metadata: Sequence[Tuple[str, str]] - ) -> Tuple[locations_pb2.GetLocationRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for get_location - - Override in a subclass to manipulate the request or metadata - before they are sent to the Versions server. - """ - return request, metadata - - def post_get_location( - self, response: locations_pb2.Location - ) -> locations_pb2.Location: - """Post-rpc interceptor for get_location - - Override in a subclass to manipulate the response - after it is returned by the Versions server but before - it is returned to user code. - """ - return response - def pre_list_locations( - self, request: locations_pb2.ListLocationsRequest, metadata: Sequence[Tuple[str, str]] - ) -> Tuple[locations_pb2.ListLocationsRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for list_locations - - Override in a subclass to manipulate the request or metadata - before they are sent to the Versions server. - """ - return request, metadata - - def post_list_locations( - self, response: locations_pb2.ListLocationsResponse - ) -> locations_pb2.ListLocationsResponse: - """Post-rpc interceptor for list_locations - - Override in a subclass to manipulate the response - after it is returned by the Versions server but before - it is returned to user code. - """ - return response - def pre_cancel_operation( - self, request: operations_pb2.CancelOperationRequest, metadata: Sequence[Tuple[str, str]] - ) -> Tuple[operations_pb2.CancelOperationRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for cancel_operation - - Override in a subclass to manipulate the request or metadata - before they are sent to the Versions server. - """ - return request, metadata - - def post_cancel_operation( - self, response: None - ) -> None: - """Post-rpc interceptor for cancel_operation - - Override in a subclass to manipulate the response - after it is returned by the Versions server but before - it is returned to user code. - """ - return response - def pre_get_operation( - self, request: operations_pb2.GetOperationRequest, metadata: Sequence[Tuple[str, str]] - ) -> Tuple[operations_pb2.GetOperationRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for get_operation - - Override in a subclass to manipulate the request or metadata - before they are sent to the Versions server. - """ - return request, metadata - - def post_get_operation( - self, response: operations_pb2.Operation - ) -> operations_pb2.Operation: - """Post-rpc interceptor for get_operation - - Override in a subclass to manipulate the response - after it is returned by the Versions server but before - it is returned to user code. - """ - return response - def pre_list_operations( - self, request: operations_pb2.ListOperationsRequest, metadata: Sequence[Tuple[str, str]] - ) -> Tuple[operations_pb2.ListOperationsRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for list_operations - - Override in a subclass to manipulate the request or metadata - before they are sent to the Versions server. - """ - return request, metadata - - def post_list_operations( - self, response: operations_pb2.ListOperationsResponse - ) -> operations_pb2.ListOperationsResponse: - """Post-rpc interceptor for list_operations - - Override in a subclass to manipulate the response - after it is returned by the Versions server but before - it is returned to user code. - """ - return response - - -@dataclasses.dataclass -class VersionsRestStub: - _session: AuthorizedSession - _host: str - _interceptor: VersionsRestInterceptor - - -class VersionsRestTransport(VersionsTransport): - """REST 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 JSON representations of protocol buffers over HTTP/1.1 - - """ - - def __init__(self, *, - host: str = 'dialogflow.googleapis.com', - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - client_cert_source_for_mtls: Optional[Callable[[ - ], Tuple[bytes, bytes]]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - url_scheme: str = 'https', - interceptor: Optional[VersionsRestInterceptor] = None, - api_audience: Optional[str] = None, - ) -> 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 ignored if ``channel`` is provided. - scopes (Optional(Sequence[str])): A list of scopes. This argument is - ignored if ``channel`` is provided. - client_cert_source_for_mtls (Callable[[], Tuple[bytes, bytes]]): Client - certificate to configure mutual TLS HTTP channel. It is ignored - if ``channel`` is provided. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you are developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - url_scheme: the protocol scheme for the API endpoint. Normally - "https", but for testing or local servers, - "http" can be specified. - """ - # Run the base constructor - # TODO(yon-mg): resolve other ctor params i.e. scopes, quota, etc. - # TODO: When custom host (api_endpoint) is set, `scopes` must *also* be set on the - # credentials object - maybe_url_match = re.match("^(?Phttp(?:s)?://)?(?P.*)$", host) - if maybe_url_match is None: - raise ValueError(f"Unexpected hostname structure: {host}") # pragma: NO COVER - - url_match_items = maybe_url_match.groupdict() - - host = f"{url_scheme}://{host}" if not url_match_items["scheme"] else host - - super().__init__( - host=host, - credentials=credentials, - client_info=client_info, - always_use_jwt_access=always_use_jwt_access, - api_audience=api_audience - ) - self._session = AuthorizedSession( - self._credentials, default_host=self.DEFAULT_HOST) - if client_cert_source_for_mtls: - self._session.configure_mtls_channel(client_cert_source_for_mtls) - self._interceptor = interceptor or VersionsRestInterceptor() - self._prep_wrapped_messages(client_info) - - class _CreateVersion(VersionsRestStub): - def __hash__(self): - return hash("CreateVersion") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: gcd_version.CreateVersionRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> gcd_version.Version: - r"""Call the create version method over HTTP. - - Args: - request (~.gcd_version.CreateVersionRequest): - The request object. The request message for - [Versions.CreateVersion][google.cloud.dialogflow.v2.Versions.CreateVersion]. - 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: - ~.gcd_version.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 `__. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'post', - 'uri': '/v2/{parent=projects/*/agent}/versions', - 'body': 'version', - }, -{ - 'method': 'post', - 'uri': '/v2/{parent=projects/*/locations/*/agent}/versions', - 'body': 'version', - }, - ] - request, metadata = self._interceptor.pre_create_version(request, metadata) - pb_request = gcd_version.CreateVersionRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request['body'], - including_default_value_fields=False, - use_integers_for_enums=True - ) - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - including_default_value_fields=False, - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = gcd_version.Version() - pb_resp = gcd_version.Version.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_create_version(resp) - return resp - - class _DeleteVersion(VersionsRestStub): - def __hash__(self): - return hash("DeleteVersion") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: version.DeleteVersionRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ): - r"""Call the delete version method over HTTP. - - Args: - request (~.version.DeleteVersionRequest): - The request object. The request message for - [Versions.DeleteVersion][google.cloud.dialogflow.v2.Versions.DeleteVersion]. - 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. - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'delete', - 'uri': '/v2/{name=projects/*/agent/versions/*}', - }, -{ - 'method': 'delete', - 'uri': '/v2/{name=projects/*/locations/*/agent/versions/*}', - }, - ] - request, metadata = self._interceptor.pre_delete_version(request, metadata) - pb_request = version.DeleteVersionRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - including_default_value_fields=False, - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - class _GetVersion(VersionsRestStub): - def __hash__(self): - return hash("GetVersion") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: version.GetVersionRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> version.Version: - r"""Call the get version method over HTTP. - - Args: - request (~.version.GetVersionRequest): - The request object. The request message for - [Versions.GetVersion][google.cloud.dialogflow.v2.Versions.GetVersion]. - 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: - ~.version.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 `__. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v2/{name=projects/*/agent/versions/*}', - }, -{ - 'method': 'get', - 'uri': '/v2/{name=projects/*/locations/*/agent/versions/*}', - }, - ] - request, metadata = self._interceptor.pre_get_version(request, metadata) - pb_request = version.GetVersionRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - including_default_value_fields=False, - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = version.Version() - pb_resp = version.Version.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_get_version(resp) - return resp - - class _ListVersions(VersionsRestStub): - def __hash__(self): - return hash("ListVersions") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: version.ListVersionsRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> version.ListVersionsResponse: - r"""Call the list versions method over HTTP. - - Args: - request (~.version.ListVersionsRequest): - The request object. The request message for - [Versions.ListVersions][google.cloud.dialogflow.v2.Versions.ListVersions]. - 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: - ~.version.ListVersionsResponse: - The response message for - [Versions.ListVersions][google.cloud.dialogflow.v2.Versions.ListVersions]. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v2/{parent=projects/*/agent}/versions', - }, -{ - 'method': 'get', - 'uri': '/v2/{parent=projects/*/locations/*/agent}/versions', - }, - ] - request, metadata = self._interceptor.pre_list_versions(request, metadata) - pb_request = version.ListVersionsRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - including_default_value_fields=False, - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = version.ListVersionsResponse() - pb_resp = version.ListVersionsResponse.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_list_versions(resp) - return resp - - class _UpdateVersion(VersionsRestStub): - def __hash__(self): - return hash("UpdateVersion") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - "updateMask" : {}, } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: gcd_version.UpdateVersionRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> gcd_version.Version: - r"""Call the update version method over HTTP. - - Args: - request (~.gcd_version.UpdateVersionRequest): - The request object. The request message for - [Versions.UpdateVersion][google.cloud.dialogflow.v2.Versions.UpdateVersion]. - 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: - ~.gcd_version.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 `__. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'patch', - 'uri': '/v2/{version.name=projects/*/agent/versions/*}', - 'body': 'version', - }, -{ - 'method': 'patch', - 'uri': '/v2/{version.name=projects/*/locations/*/agent/versions/*}', - 'body': 'version', - }, - ] - request, metadata = self._interceptor.pre_update_version(request, metadata) - pb_request = gcd_version.UpdateVersionRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request['body'], - including_default_value_fields=False, - use_integers_for_enums=True - ) - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - including_default_value_fields=False, - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = gcd_version.Version() - pb_resp = gcd_version.Version.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_update_version(resp) - return resp - - @property - def create_version(self) -> Callable[ - [gcd_version.CreateVersionRequest], - gcd_version.Version]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._CreateVersion(self._session, self._host, self._interceptor) # type: ignore - - @property - def delete_version(self) -> Callable[ - [version.DeleteVersionRequest], - empty_pb2.Empty]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._DeleteVersion(self._session, self._host, self._interceptor) # type: ignore - - @property - def get_version(self) -> Callable[ - [version.GetVersionRequest], - version.Version]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._GetVersion(self._session, self._host, self._interceptor) # type: ignore - - @property - def list_versions(self) -> Callable[ - [version.ListVersionsRequest], - version.ListVersionsResponse]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._ListVersions(self._session, self._host, self._interceptor) # type: ignore - - @property - def update_version(self) -> Callable[ - [gcd_version.UpdateVersionRequest], - gcd_version.Version]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._UpdateVersion(self._session, self._host, self._interceptor) # type: ignore - - @property - def get_location(self): - return self._GetLocation(self._session, self._host, self._interceptor) # type: ignore - - class _GetLocation(VersionsRestStub): - def __call__(self, - request: locations_pb2.GetLocationRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> locations_pb2.Location: - - r"""Call the get location method over HTTP. - - Args: - request (locations_pb2.GetLocationRequest): - The request object for GetLocation method. - 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: - locations_pb2.Location: Response from GetLocation method. - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v2/{name=projects/*/locations/*}', - }, - ] - - request, metadata = self._interceptor.pre_get_location(request, metadata) - request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode( - http_options, **request_kwargs) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json.dumps(transcoded_request['query_params'])) - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - resp = locations_pb2.Location() - resp = json_format.Parse(response.content.decode("utf-8"), resp) - resp = self._interceptor.post_get_location(resp) - return resp - - @property - def list_locations(self): - return self._ListLocations(self._session, self._host, self._interceptor) # type: ignore - - class _ListLocations(VersionsRestStub): - def __call__(self, - request: locations_pb2.ListLocationsRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> locations_pb2.ListLocationsResponse: - - r"""Call the list locations method over HTTP. - - Args: - request (locations_pb2.ListLocationsRequest): - The request object for ListLocations method. - 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: - locations_pb2.ListLocationsResponse: Response from ListLocations method. - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v2/{name=projects/*}/locations', - }, - ] - - request, metadata = self._interceptor.pre_list_locations(request, metadata) - request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode( - http_options, **request_kwargs) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json.dumps(transcoded_request['query_params'])) - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - resp = locations_pb2.ListLocationsResponse() - resp = json_format.Parse(response.content.decode("utf-8"), resp) - resp = self._interceptor.post_list_locations(resp) - return resp - - @property - def cancel_operation(self): - return self._CancelOperation(self._session, self._host, self._interceptor) # type: ignore - - class _CancelOperation(VersionsRestStub): - def __call__(self, - request: operations_pb2.CancelOperationRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> None: - - r"""Call the cancel operation method over HTTP. - - Args: - request (operations_pb2.CancelOperationRequest): - The request object for CancelOperation method. - 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. - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'post', - 'uri': '/v2/{name=projects/*/operations/*}:cancel', - }, -{ - 'method': 'post', - 'uri': '/v2/{name=projects/*/locations/*/operations/*}:cancel', - }, - ] - - request, metadata = self._interceptor.pre_cancel_operation(request, metadata) - request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode( - http_options, **request_kwargs) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json.dumps(transcoded_request['query_params'])) - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - return self._interceptor.post_cancel_operation(None) - - @property - def get_operation(self): - return self._GetOperation(self._session, self._host, self._interceptor) # type: ignore - - class _GetOperation(VersionsRestStub): - def __call__(self, - request: operations_pb2.GetOperationRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> operations_pb2.Operation: - - r"""Call the get operation method over HTTP. - - Args: - request (operations_pb2.GetOperationRequest): - The request object for GetOperation method. - 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: - operations_pb2.Operation: Response from GetOperation method. - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v2/{name=projects/*/operations/*}', - }, -{ - 'method': 'get', - 'uri': '/v2/{name=projects/*/locations/*/operations/*}', - }, - ] - - request, metadata = self._interceptor.pre_get_operation(request, metadata) - request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode( - http_options, **request_kwargs) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json.dumps(transcoded_request['query_params'])) - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - resp = operations_pb2.Operation() - resp = json_format.Parse(response.content.decode("utf-8"), resp) - resp = self._interceptor.post_get_operation(resp) - return resp - - @property - def list_operations(self): - return self._ListOperations(self._session, self._host, self._interceptor) # type: ignore - - class _ListOperations(VersionsRestStub): - def __call__(self, - request: operations_pb2.ListOperationsRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> operations_pb2.ListOperationsResponse: - - r"""Call the list operations method over HTTP. - - Args: - request (operations_pb2.ListOperationsRequest): - The request object for ListOperations method. - 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: - operations_pb2.ListOperationsResponse: Response from ListOperations method. - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v2/{name=projects/*}/operations', - }, -{ - 'method': 'get', - 'uri': '/v2/{name=projects/*/locations/*}/operations', - }, - ] - - request, metadata = self._interceptor.pre_list_operations(request, metadata) - request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode( - http_options, **request_kwargs) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json.dumps(transcoded_request['query_params'])) - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - resp = operations_pb2.ListOperationsResponse() - resp = json_format.Parse(response.content.decode("utf-8"), resp) - resp = self._interceptor.post_list_operations(resp) - return resp - - @property - def kind(self) -> str: - return "rest" - - def close(self): - self._session.close() - - -__all__=( - 'VersionsRestTransport', -) diff --git a/owl-bot-staging/v2/google/cloud/dialogflow_v2/types/__init__.py b/owl-bot-staging/v2/google/cloud/dialogflow_v2/types/__init__.py deleted file mode 100644 index f3a20c697..000000000 --- a/owl-bot-staging/v2/google/cloud/dialogflow_v2/types/__init__.py +++ /dev/null @@ -1,520 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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 .agent import ( - Agent, - DeleteAgentRequest, - ExportAgentRequest, - ExportAgentResponse, - GetAgentRequest, - GetValidationResultRequest, - ImportAgentRequest, - RestoreAgentRequest, - SearchAgentsRequest, - SearchAgentsResponse, - SetAgentRequest, - TrainAgentRequest, -) -from .answer_record import ( - AgentAssistantFeedback, - AgentAssistantRecord, - AnswerFeedback, - AnswerRecord, - ListAnswerRecordsRequest, - ListAnswerRecordsResponse, - UpdateAnswerRecordRequest, -) -from .audio_config import ( - InputAudioConfig, - OutputAudioConfig, - SpeechContext, - SpeechToTextConfig, - SpeechWordInfo, - SynthesizeSpeechConfig, - TelephonyDtmfEvents, - VoiceSelectionParams, - AudioEncoding, - OutputAudioEncoding, - SpeechModelVariant, - SsmlVoiceGender, - TelephonyDtmf, -) -from .context import ( - Context, - CreateContextRequest, - DeleteAllContextsRequest, - DeleteContextRequest, - GetContextRequest, - ListContextsRequest, - ListContextsResponse, - UpdateContextRequest, -) -from .conversation import ( - CompleteConversationRequest, - Conversation, - ConversationPhoneNumber, - CreateConversationRequest, - GetConversationRequest, - ListConversationsRequest, - ListConversationsResponse, - ListMessagesRequest, - ListMessagesResponse, - SuggestConversationSummaryRequest, - SuggestConversationSummaryResponse, -) -from .conversation_dataset import ( - ConversationDataset, - ConversationInfo, - CreateConversationDatasetOperationMetadata, - CreateConversationDatasetRequest, - DeleteConversationDatasetOperationMetadata, - DeleteConversationDatasetRequest, - GetConversationDatasetRequest, - ImportConversationDataOperationMetadata, - ImportConversationDataOperationResponse, - ImportConversationDataRequest, - InputConfig, - ListConversationDatasetsRequest, - ListConversationDatasetsResponse, -) -from .conversation_event import ( - ConversationEvent, -) -from .conversation_model import ( - ArticleSuggestionModelMetadata, - ConversationModel, - ConversationModelEvaluation, - CreateConversationModelEvaluationOperationMetadata, - CreateConversationModelEvaluationRequest, - CreateConversationModelOperationMetadata, - CreateConversationModelRequest, - DeleteConversationModelOperationMetadata, - DeleteConversationModelRequest, - DeployConversationModelOperationMetadata, - DeployConversationModelRequest, - EvaluationConfig, - GetConversationModelEvaluationRequest, - GetConversationModelRequest, - InputDataset, - ListConversationModelEvaluationsRequest, - ListConversationModelEvaluationsResponse, - ListConversationModelsRequest, - ListConversationModelsResponse, - SmartReplyMetrics, - SmartReplyModelMetadata, - UndeployConversationModelOperationMetadata, - UndeployConversationModelRequest, -) -from .conversation_profile import ( - AutomatedAgentConfig, - ClearSuggestionFeatureConfigOperationMetadata, - ClearSuggestionFeatureConfigRequest, - ConversationProfile, - CreateConversationProfileRequest, - DeleteConversationProfileRequest, - GetConversationProfileRequest, - HumanAgentAssistantConfig, - HumanAgentHandoffConfig, - ListConversationProfilesRequest, - ListConversationProfilesResponse, - LoggingConfig, - NotificationConfig, - SetSuggestionFeatureConfigOperationMetadata, - SetSuggestionFeatureConfigRequest, - SuggestionFeature, - UpdateConversationProfileRequest, -) -from .document import ( - CreateDocumentRequest, - DeleteDocumentRequest, - Document, - ExportDocumentRequest, - ExportOperationMetadata, - GetDocumentRequest, - ImportDocumentsRequest, - ImportDocumentsResponse, - ImportDocumentTemplate, - KnowledgeOperationMetadata, - ListDocumentsRequest, - ListDocumentsResponse, - ReloadDocumentRequest, - UpdateDocumentRequest, -) -from .entity_type import ( - BatchCreateEntitiesRequest, - BatchDeleteEntitiesRequest, - BatchDeleteEntityTypesRequest, - BatchUpdateEntitiesRequest, - BatchUpdateEntityTypesRequest, - BatchUpdateEntityTypesResponse, - CreateEntityTypeRequest, - DeleteEntityTypeRequest, - EntityType, - EntityTypeBatch, - GetEntityTypeRequest, - ListEntityTypesRequest, - ListEntityTypesResponse, - UpdateEntityTypeRequest, -) -from .environment import ( - CreateEnvironmentRequest, - DeleteEnvironmentRequest, - Environment, - EnvironmentHistory, - GetEnvironmentHistoryRequest, - GetEnvironmentRequest, - ListEnvironmentsRequest, - ListEnvironmentsResponse, - TextToSpeechSettings, - UpdateEnvironmentRequest, -) -from .fulfillment import ( - Fulfillment, - GetFulfillmentRequest, - UpdateFulfillmentRequest, -) -from .gcs import ( - GcsDestination, - GcsSources, -) -from .human_agent_assistant_event import ( - HumanAgentAssistantEvent, -) -from .intent import ( - BatchDeleteIntentsRequest, - BatchUpdateIntentsRequest, - BatchUpdateIntentsResponse, - CreateIntentRequest, - DeleteIntentRequest, - GetIntentRequest, - Intent, - IntentBatch, - ListIntentsRequest, - ListIntentsResponse, - UpdateIntentRequest, - IntentView, -) -from .knowledge_base import ( - CreateKnowledgeBaseRequest, - DeleteKnowledgeBaseRequest, - GetKnowledgeBaseRequest, - KnowledgeBase, - ListKnowledgeBasesRequest, - ListKnowledgeBasesResponse, - UpdateKnowledgeBaseRequest, -) -from .participant import ( - AnalyzeContentRequest, - AnalyzeContentResponse, - AnnotatedMessagePart, - ArticleAnswer, - AssistQueryParameters, - AutomatedAgentReply, - CreateParticipantRequest, - DtmfParameters, - FaqAnswer, - GetParticipantRequest, - InputTextConfig, - ListParticipantsRequest, - ListParticipantsResponse, - Message, - MessageAnnotation, - OutputAudio, - Participant, - SmartReplyAnswer, - StreamingAnalyzeContentRequest, - StreamingAnalyzeContentResponse, - SuggestArticlesRequest, - SuggestArticlesResponse, - SuggestFaqAnswersRequest, - SuggestFaqAnswersResponse, - SuggestionResult, - SuggestSmartRepliesRequest, - SuggestSmartRepliesResponse, - UpdateParticipantRequest, -) -from .session import ( - DetectIntentRequest, - DetectIntentResponse, - EventInput, - QueryInput, - QueryParameters, - QueryResult, - Sentiment, - SentimentAnalysisRequestConfig, - SentimentAnalysisResult, - StreamingDetectIntentRequest, - StreamingDetectIntentResponse, - StreamingRecognitionResult, - TextInput, -) -from .session_entity_type import ( - CreateSessionEntityTypeRequest, - DeleteSessionEntityTypeRequest, - GetSessionEntityTypeRequest, - ListSessionEntityTypesRequest, - ListSessionEntityTypesResponse, - SessionEntityType, - UpdateSessionEntityTypeRequest, -) -from .validation_result import ( - ValidationError, - ValidationResult, -) -from .version import ( - CreateVersionRequest, - DeleteVersionRequest, - GetVersionRequest, - ListVersionsRequest, - ListVersionsResponse, - UpdateVersionRequest, - Version, -) -from .webhook import ( - OriginalDetectIntentRequest, - WebhookRequest, - WebhookResponse, -) - -__all__ = ( - 'Agent', - 'DeleteAgentRequest', - 'ExportAgentRequest', - 'ExportAgentResponse', - 'GetAgentRequest', - 'GetValidationResultRequest', - 'ImportAgentRequest', - 'RestoreAgentRequest', - 'SearchAgentsRequest', - 'SearchAgentsResponse', - 'SetAgentRequest', - 'TrainAgentRequest', - 'AgentAssistantFeedback', - 'AgentAssistantRecord', - 'AnswerFeedback', - 'AnswerRecord', - 'ListAnswerRecordsRequest', - 'ListAnswerRecordsResponse', - 'UpdateAnswerRecordRequest', - 'InputAudioConfig', - 'OutputAudioConfig', - 'SpeechContext', - 'SpeechToTextConfig', - 'SpeechWordInfo', - 'SynthesizeSpeechConfig', - 'TelephonyDtmfEvents', - 'VoiceSelectionParams', - 'AudioEncoding', - 'OutputAudioEncoding', - 'SpeechModelVariant', - 'SsmlVoiceGender', - 'TelephonyDtmf', - 'Context', - 'CreateContextRequest', - 'DeleteAllContextsRequest', - 'DeleteContextRequest', - 'GetContextRequest', - 'ListContextsRequest', - 'ListContextsResponse', - 'UpdateContextRequest', - 'CompleteConversationRequest', - 'Conversation', - 'ConversationPhoneNumber', - 'CreateConversationRequest', - 'GetConversationRequest', - 'ListConversationsRequest', - 'ListConversationsResponse', - 'ListMessagesRequest', - 'ListMessagesResponse', - 'SuggestConversationSummaryRequest', - 'SuggestConversationSummaryResponse', - 'ConversationDataset', - 'ConversationInfo', - 'CreateConversationDatasetOperationMetadata', - 'CreateConversationDatasetRequest', - 'DeleteConversationDatasetOperationMetadata', - 'DeleteConversationDatasetRequest', - 'GetConversationDatasetRequest', - 'ImportConversationDataOperationMetadata', - 'ImportConversationDataOperationResponse', - 'ImportConversationDataRequest', - 'InputConfig', - 'ListConversationDatasetsRequest', - 'ListConversationDatasetsResponse', - 'ConversationEvent', - 'ArticleSuggestionModelMetadata', - 'ConversationModel', - 'ConversationModelEvaluation', - 'CreateConversationModelEvaluationOperationMetadata', - 'CreateConversationModelEvaluationRequest', - 'CreateConversationModelOperationMetadata', - 'CreateConversationModelRequest', - 'DeleteConversationModelOperationMetadata', - 'DeleteConversationModelRequest', - 'DeployConversationModelOperationMetadata', - 'DeployConversationModelRequest', - 'EvaluationConfig', - 'GetConversationModelEvaluationRequest', - 'GetConversationModelRequest', - 'InputDataset', - 'ListConversationModelEvaluationsRequest', - 'ListConversationModelEvaluationsResponse', - 'ListConversationModelsRequest', - 'ListConversationModelsResponse', - 'SmartReplyMetrics', - 'SmartReplyModelMetadata', - 'UndeployConversationModelOperationMetadata', - 'UndeployConversationModelRequest', - 'AutomatedAgentConfig', - 'ClearSuggestionFeatureConfigOperationMetadata', - 'ClearSuggestionFeatureConfigRequest', - 'ConversationProfile', - 'CreateConversationProfileRequest', - 'DeleteConversationProfileRequest', - 'GetConversationProfileRequest', - 'HumanAgentAssistantConfig', - 'HumanAgentHandoffConfig', - 'ListConversationProfilesRequest', - 'ListConversationProfilesResponse', - 'LoggingConfig', - 'NotificationConfig', - 'SetSuggestionFeatureConfigOperationMetadata', - 'SetSuggestionFeatureConfigRequest', - 'SuggestionFeature', - 'UpdateConversationProfileRequest', - 'CreateDocumentRequest', - 'DeleteDocumentRequest', - 'Document', - 'ExportDocumentRequest', - 'ExportOperationMetadata', - 'GetDocumentRequest', - 'ImportDocumentsRequest', - 'ImportDocumentsResponse', - 'ImportDocumentTemplate', - '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', - 'GcsDestination', - 'GcsSources', - 'HumanAgentAssistantEvent', - 'BatchDeleteIntentsRequest', - 'BatchUpdateIntentsRequest', - 'BatchUpdateIntentsResponse', - 'CreateIntentRequest', - 'DeleteIntentRequest', - 'GetIntentRequest', - 'Intent', - 'IntentBatch', - 'ListIntentsRequest', - 'ListIntentsResponse', - 'UpdateIntentRequest', - 'IntentView', - 'CreateKnowledgeBaseRequest', - 'DeleteKnowledgeBaseRequest', - 'GetKnowledgeBaseRequest', - 'KnowledgeBase', - 'ListKnowledgeBasesRequest', - 'ListKnowledgeBasesResponse', - 'UpdateKnowledgeBaseRequest', - 'AnalyzeContentRequest', - 'AnalyzeContentResponse', - 'AnnotatedMessagePart', - 'ArticleAnswer', - 'AssistQueryParameters', - 'AutomatedAgentReply', - 'CreateParticipantRequest', - 'DtmfParameters', - 'FaqAnswer', - 'GetParticipantRequest', - 'InputTextConfig', - 'ListParticipantsRequest', - 'ListParticipantsResponse', - 'Message', - 'MessageAnnotation', - 'OutputAudio', - 'Participant', - 'SmartReplyAnswer', - 'StreamingAnalyzeContentRequest', - 'StreamingAnalyzeContentResponse', - 'SuggestArticlesRequest', - 'SuggestArticlesResponse', - 'SuggestFaqAnswersRequest', - 'SuggestFaqAnswersResponse', - 'SuggestionResult', - 'SuggestSmartRepliesRequest', - 'SuggestSmartRepliesResponse', - 'UpdateParticipantRequest', - 'DetectIntentRequest', - 'DetectIntentResponse', - 'EventInput', - 'QueryInput', - 'QueryParameters', - 'QueryResult', - 'Sentiment', - 'SentimentAnalysisRequestConfig', - 'SentimentAnalysisResult', - 'StreamingDetectIntentRequest', - 'StreamingDetectIntentResponse', - 'StreamingRecognitionResult', - 'TextInput', - 'CreateSessionEntityTypeRequest', - 'DeleteSessionEntityTypeRequest', - 'GetSessionEntityTypeRequest', - 'ListSessionEntityTypesRequest', - 'ListSessionEntityTypesResponse', - 'SessionEntityType', - 'UpdateSessionEntityTypeRequest', - 'ValidationError', - 'ValidationResult', - 'CreateVersionRequest', - 'DeleteVersionRequest', - 'GetVersionRequest', - 'ListVersionsRequest', - 'ListVersionsResponse', - 'UpdateVersionRequest', - 'Version', - 'OriginalDetectIntentRequest', - 'WebhookRequest', - 'WebhookResponse', -) diff --git a/owl-bot-staging/v2/google/cloud/dialogflow_v2/types/agent.py b/owl-bot-staging/v2/google/cloud/dialogflow_v2/types/agent.py deleted file mode 100644 index 44df7c7af..000000000 --- a/owl-bot-staging/v2/google/cloud/dialogflow_v2/types/agent.py +++ /dev/null @@ -1,550 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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 __future__ import annotations - -from typing import MutableMapping, MutableSequence - -import proto # type: ignore - -from google.protobuf import field_mask_pb2 # type: ignore - - -__protobuf__ = proto.module( - package='google.cloud.dialogflow.v2', - manifest={ - 'Agent', - 'GetAgentRequest', - 'SetAgentRequest', - 'DeleteAgentRequest', - 'SearchAgentsRequest', - 'SearchAgentsResponse', - 'TrainAgentRequest', - 'ExportAgentRequest', - 'ExportAgentResponse', - 'ImportAgentRequest', - 'RestoreAgentRequest', - 'GetValidationResultRequest', - }, -) - - -class Agent(proto.Message): - r"""A Dialogflow agent is a virtual agent that handles conversations - with your end-users. It is a natural language understanding module - that understands the nuances of human language. Dialogflow - translates end-user text or audio during a conversation to - structured data that your apps and services can understand. You - design and build a Dialogflow agent to handle the types of - conversations required for your system. - - For more information about agents, see the `Agent - guide `__. - - Attributes: - parent (str): - Required. The project of this agent. Format: - ``projects/``. - display_name (str): - Required. The name of this agent. - default_language_code (str): - Required. The default language of the agent as a language - tag. See `Language - Support `__ - for a list of the currently supported language codes. This - field cannot be set by the ``Update`` method. - supported_language_codes (MutableSequence[str]): - Optional. The list of all languages supported by this agent - (except for the ``default_language_code``). - time_zone (str): - Required. The time zone of this agent from the `time zone - database `__, e.g., - America/New_York, Europe/Paris. - description (str): - Optional. The description of this agent. - The maximum length is 500 characters. If - exceeded, the request is rejected. - avatar_uri (str): - Optional. The URI of the agent's avatar. Avatars are used - throughout the Dialogflow console and in the self-hosted - `Web - Demo `__ - integration. - enable_logging (bool): - Optional. Determines whether this agent - should log conversation queries. - match_mode (google.cloud.dialogflow_v2.types.Agent.MatchMode): - Optional. Determines how intents are detected - from user queries. - classification_threshold (float): - Optional. To filter out false positive - results and still get variety in matched natural - language inputs for your agent, you can tune the - machine learning classification threshold. If - the returned score value is less than the - threshold value, then a fallback intent will be - triggered or, if there are no fallback intents - defined, no intent will be triggered. The score - values range from 0.0 (completely uncertain) to - 1.0 (completely certain). If set to 0.0, the - default of 0.3 is used. - api_version (google.cloud.dialogflow_v2.types.Agent.ApiVersion): - Optional. API version displayed in Dialogflow - console. If not specified, V2 API is assumed. - Clients are free to query different service - endpoints for different API versions. However, - bots connectors and webhook calls will follow - the specified API version. - tier (google.cloud.dialogflow_v2.types.Agent.Tier): - Optional. The agent tier. If not specified, TIER_STANDARD is - assumed. - """ - class MatchMode(proto.Enum): - r"""Match mode determines how intents are detected from user - queries. - - Values: - MATCH_MODE_UNSPECIFIED (0): - Not specified. - MATCH_MODE_HYBRID (1): - Best for agents with a small number of - examples in intents and/or wide use of templates - syntax and composite entities. - MATCH_MODE_ML_ONLY (2): - Can be used for agents with a large number of - examples in intents, especially the ones using - @sys.any or very large custom entities. - """ - MATCH_MODE_UNSPECIFIED = 0 - MATCH_MODE_HYBRID = 1 - MATCH_MODE_ML_ONLY = 2 - - class ApiVersion(proto.Enum): - r"""API version for the agent. - - Values: - API_VERSION_UNSPECIFIED (0): - Not specified. - API_VERSION_V1 (1): - Legacy V1 API. - API_VERSION_V2 (2): - V2 API. - API_VERSION_V2_BETA_1 (3): - V2beta1 API. - """ - API_VERSION_UNSPECIFIED = 0 - API_VERSION_V1 = 1 - API_VERSION_V2 = 2 - API_VERSION_V2_BETA_1 = 3 - - class Tier(proto.Enum): - r"""Represents the agent tier. - - Values: - TIER_UNSPECIFIED (0): - Not specified. This value should never be - used. - TIER_STANDARD (1): - Trial Edition, previously known as Standard - Edition. - TIER_ENTERPRISE (2): - Essentials Edition, previously known as - Enterprise Essential Edition. - TIER_ENTERPRISE_PLUS (3): - Essentials Edition (same as TIER_ENTERPRISE), previously - known as Enterprise Plus Edition. - """ - TIER_UNSPECIFIED = 0 - TIER_STANDARD = 1 - TIER_ENTERPRISE = 2 - TIER_ENTERPRISE_PLUS = 3 - - parent: str = proto.Field( - proto.STRING, - number=1, - ) - display_name: str = proto.Field( - proto.STRING, - number=2, - ) - default_language_code: str = proto.Field( - proto.STRING, - number=3, - ) - supported_language_codes: MutableSequence[str] = proto.RepeatedField( - proto.STRING, - number=4, - ) - time_zone: str = proto.Field( - proto.STRING, - number=5, - ) - description: str = proto.Field( - proto.STRING, - number=6, - ) - avatar_uri: str = proto.Field( - proto.STRING, - number=7, - ) - enable_logging: bool = proto.Field( - proto.BOOL, - number=8, - ) - match_mode: MatchMode = proto.Field( - proto.ENUM, - number=9, - enum=MatchMode, - ) - classification_threshold: float = proto.Field( - proto.FLOAT, - number=10, - ) - api_version: ApiVersion = proto.Field( - proto.ENUM, - number=14, - enum=ApiVersion, - ) - tier: Tier = proto.Field( - proto.ENUM, - number=15, - enum=Tier, - ) - - -class GetAgentRequest(proto.Message): - r"""The request message for - [Agents.GetAgent][google.cloud.dialogflow.v2.Agents.GetAgent]. - - Attributes: - parent (str): - Required. The project that the agent to fetch is associated - with. Format: ``projects/``. - """ - - parent: str = proto.Field( - proto.STRING, - number=1, - ) - - -class SetAgentRequest(proto.Message): - r"""The request message for - [Agents.SetAgent][google.cloud.dialogflow.v2.Agents.SetAgent]. - - Attributes: - agent (google.cloud.dialogflow_v2.types.Agent): - Required. The agent to update. - update_mask (google.protobuf.field_mask_pb2.FieldMask): - Optional. The mask to control which fields - get updated. - """ - - agent: 'Agent' = proto.Field( - proto.MESSAGE, - number=1, - message='Agent', - ) - update_mask: field_mask_pb2.FieldMask = proto.Field( - proto.MESSAGE, - number=2, - message=field_mask_pb2.FieldMask, - ) - - -class DeleteAgentRequest(proto.Message): - r"""The request message for - [Agents.DeleteAgent][google.cloud.dialogflow.v2.Agents.DeleteAgent]. - - Attributes: - parent (str): - Required. The project that the agent to delete is associated - with. Format: ``projects/``. - """ - - parent: str = proto.Field( - proto.STRING, - number=1, - ) - - -class SearchAgentsRequest(proto.Message): - r"""The request message for - [Agents.SearchAgents][google.cloud.dialogflow.v2.Agents.SearchAgents]. - - Attributes: - parent (str): - Required. The project to list agents from. Format: - ``projects/``. - 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): - The next_page_token value returned from a previous list - request. - """ - - parent: str = proto.Field( - proto.STRING, - number=1, - ) - page_size: int = proto.Field( - proto.INT32, - number=2, - ) - page_token: str = proto.Field( - proto.STRING, - number=3, - ) - - -class SearchAgentsResponse(proto.Message): - r"""The response message for - [Agents.SearchAgents][google.cloud.dialogflow.v2.Agents.SearchAgents]. - - Attributes: - agents (MutableSequence[google.cloud.dialogflow_v2.types.Agent]): - The list of agents. 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 - - agents: MutableSequence['Agent'] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message='Agent', - ) - next_page_token: str = proto.Field( - proto.STRING, - number=2, - ) - - -class TrainAgentRequest(proto.Message): - r"""The request message for - [Agents.TrainAgent][google.cloud.dialogflow.v2.Agents.TrainAgent]. - - Attributes: - parent (str): - Required. The project that the agent to train is associated - with. Format: ``projects/``. - """ - - parent: str = proto.Field( - proto.STRING, - number=1, - ) - - -class ExportAgentRequest(proto.Message): - r"""The request message for - [Agents.ExportAgent][google.cloud.dialogflow.v2.Agents.ExportAgent]. - - Attributes: - parent (str): - Required. The project that the agent to export is associated - with. Format: ``projects/``. - agent_uri (str): - Required. The `Google Cloud - Storage `__ URI to - export the agent to. The format of this URI must be - ``gs:///``. If left unspecified, - the serialized agent is returned inline. - - Dialogflow performs a write operation for the Cloud Storage - object on the caller's behalf, so your request - authentication must have write permissions for the object. - For more information, see `Dialogflow access - control `__. - """ - - parent: str = proto.Field( - proto.STRING, - number=1, - ) - agent_uri: str = proto.Field( - proto.STRING, - number=2, - ) - - -class ExportAgentResponse(proto.Message): - r"""The response message for - [Agents.ExportAgent][google.cloud.dialogflow.v2.Agents.ExportAgent]. - - This message has `oneof`_ fields (mutually exclusive fields). - For each oneof, at most one member field can be set at the same time. - Setting any member of the oneof automatically clears all other - members. - - .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields - - Attributes: - agent_uri (str): - The URI to a file containing the exported agent. This field - is populated only if ``agent_uri`` is specified in - ``ExportAgentRequest``. - - This field is a member of `oneof`_ ``agent``. - agent_content (bytes): - Zip compressed raw byte content for agent. - - This field is a member of `oneof`_ ``agent``. - """ - - agent_uri: str = proto.Field( - proto.STRING, - number=1, - oneof='agent', - ) - agent_content: bytes = proto.Field( - proto.BYTES, - number=2, - oneof='agent', - ) - - -class ImportAgentRequest(proto.Message): - r"""The request message for - [Agents.ImportAgent][google.cloud.dialogflow.v2.Agents.ImportAgent]. - - This message has `oneof`_ fields (mutually exclusive fields). - For each oneof, at most one member field can be set at the same time. - Setting any member of the oneof automatically clears all other - members. - - .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields - - Attributes: - parent (str): - Required. The project that the agent to import is associated - with. Format: ``projects/``. - agent_uri (str): - The URI to a Google Cloud Storage file containing the agent - to import. Note: The URI must start with "gs://". - - Dialogflow performs a read operation for the Cloud Storage - object on the caller's behalf, so your request - authentication must have read permissions for the object. - For more information, see `Dialogflow access - control `__. - - This field is a member of `oneof`_ ``agent``. - agent_content (bytes): - Zip compressed raw byte content for agent. - - This field is a member of `oneof`_ ``agent``. - """ - - parent: str = proto.Field( - proto.STRING, - number=1, - ) - agent_uri: str = proto.Field( - proto.STRING, - number=2, - oneof='agent', - ) - agent_content: bytes = proto.Field( - proto.BYTES, - number=3, - oneof='agent', - ) - - -class RestoreAgentRequest(proto.Message): - r"""The request message for - [Agents.RestoreAgent][google.cloud.dialogflow.v2.Agents.RestoreAgent]. - - This message has `oneof`_ fields (mutually exclusive fields). - For each oneof, at most one member field can be set at the same time. - Setting any member of the oneof automatically clears all other - members. - - .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields - - Attributes: - parent (str): - Required. The project that the agent to restore is - associated with. Format: ``projects/``. - agent_uri (str): - The URI to a Google Cloud Storage file containing the agent - to restore. Note: The URI must start with "gs://". - - Dialogflow performs a read operation for the Cloud Storage - object on the caller's behalf, so your request - authentication must have read permissions for the object. - For more information, see `Dialogflow access - control `__. - - This field is a member of `oneof`_ ``agent``. - agent_content (bytes): - Zip compressed raw byte content for agent. - - This field is a member of `oneof`_ ``agent``. - """ - - parent: str = proto.Field( - proto.STRING, - number=1, - ) - agent_uri: str = proto.Field( - proto.STRING, - number=2, - oneof='agent', - ) - agent_content: bytes = proto.Field( - proto.BYTES, - number=3, - oneof='agent', - ) - - -class GetValidationResultRequest(proto.Message): - r"""The request message for - [Agents.GetValidationResult][google.cloud.dialogflow.v2.Agents.GetValidationResult]. - - Attributes: - parent (str): - Required. The project that the agent is associated with. - Format: ``projects/``. - language_code (str): - Optional. The language for which you want a validation - result. If not specified, the agent's default language is - used. `Many - languages `__ - are supported. Note: languages must be enabled in the agent - before they can be used. - """ - - parent: str = proto.Field( - proto.STRING, - number=1, - ) - language_code: str = proto.Field( - proto.STRING, - number=3, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v2/google/cloud/dialogflow_v2/types/answer_record.py b/owl-bot-staging/v2/google/cloud/dialogflow_v2/types/answer_record.py deleted file mode 100644 index 81932c1e4..000000000 --- a/owl-bot-staging/v2/google/cloud/dialogflow_v2/types/answer_record.py +++ /dev/null @@ -1,452 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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 __future__ import annotations - -from typing import MutableMapping, MutableSequence - -import proto # type: ignore - -from google.cloud.dialogflow_v2.types import participant -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={ - 'AnswerRecord', - 'ListAnswerRecordsRequest', - 'ListAnswerRecordsResponse', - 'UpdateAnswerRecordRequest', - 'AnswerFeedback', - 'AgentAssistantFeedback', - 'AgentAssistantRecord', - }, -) - - -class AnswerRecord(proto.Message): - r"""Answer records are records to manage answer history and feedbacks - for Dialogflow. - - Currently, answer record includes: - - - human agent assistant article suggestion - - human agent assistant faq article - - It doesn't include: - - - ``DetectIntent`` intent matching - - ``DetectIntent`` knowledge - - Answer records are not related to the conversation history in the - Dialogflow Console. A Record is generated even when the end-user - disables conversation history in the console. Records are created - when there's a human agent assistant suggestion generated. - - A typical workflow for customers provide feedback to an answer is: - - 1. For human agent assistant, customers get suggestion via - ListSuggestions API. Together with 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. - - - .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields - - Attributes: - name (str): - The unique identifier of this answer record. Format: - ``projects//locations//answerRecords/``. - answer_feedback (google.cloud.dialogflow_v2.types.AnswerFeedback): - Required. The AnswerFeedback for this record. You can set - this with - [AnswerRecords.UpdateAnswerRecord][google.cloud.dialogflow.v2.AnswerRecords.UpdateAnswerRecord] - in order to give us feedback about this answer. - agent_assistant_record (google.cloud.dialogflow_v2.types.AgentAssistantRecord): - Output only. The record for human agent - assistant. - - This field is a member of `oneof`_ ``record``. - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - answer_feedback: 'AnswerFeedback' = proto.Field( - proto.MESSAGE, - number=2, - message='AnswerFeedback', - ) - agent_assistant_record: 'AgentAssistantRecord' = proto.Field( - proto.MESSAGE, - number=4, - oneof='record', - message='AgentAssistantRecord', - ) - - -class ListAnswerRecordsRequest(proto.Message): - r"""Request message for - [AnswerRecords.ListAnswerRecords][google.cloud.dialogflow.v2.AnswerRecords.ListAnswerRecords]. - - Attributes: - parent (str): - Required. The project to list all answer records for in - reverse chronological order. Format: - ``projects//locations/``. - filter (str): - Optional. Filters to restrict results to specific answer - records. - - Marked deprecated as it hasn't been, and isn't currently, - supported. - - For more information about filtering, see `API - Filtering `__. - page_size (int): - Optional. The maximum number of records to - return in a single page. The server may return - fewer records than this. If unspecified, we use - 10. The maximum is 100. - page_token (str): - Optional. The - [ListAnswerRecordsResponse.next_page_token][google.cloud.dialogflow.v2.ListAnswerRecordsResponse.next_page_token] - value returned from a previous list request used to continue - listing on the next page. - """ - - parent: str = proto.Field( - proto.STRING, - number=1, - ) - filter: str = proto.Field( - proto.STRING, - number=2, - ) - page_size: int = proto.Field( - proto.INT32, - number=3, - ) - page_token: str = proto.Field( - proto.STRING, - number=4, - ) - - -class ListAnswerRecordsResponse(proto.Message): - r"""Response message for - [AnswerRecords.ListAnswerRecords][google.cloud.dialogflow.v2.AnswerRecords.ListAnswerRecords]. - - Attributes: - answer_records (MutableSequence[google.cloud.dialogflow_v2.types.AnswerRecord]): - The list of answer records. - next_page_token (str): - A token to retrieve next page of results. Or empty if there - are no more results. Pass this value in the - [ListAnswerRecordsRequest.page_token][google.cloud.dialogflow.v2.ListAnswerRecordsRequest.page_token] - field in the subsequent call to ``ListAnswerRecords`` method - to retrieve the next page of results. - """ - - @property - def raw_page(self): - return self - - answer_records: MutableSequence['AnswerRecord'] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message='AnswerRecord', - ) - next_page_token: str = proto.Field( - proto.STRING, - number=2, - ) - - -class UpdateAnswerRecordRequest(proto.Message): - r"""Request message for - [AnswerRecords.UpdateAnswerRecord][google.cloud.dialogflow.v2.AnswerRecords.UpdateAnswerRecord]. - - Attributes: - answer_record (google.cloud.dialogflow_v2.types.AnswerRecord): - Required. Answer record to update. - update_mask (google.protobuf.field_mask_pb2.FieldMask): - Required. The mask to control which fields - get updated. - """ - - answer_record: 'AnswerRecord' = proto.Field( - proto.MESSAGE, - number=1, - message='AnswerRecord', - ) - update_mask: field_mask_pb2.FieldMask = proto.Field( - proto.MESSAGE, - number=2, - message=field_mask_pb2.FieldMask, - ) - - -class AnswerFeedback(proto.Message): - r"""Represents feedback the customer has about the quality & - correctness of a certain answer in a conversation. - - - .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields - - Attributes: - correctness_level (google.cloud.dialogflow_v2.types.AnswerFeedback.CorrectnessLevel): - The correctness level of the specific answer. - agent_assistant_detail_feedback (google.cloud.dialogflow_v2.types.AgentAssistantFeedback): - Detail feedback of agent assist suggestions. - - This field is a member of `oneof`_ ``detail_feedback``. - clicked (bool): - Indicates whether the answer/item was clicked - by the human agent or not. Default to false. - click_time (google.protobuf.timestamp_pb2.Timestamp): - Time when the answer/item was clicked. - displayed (bool): - Indicates whether the answer/item was - displayed to the human agent in the agent - desktop UI. Default to false. - display_time (google.protobuf.timestamp_pb2.Timestamp): - Time when the answer/item was displayed. - """ - class CorrectnessLevel(proto.Enum): - r"""The correctness level of an answer. - - Values: - CORRECTNESS_LEVEL_UNSPECIFIED (0): - Correctness level unspecified. - NOT_CORRECT (1): - Answer is totally wrong. - PARTIALLY_CORRECT (2): - Answer is partially correct. - FULLY_CORRECT (3): - Answer is fully correct. - """ - CORRECTNESS_LEVEL_UNSPECIFIED = 0 - NOT_CORRECT = 1 - PARTIALLY_CORRECT = 2 - FULLY_CORRECT = 3 - - correctness_level: CorrectnessLevel = proto.Field( - proto.ENUM, - number=1, - enum=CorrectnessLevel, - ) - agent_assistant_detail_feedback: 'AgentAssistantFeedback' = proto.Field( - proto.MESSAGE, - number=2, - oneof='detail_feedback', - message='AgentAssistantFeedback', - ) - clicked: bool = proto.Field( - proto.BOOL, - number=3, - ) - click_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=5, - message=timestamp_pb2.Timestamp, - ) - displayed: bool = proto.Field( - proto.BOOL, - number=4, - ) - display_time: timestamp_pb2.Timestamp = 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. - - For example: - - - Query: "Can I change my mailing address?" - - Suggested document says: "Items must be - returned/exchanged within 60 days of the purchase date." - - [answer_relevance][google.cloud.dialogflow.v2.AgentAssistantFeedback.answer_relevance]: - [AnswerRelevance.IRRELEVANT][google.cloud.dialogflow.v2.AgentAssistantFeedback.AnswerRelevance.IRRELEVANT] - document_correctness (google.cloud.dialogflow_v2.types.AgentAssistantFeedback.DocumentCorrectness): - Optional. Whether or not the information in the document is - correct. - - For example: - - - Query: "Can I return the package in 2 days once - received?" - - Suggested document says: "Items must be - returned/exchanged within 60 days of the purchase date." - - Ground truth: "No return or exchange is allowed." - - - document_efficiency (google.cloud.dialogflow_v2.types.AgentAssistantFeedback.DocumentEfficiency): - Optional. Whether or not the suggested document is - efficient. For example, if the document is poorly written, - hard to understand, hard to use or too long to find useful - information, - [document_efficiency][google.cloud.dialogflow.v2.AgentAssistantFeedback.document_efficiency] - is - [DocumentEfficiency.INEFFICIENT][google.cloud.dialogflow.v2.AgentAssistantFeedback.DocumentEfficiency.INEFFICIENT]. - summarization_feedback (google.cloud.dialogflow_v2.types.AgentAssistantFeedback.SummarizationFeedback): - Optional. Feedback for conversation - summarization. - """ - class AnswerRelevance(proto.Enum): - r"""Relevance of an answer. - - Values: - ANSWER_RELEVANCE_UNSPECIFIED (0): - Answer relevance unspecified. - IRRELEVANT (1): - Answer is irrelevant to query. - RELEVANT (2): - Answer is relevant to query. - """ - ANSWER_RELEVANCE_UNSPECIFIED = 0 - IRRELEVANT = 1 - RELEVANT = 2 - - class DocumentCorrectness(proto.Enum): - r"""Correctness of document. - - Values: - DOCUMENT_CORRECTNESS_UNSPECIFIED (0): - Document correctness unspecified. - INCORRECT (1): - Information in document is incorrect. - CORRECT (2): - Information in document is correct. - """ - DOCUMENT_CORRECTNESS_UNSPECIFIED = 0 - INCORRECT = 1 - CORRECT = 2 - - class DocumentEfficiency(proto.Enum): - r"""Efficiency of document. - - Values: - DOCUMENT_EFFICIENCY_UNSPECIFIED (0): - Document efficiency unspecified. - INEFFICIENT (1): - Document is inefficient. - EFFICIENT (2): - Document is efficient. - """ - DOCUMENT_EFFICIENCY_UNSPECIFIED = 0 - INEFFICIENT = 1 - EFFICIENT = 2 - - class SummarizationFeedback(proto.Message): - r"""Feedback for conversation summarization. - - Attributes: - start_time (google.protobuf.timestamp_pb2.Timestamp): - Timestamp when composing of the summary - starts. - submit_time (google.protobuf.timestamp_pb2.Timestamp): - Timestamp when the summary was submitted. - summary_text (str): - Text of actual submitted summary. - """ - - start_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=1, - message=timestamp_pb2.Timestamp, - ) - submit_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=2, - message=timestamp_pb2.Timestamp, - ) - summary_text: str = proto.Field( - proto.STRING, - number=3, - ) - - answer_relevance: AnswerRelevance = proto.Field( - proto.ENUM, - number=1, - enum=AnswerRelevance, - ) - document_correctness: DocumentCorrectness = proto.Field( - proto.ENUM, - number=2, - enum=DocumentCorrectness, - ) - document_efficiency: DocumentEfficiency = proto.Field( - proto.ENUM, - number=3, - enum=DocumentEfficiency, - ) - summarization_feedback: SummarizationFeedback = proto.Field( - proto.MESSAGE, - number=4, - message=SummarizationFeedback, - ) - - -class AgentAssistantRecord(proto.Message): - r"""Represents a record of a human agent assist answer. - - This message has `oneof`_ fields (mutually exclusive fields). - For each oneof, at most one member field can be set at the same time. - Setting any member of the oneof automatically clears all other - members. - - .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields - - Attributes: - article_suggestion_answer (google.cloud.dialogflow_v2.types.ArticleAnswer): - Output only. The article suggestion answer. - - This field is a member of `oneof`_ ``answer``. - faq_answer (google.cloud.dialogflow_v2.types.FaqAnswer): - Output only. The FAQ answer. - - This field is a member of `oneof`_ ``answer``. - """ - - article_suggestion_answer: participant.ArticleAnswer = proto.Field( - proto.MESSAGE, - number=5, - oneof='answer', - message=participant.ArticleAnswer, - ) - faq_answer: participant.FaqAnswer = proto.Field( - proto.MESSAGE, - number=6, - oneof='answer', - message=participant.FaqAnswer, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v2/google/cloud/dialogflow_v2/types/audio_config.py b/owl-bot-staging/v2/google/cloud/dialogflow_v2/types/audio_config.py deleted file mode 100644 index 1c5bfb3ec..000000000 --- a/owl-bot-staging/v2/google/cloud/dialogflow_v2/types/audio_config.py +++ /dev/null @@ -1,674 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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 __future__ import annotations - -from typing import MutableMapping, MutableSequence - -import proto # type: ignore - -from google.protobuf import duration_pb2 # type: ignore - - -__protobuf__ = proto.module( - package='google.cloud.dialogflow.v2', - manifest={ - 'AudioEncoding', - 'SpeechModelVariant', - 'SsmlVoiceGender', - 'OutputAudioEncoding', - 'TelephonyDtmf', - 'SpeechContext', - 'SpeechWordInfo', - 'InputAudioConfig', - 'VoiceSelectionParams', - 'SynthesizeSpeechConfig', - 'OutputAudioConfig', - 'TelephonyDtmfEvents', - 'SpeechToTextConfig', - }, -) - - -class AudioEncoding(proto.Enum): - r"""Audio encoding of the audio content sent in the conversational query - request. Refer to the `Cloud Speech API - documentation `__ - for more details. - - Values: - AUDIO_ENCODING_UNSPECIFIED (0): - Not specified. - AUDIO_ENCODING_LINEAR_16 (1): - Uncompressed 16-bit signed little-endian - samples (Linear PCM). - AUDIO_ENCODING_FLAC (2): - ```FLAC`` `__ - (Free Lossless Audio Codec) is the recommended encoding - because it is lossless (therefore recognition is not - compromised) and requires only about half the bandwidth of - ``LINEAR16``. ``FLAC`` stream encoding supports 16-bit and - 24-bit samples, however, not all fields in ``STREAMINFO`` - are supported. - AUDIO_ENCODING_MULAW (3): - 8-bit samples that compand 14-bit audio - samples using G.711 PCMU/mu-law. - AUDIO_ENCODING_AMR (4): - Adaptive Multi-Rate Narrowband codec. ``sample_rate_hertz`` - must be 8000. - AUDIO_ENCODING_AMR_WB (5): - Adaptive Multi-Rate Wideband codec. ``sample_rate_hertz`` - must be 16000. - AUDIO_ENCODING_OGG_OPUS (6): - Opus encoded audio frames in Ogg container - (`OggOpus `__). - ``sample_rate_hertz`` must be 16000. - AUDIO_ENCODING_SPEEX_WITH_HEADER_BYTE (7): - Although the use of lossy encodings is not recommended, if a - very low bitrate encoding is required, ``OGG_OPUS`` is - highly preferred over Speex encoding. The - `Speex `__ encoding supported by - Dialogflow API has a header byte in each block, as in MIME - type ``audio/x-speex-with-header-byte``. It is a variant of - the RTP Speex encoding defined in `RFC - 5574 `__. The stream is - a sequence of blocks, one block per RTP packet. Each block - starts with a byte containing the length of the block, in - bytes, followed by one or more frames of Speex data, padded - to an integral number of bytes (octets) as specified in RFC - 5574. In other words, each RTP header is replaced with a - single byte containing the block length. Only Speex wideband - is supported. ``sample_rate_hertz`` must be 16000. - """ - AUDIO_ENCODING_UNSPECIFIED = 0 - AUDIO_ENCODING_LINEAR_16 = 1 - AUDIO_ENCODING_FLAC = 2 - AUDIO_ENCODING_MULAW = 3 - AUDIO_ENCODING_AMR = 4 - AUDIO_ENCODING_AMR_WB = 5 - AUDIO_ENCODING_OGG_OPUS = 6 - AUDIO_ENCODING_SPEEX_WITH_HEADER_BYTE = 7 - - -class SpeechModelVariant(proto.Enum): - r"""Variant of the specified [Speech - model][google.cloud.dialogflow.v2.InputAudioConfig.model] to use. - - See the `Cloud Speech - documentation `__ - for which models have different variants. For example, the - "phone_call" model has both a standard and an enhanced variant. When - you use an enhanced model, you will generally receive higher quality - results than for a standard model. - - Values: - SPEECH_MODEL_VARIANT_UNSPECIFIED (0): - No model variant specified. In this case Dialogflow defaults - to USE_BEST_AVAILABLE. - USE_BEST_AVAILABLE (1): - Use the best available variant of the [Speech - model][InputAudioConfig.model] that the caller is eligible - for. - - Please see the `Dialogflow - docs `__ - for how to make your project eligible for enhanced models. - USE_STANDARD (2): - Use standard model variant even if an enhanced model is - available. See the `Cloud Speech - documentation `__ - for details about enhanced models. - USE_ENHANCED (3): - Use an enhanced model variant: - - - If an enhanced variant does not exist for the given - [model][google.cloud.dialogflow.v2.InputAudioConfig.model] - and request language, Dialogflow falls back to the - standard variant. - - The `Cloud Speech - documentation `__ - describes which models have enhanced variants. - - - If the API caller isn't eligible for enhanced models, - Dialogflow returns an error. Please see the `Dialogflow - docs `__ - for how to make your project eligible. - """ - SPEECH_MODEL_VARIANT_UNSPECIFIED = 0 - USE_BEST_AVAILABLE = 1 - USE_STANDARD = 2 - USE_ENHANCED = 3 - - -class SsmlVoiceGender(proto.Enum): - r"""Gender of the voice as described in `SSML voice - element `__. - - Values: - SSML_VOICE_GENDER_UNSPECIFIED (0): - An unspecified gender, which means that the - client doesn't care which gender the selected - voice will have. - SSML_VOICE_GENDER_MALE (1): - A male voice. - SSML_VOICE_GENDER_FEMALE (2): - A female voice. - SSML_VOICE_GENDER_NEUTRAL (3): - A gender-neutral voice. - """ - SSML_VOICE_GENDER_UNSPECIFIED = 0 - SSML_VOICE_GENDER_MALE = 1 - SSML_VOICE_GENDER_FEMALE = 2 - SSML_VOICE_GENDER_NEUTRAL = 3 - - -class OutputAudioEncoding(proto.Enum): - r"""Audio encoding of the output audio format in Text-To-Speech. - - Values: - OUTPUT_AUDIO_ENCODING_UNSPECIFIED (0): - Not specified. - OUTPUT_AUDIO_ENCODING_LINEAR_16 (1): - Uncompressed 16-bit signed little-endian - samples (Linear PCM). Audio content returned as - LINEAR16 also contains a WAV header. - OUTPUT_AUDIO_ENCODING_MP3 (2): - MP3 audio at 32kbps. - OUTPUT_AUDIO_ENCODING_MP3_64_KBPS (4): - MP3 audio at 64kbps. - OUTPUT_AUDIO_ENCODING_OGG_OPUS (3): - Opus encoded audio wrapped in an ogg - container. The result will be a file which can - be played natively on Android, and in browsers - (at least Chrome and Firefox). The quality of - the encoding is considerably higher than MP3 - while using approximately the same bitrate. - OUTPUT_AUDIO_ENCODING_MULAW (5): - 8-bit samples that compand 14-bit audio - samples using G.711 PCMU/mu-law. - """ - OUTPUT_AUDIO_ENCODING_UNSPECIFIED = 0 - OUTPUT_AUDIO_ENCODING_LINEAR_16 = 1 - OUTPUT_AUDIO_ENCODING_MP3 = 2 - OUTPUT_AUDIO_ENCODING_MP3_64_KBPS = 4 - OUTPUT_AUDIO_ENCODING_OGG_OPUS = 3 - OUTPUT_AUDIO_ENCODING_MULAW = 5 - - -class TelephonyDtmf(proto.Enum): - r"""`DTMF `__ - digit in Telephony Gateway. - - Values: - TELEPHONY_DTMF_UNSPECIFIED (0): - Not specified. This value may be used to - indicate an absent digit. - DTMF_ONE (1): - Number: '1'. - DTMF_TWO (2): - Number: '2'. - DTMF_THREE (3): - Number: '3'. - DTMF_FOUR (4): - Number: '4'. - DTMF_FIVE (5): - Number: '5'. - DTMF_SIX (6): - Number: '6'. - DTMF_SEVEN (7): - Number: '7'. - DTMF_EIGHT (8): - Number: '8'. - DTMF_NINE (9): - Number: '9'. - DTMF_ZERO (10): - Number: '0'. - DTMF_A (11): - Letter: 'A'. - DTMF_B (12): - Letter: 'B'. - DTMF_C (13): - Letter: 'C'. - DTMF_D (14): - Letter: 'D'. - DTMF_STAR (15): - Asterisk/star: '*'. - DTMF_POUND (16): - Pound/diamond/hash/square/gate/octothorpe: - '#'. - """ - TELEPHONY_DTMF_UNSPECIFIED = 0 - DTMF_ONE = 1 - DTMF_TWO = 2 - DTMF_THREE = 3 - DTMF_FOUR = 4 - DTMF_FIVE = 5 - DTMF_SIX = 6 - DTMF_SEVEN = 7 - DTMF_EIGHT = 8 - DTMF_NINE = 9 - DTMF_ZERO = 10 - DTMF_A = 11 - DTMF_B = 12 - DTMF_C = 13 - DTMF_D = 14 - DTMF_STAR = 15 - DTMF_POUND = 16 - - -class SpeechContext(proto.Message): - r"""Hints for the speech recognizer to help with recognition in a - specific conversation state. - - Attributes: - phrases (MutableSequence[str]): - Optional. A list of strings containing words and phrases - that the speech recognizer should recognize with higher - likelihood. - - This list can be used to: - - - improve accuracy for words and phrases you expect the - user to say, e.g. typical commands for your Dialogflow - agent - - add additional words to the speech recognizer vocabulary - - ... - - See the `Cloud Speech - documentation `__ - for usage limits. - boost (float): - Optional. Boost for this context compared to other contexts: - - - If the boost is positive, Dialogflow will increase the - probability that the phrases in this context are - recognized over similar sounding phrases. - - If the boost is unspecified or non-positive, Dialogflow - will not apply any boost. - - Dialogflow recommends that you use boosts in the range (0, - 20] and that you find a value that fits your use case with - binary search. - """ - - phrases: MutableSequence[str] = proto.RepeatedField( - proto.STRING, - number=1, - ) - boost: float = 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. - start_offset (google.protobuf.duration_pb2.Duration): - Time offset relative to the beginning of the - audio that corresponds to the start of the - spoken word. This is an experimental feature and - the accuracy of the time offset can vary. - end_offset (google.protobuf.duration_pb2.Duration): - Time offset relative to the beginning of the - audio that corresponds to the end of the spoken - word. This is an experimental feature and the - accuracy of the time offset can vary. - confidence (float): - The Speech confidence between 0.0 and 1.0 for - this word. A higher number indicates an - estimated greater likelihood that the recognized - word is correct. The default of 0.0 is a - sentinel value indicating that confidence was - not set. - - This field is not guaranteed to be fully stable - over time for the same audio input. Users should - also not rely on it to always be provided. - """ - - word: str = proto.Field( - proto.STRING, - number=3, - ) - start_offset: duration_pb2.Duration = proto.Field( - proto.MESSAGE, - number=1, - message=duration_pb2.Duration, - ) - end_offset: duration_pb2.Duration = proto.Field( - proto.MESSAGE, - number=2, - message=duration_pb2.Duration, - ) - confidence: float = proto.Field( - proto.FLOAT, - number=4, - ) - - -class InputAudioConfig(proto.Message): - r"""Instructs the speech recognizer how to process the audio - content. - - Attributes: - audio_encoding (google.cloud.dialogflow_v2.types.AudioEncoding): - Required. Audio encoding of the audio content - to process. - sample_rate_hertz (int): - Required. Sample rate (in Hertz) of the audio content sent - in the query. Refer to `Cloud Speech API - documentation `__ - for more details. - language_code (str): - Required. The language of the supplied audio. Dialogflow - does not do translations. See `Language - Support `__ - for a list of the currently supported language codes. Note - that queries in the same session do not necessarily need to - specify the same language. - enable_word_info (bool): - If ``true``, Dialogflow returns - [SpeechWordInfo][google.cloud.dialogflow.v2.SpeechWordInfo] - in - [StreamingRecognitionResult][google.cloud.dialogflow.v2.StreamingRecognitionResult] - with information about the recognized speech words, e.g. - start and end time offsets. If false or unspecified, Speech - doesn't return any word-level information. - phrase_hints (MutableSequence[str]): - A list of strings containing words and phrases that the - speech recognizer should recognize with higher likelihood. - - See `the Cloud Speech - documentation `__ - for more details. - - This field is deprecated. Please use `speech_contexts <>`__ - instead. If you specify both `phrase_hints <>`__ and - `speech_contexts <>`__, Dialogflow will treat the - `phrase_hints <>`__ as a single additional - `SpeechContext <>`__. - speech_contexts (MutableSequence[google.cloud.dialogflow_v2.types.SpeechContext]): - Context information to assist speech recognition. - - See `the Cloud Speech - documentation `__ - for more details. - model (str): - Which Speech model to select for the given request. Select - the model best suited to your domain to get best results. If - a model is not explicitly specified, then we auto-select a - model based on the parameters in the InputAudioConfig. If - enhanced speech model is enabled for the agent and an - enhanced version of the specified model for the language - does not exist, then the speech is recognized using the - standard version of the specified model. Refer to `Cloud - Speech API - documentation `__ - for more details. - model_variant (google.cloud.dialogflow_v2.types.SpeechModelVariant): - Which variant of the [Speech - model][google.cloud.dialogflow.v2.InputAudioConfig.model] to - use. - single_utterance (bool): - If ``false`` (default), recognition does not cease until the - client closes the stream. If ``true``, the recognizer will - detect a single spoken utterance in input audio. Recognition - ceases when it detects the audio's voice has stopped or - paused. In this case, once a detected intent is received, - the client should close the stream and start a new request - with a new stream as needed. Note: This setting is relevant - only for streaming methods. Note: When specified, - InputAudioConfig.single_utterance takes precedence over - StreamingDetectIntentRequest.single_utterance. - disable_no_speech_recognized_event (bool): - Only used in - [Participants.AnalyzeContent][google.cloud.dialogflow.v2.Participants.AnalyzeContent] - and - [Participants.StreamingAnalyzeContent][google.cloud.dialogflow.v2.Participants.StreamingAnalyzeContent]. - If ``false`` and recognition doesn't return any result, - trigger ``NO_SPEECH_RECOGNIZED`` event to Dialogflow agent. - """ - - audio_encoding: 'AudioEncoding' = proto.Field( - proto.ENUM, - number=1, - enum='AudioEncoding', - ) - sample_rate_hertz: int = proto.Field( - proto.INT32, - number=2, - ) - language_code: str = proto.Field( - proto.STRING, - number=3, - ) - enable_word_info: bool = proto.Field( - proto.BOOL, - number=13, - ) - phrase_hints: MutableSequence[str] = proto.RepeatedField( - proto.STRING, - number=4, - ) - speech_contexts: MutableSequence['SpeechContext'] = proto.RepeatedField( - proto.MESSAGE, - number=11, - message='SpeechContext', - ) - model: str = proto.Field( - proto.STRING, - number=7, - ) - model_variant: 'SpeechModelVariant' = proto.Field( - proto.ENUM, - number=10, - enum='SpeechModelVariant', - ) - single_utterance: bool = proto.Field( - proto.BOOL, - number=8, - ) - disable_no_speech_recognized_event: bool = 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 - will choose a voice based on the other parameters such as - language_code and - [ssml_gender][google.cloud.dialogflow.v2.VoiceSelectionParams.ssml_gender]. - ssml_gender (google.cloud.dialogflow_v2.types.SsmlVoiceGender): - Optional. The preferred gender of the voice. If not set, the - service will choose a voice based on the other parameters - such as language_code and - [name][google.cloud.dialogflow.v2.VoiceSelectionParams.name]. - Note that this is only a preference, not requirement. If a - voice of the appropriate gender is not available, the - synthesizer should substitute a voice with a different - gender rather than failing the request. - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - ssml_gender: 'SsmlVoiceGender' = 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 - is the normal native speed supported by the specific voice. - 2.0 is twice as fast, and 0.5 is half as fast. If - unset(0.0), defaults to the native 1.0 speed. Any other - values < 0.25 or > 4.0 will return an error. - pitch (float): - Optional. Speaking pitch, in the range [-20.0, 20.0]. 20 - means increase 20 semitones from the original pitch. -20 - means decrease 20 semitones from the original pitch. - volume_gain_db (float): - Optional. Volume gain (in dB) of the normal native volume - supported by the specific voice, in the range [-96.0, 16.0]. - If unset, or set to a value of 0.0 (dB), will play at normal - native signal amplitude. A value of -6.0 (dB) will play at - approximately half the amplitude of the normal native signal - amplitude. A value of +6.0 (dB) will play at approximately - twice the amplitude of the normal native signal amplitude. - We strongly recommend not to exceed +10 (dB) as there's - usually no effective increase in loudness for any value - greater than that. - effects_profile_id (MutableSequence[str]): - Optional. An identifier which selects 'audio - effects' profiles that are applied on (post - synthesized) text to speech. Effects are applied - on top of each other in the order they are - given. - voice (google.cloud.dialogflow_v2.types.VoiceSelectionParams): - Optional. The desired voice of the - synthesized audio. - """ - - speaking_rate: float = proto.Field( - proto.DOUBLE, - number=1, - ) - pitch: float = proto.Field( - proto.DOUBLE, - number=2, - ) - volume_gain_db: float = proto.Field( - proto.DOUBLE, - number=3, - ) - effects_profile_id: MutableSequence[str] = proto.RepeatedField( - proto.STRING, - number=5, - ) - voice: 'VoiceSelectionParams' = proto.Field( - proto.MESSAGE, - number=4, - message='VoiceSelectionParams', - ) - - -class OutputAudioConfig(proto.Message): - r"""Instructs the speech synthesizer on how to generate the - output audio content. If this audio config is supplied in a - request, it overrides all existing text-to-speech settings - applied to the agent. - - Attributes: - audio_encoding (google.cloud.dialogflow_v2.types.OutputAudioEncoding): - Required. Audio encoding of the synthesized - audio content. - sample_rate_hertz (int): - 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_config (google.cloud.dialogflow_v2.types.SynthesizeSpeechConfig): - Configuration of how speech should be - synthesized. - """ - - audio_encoding: 'OutputAudioEncoding' = proto.Field( - proto.ENUM, - number=1, - enum='OutputAudioEncoding', - ) - sample_rate_hertz: int = proto.Field( - proto.INT32, - number=2, - ) - synthesize_speech_config: 'SynthesizeSpeechConfig' = proto.Field( - proto.MESSAGE, - number=3, - message='SynthesizeSpeechConfig', - ) - - -class TelephonyDtmfEvents(proto.Message): - r"""A wrapper of repeated TelephonyDtmf digits. - - Attributes: - dtmf_events (MutableSequence[google.cloud.dialogflow_v2.types.TelephonyDtmf]): - A sequence of TelephonyDtmf digits. - """ - - dtmf_events: MutableSequence['TelephonyDtmf'] = proto.RepeatedField( - proto.ENUM, - number=1, - enum='TelephonyDtmf', - ) - - -class SpeechToTextConfig(proto.Message): - r"""Configures speech transcription for - [ConversationProfile][google.cloud.dialogflow.v2.ConversationProfile]. - - Attributes: - speech_model_variant (google.cloud.dialogflow_v2.types.SpeechModelVariant): - The speech model used in speech to text. - ``SPEECH_MODEL_VARIANT_UNSPECIFIED``, ``USE_BEST_AVAILABLE`` - will be treated as ``USE_ENHANCED``. It can be overridden in - [AnalyzeContentRequest][google.cloud.dialogflow.v2.AnalyzeContentRequest] - and - [StreamingAnalyzeContentRequest][google.cloud.dialogflow.v2.StreamingAnalyzeContentRequest] - request. If enhanced model variant is specified and an - enhanced version of the specified model for the language - does not exist, then it would emit an error. - model (str): - Which Speech model to select. Select the model best suited - to your domain to get best results. If a model is not - explicitly specified, then a default model is used. Refer to - `Cloud Speech API - documentation `__ - for more details. - """ - - speech_model_variant: 'SpeechModelVariant' = proto.Field( - proto.ENUM, - number=1, - enum='SpeechModelVariant', - ) - model: str = proto.Field( - proto.STRING, - number=2, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v2/google/cloud/dialogflow_v2/types/context.py b/owl-bot-staging/v2/google/cloud/dialogflow_v2/types/context.py deleted file mode 100644 index c51b7f3ba..000000000 --- a/owl-bot-staging/v2/google/cloud/dialogflow_v2/types/context.py +++ /dev/null @@ -1,302 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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 __future__ import annotations - -from typing import MutableMapping, MutableSequence - -import proto # type: ignore - -from google.protobuf import field_mask_pb2 # type: ignore -from google.protobuf import struct_pb2 # type: ignore - - -__protobuf__ = proto.module( - package='google.cloud.dialogflow.v2', - manifest={ - 'Context', - 'ListContextsRequest', - 'ListContextsResponse', - 'GetContextRequest', - 'CreateContextRequest', - 'UpdateContextRequest', - 'DeleteContextRequest', - 'DeleteAllContextsRequest', - }, -) - - -class Context(proto.Message): - r"""Dialogflow contexts are similar to natural language context. If a - person says to you "they are orange", you need context in order to - understand what "they" is referring to. Similarly, for Dialogflow to - handle an end-user expression like that, it needs to be provided - with context in order to correctly match an intent. - - Using contexts, you can control the flow of a conversation. You can - configure contexts for an intent by setting input and output - contexts, which are identified by string names. When an intent is - matched, any configured output contexts for that intent become - active. While any contexts are active, Dialogflow is more likely to - match intents that are configured with input contexts that - correspond to the currently active contexts. - - For more information about context, see the `Contexts - guide `__. - - Attributes: - name (str): - Required. The unique identifier of the context. Format: - ``projects//agent/sessions//contexts/``, - or - ``projects//agent/environments//users//sessions//contexts/``. - - The ``Context ID`` is always converted to lowercase, may - only contain characters in a-zA-Z0-9_-% and may be at most - 250 bytes long. - - If ``Environment ID`` is not specified, we assume default - 'draft' environment. If ``User ID`` is not specified, we - assume default '-' user. - - The following context names are reserved for internal use by - Dialogflow. You should not use these contexts or create - contexts with these names: - - - ``__system_counters__`` - - ``*_id_dialog_context`` - - ``*_dialog_params_size`` - lifespan_count (int): - Optional. The number of conversational query requests after - which the context expires. The default is ``0``. If set to - ``0``, the context expires immediately. Contexts expire - automatically after 20 minutes if there are no matching - queries. - parameters (google.protobuf.struct_pb2.Struct): - Optional. The collection of parameters - associated with this context. - Depending on your protocol or client library - language, this is a map, associative array, - symbol table, dictionary, or JSON object - composed of a collection of (MapKey, MapValue) - pairs: - - MapKey type: string - - MapKey value: parameter name - - MapValue type: - - If parameter's entity type is a - composite entity: map - Else: depending on - parameter value type, could be one of string, - number, boolean, null, list or map - - MapValue value: - - If parameter's entity type is a - composite entity: map from composite - entity property names to property values - - Else: parameter value - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - lifespan_count: int = proto.Field( - proto.INT32, - number=2, - ) - parameters: struct_pb2.Struct = proto.Field( - proto.MESSAGE, - number=3, - message=struct_pb2.Struct, - ) - - -class ListContextsRequest(proto.Message): - r"""The request message for - [Contexts.ListContexts][google.cloud.dialogflow.v2.Contexts.ListContexts]. - - Attributes: - parent (str): - Required. The session to list all contexts from. Format: - ``projects//agent/sessions/`` or - ``projects//agent/environments//users//sessions/``. - If ``Environment ID`` is not specified, we assume default - 'draft' environment. If ``User ID`` is not specified, we - assume default '-' user. - 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: str = proto.Field( - proto.STRING, - number=1, - ) - page_size: int = proto.Field( - proto.INT32, - number=2, - ) - page_token: str = proto.Field( - proto.STRING, - number=3, - ) - - -class ListContextsResponse(proto.Message): - r"""The response message for - [Contexts.ListContexts][google.cloud.dialogflow.v2.Contexts.ListContexts]. - - Attributes: - contexts (MutableSequence[google.cloud.dialogflow_v2.types.Context]): - The list of contexts. 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 - - contexts: MutableSequence['Context'] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message='Context', - ) - next_page_token: str = proto.Field( - proto.STRING, - number=2, - ) - - -class GetContextRequest(proto.Message): - r"""The request message for - [Contexts.GetContext][google.cloud.dialogflow.v2.Contexts.GetContext]. - - Attributes: - name (str): - Required. The name of the context. Format: - ``projects//agent/sessions//contexts/`` - or - ``projects//agent/environments//users//sessions//contexts/``. - If ``Environment ID`` is not specified, we assume default - 'draft' environment. If ``User ID`` is not specified, we - assume default '-' user. - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - - -class CreateContextRequest(proto.Message): - r"""The request message for - [Contexts.CreateContext][google.cloud.dialogflow.v2.Contexts.CreateContext]. - - Attributes: - parent (str): - Required. The session to create a context for. Format: - ``projects//agent/sessions/`` or - ``projects//agent/environments//users//sessions/``. - If ``Environment ID`` is not specified, we assume default - 'draft' environment. If ``User ID`` is not specified, we - assume default '-' user. - context (google.cloud.dialogflow_v2.types.Context): - Required. The context to create. - """ - - parent: str = proto.Field( - proto.STRING, - number=1, - ) - context: 'Context' = proto.Field( - proto.MESSAGE, - number=2, - message='Context', - ) - - -class UpdateContextRequest(proto.Message): - r"""The request message for - [Contexts.UpdateContext][google.cloud.dialogflow.v2.Contexts.UpdateContext]. - - Attributes: - context (google.cloud.dialogflow_v2.types.Context): - Required. The context to update. - update_mask (google.protobuf.field_mask_pb2.FieldMask): - Optional. The mask to control which fields - get updated. - """ - - context: 'Context' = proto.Field( - proto.MESSAGE, - number=1, - message='Context', - ) - update_mask: field_mask_pb2.FieldMask = proto.Field( - proto.MESSAGE, - number=2, - message=field_mask_pb2.FieldMask, - ) - - -class DeleteContextRequest(proto.Message): - r"""The request message for - [Contexts.DeleteContext][google.cloud.dialogflow.v2.Contexts.DeleteContext]. - - Attributes: - name (str): - Required. The name of the context to delete. Format: - ``projects//agent/sessions//contexts/`` - or - ``projects//agent/environments//users//sessions//contexts/``. - If ``Environment ID`` is not specified, we assume default - 'draft' environment. If ``User ID`` is not specified, we - assume default '-' user. - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - - -class DeleteAllContextsRequest(proto.Message): - r"""The request message for - [Contexts.DeleteAllContexts][google.cloud.dialogflow.v2.Contexts.DeleteAllContexts]. - - Attributes: - parent (str): - Required. The name of the session to delete all contexts - from. Format: - ``projects//agent/sessions/`` or - ``projects//agent/environments//users//sessions/``. - If ``Environment ID`` is not specified we assume default - 'draft' environment. If ``User ID`` is not specified, we - assume default '-' user. - """ - - parent: str = proto.Field( - proto.STRING, - number=1, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v2/google/cloud/dialogflow_v2/types/conversation.py b/owl-bot-staging/v2/google/cloud/dialogflow_v2/types/conversation.py deleted file mode 100644 index 312d06591..000000000 --- a/owl-bot-staging/v2/google/cloud/dialogflow_v2/types/conversation.py +++ /dev/null @@ -1,526 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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 __future__ import annotations - -from typing import MutableMapping, MutableSequence - -import proto # type: ignore - -from google.cloud.dialogflow_v2.types import participant -from google.protobuf import timestamp_pb2 # type: ignore - - -__protobuf__ = proto.module( - package='google.cloud.dialogflow.v2', - manifest={ - 'Conversation', - 'CreateConversationRequest', - 'ListConversationsRequest', - 'ListConversationsResponse', - 'GetConversationRequest', - 'CompleteConversationRequest', - 'ListMessagesRequest', - 'ListMessagesResponse', - 'ConversationPhoneNumber', - 'SuggestConversationSummaryRequest', - 'SuggestConversationSummaryResponse', - }, -) - - -class Conversation(proto.Message): - r"""Represents a conversation. - A conversation is an interaction between an agent, including - live agents and Dialogflow agents, and a support customer. - Conversations can include phone calls and text-based chat - sessions. - - Attributes: - name (str): - Output only. The unique identifier of this conversation. - Format: - ``projects//locations//conversations/``. - lifecycle_state (google.cloud.dialogflow_v2.types.Conversation.LifecycleState): - Output only. The current state of the - Conversation. - conversation_profile (str): - Required. The Conversation Profile to be used to configure - this Conversation. This field cannot be updated. Format: - ``projects//locations//conversationProfiles/``. - phone_number (google.cloud.dialogflow_v2.types.ConversationPhoneNumber): - Output only. It will not be empty if the - conversation is to be connected over telephony. - start_time (google.protobuf.timestamp_pb2.Timestamp): - Output only. The time the conversation was - started. - end_time (google.protobuf.timestamp_pb2.Timestamp): - Output only. The time the conversation was - finished. - conversation_stage (google.cloud.dialogflow_v2.types.Conversation.ConversationStage): - The stage of a conversation. It indicates whether the - virtual agent or a human agent is handling the conversation. - - If the conversation is created with the conversation profile - that has Dialogflow config set, defaults to - [ConversationStage.VIRTUAL_AGENT_STAGE][google.cloud.dialogflow.v2.Conversation.ConversationStage.VIRTUAL_AGENT_STAGE]; - Otherwise, defaults to - [ConversationStage.HUMAN_ASSIST_STAGE][google.cloud.dialogflow.v2.Conversation.ConversationStage.HUMAN_ASSIST_STAGE]. - - If the conversation is created with the conversation profile - that has Dialogflow config set but explicitly sets - conversation_stage to - [ConversationStage.HUMAN_ASSIST_STAGE][google.cloud.dialogflow.v2.Conversation.ConversationStage.HUMAN_ASSIST_STAGE], - it skips - [ConversationStage.VIRTUAL_AGENT_STAGE][google.cloud.dialogflow.v2.Conversation.ConversationStage.VIRTUAL_AGENT_STAGE] - stage and directly goes to - [ConversationStage.HUMAN_ASSIST_STAGE][google.cloud.dialogflow.v2.Conversation.ConversationStage.HUMAN_ASSIST_STAGE]. - """ - class LifecycleState(proto.Enum): - r"""Enumeration of the completion status of the conversation. - - Values: - LIFECYCLE_STATE_UNSPECIFIED (0): - Unknown. - IN_PROGRESS (1): - Conversation is currently open for media - analysis. - COMPLETED (2): - Conversation has been completed. - """ - LIFECYCLE_STATE_UNSPECIFIED = 0 - IN_PROGRESS = 1 - COMPLETED = 2 - - class ConversationStage(proto.Enum): - r"""Enumeration of the different conversation stages a - conversation can be in. Reference: - https://cloud.google.com/dialogflow/priv/docs/contact-center/basics#stages - - Values: - CONVERSATION_STAGE_UNSPECIFIED (0): - Unknown. Should never be used after a - conversation is successfully created. - VIRTUAL_AGENT_STAGE (1): - The conversation should return virtual agent - responses into the conversation. - HUMAN_ASSIST_STAGE (2): - The conversation should not provide - responses, just listen and provide suggestions. - """ - CONVERSATION_STAGE_UNSPECIFIED = 0 - VIRTUAL_AGENT_STAGE = 1 - HUMAN_ASSIST_STAGE = 2 - - name: str = proto.Field( - proto.STRING, - number=1, - ) - lifecycle_state: LifecycleState = proto.Field( - proto.ENUM, - number=2, - enum=LifecycleState, - ) - conversation_profile: str = proto.Field( - proto.STRING, - number=3, - ) - phone_number: 'ConversationPhoneNumber' = proto.Field( - proto.MESSAGE, - number=4, - message='ConversationPhoneNumber', - ) - start_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=5, - message=timestamp_pb2.Timestamp, - ) - end_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=6, - message=timestamp_pb2.Timestamp, - ) - conversation_stage: ConversationStage = proto.Field( - proto.ENUM, - number=7, - enum=ConversationStage, - ) - - -class CreateConversationRequest(proto.Message): - r"""The request message for - [Conversations.CreateConversation][google.cloud.dialogflow.v2.Conversations.CreateConversation]. - - Attributes: - parent (str): - Required. Resource identifier of the project creating the - conversation. Format: - ``projects//locations/``. - conversation (google.cloud.dialogflow_v2.types.Conversation): - Required. The conversation to create. - conversation_id (str): - Optional. Identifier of the conversation. Generally it's - auto generated by Google. Only set it if you cannot wait for - the response to return a auto-generated one to you. - - The conversation ID must be compliant with the regression - fomula "[a-zA-Z][a-zA-Z0-9_-]*" with the characters length - in range of [3,64]. If the field is provided, the caller is - resposible for - - 1. the uniqueness of the ID, otherwise the request will be - rejected. - 2. the consistency for whether to use custom ID or not under - a project to better ensure uniqueness. - """ - - parent: str = proto.Field( - proto.STRING, - number=1, - ) - conversation: 'Conversation' = proto.Field( - proto.MESSAGE, - number=2, - message='Conversation', - ) - conversation_id: str = proto.Field( - proto.STRING, - number=3, - ) - - -class ListConversationsRequest(proto.Message): - r"""The request message for - [Conversations.ListConversations][google.cloud.dialogflow.v2.Conversations.ListConversations]. - - Attributes: - parent (str): - Required. The project from which to list all conversation. - Format: ``projects//locations/``. - 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. - filter (str): - A filter expression that filters conversations listed in the - response. In general, the expression must specify the field - name, a comparison operator, and the value to use for - filtering: - - .. raw:: html - -
    -
  • The value must be a string, a number, or a boolean.
  • -
  • The comparison operator must be either `=`,`!=`, `>`, or `<`.
  • -
  • To filter on multiple expressions, separate the - expressions with `AND` or `OR` (omitting both implies `AND`).
  • -
  • For clarity, expressions can be enclosed in parentheses.
  • -
- Only `lifecycle_state` can be filtered on in this way. For example, - the following expression only returns `COMPLETED` conversations: - - ``lifecycle_state = "COMPLETED"`` - - For more information about filtering, see `API - Filtering `__. - """ - - parent: str = proto.Field( - proto.STRING, - number=1, - ) - page_size: int = proto.Field( - proto.INT32, - number=2, - ) - page_token: str = proto.Field( - proto.STRING, - number=3, - ) - filter: str = proto.Field( - proto.STRING, - number=4, - ) - - -class ListConversationsResponse(proto.Message): - r"""The response message for - [Conversations.ListConversations][google.cloud.dialogflow.v2.Conversations.ListConversations]. - - Attributes: - conversations (MutableSequence[google.cloud.dialogflow_v2.types.Conversation]): - The list of conversations. 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 - - conversations: MutableSequence['Conversation'] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message='Conversation', - ) - next_page_token: str = proto.Field( - proto.STRING, - number=2, - ) - - -class GetConversationRequest(proto.Message): - r"""The request message for - [Conversations.GetConversation][google.cloud.dialogflow.v2.Conversations.GetConversation]. - - Attributes: - name (str): - Required. The name of the conversation. Format: - ``projects//locations//conversations/``. - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - - -class CompleteConversationRequest(proto.Message): - r"""The request message for - [Conversations.CompleteConversation][google.cloud.dialogflow.v2.Conversations.CompleteConversation]. - - Attributes: - name (str): - Required. Resource identifier of the conversation to close. - Format: - ``projects//locations//conversations/``. - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - - -class ListMessagesRequest(proto.Message): - r"""The request message for - [Conversations.ListMessages][google.cloud.dialogflow.v2.Conversations.ListMessages]. - - Attributes: - parent (str): - Required. The name of the conversation to list messages for. - Format: - ``projects//locations//conversations/`` - filter (str): - Optional. Filter on message fields. Currently predicates on - ``create_time`` and ``create_time_epoch_microseconds`` are - supported. ``create_time`` only support milliseconds - accuracy. E.g., - ``create_time_epoch_microseconds > 1551790877964485`` or - ``create_time > 2017-01-15T01:30:15.01Z``. - - For more information about filtering, see `API - Filtering `__. - 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: str = proto.Field( - proto.STRING, - number=1, - ) - filter: str = proto.Field( - proto.STRING, - number=4, - ) - page_size: int = proto.Field( - proto.INT32, - number=2, - ) - page_token: str = proto.Field( - proto.STRING, - number=3, - ) - - -class ListMessagesResponse(proto.Message): - r"""The response message for - [Conversations.ListMessages][google.cloud.dialogflow.v2.Conversations.ListMessages]. - - Attributes: - messages (MutableSequence[google.cloud.dialogflow_v2.types.Message]): - The list of messages. There will be a maximum number of - items returned based on the page_size field in the request. - ``messages`` is sorted by ``create_time`` in descending - order. - 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 - - messages: MutableSequence[participant.Message] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message=participant.Message, - ) - next_page_token: str = proto.Field( - proto.STRING, - number=2, - ) - - -class ConversationPhoneNumber(proto.Message): - r"""Represents a phone number for telephony integration. It - allows for connecting a particular conversation over telephony. - - Attributes: - phone_number (str): - Output only. The phone number to connect to - this conversation. - """ - - phone_number: str = proto.Field( - proto.STRING, - number=3, - ) - - -class SuggestConversationSummaryRequest(proto.Message): - r"""The request message for - [Conversations.SuggestConversationSummary][google.cloud.dialogflow.v2.Conversations.SuggestConversationSummary]. - - Attributes: - conversation (str): - Required. The conversation to fetch suggestion for. Format: - ``projects//locations//conversations/``. - latest_message (str): - The name of the latest conversation message used as context - for compiling suggestion. If empty, the latest message of - the conversation will be used. - - Format: - ``projects//locations//conversations//messages/``. - context_size (int): - Max number of messages prior to and including - [latest_message] to use as context when compiling the - suggestion. By default 500 and at most 1000. - assist_query_params (google.cloud.dialogflow_v2.types.AssistQueryParameters): - Parameters for a human assist query. - """ - - conversation: str = proto.Field( - proto.STRING, - number=1, - ) - latest_message: str = proto.Field( - proto.STRING, - number=3, - ) - context_size: int = proto.Field( - proto.INT32, - number=4, - ) - assist_query_params: participant.AssistQueryParameters = proto.Field( - proto.MESSAGE, - number=5, - message=participant.AssistQueryParameters, - ) - - -class SuggestConversationSummaryResponse(proto.Message): - r"""The response message for - [Conversations.SuggestConversationSummary][google.cloud.dialogflow.v2.Conversations.SuggestConversationSummary]. - - Attributes: - summary (google.cloud.dialogflow_v2.types.SuggestConversationSummaryResponse.Summary): - Generated summary. - latest_message (str): - The name of the latest conversation message used as context - for compiling suggestion. - - Format: - ``projects//locations//conversations//messages/``. - context_size (int): - Number of messages prior to and including - [last_conversation_message][] used to compile the - suggestion. It may be smaller than the - [SuggestSummaryRequest.context_size][] field in the request - if there weren't that many messages in the conversation. - """ - - class Summary(proto.Message): - r"""Generated summary for a conversation. - - Attributes: - text (str): - The summary content that is concatenated into - one string. - text_sections (MutableMapping[str, str]): - The summary content that is divided into - sections. The key is the section's name and the - value is the section's content. There is no - specific format for the key or value. - answer_record (str): - The name of the answer record. Format: - "projects//answerRecords/". - """ - - text: str = proto.Field( - proto.STRING, - number=1, - ) - text_sections: MutableMapping[str, str] = proto.MapField( - proto.STRING, - proto.STRING, - number=4, - ) - answer_record: str = proto.Field( - proto.STRING, - number=3, - ) - - summary: Summary = proto.Field( - proto.MESSAGE, - number=1, - message=Summary, - ) - latest_message: str = proto.Field( - proto.STRING, - number=2, - ) - context_size: int = proto.Field( - proto.INT32, - number=3, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v2/google/cloud/dialogflow_v2/types/conversation_dataset.py b/owl-bot-staging/v2/google/cloud/dialogflow_v2/types/conversation_dataset.py deleted file mode 100644 index 0be6db964..000000000 --- a/owl-bot-staging/v2/google/cloud/dialogflow_v2/types/conversation_dataset.py +++ /dev/null @@ -1,372 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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 __future__ import annotations - -from typing import MutableMapping, MutableSequence - -import proto # type: ignore - -from google.cloud.dialogflow_v2.types import gcs -from google.protobuf import timestamp_pb2 # type: ignore -from google.rpc import status_pb2 # type: ignore - - -__protobuf__ = proto.module( - package='google.cloud.dialogflow.v2', - manifest={ - 'ConversationInfo', - 'InputConfig', - 'ConversationDataset', - 'CreateConversationDatasetRequest', - 'GetConversationDatasetRequest', - 'ListConversationDatasetsRequest', - 'ListConversationDatasetsResponse', - 'DeleteConversationDatasetRequest', - 'ImportConversationDataRequest', - 'ImportConversationDataOperationMetadata', - 'ImportConversationDataOperationResponse', - 'CreateConversationDatasetOperationMetadata', - 'DeleteConversationDatasetOperationMetadata', - }, -) - - -class ConversationInfo(proto.Message): - r"""Represents metadata of a conversation. - - Attributes: - language_code (str): - Optional. The language code of the conversation data within - this dataset. See - https://cloud.google.com/apis/design/standard_fields for - more information. Supports all UTF-8 languages. - """ - - language_code: str = proto.Field( - proto.STRING, - number=1, - ) - - -class InputConfig(proto.Message): - r"""Represents the configuration of importing a set of - conversation files in Google Cloud Storage. - - - .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields - - Attributes: - gcs_source (google.cloud.dialogflow_v2.types.GcsSources): - The Cloud Storage URI has the form gs:////agent*.json. - Wildcards are allowed and will be expanded into all matched - JSON files, which will be read as one conversation per file. - - This field is a member of `oneof`_ ``source``. - """ - - gcs_source: gcs.GcsSources = proto.Field( - proto.MESSAGE, - number=1, - oneof='source', - message=gcs.GcsSources, - ) - - -class ConversationDataset(proto.Message): - r"""Represents a conversation dataset that a user imports raw - data into. The data inside ConversationDataset can not be - changed after ImportConversationData finishes (and calling - ImportConversationData on a dataset that already has data is not - allowed). - - Attributes: - name (str): - Output only. ConversationDataset resource name. Format: - ``projects//locations//conversationDatasets/`` - display_name (str): - Required. The display name of the dataset. - Maximum of 64 bytes. - description (str): - Optional. The description of the dataset. - Maximum of 10000 bytes. - create_time (google.protobuf.timestamp_pb2.Timestamp): - Output only. Creation time of this dataset. - input_config (google.cloud.dialogflow_v2.types.InputConfig): - Output only. Input configurations set during - conversation data import. - conversation_info (google.cloud.dialogflow_v2.types.ConversationInfo): - Output only. Metadata set during conversation - data import. - conversation_count (int): - Output only. The number of conversations this - conversation dataset contains. - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - display_name: str = proto.Field( - proto.STRING, - number=2, - ) - description: str = proto.Field( - proto.STRING, - number=3, - ) - create_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=4, - message=timestamp_pb2.Timestamp, - ) - input_config: 'InputConfig' = proto.Field( - proto.MESSAGE, - number=5, - message='InputConfig', - ) - conversation_info: 'ConversationInfo' = proto.Field( - proto.MESSAGE, - number=6, - message='ConversationInfo', - ) - conversation_count: int = proto.Field( - proto.INT64, - number=7, - ) - - -class CreateConversationDatasetRequest(proto.Message): - r"""The request message for - [ConversationDatasets.CreateConversationDataset][google.cloud.dialogflow.v2.ConversationDatasets.CreateConversationDataset]. - - Attributes: - parent (str): - Required. The project to create conversation dataset for. - Format: ``projects//locations/`` - conversation_dataset (google.cloud.dialogflow_v2.types.ConversationDataset): - Required. The conversation dataset to create. - """ - - parent: str = proto.Field( - proto.STRING, - number=1, - ) - conversation_dataset: 'ConversationDataset' = proto.Field( - proto.MESSAGE, - number=2, - message='ConversationDataset', - ) - - -class GetConversationDatasetRequest(proto.Message): - r"""The request message for - [ConversationDatasets.GetConversationDataset][google.cloud.dialogflow.v2.ConversationDatasets.GetConversationDataset]. - - Attributes: - name (str): - Required. The conversation dataset to retrieve. Format: - ``projects//locations//conversationDatasets/`` - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - - -class ListConversationDatasetsRequest(proto.Message): - r"""The request message for - [ConversationDatasets.ListConversationDatasets][google.cloud.dialogflow.v2.ConversationDatasets.ListConversationDatasets]. - - Attributes: - parent (str): - Required. The project and location name to list all - conversation datasets for. Format: - ``projects//locations/`` - page_size (int): - Optional. Maximum number of conversation - datasets 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: str = proto.Field( - proto.STRING, - number=1, - ) - page_size: int = proto.Field( - proto.INT32, - number=2, - ) - page_token: str = proto.Field( - proto.STRING, - number=3, - ) - - -class ListConversationDatasetsResponse(proto.Message): - r"""The response message for - [ConversationDatasets.ListConversationDatasets][google.cloud.dialogflow.v2.ConversationDatasets.ListConversationDatasets]. - - Attributes: - conversation_datasets (MutableSequence[google.cloud.dialogflow_v2.types.ConversationDataset]): - The list of datasets to return. - next_page_token (str): - The token to use 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 - - conversation_datasets: MutableSequence['ConversationDataset'] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message='ConversationDataset', - ) - next_page_token: str = proto.Field( - proto.STRING, - number=2, - ) - - -class DeleteConversationDatasetRequest(proto.Message): - r"""The request message for - [ConversationDatasets.DeleteConversationDataset][google.cloud.dialogflow.v2.ConversationDatasets.DeleteConversationDataset]. - - Attributes: - name (str): - Required. The conversation dataset to delete. Format: - ``projects//locations//conversationDatasets/`` - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - - -class ImportConversationDataRequest(proto.Message): - r"""The request message for - [ConversationDatasets.ImportConversationData][google.cloud.dialogflow.v2.ConversationDatasets.ImportConversationData]. - - Attributes: - name (str): - Required. Dataset resource name. Format: - ``projects//locations//conversationDatasets/`` - input_config (google.cloud.dialogflow_v2.types.InputConfig): - Required. Configuration describing where to - import data from. - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - input_config: 'InputConfig' = proto.Field( - proto.MESSAGE, - number=2, - message='InputConfig', - ) - - -class ImportConversationDataOperationMetadata(proto.Message): - r"""Metadata for a - [ConversationDatasets.ImportConversationData][google.cloud.dialogflow.v2.ConversationDatasets.ImportConversationData] - operation. - - Attributes: - conversation_dataset (str): - The resource name of the imported conversation dataset. - Format: - ``projects//locations//conversationDatasets/`` - partial_failures (MutableSequence[google.rpc.status_pb2.Status]): - Partial failures are failures that don't fail - the whole long running operation, e.g. single - files that couldn't be read. - create_time (google.protobuf.timestamp_pb2.Timestamp): - Timestamp when import conversation data - request was created. The time is measured on - server side. - """ - - conversation_dataset: str = proto.Field( - proto.STRING, - number=1, - ) - partial_failures: MutableSequence[status_pb2.Status] = proto.RepeatedField( - proto.MESSAGE, - number=2, - message=status_pb2.Status, - ) - create_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=3, - message=timestamp_pb2.Timestamp, - ) - - -class ImportConversationDataOperationResponse(proto.Message): - r"""Response used for - [ConversationDatasets.ImportConversationData][google.cloud.dialogflow.v2.ConversationDatasets.ImportConversationData] - long running operation. - - Attributes: - conversation_dataset (str): - The resource name of the imported conversation dataset. - Format: - ``projects//locations//conversationDatasets/`` - import_count (int): - Number of conversations imported - successfully. - """ - - conversation_dataset: str = proto.Field( - proto.STRING, - number=1, - ) - import_count: int = proto.Field( - proto.INT32, - number=3, - ) - - -class CreateConversationDatasetOperationMetadata(proto.Message): - r"""Metadata for [ConversationDatasets][CreateConversationDataset]. - - Attributes: - conversation_dataset (str): - The resource name of the conversation dataset that will be - created. Format: - ``projects//locations//conversationDatasets/`` - """ - - conversation_dataset: str = proto.Field( - proto.STRING, - number=1, - ) - - -class DeleteConversationDatasetOperationMetadata(proto.Message): - r"""Metadata for [ConversationDatasets][DeleteConversationDataset]. - """ - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v2/google/cloud/dialogflow_v2/types/conversation_event.py b/owl-bot-staging/v2/google/cloud/dialogflow_v2/types/conversation_event.py deleted file mode 100644 index 4b52c3f08..000000000 --- a/owl-bot-staging/v2/google/cloud/dialogflow_v2/types/conversation_event.py +++ /dev/null @@ -1,122 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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 __future__ import annotations - -from typing import MutableMapping, MutableSequence - -import proto # type: ignore - -from google.cloud.dialogflow_v2.types import participant -from google.rpc import status_pb2 # type: ignore - - -__protobuf__ = proto.module( - package='google.cloud.dialogflow.v2', - manifest={ - 'ConversationEvent', - }, -) - - -class ConversationEvent(proto.Message): - r"""Represents a notification sent to Pub/Sub subscribers for - conversation lifecycle events. - - - .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields - - Attributes: - conversation (str): - The unique identifier of the conversation this notification - refers to. Format: - ``projects//conversations/``. - type_ (google.cloud.dialogflow_v2.types.ConversationEvent.Type): - The type of the event that this notification - refers to. - error_status (google.rpc.status_pb2.Status): - More detailed information about an error. Only set for type - UNRECOVERABLE_ERROR_IN_PHONE_CALL. - new_message_payload (google.cloud.dialogflow_v2.types.Message): - Payload of NEW_MESSAGE event. - - This field is a member of `oneof`_ ``payload``. - """ - class Type(proto.Enum): - r"""Enumeration of the types of events available. - - Values: - TYPE_UNSPECIFIED (0): - Type not set. - CONVERSATION_STARTED (1): - A new conversation has been opened. This is - fired when a telephone call is answered, or a - conversation is created via the API. - CONVERSATION_FINISHED (2): - An existing conversation has closed. This is - fired when a telephone call is terminated, or a - conversation is closed via the API. - HUMAN_INTERVENTION_NEEDED (3): - An existing conversation has received - notification from Dialogflow that human - intervention is required. - NEW_MESSAGE (5): - An existing conversation has received a new message, either - from API or telephony. It is configured in - [ConversationProfile.new_message_event_notification_config][google.cloud.dialogflow.v2.ConversationProfile.new_message_event_notification_config] - UNRECOVERABLE_ERROR (4): - Unrecoverable error during a telephone call. - - In general non-recoverable errors only occur if something - was misconfigured in the ConversationProfile corresponding - to the call. After a non-recoverable error, Dialogflow may - stop responding. - - We don't fire this event: - - - in an API call because we can directly return the error, - or, - - when we can recover from an error. - """ - TYPE_UNSPECIFIED = 0 - CONVERSATION_STARTED = 1 - CONVERSATION_FINISHED = 2 - HUMAN_INTERVENTION_NEEDED = 3 - NEW_MESSAGE = 5 - UNRECOVERABLE_ERROR = 4 - - conversation: str = proto.Field( - proto.STRING, - number=1, - ) - type_: Type = proto.Field( - proto.ENUM, - number=2, - enum=Type, - ) - error_status: status_pb2.Status = proto.Field( - proto.MESSAGE, - number=3, - message=status_pb2.Status, - ) - new_message_payload: participant.Message = proto.Field( - proto.MESSAGE, - number=4, - oneof='payload', - message=participant.Message, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v2/google/cloud/dialogflow_v2/types/conversation_model.py b/owl-bot-staging/v2/google/cloud/dialogflow_v2/types/conversation_model.py deleted file mode 100644 index 305523c95..000000000 --- a/owl-bot-staging/v2/google/cloud/dialogflow_v2/types/conversation_model.py +++ /dev/null @@ -1,906 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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 __future__ import annotations - -from typing import MutableMapping, MutableSequence - -import proto # type: ignore - -from google.protobuf import timestamp_pb2 # type: ignore - - -__protobuf__ = proto.module( - package='google.cloud.dialogflow.v2', - manifest={ - 'ConversationModel', - 'ConversationModelEvaluation', - 'EvaluationConfig', - 'InputDataset', - 'ArticleSuggestionModelMetadata', - 'SmartReplyModelMetadata', - 'SmartReplyMetrics', - 'CreateConversationModelRequest', - 'GetConversationModelRequest', - 'ListConversationModelsRequest', - 'ListConversationModelsResponse', - 'DeleteConversationModelRequest', - 'DeployConversationModelRequest', - 'UndeployConversationModelRequest', - 'GetConversationModelEvaluationRequest', - 'ListConversationModelEvaluationsRequest', - 'ListConversationModelEvaluationsResponse', - 'CreateConversationModelEvaluationRequest', - 'CreateConversationModelOperationMetadata', - 'DeployConversationModelOperationMetadata', - 'UndeployConversationModelOperationMetadata', - 'DeleteConversationModelOperationMetadata', - 'CreateConversationModelEvaluationOperationMetadata', - }, -) - - -class ConversationModel(proto.Message): - r"""Represents a conversation model. - - This message has `oneof`_ fields (mutually exclusive fields). - For each oneof, at most one member field can be set at the same time. - Setting any member of the oneof automatically clears all other - members. - - .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields - - Attributes: - name (str): - ConversationModel resource name. Format: - ``projects//conversationModels/`` - display_name (str): - Required. The display name of the model. At - most 64 bytes long. - create_time (google.protobuf.timestamp_pb2.Timestamp): - Output only. Creation time of this model. - datasets (MutableSequence[google.cloud.dialogflow_v2.types.InputDataset]): - Required. Datasets used to create model. - state (google.cloud.dialogflow_v2.types.ConversationModel.State): - Output only. State of the model. A model can - only serve prediction requests after it gets - deployed. - language_code (str): - Language code for the conversation model. If not specified, - the language is en-US. Language at ConversationModel should - be set for all non en-us languages. This should be a - `BCP-47 `__ - language tag. Example: "en-US". - article_suggestion_model_metadata (google.cloud.dialogflow_v2.types.ArticleSuggestionModelMetadata): - Metadata for article suggestion models. - - This field is a member of `oneof`_ ``model_metadata``. - smart_reply_model_metadata (google.cloud.dialogflow_v2.types.SmartReplyModelMetadata): - Metadata for smart reply models. - - This field is a member of `oneof`_ ``model_metadata``. - """ - class State(proto.Enum): - r"""State of the model. - - Values: - STATE_UNSPECIFIED (0): - Should not be used, an un-set enum has this - value by default. - CREATING (1): - Model being created. - UNDEPLOYED (2): - Model is not deployed but ready to deploy. - DEPLOYING (3): - Model is deploying. - DEPLOYED (4): - Model is deployed and ready to use. - UNDEPLOYING (5): - Model is undeploying. - DELETING (6): - Model is deleting. - FAILED (7): - Model is in error state. Not ready to deploy - and use. - PENDING (8): - Model is being created but the training has - not started, The model may remain in this state - until there is enough capacity to start - training. - """ - STATE_UNSPECIFIED = 0 - CREATING = 1 - UNDEPLOYED = 2 - DEPLOYING = 3 - DEPLOYED = 4 - UNDEPLOYING = 5 - DELETING = 6 - FAILED = 7 - PENDING = 8 - - class ModelType(proto.Enum): - r"""Model type. - - Values: - MODEL_TYPE_UNSPECIFIED (0): - ModelType unspecified. - SMART_REPLY_DUAL_ENCODER_MODEL (2): - ModelType smart reply dual encoder model. - SMART_REPLY_BERT_MODEL (6): - ModelType smart reply bert model. - """ - MODEL_TYPE_UNSPECIFIED = 0 - SMART_REPLY_DUAL_ENCODER_MODEL = 2 - SMART_REPLY_BERT_MODEL = 6 - - name: str = proto.Field( - proto.STRING, - number=1, - ) - display_name: str = proto.Field( - proto.STRING, - number=2, - ) - create_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=3, - message=timestamp_pb2.Timestamp, - ) - datasets: MutableSequence['InputDataset'] = proto.RepeatedField( - proto.MESSAGE, - number=4, - message='InputDataset', - ) - state: State = proto.Field( - proto.ENUM, - number=7, - enum=State, - ) - language_code: str = proto.Field( - proto.STRING, - number=19, - ) - article_suggestion_model_metadata: 'ArticleSuggestionModelMetadata' = proto.Field( - proto.MESSAGE, - number=8, - oneof='model_metadata', - message='ArticleSuggestionModelMetadata', - ) - smart_reply_model_metadata: 'SmartReplyModelMetadata' = proto.Field( - proto.MESSAGE, - number=9, - oneof='model_metadata', - message='SmartReplyModelMetadata', - ) - - -class ConversationModelEvaluation(proto.Message): - r"""Represents evaluation result of a conversation model. - - .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields - - Attributes: - name (str): - The resource name of the evaluation. Format: - ``projects//conversationModels//evaluations/`` - display_name (str): - Optional. The display name of the model - evaluation. At most 64 bytes long. - evaluation_config (google.cloud.dialogflow_v2.types.EvaluationConfig): - Optional. The configuration of the evaluation - task. - create_time (google.protobuf.timestamp_pb2.Timestamp): - Output only. Creation time of this model. - smart_reply_metrics (google.cloud.dialogflow_v2.types.SmartReplyMetrics): - Output only. Only available when model is for - smart reply. - - This field is a member of `oneof`_ ``metrics``. - raw_human_eval_template_csv (str): - Output only. Human eval template in csv format. It tooks - real-world conversations provided through input dataset, - generates example suggestions for customer to verify quality - of the model. For Smart Reply, the generated csv file - contains columns of Context, (Suggestions,Q1,Q2)*3, Actual - reply. Context contains at most 10 latest messages in the - conversation prior to the current suggestion. Q1: "Would you - send it as the next message of agent?" Evaluated based on - whether the suggest is appropriate to be sent by agent in - current context. Q2: "Does the suggestion move the - conversation closer to resolution?" Evaluated based on - whether the suggestion provide solutions, or answers - customer's question or collect information from customer to - resolve the customer's issue. Actual reply column contains - the actual agent reply sent in the context. - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - display_name: str = proto.Field( - proto.STRING, - number=2, - ) - evaluation_config: 'EvaluationConfig' = proto.Field( - proto.MESSAGE, - number=6, - message='EvaluationConfig', - ) - create_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=3, - message=timestamp_pb2.Timestamp, - ) - smart_reply_metrics: 'SmartReplyMetrics' = proto.Field( - proto.MESSAGE, - number=5, - oneof='metrics', - message='SmartReplyMetrics', - ) - raw_human_eval_template_csv: str = proto.Field( - proto.STRING, - number=8, - ) - - -class EvaluationConfig(proto.Message): - r"""The configuration for model evaluation. - - This message has `oneof`_ fields (mutually exclusive fields). - For each oneof, at most one member field can be set at the same time. - Setting any member of the oneof automatically clears all other - members. - - .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields - - Attributes: - datasets (MutableSequence[google.cloud.dialogflow_v2.types.InputDataset]): - Required. Datasets used for evaluation. - smart_reply_config (google.cloud.dialogflow_v2.types.EvaluationConfig.SmartReplyConfig): - Configuration for smart reply model - evalution. - - This field is a member of `oneof`_ ``model_specific_config``. - smart_compose_config (google.cloud.dialogflow_v2.types.EvaluationConfig.SmartComposeConfig): - Configuration for smart compose model - evalution. - - This field is a member of `oneof`_ ``model_specific_config``. - """ - - class SmartReplyConfig(proto.Message): - r"""Smart reply specific configuration for evaluation job. - - Attributes: - allowlist_document (str): - The allowlist document resource name. Format: - ``projects//knowledgeBases//documents/``. - Only used for smart reply model. - max_result_count (int): - Required. The model to be evaluated can return multiple - results with confidence score on each query. These results - will be sorted by the descending order of the scores and we - only keep the first max_result_count results as the final - results to evaluate. - """ - - allowlist_document: str = proto.Field( - proto.STRING, - number=1, - ) - max_result_count: int = proto.Field( - proto.INT32, - number=2, - ) - - class SmartComposeConfig(proto.Message): - r"""Smart compose specific configuration for evaluation job. - - Attributes: - allowlist_document (str): - The allowlist document resource name. Format: - ``projects//knowledgeBases//documents/``. - Only used for smart compose model. - max_result_count (int): - Required. The model to be evaluated can return multiple - results with confidence score on each query. These results - will be sorted by the descending order of the scores and we - only keep the first max_result_count results as the final - results to evaluate. - """ - - allowlist_document: str = proto.Field( - proto.STRING, - number=1, - ) - max_result_count: int = proto.Field( - proto.INT32, - number=2, - ) - - datasets: MutableSequence['InputDataset'] = proto.RepeatedField( - proto.MESSAGE, - number=3, - message='InputDataset', - ) - smart_reply_config: SmartReplyConfig = proto.Field( - proto.MESSAGE, - number=2, - oneof='model_specific_config', - message=SmartReplyConfig, - ) - smart_compose_config: SmartComposeConfig = proto.Field( - proto.MESSAGE, - number=4, - oneof='model_specific_config', - message=SmartComposeConfig, - ) - - -class InputDataset(proto.Message): - r"""InputDataset used to create model or do evaluation. - NextID:5 - - Attributes: - dataset (str): - Required. ConversationDataset resource name. Format: - ``projects//locations//conversationDatasets/`` - """ - - dataset: str = proto.Field( - proto.STRING, - number=1, - ) - - -class ArticleSuggestionModelMetadata(proto.Message): - r"""Metadata for article suggestion models. - - Attributes: - training_model_type (google.cloud.dialogflow_v2.types.ConversationModel.ModelType): - Optional. Type of the article suggestion model. If not - provided, model_type is used. - """ - - training_model_type: 'ConversationModel.ModelType' = proto.Field( - proto.ENUM, - number=3, - enum='ConversationModel.ModelType', - ) - - -class SmartReplyModelMetadata(proto.Message): - r"""Metadata for smart reply models. - - Attributes: - training_model_type (google.cloud.dialogflow_v2.types.ConversationModel.ModelType): - Optional. Type of the smart reply model. If not provided, - model_type is used. - """ - - training_model_type: 'ConversationModel.ModelType' = proto.Field( - proto.ENUM, - number=6, - enum='ConversationModel.ModelType', - ) - - -class SmartReplyMetrics(proto.Message): - r"""The evaluation metrics for smart reply model. - - Attributes: - allowlist_coverage (float): - Percentage of target participant messages in the evaluation - dataset for which similar messages have appeared at least - once in the allowlist. Should be [0, 1]. - top_n_metrics (MutableSequence[google.cloud.dialogflow_v2.types.SmartReplyMetrics.TopNMetrics]): - Metrics of top n smart replies, sorted by [TopNMetric.n][]. - conversation_count (int): - Total number of conversations used to - generate this metric. - """ - - class TopNMetrics(proto.Message): - r"""Evaluation metrics when retrieving ``n`` smart replies with the - model. - - Attributes: - n (int): - Number of retrieved smart replies. For example, when ``n`` - is 3, this evaluation contains metrics for when Dialogflow - retrieves 3 smart replies with the model. - recall (float): - Defined as - ``number of queries whose top n smart replies have at least one similar (token match similarity above the defined threshold) reply as the real reply`` - divided by - ``number of queries with at least one smart reply``. Value - ranges from 0.0 to 1.0 inclusive. - """ - - n: int = proto.Field( - proto.INT32, - number=1, - ) - recall: float = proto.Field( - proto.FLOAT, - number=2, - ) - - allowlist_coverage: float = proto.Field( - proto.FLOAT, - number=1, - ) - top_n_metrics: MutableSequence[TopNMetrics] = proto.RepeatedField( - proto.MESSAGE, - number=2, - message=TopNMetrics, - ) - conversation_count: int = proto.Field( - proto.INT64, - number=3, - ) - - -class CreateConversationModelRequest(proto.Message): - r"""The request message for - [ConversationModels.CreateConversationModel][google.cloud.dialogflow.v2.ConversationModels.CreateConversationModel] - - Attributes: - parent (str): - The project to create conversation model for. Format: - ``projects/`` - conversation_model (google.cloud.dialogflow_v2.types.ConversationModel): - Required. The conversation model to create. - """ - - parent: str = proto.Field( - proto.STRING, - number=1, - ) - conversation_model: 'ConversationModel' = proto.Field( - proto.MESSAGE, - number=2, - message='ConversationModel', - ) - - -class GetConversationModelRequest(proto.Message): - r"""The request message for - [ConversationModels.GetConversationModel][google.cloud.dialogflow.v2.ConversationModels.GetConversationModel] - - Attributes: - name (str): - Required. The conversation model to retrieve. Format: - ``projects//conversationModels/`` - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - - -class ListConversationModelsRequest(proto.Message): - r"""The request message for - [ConversationModels.ListConversationModels][google.cloud.dialogflow.v2.ConversationModels.ListConversationModels] - - Attributes: - parent (str): - Required. The project to list all conversation models for. - Format: ``projects/`` - page_size (int): - Optional. Maximum number of conversation - models 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: str = proto.Field( - proto.STRING, - number=1, - ) - page_size: int = proto.Field( - proto.INT32, - number=2, - ) - page_token: str = proto.Field( - proto.STRING, - number=3, - ) - - -class ListConversationModelsResponse(proto.Message): - r"""The response message for - [ConversationModels.ListConversationModels][google.cloud.dialogflow.v2.ConversationModels.ListConversationModels] - - Attributes: - conversation_models (MutableSequence[google.cloud.dialogflow_v2.types.ConversationModel]): - The list of models to return. - 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 - - conversation_models: MutableSequence['ConversationModel'] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message='ConversationModel', - ) - next_page_token: str = proto.Field( - proto.STRING, - number=2, - ) - - -class DeleteConversationModelRequest(proto.Message): - r"""The request message for - [ConversationModels.DeleteConversationModel][google.cloud.dialogflow.v2.ConversationModels.DeleteConversationModel] - - Attributes: - name (str): - Required. The conversation model to delete. Format: - ``projects//conversationModels/`` - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - - -class DeployConversationModelRequest(proto.Message): - r"""The request message for - [ConversationModels.DeployConversationModel][google.cloud.dialogflow.v2.ConversationModels.DeployConversationModel] - - Attributes: - name (str): - Required. The conversation model to deploy. Format: - ``projects//conversationModels/`` - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - - -class UndeployConversationModelRequest(proto.Message): - r"""The request message for - [ConversationModels.UndeployConversationModel][google.cloud.dialogflow.v2.ConversationModels.UndeployConversationModel] - - Attributes: - name (str): - Required. The conversation model to undeploy. Format: - ``projects//conversationModels/`` - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - - -class GetConversationModelEvaluationRequest(proto.Message): - r"""The request message for - [ConversationModels.GetConversationModelEvaluation][google.cloud.dialogflow.v2.ConversationModels.GetConversationModelEvaluation] - - Attributes: - name (str): - Required. The conversation model evaluation resource name. - Format: - ``projects//conversationModels//evaluations/`` - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - - -class ListConversationModelEvaluationsRequest(proto.Message): - r"""The request message for - [ConversationModels.ListConversationModelEvaluations][google.cloud.dialogflow.v2.ConversationModels.ListConversationModelEvaluations] - - Attributes: - parent (str): - Required. The conversation model resource name. Format: - ``projects//conversationModels/`` - page_size (int): - Optional. Maximum number of evaluations 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: str = proto.Field( - proto.STRING, - number=1, - ) - page_size: int = proto.Field( - proto.INT32, - number=2, - ) - page_token: str = proto.Field( - proto.STRING, - number=3, - ) - - -class ListConversationModelEvaluationsResponse(proto.Message): - r"""The response message for - [ConversationModels.ListConversationModelEvaluations][google.cloud.dialogflow.v2.ConversationModels.ListConversationModelEvaluations] - - Attributes: - conversation_model_evaluations (MutableSequence[google.cloud.dialogflow_v2.types.ConversationModelEvaluation]): - The list of evaluations to return. - 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 - - conversation_model_evaluations: MutableSequence['ConversationModelEvaluation'] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message='ConversationModelEvaluation', - ) - next_page_token: str = proto.Field( - proto.STRING, - number=2, - ) - - -class CreateConversationModelEvaluationRequest(proto.Message): - r"""The request message for - [ConversationModels.CreateConversationModelEvaluation][google.cloud.dialogflow.v2.ConversationModels.CreateConversationModelEvaluation] - - Attributes: - parent (str): - Required. The conversation model resource name. Format: - ``projects//locations//conversationModels/`` - conversation_model_evaluation (google.cloud.dialogflow_v2.types.ConversationModelEvaluation): - Required. The conversation model evaluation - to be created. - """ - - parent: str = proto.Field( - proto.STRING, - number=1, - ) - conversation_model_evaluation: 'ConversationModelEvaluation' = proto.Field( - proto.MESSAGE, - number=2, - message='ConversationModelEvaluation', - ) - - -class CreateConversationModelOperationMetadata(proto.Message): - r"""Metadata for a - [ConversationModels.CreateConversationModel][google.cloud.dialogflow.v2.ConversationModels.CreateConversationModel] - operation. - - Attributes: - conversation_model (str): - The resource name of the conversation model. Format: - ``projects//conversationModels/`` - state (google.cloud.dialogflow_v2.types.CreateConversationModelOperationMetadata.State): - State of CreateConversationModel operation. - create_time (google.protobuf.timestamp_pb2.Timestamp): - Timestamp when the request to create - conversation model is submitted. The time is - measured on server side. - """ - class State(proto.Enum): - r"""State of CreateConversationModel operation. - - Values: - STATE_UNSPECIFIED (0): - Invalid. - PENDING (1): - Request is submitted, but training has not - started yet. The model may remain in this state - until there is enough capacity to start - training. - SUCCEEDED (2): - The training has succeeded. - FAILED (3): - The training has succeeded. - CANCELLED (4): - The training has been cancelled. - CANCELLING (5): - The training is in cancelling state. - TRAINING (6): - Custom model is training. - """ - STATE_UNSPECIFIED = 0 - PENDING = 1 - SUCCEEDED = 2 - FAILED = 3 - CANCELLED = 4 - CANCELLING = 5 - TRAINING = 6 - - conversation_model: str = proto.Field( - proto.STRING, - number=1, - ) - state: State = proto.Field( - proto.ENUM, - number=2, - enum=State, - ) - create_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=3, - message=timestamp_pb2.Timestamp, - ) - - -class DeployConversationModelOperationMetadata(proto.Message): - r"""Metadata for a - [ConversationModels.DeployConversationModel][google.cloud.dialogflow.v2.ConversationModels.DeployConversationModel] - operation. - - Attributes: - conversation_model (str): - The resource name of the conversation model. Format: - ``projects//conversationModels/`` - create_time (google.protobuf.timestamp_pb2.Timestamp): - Timestamp when request to deploy conversation - model was submitted. The time is measured on - server side. - """ - - conversation_model: str = proto.Field( - proto.STRING, - number=1, - ) - create_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=3, - message=timestamp_pb2.Timestamp, - ) - - -class UndeployConversationModelOperationMetadata(proto.Message): - r"""Metadata for a - [ConversationModels.UndeployConversationModel][google.cloud.dialogflow.v2.ConversationModels.UndeployConversationModel] - operation. - - Attributes: - conversation_model (str): - The resource name of the conversation model. Format: - ``projects//conversationModels/`` - create_time (google.protobuf.timestamp_pb2.Timestamp): - Timestamp when the request to undeploy - conversation model was submitted. The time is - measured on server side. - """ - - conversation_model: str = proto.Field( - proto.STRING, - number=1, - ) - create_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=3, - message=timestamp_pb2.Timestamp, - ) - - -class DeleteConversationModelOperationMetadata(proto.Message): - r"""Metadata for a - [ConversationModels.DeleteConversationModel][google.cloud.dialogflow.v2.ConversationModels.DeleteConversationModel] - operation. - - Attributes: - conversation_model (str): - The resource name of the conversation model. Format: - ``projects//conversationModels/`` - create_time (google.protobuf.timestamp_pb2.Timestamp): - Timestamp when delete conversation model - request was created. The time is measured on - server side. - """ - - conversation_model: str = proto.Field( - proto.STRING, - number=1, - ) - create_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=3, - message=timestamp_pb2.Timestamp, - ) - - -class CreateConversationModelEvaluationOperationMetadata(proto.Message): - r"""Metadata for a - [ConversationModels.CreateConversationModelEvaluation][google.cloud.dialogflow.v2.ConversationModels.CreateConversationModelEvaluation] - operation. - - Attributes: - conversation_model_evaluation (str): - The resource name of the conversation model. Format: - ``projects//locations//conversationModels//evaluations/`` - conversation_model (str): - The resource name of the conversation model. Format: - ``projects//locations//conversationModels/`` - state (google.cloud.dialogflow_v2.types.CreateConversationModelEvaluationOperationMetadata.State): - State of CreateConversationModel operation. - create_time (google.protobuf.timestamp_pb2.Timestamp): - Timestamp when the request to create - conversation model was submitted. The time is - measured on server side. - """ - class State(proto.Enum): - r"""State of CreateConversationModel operation. - - Values: - STATE_UNSPECIFIED (0): - Operation status not specified. - INITIALIZING (1): - The operation is being prepared. - RUNNING (2): - The operation is running. - CANCELLED (3): - The operation is cancelled. - SUCCEEDED (4): - The operation has succeeded. - FAILED (5): - The operation has failed. - """ - STATE_UNSPECIFIED = 0 - INITIALIZING = 1 - RUNNING = 2 - CANCELLED = 3 - SUCCEEDED = 4 - FAILED = 5 - - conversation_model_evaluation: str = proto.Field( - proto.STRING, - number=1, - ) - conversation_model: str = proto.Field( - proto.STRING, - number=4, - ) - state: State = proto.Field( - proto.ENUM, - number=2, - enum=State, - ) - create_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=3, - message=timestamp_pb2.Timestamp, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v2/google/cloud/dialogflow_v2/types/conversation_profile.py b/owl-bot-staging/v2/google/cloud/dialogflow_v2/types/conversation_profile.py deleted file mode 100644 index 0f55ba9cf..000000000 --- a/owl-bot-staging/v2/google/cloud/dialogflow_v2/types/conversation_profile.py +++ /dev/null @@ -1,1107 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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 __future__ import annotations - -from typing import MutableMapping, MutableSequence - -import proto # type: ignore - -from google.cloud.dialogflow_v2.types import audio_config -from google.cloud.dialogflow_v2.types import participant -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={ - 'ConversationProfile', - 'ListConversationProfilesRequest', - 'ListConversationProfilesResponse', - 'GetConversationProfileRequest', - 'CreateConversationProfileRequest', - 'UpdateConversationProfileRequest', - 'DeleteConversationProfileRequest', - 'AutomatedAgentConfig', - 'HumanAgentAssistantConfig', - 'HumanAgentHandoffConfig', - 'NotificationConfig', - 'LoggingConfig', - 'SuggestionFeature', - 'SetSuggestionFeatureConfigRequest', - 'ClearSuggestionFeatureConfigRequest', - 'SetSuggestionFeatureConfigOperationMetadata', - 'ClearSuggestionFeatureConfigOperationMetadata', - }, -) - - -class ConversationProfile(proto.Message): - r"""Defines the services to connect to incoming Dialogflow - conversations. - - Attributes: - name (str): - The unique identifier of this conversation profile. Format: - ``projects//locations//conversationProfiles/``. - display_name (str): - Required. Human readable name for this - profile. Max length 1024 bytes. - create_time (google.protobuf.timestamp_pb2.Timestamp): - Output only. Create time of the conversation - profile. - update_time (google.protobuf.timestamp_pb2.Timestamp): - Output only. Update time of the conversation - profile. - automated_agent_config (google.cloud.dialogflow_v2.types.AutomatedAgentConfig): - Configuration for an automated agent to use - with this profile. - human_agent_assistant_config (google.cloud.dialogflow_v2.types.HumanAgentAssistantConfig): - Configuration for agent assistance to use - 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. - logging_config (google.cloud.dialogflow_v2.types.LoggingConfig): - Configuration for logging conversation - lifecycle events. - new_message_event_notification_config (google.cloud.dialogflow_v2.types.NotificationConfig): - Configuration for publishing new message events. Event will - be sent in format of - [ConversationEvent][google.cloud.dialogflow.v2.ConversationEvent] - stt_config (google.cloud.dialogflow_v2.types.SpeechToTextConfig): - Settings for speech transcription. - language_code (str): - Language code for the conversation profile. If not - specified, the language is en-US. Language at - ConversationProfile should be set for all non en-US - languages. This should be a - `BCP-47 `__ - language tag. Example: "en-US". - time_zone (str): - The time zone of this conversational profile from the `time - zone database `__, e.g., - America/New_York, Europe/Paris. Defaults to - America/New_York. - security_settings (str): - Name of the CX SecuritySettings reference for the agent. - Format: - ``projects//locations//securitySettings/``. - tts_config (google.cloud.dialogflow_v2.types.SynthesizeSpeechConfig): - Configuration for Text-to-Speech - synthesization. - Used by Phone Gateway to specify synthesization - options. If agent defines synthesization options - as well, agent settings overrides the option - here. - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - display_name: str = proto.Field( - proto.STRING, - number=2, - ) - create_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=11, - message=timestamp_pb2.Timestamp, - ) - update_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=12, - message=timestamp_pb2.Timestamp, - ) - automated_agent_config: 'AutomatedAgentConfig' = proto.Field( - proto.MESSAGE, - number=3, - message='AutomatedAgentConfig', - ) - human_agent_assistant_config: 'HumanAgentAssistantConfig' = proto.Field( - proto.MESSAGE, - number=4, - message='HumanAgentAssistantConfig', - ) - human_agent_handoff_config: 'HumanAgentHandoffConfig' = proto.Field( - proto.MESSAGE, - number=5, - message='HumanAgentHandoffConfig', - ) - notification_config: 'NotificationConfig' = proto.Field( - proto.MESSAGE, - number=6, - message='NotificationConfig', - ) - logging_config: 'LoggingConfig' = proto.Field( - proto.MESSAGE, - number=7, - message='LoggingConfig', - ) - new_message_event_notification_config: 'NotificationConfig' = proto.Field( - proto.MESSAGE, - number=8, - message='NotificationConfig', - ) - stt_config: audio_config.SpeechToTextConfig = proto.Field( - proto.MESSAGE, - number=9, - message=audio_config.SpeechToTextConfig, - ) - language_code: str = proto.Field( - proto.STRING, - number=10, - ) - time_zone: str = proto.Field( - proto.STRING, - number=14, - ) - security_settings: str = proto.Field( - proto.STRING, - number=13, - ) - tts_config: audio_config.SynthesizeSpeechConfig = proto.Field( - proto.MESSAGE, - number=18, - message=audio_config.SynthesizeSpeechConfig, - ) - - -class ListConversationProfilesRequest(proto.Message): - r"""The request message for - [ConversationProfiles.ListConversationProfiles][google.cloud.dialogflow.v2.ConversationProfiles.ListConversationProfiles]. - - Attributes: - parent (str): - Required. The project to list all conversation profiles - from. Format: - ``projects//locations/``. - page_size (int): - The maximum number of items to return in a - single page. By default 100 and at most 1000. - page_token (str): - The next_page_token value returned from a previous list - request. - """ - - parent: str = proto.Field( - proto.STRING, - number=1, - ) - page_size: int = proto.Field( - proto.INT32, - number=2, - ) - page_token: str = proto.Field( - proto.STRING, - number=3, - ) - - -class ListConversationProfilesResponse(proto.Message): - r"""The response message for - [ConversationProfiles.ListConversationProfiles][google.cloud.dialogflow.v2.ConversationProfiles.ListConversationProfiles]. - - Attributes: - conversation_profiles (MutableSequence[google.cloud.dialogflow_v2.types.ConversationProfile]): - The list of project conversation profiles. There is 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 - - conversation_profiles: MutableSequence['ConversationProfile'] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message='ConversationProfile', - ) - next_page_token: str = proto.Field( - proto.STRING, - number=2, - ) - - -class GetConversationProfileRequest(proto.Message): - r"""The request message for - [ConversationProfiles.GetConversationProfile][google.cloud.dialogflow.v2.ConversationProfiles.GetConversationProfile]. - - Attributes: - name (str): - Required. The resource name of the conversation profile. - Format: - ``projects//locations//conversationProfiles/``. - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - - -class CreateConversationProfileRequest(proto.Message): - r"""The request message for - [ConversationProfiles.CreateConversationProfile][google.cloud.dialogflow.v2.ConversationProfiles.CreateConversationProfile]. - - Attributes: - parent (str): - Required. The project to create a conversation profile for. - Format: ``projects//locations/``. - conversation_profile (google.cloud.dialogflow_v2.types.ConversationProfile): - Required. The conversation profile to create. - """ - - parent: str = proto.Field( - proto.STRING, - number=1, - ) - conversation_profile: 'ConversationProfile' = proto.Field( - proto.MESSAGE, - number=2, - message='ConversationProfile', - ) - - -class UpdateConversationProfileRequest(proto.Message): - r"""The request message for - [ConversationProfiles.UpdateConversationProfile][google.cloud.dialogflow.v2.ConversationProfiles.UpdateConversationProfile]. - - Attributes: - conversation_profile (google.cloud.dialogflow_v2.types.ConversationProfile): - Required. The conversation profile to update. - update_mask (google.protobuf.field_mask_pb2.FieldMask): - Required. The mask to control which fields to - update. - """ - - conversation_profile: 'ConversationProfile' = proto.Field( - proto.MESSAGE, - number=1, - message='ConversationProfile', - ) - update_mask: field_mask_pb2.FieldMask = proto.Field( - proto.MESSAGE, - number=2, - message=field_mask_pb2.FieldMask, - ) - - -class DeleteConversationProfileRequest(proto.Message): - r"""The request message for - [ConversationProfiles.DeleteConversationProfile][google.cloud.dialogflow.v2.ConversationProfiles.DeleteConversationProfile]. - - This operation fails if the conversation profile is still referenced - from a phone number. - - Attributes: - name (str): - Required. The name of the conversation profile to delete. - Format: - ``projects//locations//conversationProfiles/``. - """ - - name: str = 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. - - This project needs to either be the same project as the - conversation or you need to grant - ``service-@gcp-sa-dialogflow.iam.gserviceaccount.com`` - the ``Dialogflow API Service Agent`` role in this project. - - - For ES agents, use format: - ``projects//locations//agent/environments/``. - If environment is not specified, the default ``draft`` - environment is used. Refer to - `DetectIntentRequest `__ - for more details. - - - For CX agents, use format - ``projects//locations//agents//environments/``. - If environment is not specified, the default ``draft`` - environment is used. - """ - - agent: str = 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 - assistant events. - human_agent_suggestion_config (google.cloud.dialogflow_v2.types.HumanAgentAssistantConfig.SuggestionConfig): - Configuration for agent assistance of human - agent participant. - 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 - talk. - only_end_user (bool): - Only trigger suggestion if participant role of last - utterance is END_USER. - """ - - no_smalltalk: bool = proto.Field( - proto.BOOL, - number=1, - ) - only_end_user: bool = 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. - enable_event_based_suggestion (bool): - Automatically iterates all participants and tries to compile - suggestions. - - Supported features: ARTICLE_SUGGESTION, FAQ, - DIALOGFLOW_ASSIST. - suggestion_trigger_settings (google.cloud.dialogflow_v2.types.HumanAgentAssistantConfig.SuggestionTriggerSettings): - Settings of suggestion trigger. - - Currently, only ARTICLE_SUGGESTION and FAQ will use this - field. - query_config (google.cloud.dialogflow_v2.types.HumanAgentAssistantConfig.SuggestionQueryConfig): - Configs of query. - conversation_model_config (google.cloud.dialogflow_v2.types.HumanAgentAssistantConfig.ConversationModelConfig): - Configs of custom conversation model. - conversation_process_config (google.cloud.dialogflow_v2.types.HumanAgentAssistantConfig.ConversationProcessConfig): - Configs for processing conversation. - """ - - suggestion_feature: 'SuggestionFeature' = proto.Field( - proto.MESSAGE, - number=5, - message='SuggestionFeature', - ) - enable_event_based_suggestion: bool = proto.Field( - proto.BOOL, - number=3, - ) - suggestion_trigger_settings: 'HumanAgentAssistantConfig.SuggestionTriggerSettings' = proto.Field( - proto.MESSAGE, - number=10, - message='HumanAgentAssistantConfig.SuggestionTriggerSettings', - ) - query_config: 'HumanAgentAssistantConfig.SuggestionQueryConfig' = proto.Field( - proto.MESSAGE, - number=6, - message='HumanAgentAssistantConfig.SuggestionQueryConfig', - ) - conversation_model_config: 'HumanAgentAssistantConfig.ConversationModelConfig' = proto.Field( - proto.MESSAGE, - number=7, - message='HumanAgentAssistantConfig.ConversationModelConfig', - ) - conversation_process_config: 'HumanAgentAssistantConfig.ConversationProcessConfig' = proto.Field( - proto.MESSAGE, - number=8, - message='HumanAgentAssistantConfig.ConversationProcessConfig', - ) - - class SuggestionConfig(proto.Message): - r"""Detail human agent assistant config. - - Attributes: - feature_configs (MutableSequence[google.cloud.dialogflow_v2.types.HumanAgentAssistantConfig.SuggestionFeatureConfig]): - Configuration of different suggestion - features. One feature can have only one config. - group_suggestion_responses (bool): - If ``group_suggestion_responses`` is false, and there are - multiple ``feature_configs`` in ``event based suggestion`` - or StreamingAnalyzeContent, we will try to deliver - suggestions to customers as soon as we get new suggestion. - Different type of suggestions based on the same context will - be in separate Pub/Sub event or - ``StreamingAnalyzeContentResponse``. - - If ``group_suggestion_responses`` set to true. All the - suggestions to the same participant based on the same - context will be grouped into a single Pub/Sub event or - StreamingAnalyzeContentResponse. - """ - - feature_configs: MutableSequence['HumanAgentAssistantConfig.SuggestionFeatureConfig'] = proto.RepeatedField( - proto.MESSAGE, - number=2, - message='HumanAgentAssistantConfig.SuggestionFeatureConfig', - ) - group_suggestion_responses: bool = proto.Field( - proto.BOOL, - number=3, - ) - - class SuggestionQueryConfig(proto.Message): - r"""Config for suggestion query. - - This message has `oneof`_ fields (mutually exclusive fields). - For each oneof, at most one member field can be set at the same time. - Setting any member of the oneof automatically clears all other - members. - - .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields - - Attributes: - knowledge_base_query_source (google.cloud.dialogflow_v2.types.HumanAgentAssistantConfig.SuggestionQueryConfig.KnowledgeBaseQuerySource): - Query from knowledgebase. It is used by: ARTICLE_SUGGESTION, - FAQ. - - This field is a member of `oneof`_ ``query_source``. - document_query_source (google.cloud.dialogflow_v2.types.HumanAgentAssistantConfig.SuggestionQueryConfig.DocumentQuerySource): - Query from knowledge base document. It is used by: - SMART_REPLY, SMART_COMPOSE. - - This field is a member of `oneof`_ ``query_source``. - dialogflow_query_source (google.cloud.dialogflow_v2.types.HumanAgentAssistantConfig.SuggestionQueryConfig.DialogflowQuerySource): - Query from Dialogflow agent. It is used by - DIALOGFLOW_ASSIST. - - This field is a member of `oneof`_ ``query_source``. - max_results (int): - Maximum number of results to return. - Currently, if unset, defaults to 10. And the max - number is 20. - confidence_threshold (float): - Confidence threshold of query result. - - Agent Assist gives each suggestion a score in the range - [0.0, 1.0], based on the relevance between the suggestion - and the current conversation context. A score of 0.0 has no - relevance, while a score of 1.0 has high relevance. Only - suggestions with a score greater than or equal to the value - of this field are included in the results. - - For a baseline model (the default), the recommended value is - in the range [0.05, 0.1]. - - For a custom model, there is no recommended value. Tune this - value by starting from a very low value and slowly - increasing until you have desired results. - - If this field is not set, it defaults to 0.0, which means - that all suggestions are returned. - - Supported features: ARTICLE_SUGGESTION, FAQ, SMART_REPLY, - SMART_COMPOSE. - context_filter_settings (google.cloud.dialogflow_v2.types.HumanAgentAssistantConfig.SuggestionQueryConfig.ContextFilterSettings): - Determines how recent conversation context is - filtered when generating suggestions. If - unspecified, no messages will be dropped. - """ - - class KnowledgeBaseQuerySource(proto.Message): - r"""Knowledge base source settings. - - Supported features: ARTICLE_SUGGESTION, FAQ. - - Attributes: - knowledge_bases (MutableSequence[str]): - Required. Knowledge bases to query. Format: - ``projects//locations//knowledgeBases/``. - Currently, at most 5 knowledge bases are supported. - """ - - knowledge_bases: MutableSequence[str] = proto.RepeatedField( - proto.STRING, - number=1, - ) - - class DocumentQuerySource(proto.Message): - r"""Document source settings. - - Supported features: SMART_REPLY, SMART_COMPOSE. - - Attributes: - documents (MutableSequence[str]): - Required. Knowledge documents to query from. Format: - ``projects//locations//knowledgeBases//documents/``. - Currently, at most 5 documents are supported. - """ - - documents: MutableSequence[str] = proto.RepeatedField( - proto.STRING, - number=1, - ) - - class DialogflowQuerySource(proto.Message): - r"""Dialogflow source setting. - - Supported feature: DIALOGFLOW_ASSIST. - - Attributes: - agent (str): - Required. The name of a Dialogflow virtual agent used for - end user side intent detection and suggestion. Format: - ``projects//locations//agent``. - When multiple agents are allowed in the same Dialogflow - project. - """ - - agent: str = proto.Field( - proto.STRING, - number=1, - ) - - class ContextFilterSettings(proto.Message): - r"""Settings that determine how to filter recent conversation - context when generating suggestions. - - Attributes: - drop_handoff_messages (bool): - If set to true, the last message from virtual - agent (hand off message) and the message before - it (trigger message of hand off) are dropped. - drop_virtual_agent_messages (bool): - If set to true, all messages from virtual - agent are dropped. - drop_ivr_messages (bool): - If set to true, all messages from ivr stage - are dropped. - """ - - drop_handoff_messages: bool = proto.Field( - proto.BOOL, - number=1, - ) - drop_virtual_agent_messages: bool = proto.Field( - proto.BOOL, - number=2, - ) - drop_ivr_messages: bool = proto.Field( - proto.BOOL, - number=3, - ) - - knowledge_base_query_source: 'HumanAgentAssistantConfig.SuggestionQueryConfig.KnowledgeBaseQuerySource' = proto.Field( - proto.MESSAGE, - number=1, - oneof='query_source', - message='HumanAgentAssistantConfig.SuggestionQueryConfig.KnowledgeBaseQuerySource', - ) - document_query_source: 'HumanAgentAssistantConfig.SuggestionQueryConfig.DocumentQuerySource' = proto.Field( - proto.MESSAGE, - number=2, - oneof='query_source', - message='HumanAgentAssistantConfig.SuggestionQueryConfig.DocumentQuerySource', - ) - dialogflow_query_source: 'HumanAgentAssistantConfig.SuggestionQueryConfig.DialogflowQuerySource' = proto.Field( - proto.MESSAGE, - number=3, - oneof='query_source', - message='HumanAgentAssistantConfig.SuggestionQueryConfig.DialogflowQuerySource', - ) - max_results: int = proto.Field( - proto.INT32, - number=4, - ) - confidence_threshold: float = proto.Field( - proto.FLOAT, - number=5, - ) - context_filter_settings: 'HumanAgentAssistantConfig.SuggestionQueryConfig.ContextFilterSettings' = proto.Field( - proto.MESSAGE, - number=7, - message='HumanAgentAssistantConfig.SuggestionQueryConfig.ContextFilterSettings', - ) - - class ConversationModelConfig(proto.Message): - r"""Custom conversation models used in agent assist feature. - - Supported feature: ARTICLE_SUGGESTION, SMART_COMPOSE, SMART_REPLY, - CONVERSATION_SUMMARIZATION. - - Attributes: - model (str): - Conversation model resource name. Format: - ``projects//conversationModels/``. - """ - - model: str = proto.Field( - proto.STRING, - number=1, - ) - - class ConversationProcessConfig(proto.Message): - r"""Config to process conversation. - - Attributes: - recent_sentences_count (int): - Number of recent non-small-talk sentences to - use as context for article and FAQ suggestion - """ - - recent_sentences_count: int = proto.Field( - proto.INT32, - number=2, - ) - - class MessageAnalysisConfig(proto.Message): - r"""Configuration for analyses to run on each conversation - message. - - Attributes: - enable_entity_extraction (bool): - Enable entity extraction in conversation messages on `agent - 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 - stage `__. - If unspecified, defaults to false. Sentiment analysis - inspects user input and identifies the prevailing subjective - opinion, especially to determine a user's attitude as - positive, negative, or neutral: - https://cloud.google.com/natural-language/docs/basics#sentiment_analysis - For - [Participants.StreamingAnalyzeContent][google.cloud.dialogflow.v2.Participants.StreamingAnalyzeContent] - method, result will be in - [StreamingAnalyzeContentResponse.message.SentimentAnalysisResult][google.cloud.dialogflow.v2.StreamingAnalyzeContentResponse.message]. - For - [Participants.AnalyzeContent][google.cloud.dialogflow.v2.Participants.AnalyzeContent] - method, result will be in - [AnalyzeContentResponse.message.SentimentAnalysisResult][google.cloud.dialogflow.v2.AnalyzeContentResponse.message] - For - [Conversations.ListMessages][google.cloud.dialogflow.v2.Conversations.ListMessages] - method, result will be in - [ListMessagesResponse.messages.SentimentAnalysisResult][google.cloud.dialogflow.v2.ListMessagesResponse.messages] - If Pub/Sub notification is configured, result will be in - [ConversationEvent.new_message_payload.SentimentAnalysisResult][google.cloud.dialogflow.v2.ConversationEvent.new_message_payload]. - """ - - enable_entity_extraction: bool = proto.Field( - proto.BOOL, - number=2, - ) - enable_sentiment_analysis: bool = proto.Field( - proto.BOOL, - number=3, - ) - - notification_config: 'NotificationConfig' = proto.Field( - proto.MESSAGE, - number=2, - message='NotificationConfig', - ) - human_agent_suggestion_config: SuggestionConfig = proto.Field( - proto.MESSAGE, - number=3, - message=SuggestionConfig, - ) - end_user_suggestion_config: SuggestionConfig = proto.Field( - proto.MESSAGE, - number=4, - message=SuggestionConfig, - ) - message_analysis_config: MessageAnalysisConfig = proto.Field( - proto.MESSAGE, - number=5, - message=MessageAnalysisConfig, - ) - - -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. - - This message has `oneof`_ fields (mutually exclusive fields). - For each oneof, at most one member field can be set at the same time. - Setting any member of the oneof automatically clears all other - members. - - .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields - - Attributes: - live_person_config (google.cloud.dialogflow_v2.types.HumanAgentHandoffConfig.LivePersonConfig): - Uses LivePerson (https://www.liveperson.com). - - This field is a member of `oneof`_ ``agent_service``. - salesforce_live_agent_config (google.cloud.dialogflow_v2.types.HumanAgentHandoffConfig.SalesforceLiveAgentConfig): - Uses Salesforce Live Agent. - - This field is a member of `oneof`_ ``agent_service``. - """ - - class LivePersonConfig(proto.Message): - r"""Configuration specific to LivePerson - (https://www.liveperson.com). - - Attributes: - account_number (str): - Required. Account number of the LivePerson - account to connect. This is the account number - you input at the login page. - """ - - account_number: str = 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 - Salesforce account. - deployment_id (str): - Required. Live Agent deployment ID. - button_id (str): - Required. Live Agent chat button ID. - endpoint_domain (str): - Required. Domain of the Live Agent endpoint for this agent. - You can find the endpoint URL in the ``Live Agent settings`` - page. For example if URL has the form - https://d.la4-c2-phx.salesforceliveagent.com/..., you should - fill in d.la4-c2-phx.salesforceliveagent.com. - """ - - organization_id: str = proto.Field( - proto.STRING, - number=1, - ) - deployment_id: str = proto.Field( - proto.STRING, - number=2, - ) - button_id: str = proto.Field( - proto.STRING, - number=3, - ) - endpoint_domain: str = proto.Field( - proto.STRING, - number=4, - ) - - live_person_config: LivePersonConfig = proto.Field( - proto.MESSAGE, - number=1, - oneof='agent_service', - message=LivePersonConfig, - ) - salesforce_live_agent_config: SalesforceLiveAgentConfig = proto.Field( - proto.MESSAGE, - number=2, - oneof='agent_service', - message=SalesforceLiveAgentConfig, - ) - - -class NotificationConfig(proto.Message): - r"""Defines notification behavior. - - Attributes: - topic (str): - Name of the Pub/Sub topic to publish conversation events - like - [CONVERSATION_STARTED][google.cloud.dialogflow.v2.ConversationEvent.Type.CONVERSATION_STARTED] - as serialized - [ConversationEvent][google.cloud.dialogflow.v2.ConversationEvent] - protos. - - For telephony integration to receive notification, make sure - either this topic is in the same project as the conversation - or you grant - ``service-@gcp-sa-dialogflow.iam.gserviceaccount.com`` - the ``Dialogflow Service Agent`` role in the topic project. - - For chat integration to receive notification, make sure API - caller has been granted the ``Dialogflow Service Agent`` - role for the topic. - - Format: - ``projects//locations//topics/``. - message_format (google.cloud.dialogflow_v2.types.NotificationConfig.MessageFormat): - Format of message. - """ - class MessageFormat(proto.Enum): - r"""Format of cloud pub/sub message. - - Values: - MESSAGE_FORMAT_UNSPECIFIED (0): - If it is unspecified, PROTO will be used. - PROTO (1): - Pub/Sub message will be serialized proto. - JSON (2): - Pub/Sub message will be json. - """ - MESSAGE_FORMAT_UNSPECIFIED = 0 - PROTO = 1 - JSON = 2 - - topic: str = proto.Field( - proto.STRING, - number=1, - ) - message_format: MessageFormat = 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 - [CONVERSATION_STARTED][google.cloud.dialogflow.v2.ConversationEvent.Type.CONVERSATION_STARTED] - to Stackdriver in the conversation project as JSON format - [ConversationEvent][google.cloud.dialogflow.v2.ConversationEvent] - protos. - """ - - enable_stackdriver_logging: bool = proto.Field( - proto.BOOL, - number=3, - ) - - -class SuggestionFeature(proto.Message): - r"""The type of Human Agent Assistant API suggestion to perform, and the - maximum number of results to return for that type. Multiple - ``Feature`` objects can be specified in the ``features`` list. - - Attributes: - type_ (google.cloud.dialogflow_v2.types.SuggestionFeature.Type): - Type of Human Agent Assistant API feature to - request. - """ - class Type(proto.Enum): - r"""Defines the type of Human Agent Assistant feature. - - Values: - TYPE_UNSPECIFIED (0): - Unspecified feature type. - ARTICLE_SUGGESTION (1): - Run article suggestion model for chat. - FAQ (2): - Run FAQ model for chat. - SMART_REPLY (3): - Run smart reply model for chat. - """ - TYPE_UNSPECIFIED = 0 - ARTICLE_SUGGESTION = 1 - FAQ = 2 - SMART_REPLY = 3 - - type_: Type = proto.Field( - proto.ENUM, - number=1, - enum=Type, - ) - - -class SetSuggestionFeatureConfigRequest(proto.Message): - r"""The request message for - [ConversationProfiles.SetSuggestionFeature][]. - - Attributes: - conversation_profile (str): - Required. The Conversation Profile to add or update the - suggestion feature config. Format: - ``projects//locations//conversationProfiles/``. - participant_role (google.cloud.dialogflow_v2.types.Participant.Role): - Required. The participant role to add or update the - suggestion feature config. Only HUMAN_AGENT or END_USER can - be used. - suggestion_feature_config (google.cloud.dialogflow_v2.types.HumanAgentAssistantConfig.SuggestionFeatureConfig): - Required. The suggestion feature config to - add or update. - """ - - conversation_profile: str = proto.Field( - proto.STRING, - number=1, - ) - participant_role: participant.Participant.Role = proto.Field( - proto.ENUM, - number=2, - enum=participant.Participant.Role, - ) - suggestion_feature_config: 'HumanAgentAssistantConfig.SuggestionFeatureConfig' = proto.Field( - proto.MESSAGE, - number=3, - message='HumanAgentAssistantConfig.SuggestionFeatureConfig', - ) - - -class ClearSuggestionFeatureConfigRequest(proto.Message): - r"""The request message for [ConversationProfiles.ClearFeature][]. - - Attributes: - conversation_profile (str): - Required. The Conversation Profile to add or update the - suggestion feature config. Format: - ``projects//locations//conversationProfiles/``. - participant_role (google.cloud.dialogflow_v2.types.Participant.Role): - Required. The participant role to remove the suggestion - feature config. Only HUMAN_AGENT or END_USER can be used. - suggestion_feature_type (google.cloud.dialogflow_v2.types.SuggestionFeature.Type): - Required. The type of the suggestion feature - to remove. - """ - - conversation_profile: str = proto.Field( - proto.STRING, - number=1, - ) - participant_role: participant.Participant.Role = proto.Field( - proto.ENUM, - number=2, - enum=participant.Participant.Role, - ) - suggestion_feature_type: 'SuggestionFeature.Type' = proto.Field( - proto.ENUM, - number=3, - enum='SuggestionFeature.Type', - ) - - -class SetSuggestionFeatureConfigOperationMetadata(proto.Message): - r"""Metadata for a [ConversationProfile.SetSuggestionFeatureConfig][] - operation. - - Attributes: - conversation_profile (str): - The resource name of the conversation profile. Format: - ``projects//locations//conversationProfiles/`` - participant_role (google.cloud.dialogflow_v2.types.Participant.Role): - Required. The participant role to add or update the - suggestion feature config. Only HUMAN_AGENT or END_USER can - be used. - suggestion_feature_type (google.cloud.dialogflow_v2.types.SuggestionFeature.Type): - Required. The type of the suggestion feature - to add or update. - create_time (google.protobuf.timestamp_pb2.Timestamp): - Timestamp whe the request was created. The - time is measured on server side. - """ - - conversation_profile: str = proto.Field( - proto.STRING, - number=1, - ) - participant_role: participant.Participant.Role = proto.Field( - proto.ENUM, - number=2, - enum=participant.Participant.Role, - ) - suggestion_feature_type: 'SuggestionFeature.Type' = proto.Field( - proto.ENUM, - number=3, - enum='SuggestionFeature.Type', - ) - create_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=4, - message=timestamp_pb2.Timestamp, - ) - - -class ClearSuggestionFeatureConfigOperationMetadata(proto.Message): - r"""Metadata for a [ConversationProfile.ClearSuggestionFeatureConfig][] - operation. - - Attributes: - conversation_profile (str): - The resource name of the conversation profile. Format: - ``projects//locations//conversationProfiles/`` - participant_role (google.cloud.dialogflow_v2.types.Participant.Role): - Required. The participant role to remove the suggestion - feature config. Only HUMAN_AGENT or END_USER can be used. - suggestion_feature_type (google.cloud.dialogflow_v2.types.SuggestionFeature.Type): - Required. The type of the suggestion feature - to remove. - create_time (google.protobuf.timestamp_pb2.Timestamp): - Timestamp whe the request was created. The - time is measured on server side. - """ - - conversation_profile: str = proto.Field( - proto.STRING, - number=1, - ) - participant_role: participant.Participant.Role = proto.Field( - proto.ENUM, - number=2, - enum=participant.Participant.Role, - ) - suggestion_feature_type: 'SuggestionFeature.Type' = proto.Field( - proto.ENUM, - number=3, - enum='SuggestionFeature.Type', - ) - create_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=4, - message=timestamp_pb2.Timestamp, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v2/google/cloud/dialogflow_v2/types/document.py b/owl-bot-staging/v2/google/cloud/dialogflow_v2/types/document.py deleted file mode 100644 index 67fb380f9..000000000 --- a/owl-bot-staging/v2/google/cloud/dialogflow_v2/types/document.py +++ /dev/null @@ -1,695 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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 __future__ import annotations - -from typing import MutableMapping, MutableSequence - -import proto # type: ignore - -from google.cloud.dialogflow_v2.types import gcs -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( - package='google.cloud.dialogflow.v2', - manifest={ - 'Document', - 'GetDocumentRequest', - 'ListDocumentsRequest', - 'ListDocumentsResponse', - 'CreateDocumentRequest', - 'ImportDocumentsRequest', - 'ImportDocumentTemplate', - 'ImportDocumentsResponse', - 'DeleteDocumentRequest', - 'UpdateDocumentRequest', - 'ReloadDocumentRequest', - 'ExportDocumentRequest', - 'ExportOperationMetadata', - 'KnowledgeOperationMetadata', - }, -) - - -class Document(proto.Message): - r"""A knowledge document to be used by a - [KnowledgeBase][google.cloud.dialogflow.v2.KnowledgeBase]. - - For more information, see the `knowledge base - guide `__. - - Note: The ``projects.agent.knowledgeBases.documents`` resource is - deprecated; only use ``projects.knowledgeBases.documents``. - - This message has `oneof`_ fields (mutually exclusive fields). - For each oneof, at most one member field can be set at the same time. - Setting any member of the oneof automatically clears all other - members. - - .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields - - Attributes: - name (str): - Optional. The document resource name. The name must be empty - when creating a document. Format: - ``projects//locations//knowledgeBases//documents/``. - display_name (str): - Required. The display name of the document. - The name must be 1024 bytes or less; otherwise, - the creation request fails. - mime_type (str): - Required. The MIME type of this document. - knowledge_types (MutableSequence[google.cloud.dialogflow_v2.types.Document.KnowledgeType]): - Required. The knowledge type of document - content. - content_uri (str): - The URI where the file content is located. - - For documents stored in Google Cloud Storage, these URIs - must have the form ``gs:///``. - - NOTE: External URLs must correspond to public webpages, - i.e., they must be indexed by Google Search. In particular, - URLs for showing documents in Google Cloud Storage (i.e. the - URL in your browser) are not supported. Instead use the - ``gs://`` format URI described above. - - This field is a member of `oneof`_ ``source``. - raw_content (bytes): - The raw content of the document. This field is only - permitted for EXTRACTIVE_QA and FAQ knowledge types. - - This field is a member of `oneof`_ ``source``. - enable_auto_reload (bool): - Optional. If true, we try to automatically reload the - document every day (at a time picked by the system). If - false or unspecified, we don't try to automatically reload - the document. - - Currently you can only enable automatic reload for documents - sourced from a public url, see ``source`` field for the - source types. - - Reload status can be tracked in ``latest_reload_status``. If - a reload fails, we will keep the document unchanged. - - If a reload fails with internal errors, the system will try - to reload the document on the next day. If a reload fails - with non-retriable errors (e.g. PERMISION_DENIED), the - system will not try to reload the document anymore. You need - to manually reload the document successfully by calling - ``ReloadDocument`` and clear the errors. - latest_reload_status (google.cloud.dialogflow_v2.types.Document.ReloadStatus): - Output only. The time and status of the - latest reload. This reload may have been - triggered automatically or manually and may not - have succeeded. - metadata (MutableMapping[str, str]): - Optional. Metadata for the document. The metadata supports - arbitrary key-value pairs. Suggested use cases include - storing a document's title, an external URL distinct from - the document's content_uri, etc. The max size of a ``key`` - or a ``value`` of the metadata is 1024 bytes. - state (google.cloud.dialogflow_v2.types.Document.State): - Output only. The current state of the - document. - """ - class KnowledgeType(proto.Enum): - r"""The knowledge type of document content. - - Values: - KNOWLEDGE_TYPE_UNSPECIFIED (0): - The type is unspecified or arbitrary. - FAQ (1): - The document content contains question and - answer pairs as either HTML or CSV. Typical FAQ - HTML formats are parsed accurately, but unusual - formats may fail to be parsed. - - CSV must have questions in the first column and - answers in the second, with no header. Because - of this explicit format, they are always parsed - accurately. - EXTRACTIVE_QA (2): - Documents for which unstructured text is - extracted and used for question answering. - ARTICLE_SUGGESTION (3): - The entire document content as a whole can be - used for query results. Only for Contact Center - Solutions on Dialogflow. - AGENT_FACING_SMART_REPLY (4): - The document contains agent-facing Smart - Reply entries. - """ - KNOWLEDGE_TYPE_UNSPECIFIED = 0 - FAQ = 1 - EXTRACTIVE_QA = 2 - ARTICLE_SUGGESTION = 3 - AGENT_FACING_SMART_REPLY = 4 - - class State(proto.Enum): - r"""Possible states of the document - - Values: - STATE_UNSPECIFIED (0): - The document state is unspecified. - CREATING (1): - The document creation is in progress. - ACTIVE (2): - The document is active and ready to use. - UPDATING (3): - The document updation is in progress. - RELOADING (4): - The document is reloading. - DELETING (5): - The document deletion is in progress. - """ - STATE_UNSPECIFIED = 0 - CREATING = 1 - ACTIVE = 2 - UPDATING = 3 - RELOADING = 4 - DELETING = 5 - - class ReloadStatus(proto.Message): - r"""The status of a reload attempt. - - Attributes: - time (google.protobuf.timestamp_pb2.Timestamp): - The time of a reload attempt. - This reload may have been triggered - automatically or manually and may not have - succeeded. - status (google.rpc.status_pb2.Status): - The status of a reload attempt or the initial - load. - """ - - time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=1, - message=timestamp_pb2.Timestamp, - ) - status: status_pb2.Status = proto.Field( - proto.MESSAGE, - number=2, - message=status_pb2.Status, - ) - - name: str = proto.Field( - proto.STRING, - number=1, - ) - display_name: str = proto.Field( - proto.STRING, - number=2, - ) - mime_type: str = proto.Field( - proto.STRING, - number=3, - ) - knowledge_types: MutableSequence[KnowledgeType] = proto.RepeatedField( - proto.ENUM, - number=4, - enum=KnowledgeType, - ) - content_uri: str = proto.Field( - proto.STRING, - number=5, - oneof='source', - ) - raw_content: bytes = proto.Field( - proto.BYTES, - number=9, - oneof='source', - ) - enable_auto_reload: bool = proto.Field( - proto.BOOL, - number=11, - ) - latest_reload_status: ReloadStatus = proto.Field( - proto.MESSAGE, - number=12, - message=ReloadStatus, - ) - metadata: MutableMapping[str, str] = proto.MapField( - proto.STRING, - proto.STRING, - number=7, - ) - state: State = proto.Field( - proto.ENUM, - number=13, - enum=State, - ) - - -class GetDocumentRequest(proto.Message): - r"""Request message for - [Documents.GetDocument][google.cloud.dialogflow.v2.Documents.GetDocument]. - - Attributes: - name (str): - Required. The name of the document to retrieve. Format - ``projects//locations//knowledgeBases//documents/``. - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - - -class ListDocumentsRequest(proto.Message): - r"""Request message for - [Documents.ListDocuments][google.cloud.dialogflow.v2.Documents.ListDocuments]. - - Attributes: - parent (str): - Required. The knowledge base to list all documents for. - Format: - ``projects//locations//knowledgeBases/``. - page_size (int): - The maximum number of items to return in a - single page. By default 10 and at most 100. - page_token (str): - The next_page_token value returned from a previous list - request. - filter (str): - The filter expression used to filter documents returned by - the list method. The expression has the following syntax: - - [AND ] ... - - The following fields and operators are supported: - - - knowledge_types with has(:) operator - - display_name with has(:) operator - - state with equals(=) operator - - Examples: - - - "knowledge_types:FAQ" matches documents with FAQ - knowledge type. - - "display_name:customer" matches documents whose display - name contains "customer". - - "state=ACTIVE" matches documents with ACTIVE state. - - "knowledge_types:FAQ AND state=ACTIVE" matches all active - FAQ documents. - - For more information about filtering, see `API - Filtering `__. - """ - - parent: str = proto.Field( - proto.STRING, - number=1, - ) - page_size: int = proto.Field( - proto.INT32, - number=2, - ) - page_token: str = proto.Field( - proto.STRING, - number=3, - ) - filter: str = proto.Field( - proto.STRING, - number=4, - ) - - -class ListDocumentsResponse(proto.Message): - r"""Response message for - [Documents.ListDocuments][google.cloud.dialogflow.v2.Documents.ListDocuments]. - - Attributes: - documents (MutableSequence[google.cloud.dialogflow_v2.types.Document]): - The list of documents. - 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 - - documents: MutableSequence['Document'] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message='Document', - ) - next_page_token: str = proto.Field( - proto.STRING, - number=2, - ) - - -class CreateDocumentRequest(proto.Message): - r"""Request message for - [Documents.CreateDocument][google.cloud.dialogflow.v2.Documents.CreateDocument]. - - Attributes: - parent (str): - Required. The knowledge base to create a document for. - Format: - ``projects//locations//knowledgeBases/``. - document (google.cloud.dialogflow_v2.types.Document): - Required. The document to create. - """ - - parent: str = proto.Field( - proto.STRING, - number=1, - ) - document: 'Document' = proto.Field( - proto.MESSAGE, - number=2, - message='Document', - ) - - -class ImportDocumentsRequest(proto.Message): - r"""Request message for - [Documents.ImportDocuments][google.cloud.dialogflow.v2.Documents.ImportDocuments]. - - - .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields - - Attributes: - parent (str): - Required. The knowledge base to import documents into. - Format: - ``projects//locations//knowledgeBases/``. - gcs_source (google.cloud.dialogflow_v2.types.GcsSources): - The Google Cloud Storage location for the documents. The - path can include a wildcard. - - These URIs may have the forms - ``gs:///``. - ``gs:////*.``. - - This field is a member of `oneof`_ ``source``. - document_template (google.cloud.dialogflow_v2.types.ImportDocumentTemplate): - Required. Document template used for - importing all the documents. - import_gcs_custom_metadata (bool): - Whether to import custom metadata from Google - Cloud Storage. Only valid when the document - source is Google Cloud Storage URI. - """ - - parent: str = proto.Field( - proto.STRING, - number=1, - ) - gcs_source: gcs.GcsSources = proto.Field( - proto.MESSAGE, - number=2, - oneof='source', - message=gcs.GcsSources, - ) - document_template: 'ImportDocumentTemplate' = proto.Field( - proto.MESSAGE, - number=3, - message='ImportDocumentTemplate', - ) - import_gcs_custom_metadata: bool = 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. - knowledge_types (MutableSequence[google.cloud.dialogflow_v2.types.Document.KnowledgeType]): - Required. The knowledge type of document - content. - metadata (MutableMapping[str, str]): - Metadata for the document. The metadata supports arbitrary - key-value pairs. Suggested use cases include storing a - document's title, an external URL distinct from the - document's content_uri, etc. The max size of a ``key`` or a - ``value`` of the metadata is 1024 bytes. - """ - - mime_type: str = proto.Field( - proto.STRING, - number=1, - ) - knowledge_types: MutableSequence['Document.KnowledgeType'] = proto.RepeatedField( - proto.ENUM, - number=2, - enum='Document.KnowledgeType', - ) - metadata: MutableMapping[str, str] = proto.MapField( - proto.STRING, - proto.STRING, - number=3, - ) - - -class ImportDocumentsResponse(proto.Message): - r"""Response message for - [Documents.ImportDocuments][google.cloud.dialogflow.v2.Documents.ImportDocuments]. - - Attributes: - warnings (MutableSequence[google.rpc.status_pb2.Status]): - Includes details about skipped documents or - any other warnings. - """ - - warnings: MutableSequence[status_pb2.Status] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message=status_pb2.Status, - ) - - -class DeleteDocumentRequest(proto.Message): - r"""Request message for - [Documents.DeleteDocument][google.cloud.dialogflow.v2.Documents.DeleteDocument]. - - Attributes: - name (str): - Required. The name of the document to delete. Format: - ``projects//locations//knowledgeBases//documents/``. - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - - -class UpdateDocumentRequest(proto.Message): - r"""Request message for - [Documents.UpdateDocument][google.cloud.dialogflow.v2.Documents.UpdateDocument]. - - Attributes: - document (google.cloud.dialogflow_v2.types.Document): - Required. The document to update. - update_mask (google.protobuf.field_mask_pb2.FieldMask): - Optional. Not specified means ``update all``. Currently, - only ``display_name`` can be updated, an InvalidArgument - will be returned for attempting to update other fields. - """ - - document: 'Document' = proto.Field( - proto.MESSAGE, - number=1, - message='Document', - ) - update_mask: field_mask_pb2.FieldMask = proto.Field( - proto.MESSAGE, - number=2, - message=field_mask_pb2.FieldMask, - ) - - -class ReloadDocumentRequest(proto.Message): - r"""Request message for - [Documents.ReloadDocument][google.cloud.dialogflow.v2.Documents.ReloadDocument]. - - - .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields - - Attributes: - name (str): - Required. The name of the document to reload. Format: - ``projects//locations//knowledgeBases//documents/`` - content_uri (str): - Optional. The path of gcs source file for reloading document - content. For now, only gcs uri is supported. - - For documents stored in Google Cloud Storage, these URIs - must have the form ``gs:///``. - - This field is a member of `oneof`_ ``source``. - import_gcs_custom_metadata (bool): - Optional. Whether to import custom metadata - from Google Cloud Storage. Only valid when the - document source is Google Cloud Storage URI. - smart_messaging_partial_update (bool): - Optional. When enabled, the reload request is - to apply partial update to the smart messaging - allowlist. - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - content_uri: str = proto.Field( - proto.STRING, - number=3, - oneof='source', - ) - import_gcs_custom_metadata: bool = proto.Field( - proto.BOOL, - number=4, - ) - smart_messaging_partial_update: bool = proto.Field( - proto.BOOL, - number=5, - ) - - -class ExportDocumentRequest(proto.Message): - r"""Request message for - [Documents.ExportDocument][google.cloud.dialogflow.v2.Documents.ExportDocument]. - - - .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields - - Attributes: - name (str): - Required. The name of the document to export. Format: - ``projects//locations//knowledgeBases//documents/``. - gcs_destination (google.cloud.dialogflow_v2.types.GcsDestination): - Cloud Storage file path to export the - document. - - This field is a member of `oneof`_ ``destination``. - export_full_content (bool): - When enabled, export the full content of the - document including empirical probability. - smart_messaging_partial_update (bool): - When enabled, export the smart messaging - allowlist document for partial update. - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - gcs_destination: gcs.GcsDestination = proto.Field( - proto.MESSAGE, - number=2, - oneof='destination', - message=gcs.GcsDestination, - ) - export_full_content: bool = proto.Field( - proto.BOOL, - number=3, - ) - smart_messaging_partial_update: bool = proto.Field( - proto.BOOL, - number=5, - ) - - -class ExportOperationMetadata(proto.Message): - r"""Metadata related to the Export Data Operations (e.g. - ExportDocument). - - Attributes: - exported_gcs_destination (google.cloud.dialogflow_v2.types.GcsDestination): - Cloud Storage file path of the exported data. - """ - - exported_gcs_destination: gcs.GcsDestination = proto.Field( - proto.MESSAGE, - number=1, - message=gcs.GcsDestination, - ) - - -class KnowledgeOperationMetadata(proto.Message): - r"""Metadata in google::longrunning::Operation for Knowledge - operations. - - - .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields - - Attributes: - state (google.cloud.dialogflow_v2.types.KnowledgeOperationMetadata.State): - Output only. The current state of this - operation. - knowledge_base (str): - The name of the knowledge base interacted - with during the operation. - export_operation_metadata (google.cloud.dialogflow_v2.types.ExportOperationMetadata): - Metadata for the Export Data Operation such - as the destination of export. - - This field is a member of `oneof`_ ``operation_metadata``. - """ - class State(proto.Enum): - r"""States of the operation. - - Values: - STATE_UNSPECIFIED (0): - State unspecified. - PENDING (1): - The operation has been created. - RUNNING (2): - The operation is currently running. - DONE (3): - The operation is done, either cancelled or - completed. - """ - STATE_UNSPECIFIED = 0 - PENDING = 1 - RUNNING = 2 - DONE = 3 - - state: State = proto.Field( - proto.ENUM, - number=1, - enum=State, - ) - knowledge_base: str = proto.Field( - proto.STRING, - number=3, - ) - export_operation_metadata: 'ExportOperationMetadata' = proto.Field( - proto.MESSAGE, - number=4, - oneof='operation_metadata', - message='ExportOperationMetadata', - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v2/google/cloud/dialogflow_v2/types/entity_type.py b/owl-bot-staging/v2/google/cloud/dialogflow_v2/types/entity_type.py deleted file mode 100644 index ea50202d1..000000000 --- a/owl-bot-staging/v2/google/cloud/dialogflow_v2/types/entity_type.py +++ /dev/null @@ -1,601 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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 __future__ import annotations - -from typing import MutableMapping, MutableSequence - -import proto # type: ignore - -from google.protobuf import field_mask_pb2 # type: ignore - - -__protobuf__ = proto.module( - package='google.cloud.dialogflow.v2', - manifest={ - 'EntityType', - 'ListEntityTypesRequest', - 'ListEntityTypesResponse', - 'GetEntityTypeRequest', - 'CreateEntityTypeRequest', - 'UpdateEntityTypeRequest', - 'DeleteEntityTypeRequest', - 'BatchUpdateEntityTypesRequest', - 'BatchUpdateEntityTypesResponse', - 'BatchDeleteEntityTypesRequest', - 'BatchCreateEntitiesRequest', - 'BatchUpdateEntitiesRequest', - 'BatchDeleteEntitiesRequest', - 'EntityTypeBatch', - }, -) - - -class EntityType(proto.Message): - r"""Each intent parameter has a type, called the entity type, which - dictates exactly how data from an end-user expression is extracted. - - Dialogflow provides predefined system entities that can match many - common types of data. For example, there are system entities for - matching dates, times, colors, email addresses, and so on. You can - also create your own custom entities for matching custom data. For - example, you could define a vegetable entity that can match the - types of vegetables available for purchase with a grocery store - agent. - - For more information, see the `Entity - guide `__. - - Attributes: - name (str): - The unique identifier of the entity type. Required for - [EntityTypes.UpdateEntityType][google.cloud.dialogflow.v2.EntityTypes.UpdateEntityType] - and - [EntityTypes.BatchUpdateEntityTypes][google.cloud.dialogflow.v2.EntityTypes.BatchUpdateEntityTypes] - methods. Format: - ``projects//agent/entityTypes/``. - display_name (str): - Required. The name of the entity type. - kind (google.cloud.dialogflow_v2.types.EntityType.Kind): - Required. Indicates the kind of entity type. - auto_expansion_mode (google.cloud.dialogflow_v2.types.EntityType.AutoExpansionMode): - Optional. Indicates whether the entity type - can be automatically expanded. - entities (MutableSequence[google.cloud.dialogflow_v2.types.EntityType.Entity]): - Optional. The collection of entity entries - associated with the entity type. - enable_fuzzy_extraction (bool): - Optional. Enables fuzzy entity extraction - during classification. - """ - class Kind(proto.Enum): - r"""Represents kinds of entities. - - Values: - KIND_UNSPECIFIED (0): - Not specified. This value should be never - used. - KIND_MAP (1): - Map entity types allow mapping of a group of - synonyms to a reference value. - KIND_LIST (2): - List entity types contain a set of entries - that do not map to reference values. However, - list entity types can contain references to - other entity types (with or without aliases). - KIND_REGEXP (3): - Regexp entity types allow to specify regular - expressions in entries values. - """ - KIND_UNSPECIFIED = 0 - KIND_MAP = 1 - KIND_LIST = 2 - KIND_REGEXP = 3 - - class AutoExpansionMode(proto.Enum): - r"""Represents different entity type expansion modes. Automated - expansion allows an agent to recognize values that have not been - explicitly listed in the entity (for example, new kinds of - shopping list items). - - Values: - AUTO_EXPANSION_MODE_UNSPECIFIED (0): - Auto expansion disabled for the entity. - AUTO_EXPANSION_MODE_DEFAULT (1): - Allows an agent to recognize values that have - not been explicitly listed in the entity. - """ - AUTO_EXPANSION_MODE_UNSPECIFIED = 0 - AUTO_EXPANSION_MODE_DEFAULT = 1 - - class Entity(proto.Message): - r"""An **entity entry** for an associated entity type. - - Attributes: - value (str): - Required. The primary value associated with this entity - entry. For example, if the entity type is *vegetable*, the - value could be *scallions*. - - For ``KIND_MAP`` entity types: - - - A reference value to be used in place of synonyms. - - For ``KIND_LIST`` entity types: - - - A string that can contain references to other entity - types (with or without aliases). - synonyms (MutableSequence[str]): - Required. A collection of value synonyms. For example, if - the entity type is *vegetable*, and ``value`` is - *scallions*, a synonym could be *green onions*. - - For ``KIND_LIST`` entity types: - - - This collection must contain exactly one synonym equal to - ``value``. - """ - - value: str = proto.Field( - proto.STRING, - number=1, - ) - synonyms: MutableSequence[str] = proto.RepeatedField( - proto.STRING, - number=2, - ) - - name: str = proto.Field( - proto.STRING, - number=1, - ) - display_name: str = proto.Field( - proto.STRING, - number=2, - ) - kind: Kind = proto.Field( - proto.ENUM, - number=3, - enum=Kind, - ) - auto_expansion_mode: AutoExpansionMode = proto.Field( - proto.ENUM, - number=4, - enum=AutoExpansionMode, - ) - entities: MutableSequence[Entity] = proto.RepeatedField( - proto.MESSAGE, - number=6, - message=Entity, - ) - enable_fuzzy_extraction: bool = proto.Field( - proto.BOOL, - number=7, - ) - - -class ListEntityTypesRequest(proto.Message): - r"""The request message for - [EntityTypes.ListEntityTypes][google.cloud.dialogflow.v2.EntityTypes.ListEntityTypes]. - - Attributes: - parent (str): - Required. The agent to list all entity types from. Format: - ``projects//agent``. - language_code (str): - Optional. The language used to access language-specific - data. If not specified, the agent's default language is - used. For more information, see `Multilingual intent and - entity - data `__. - 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: str = proto.Field( - proto.STRING, - number=1, - ) - language_code: str = proto.Field( - proto.STRING, - number=2, - ) - page_size: int = proto.Field( - proto.INT32, - number=3, - ) - page_token: str = proto.Field( - proto.STRING, - number=4, - ) - - -class ListEntityTypesResponse(proto.Message): - r"""The response message for - [EntityTypes.ListEntityTypes][google.cloud.dialogflow.v2.EntityTypes.ListEntityTypes]. - - Attributes: - entity_types (MutableSequence[google.cloud.dialogflow_v2.types.EntityType]): - The list of agent entity types. 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 - - entity_types: MutableSequence['EntityType'] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message='EntityType', - ) - next_page_token: str = proto.Field( - proto.STRING, - number=2, - ) - - -class GetEntityTypeRequest(proto.Message): - r"""The request message for - [EntityTypes.GetEntityType][google.cloud.dialogflow.v2.EntityTypes.GetEntityType]. - - Attributes: - name (str): - Required. The name of the entity type. Format: - ``projects//agent/entityTypes/``. - language_code (str): - Optional. The language used to access language-specific - data. If not specified, the agent's default language is - used. For more information, see `Multilingual intent and - entity - data `__. - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - language_code: str = proto.Field( - proto.STRING, - number=2, - ) - - -class CreateEntityTypeRequest(proto.Message): - r"""The request message for - [EntityTypes.CreateEntityType][google.cloud.dialogflow.v2.EntityTypes.CreateEntityType]. - - Attributes: - parent (str): - Required. The agent to create a entity type for. Format: - ``projects//agent``. - entity_type (google.cloud.dialogflow_v2.types.EntityType): - Required. The entity type to create. - language_code (str): - Optional. The language used to access language-specific - data. If not specified, the agent's default language is - used. For more information, see `Multilingual intent and - entity - data `__. - """ - - parent: str = proto.Field( - proto.STRING, - number=1, - ) - entity_type: 'EntityType' = proto.Field( - proto.MESSAGE, - number=2, - message='EntityType', - ) - language_code: str = proto.Field( - proto.STRING, - number=3, - ) - - -class UpdateEntityTypeRequest(proto.Message): - r"""The request message for - [EntityTypes.UpdateEntityType][google.cloud.dialogflow.v2.EntityTypes.UpdateEntityType]. - - Attributes: - entity_type (google.cloud.dialogflow_v2.types.EntityType): - Required. The entity type to update. - language_code (str): - Optional. The language used to access language-specific - data. If not specified, the agent's default language is - used. For more information, see `Multilingual intent and - entity - data `__. - update_mask (google.protobuf.field_mask_pb2.FieldMask): - Optional. The mask to control which fields - get updated. - """ - - entity_type: 'EntityType' = proto.Field( - proto.MESSAGE, - number=1, - message='EntityType', - ) - language_code: str = proto.Field( - proto.STRING, - number=2, - ) - update_mask: field_mask_pb2.FieldMask = proto.Field( - proto.MESSAGE, - number=3, - message=field_mask_pb2.FieldMask, - ) - - -class DeleteEntityTypeRequest(proto.Message): - r"""The request message for - [EntityTypes.DeleteEntityType][google.cloud.dialogflow.v2.EntityTypes.DeleteEntityType]. - - Attributes: - name (str): - Required. The name of the entity type to delete. Format: - ``projects//agent/entityTypes/``. - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - - -class BatchUpdateEntityTypesRequest(proto.Message): - r"""The request message for - [EntityTypes.BatchUpdateEntityTypes][google.cloud.dialogflow.v2.EntityTypes.BatchUpdateEntityTypes]. - - This message has `oneof`_ fields (mutually exclusive fields). - For each oneof, at most one member field can be set at the same time. - Setting any member of the oneof automatically clears all other - members. - - .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields - - Attributes: - parent (str): - Required. The name of the agent to update or create entity - types in. Format: ``projects//agent``. - entity_type_batch_uri (str): - The URI to a Google Cloud Storage file - containing entity types to update or create. The - file format can either be a serialized proto (of - EntityBatch type) or a JSON object. Note: The - URI must start with "gs://". - - This field is a member of `oneof`_ ``entity_type_batch``. - entity_type_batch_inline (google.cloud.dialogflow_v2.types.EntityTypeBatch): - The collection of entity types to update or - create. - - This field is a member of `oneof`_ ``entity_type_batch``. - language_code (str): - Optional. The language used to access language-specific - data. If not specified, the agent's default language is - used. For more information, see `Multilingual intent and - entity - data `__. - update_mask (google.protobuf.field_mask_pb2.FieldMask): - Optional. The mask to control which fields - get updated. - """ - - parent: str = proto.Field( - proto.STRING, - number=1, - ) - entity_type_batch_uri: str = proto.Field( - proto.STRING, - number=2, - oneof='entity_type_batch', - ) - entity_type_batch_inline: 'EntityTypeBatch' = proto.Field( - proto.MESSAGE, - number=3, - oneof='entity_type_batch', - message='EntityTypeBatch', - ) - language_code: str = proto.Field( - proto.STRING, - number=4, - ) - update_mask: field_mask_pb2.FieldMask = proto.Field( - proto.MESSAGE, - number=5, - message=field_mask_pb2.FieldMask, - ) - - -class BatchUpdateEntityTypesResponse(proto.Message): - r"""The response message for - [EntityTypes.BatchUpdateEntityTypes][google.cloud.dialogflow.v2.EntityTypes.BatchUpdateEntityTypes]. - - Attributes: - entity_types (MutableSequence[google.cloud.dialogflow_v2.types.EntityType]): - The collection of updated or created entity - types. - """ - - entity_types: MutableSequence['EntityType'] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message='EntityType', - ) - - -class BatchDeleteEntityTypesRequest(proto.Message): - r"""The request message for - [EntityTypes.BatchDeleteEntityTypes][google.cloud.dialogflow.v2.EntityTypes.BatchDeleteEntityTypes]. - - Attributes: - parent (str): - Required. The name of the agent to delete all entities types - for. Format: ``projects//agent``. - entity_type_names (MutableSequence[str]): - Required. The names entity types to delete. All names must - point to the same agent as ``parent``. - """ - - parent: str = proto.Field( - proto.STRING, - number=1, - ) - entity_type_names: MutableSequence[str] = proto.RepeatedField( - proto.STRING, - number=2, - ) - - -class BatchCreateEntitiesRequest(proto.Message): - r"""The request message for - [EntityTypes.BatchCreateEntities][google.cloud.dialogflow.v2.EntityTypes.BatchCreateEntities]. - - Attributes: - parent (str): - Required. The name of the entity type to create entities in. - Format: - ``projects//agent/entityTypes/``. - entities (MutableSequence[google.cloud.dialogflow_v2.types.EntityType.Entity]): - Required. The entities to create. - language_code (str): - Optional. The language used to access language-specific - data. If not specified, the agent's default language is - used. For more information, see `Multilingual intent and - entity - data `__. - """ - - parent: str = proto.Field( - proto.STRING, - number=1, - ) - entities: MutableSequence['EntityType.Entity'] = proto.RepeatedField( - proto.MESSAGE, - number=2, - message='EntityType.Entity', - ) - language_code: str = proto.Field( - proto.STRING, - number=3, - ) - - -class BatchUpdateEntitiesRequest(proto.Message): - r"""The request message for - [EntityTypes.BatchUpdateEntities][google.cloud.dialogflow.v2.EntityTypes.BatchUpdateEntities]. - - Attributes: - parent (str): - Required. The name of the entity type to update or create - entities in. Format: - ``projects//agent/entityTypes/``. - entities (MutableSequence[google.cloud.dialogflow_v2.types.EntityType.Entity]): - Required. The entities to update or create. - language_code (str): - Optional. The language used to access language-specific - data. If not specified, the agent's default language is - used. For more information, see `Multilingual intent and - entity - data `__. - update_mask (google.protobuf.field_mask_pb2.FieldMask): - Optional. The mask to control which fields - get updated. - """ - - parent: str = proto.Field( - proto.STRING, - number=1, - ) - entities: MutableSequence['EntityType.Entity'] = proto.RepeatedField( - proto.MESSAGE, - number=2, - message='EntityType.Entity', - ) - language_code: str = proto.Field( - proto.STRING, - number=3, - ) - update_mask: field_mask_pb2.FieldMask = proto.Field( - proto.MESSAGE, - number=4, - message=field_mask_pb2.FieldMask, - ) - - -class BatchDeleteEntitiesRequest(proto.Message): - r"""The request message for - [EntityTypes.BatchDeleteEntities][google.cloud.dialogflow.v2.EntityTypes.BatchDeleteEntities]. - - Attributes: - parent (str): - Required. The name of the entity type to delete entries for. - Format: - ``projects//agent/entityTypes/``. - entity_values (MutableSequence[str]): - Required. The reference ``values`` of the entities to - delete. Note that these are not fully-qualified names, i.e. - they don't start with ``projects/``. - language_code (str): - Optional. The language used to access language-specific - data. If not specified, the agent's default language is - used. For more information, see `Multilingual intent and - entity - data `__. - """ - - parent: str = proto.Field( - proto.STRING, - number=1, - ) - entity_values: MutableSequence[str] = proto.RepeatedField( - proto.STRING, - number=2, - ) - language_code: str = proto.Field( - proto.STRING, - number=3, - ) - - -class EntityTypeBatch(proto.Message): - r"""This message is a wrapper around a collection of entity - types. - - Attributes: - entity_types (MutableSequence[google.cloud.dialogflow_v2.types.EntityType]): - A collection of entity types. - """ - - entity_types: MutableSequence['EntityType'] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message='EntityType', - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v2/google/cloud/dialogflow_v2/types/environment.py b/owl-bot-staging/v2/google/cloud/dialogflow_v2/types/environment.py deleted file mode 100644 index e690fb6c7..000000000 --- a/owl-bot-staging/v2/google/cloud/dialogflow_v2/types/environment.py +++ /dev/null @@ -1,484 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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 __future__ import annotations - -from typing import MutableMapping, MutableSequence - -import proto # 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', - 'TextToSpeechSettings', - 'ListEnvironmentsRequest', - 'ListEnvironmentsResponse', - 'GetEnvironmentRequest', - 'CreateEnvironmentRequest', - 'UpdateEnvironmentRequest', - 'DeleteEnvironmentRequest', - 'GetEnvironmentHistoryRequest', - 'EnvironmentHistory', - }, -) - - -class Environment(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 - environment. Supported formats: - - - ``projects//agent/environments/`` - - ``projects//locations//agent/environments/`` - - The environment ID for the default environment is ``-``. - description (str): - Optional. The developer-provided description - for this environment. The maximum length is 500 - characters. If exceeded, the request is - rejected. - agent_version (str): - Optional. The agent version loaded into this environment. - 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 - by create and update methods. - update_time (google.protobuf.timestamp_pb2.Timestamp): - 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): - r"""Represents an environment state. When an environment is pointed to a - new 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. - - Values: - STATE_UNSPECIFIED (0): - Not specified. This value is not used. - STOPPED (1): - Stopped. - LOADING (2): - Loading. - RUNNING (3): - Running. - """ - STATE_UNSPECIFIED = 0 - STOPPED = 1 - LOADING = 2 - RUNNING = 3 - - name: str = proto.Field( - proto.STRING, - number=1, - ) - description: str = proto.Field( - proto.STRING, - number=2, - ) - agent_version: str = proto.Field( - proto.STRING, - number=3, - ) - state: State = proto.Field( - proto.ENUM, - number=4, - enum=State, - ) - update_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=5, - message=timestamp_pb2.Timestamp, - ) - text_to_speech_settings: 'TextToSpeechSettings' = proto.Field( - proto.MESSAGE, - number=7, - message='TextToSpeechSettings', - ) - fulfillment: gcd_fulfillment.Fulfillment = proto.Field( - proto.MESSAGE, - number=8, - message=gcd_fulfillment.Fulfillment, - ) - - -class TextToSpeechSettings(proto.Message): - r"""Instructs the speech synthesizer on how to generate the - output audio content. - - 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 (MutableMapping[str, google.cloud.dialogflow_v2.types.SynthesizeSpeechConfig]): - Optional. Configuration of how speech should - be synthesized, mapping from language - (https://cloud.google.com/dialogflow/docs/reference/language) - to SynthesizeSpeechConfig. - """ - - enable_text_to_speech: bool = proto.Field( - proto.BOOL, - number=1, - ) - output_audio_encoding: audio_config.OutputAudioEncoding = proto.Field( - proto.ENUM, - number=2, - enum=audio_config.OutputAudioEncoding, - ) - sample_rate_hertz: int = proto.Field( - proto.INT32, - number=3, - ) - synthesize_speech_configs: MutableMapping[str, audio_config.SynthesizeSpeechConfig] = proto.MapField( - proto.STRING, - proto.MESSAGE, - number=4, - message=audio_config.SynthesizeSpeechConfig, - ) - - -class ListEnvironmentsRequest(proto.Message): - r"""The request message for - [Environments.ListEnvironments][google.cloud.dialogflow.v2.Environments.ListEnvironments]. - - Attributes: - parent (str): - Required. The agent to list all environments from. Format: - - - ``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: str = proto.Field( - proto.STRING, - number=1, - ) - page_size: int = proto.Field( - proto.INT32, - number=2, - ) - page_token: str = proto.Field( - proto.STRING, - number=3, - ) - - -class ListEnvironmentsResponse(proto.Message): - r"""The response message for - [Environments.ListEnvironments][google.cloud.dialogflow.v2.Environments.ListEnvironments]. - - Attributes: - environments (MutableSequence[google.cloud.dialogflow_v2.types.Environment]): - 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): - 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 - - environments: MutableSequence['Environment'] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message='Environment', - ) - next_page_token: str = 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/`` - - The environment ID for the default environment is ``-``. - """ - - name: str = 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: str = proto.Field( - proto.STRING, - number=1, - ) - environment: 'Environment' = proto.Field( - proto.MESSAGE, - number=2, - message='Environment', - ) - environment_id: str = 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 default 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 default environment (environment ID = ``-``). - """ - - environment: 'Environment' = proto.Field( - proto.MESSAGE, - number=1, - message='Environment', - ) - update_mask: field_mask_pb2.FieldMask = proto.Field( - proto.MESSAGE, - number=2, - message=field_mask_pb2.FieldMask, - ) - allow_load_to_draft_and_discard_changes: bool = 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/`` - - The environment ID for the default environment is ``-``. - """ - - name: str = 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/`` - - The environment ID for the default environment is ``-``. - 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: str = proto.Field( - proto.STRING, - number=1, - ) - page_size: int = proto.Field( - proto.INT32, - number=2, - ) - page_token: str = 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/`` - - The environment ID for the default environment is ``-``. - entries (MutableSequence[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: str = proto.Field( - proto.STRING, - number=1, - ) - description: str = proto.Field( - proto.STRING, - number=2, - ) - create_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=3, - message=timestamp_pb2.Timestamp, - ) - - @property - def raw_page(self): - return self - - parent: str = proto.Field( - proto.STRING, - number=1, - ) - entries: MutableSequence[Entry] = proto.RepeatedField( - proto.MESSAGE, - number=2, - message=Entry, - ) - next_page_token: str = proto.Field( - proto.STRING, - number=3, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v2/google/cloud/dialogflow_v2/types/fulfillment.py b/owl-bot-staging/v2/google/cloud/dialogflow_v2/types/fulfillment.py deleted file mode 100644 index 2e7fb0163..000000000 --- a/owl-bot-staging/v2/google/cloud/dialogflow_v2/types/fulfillment.py +++ /dev/null @@ -1,219 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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 __future__ import annotations - -from typing import MutableMapping, MutableSequence - -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 `__. - - - .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields - - 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. - - This field is a member of `oneof`_ ``fulfillment``. - enabled (bool): - Optional. Whether fulfillment is enabled. - features (MutableSequence[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 (MutableMapping[str, str]): - 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: str = proto.Field( - proto.STRING, - number=1, - ) - username: str = proto.Field( - proto.STRING, - number=2, - ) - password: str = proto.Field( - proto.STRING, - number=3, - ) - request_headers: MutableMapping[str, str] = proto.MapField( - proto.STRING, - proto.STRING, - number=4, - ) - is_cloud_function: bool = 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. - - Values: - TYPE_UNSPECIFIED (0): - Feature type not specified. - SMALLTALK (1): - Fulfillment is enabled for SmallTalk. - """ - TYPE_UNSPECIFIED = 0 - SMALLTALK = 1 - - type_: 'Fulfillment.Feature.Type' = proto.Field( - proto.ENUM, - number=1, - enum='Fulfillment.Feature.Type', - ) - - name: str = proto.Field( - proto.STRING, - number=1, - ) - display_name: str = proto.Field( - proto.STRING, - number=2, - ) - generic_web_service: GenericWebService = proto.Field( - proto.MESSAGE, - number=3, - oneof='fulfillment', - message=GenericWebService, - ) - enabled: bool = proto.Field( - proto.BOOL, - number=4, - ) - features: MutableSequence[Feature] = 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: str = 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: 'Fulfillment' = proto.Field( - proto.MESSAGE, - number=1, - message='Fulfillment', - ) - update_mask: field_mask_pb2.FieldMask = proto.Field( - proto.MESSAGE, - number=2, - message=field_mask_pb2.FieldMask, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v2/google/cloud/dialogflow_v2/types/gcs.py b/owl-bot-staging/v2/google/cloud/dialogflow_v2/types/gcs.py deleted file mode 100644 index 5225a911d..000000000 --- a/owl-bot-staging/v2/google/cloud/dialogflow_v2/types/gcs.py +++ /dev/null @@ -1,68 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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 __future__ import annotations - -from typing import MutableMapping, MutableSequence - -import proto # type: ignore - - -__protobuf__ = proto.module( - package='google.cloud.dialogflow.v2', - manifest={ - 'GcsSources', - 'GcsDestination', - }, -) - - -class GcsSources(proto.Message): - r"""Google Cloud Storage location for the inputs. - - Attributes: - uris (MutableSequence[str]): - Required. Google Cloud Storage URIs for the - inputs. A URI is of the form: - gs://bucket/object-prefix-or-name Whether a - prefix or name is used depends on the use case. - """ - - uris: MutableSequence[str] = proto.RepeatedField( - proto.STRING, - number=2, - ) - - -class GcsDestination(proto.Message): - r"""Google Cloud Storage location for the output. - - Attributes: - uri (str): - The Google Cloud Storage URIs for the output. - A URI is of the form: - gs://bucket/object-prefix-or-name - Whether a prefix or name is used depends on the - use case. The requesting user must have - "write-permission" to the bucket. - """ - - uri: str = proto.Field( - proto.STRING, - number=1, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v2/google/cloud/dialogflow_v2/types/human_agent_assistant_event.py b/owl-bot-staging/v2/google/cloud/dialogflow_v2/types/human_agent_assistant_event.py deleted file mode 100644 index 0db4a6929..000000000 --- a/owl-bot-staging/v2/google/cloud/dialogflow_v2/types/human_agent_assistant_event.py +++ /dev/null @@ -1,65 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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 __future__ import annotations - -from typing import MutableMapping, MutableSequence - -import proto # type: ignore - -from google.cloud.dialogflow_v2.types import participant as gcd_participant - - -__protobuf__ = proto.module( - package='google.cloud.dialogflow.v2', - manifest={ - 'HumanAgentAssistantEvent', - }, -) - - -class HumanAgentAssistantEvent(proto.Message): - r"""Represents a notification sent to Cloud Pub/Sub subscribers - for human agent assistant events in a specific conversation. - - Attributes: - conversation (str): - The conversation this notification refers to. Format: - ``projects//conversations/``. - participant (str): - The participant that the suggestion is compiled for. Format: - ``projects//conversations//participants/``. - It will not be set in legacy workflow. - suggestion_results (MutableSequence[google.cloud.dialogflow_v2.types.SuggestionResult]): - The suggestion results payload that this - notification refers to. - """ - - conversation: str = proto.Field( - proto.STRING, - number=1, - ) - participant: str = proto.Field( - proto.STRING, - number=3, - ) - suggestion_results: MutableSequence[gcd_participant.SuggestionResult] = proto.RepeatedField( - proto.MESSAGE, - number=5, - message=gcd_participant.SuggestionResult, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v2/google/cloud/dialogflow_v2/types/intent.py b/owl-bot-staging/v2/google/cloud/dialogflow_v2/types/intent.py deleted file mode 100644 index 86b60c4e3..000000000 --- a/owl-bot-staging/v2/google/cloud/dialogflow_v2/types/intent.py +++ /dev/null @@ -1,1823 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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 __future__ import annotations - -from typing import MutableMapping, MutableSequence - -import proto # type: ignore - -from google.cloud.dialogflow_v2.types import context -from google.protobuf import field_mask_pb2 # type: ignore -from google.protobuf import struct_pb2 # type: ignore - - -__protobuf__ = proto.module( - package='google.cloud.dialogflow.v2', - manifest={ - 'IntentView', - 'Intent', - 'ListIntentsRequest', - 'ListIntentsResponse', - 'GetIntentRequest', - 'CreateIntentRequest', - 'UpdateIntentRequest', - 'DeleteIntentRequest', - 'BatchUpdateIntentsRequest', - 'BatchUpdateIntentsResponse', - 'BatchDeleteIntentsRequest', - 'IntentBatch', - }, -) - - -class IntentView(proto.Enum): - r"""Represents the options for views of an intent. - An intent can be a sizable object. Therefore, we provide a - resource view that does not return training phrases in the - response by default. - - Values: - INTENT_VIEW_UNSPECIFIED (0): - Training phrases field is not populated in - the response. - INTENT_VIEW_FULL (1): - All fields are populated. - """ - INTENT_VIEW_UNSPECIFIED = 0 - INTENT_VIEW_FULL = 1 - - -class Intent(proto.Message): - r"""An intent categorizes an end-user's intention for one conversation - turn. For each agent, you define many intents, where your combined - intents can handle a complete conversation. When an end-user writes - or says something, referred to as an end-user expression or end-user - input, Dialogflow matches the end-user input to the best intent in - your agent. Matching an intent is also known as intent - classification. - - For more information, see the `intent - guide `__. - - Attributes: - name (str): - Optional. The unique identifier of this intent. Required for - [Intents.UpdateIntent][google.cloud.dialogflow.v2.Intents.UpdateIntent] - and - [Intents.BatchUpdateIntents][google.cloud.dialogflow.v2.Intents.BatchUpdateIntents] - methods. Format: - ``projects//agent/intents/``. - display_name (str): - Required. The name of this intent. - webhook_state (google.cloud.dialogflow_v2.types.Intent.WebhookState): - Optional. Indicates whether webhooks are - enabled for the intent. - priority (int): - Optional. The priority of this intent. Higher numbers - represent higher priorities. - - - If the supplied value is unspecified or 0, the service - translates the value to 500,000, which corresponds to the - ``Normal`` priority in the console. - - If the supplied value is negative, the intent is ignored - in runtime detect intent requests. - is_fallback (bool): - Optional. Indicates whether this is a - fallback intent. - ml_disabled (bool): - Optional. Indicates whether Machine Learning is disabled for - the intent. Note: If ``ml_disabled`` setting is set to true, - then this intent is not taken into account during inference - in ``ML ONLY`` match mode. Also, auto-markup in the UI is - turned off. - live_agent_handoff (bool): - Optional. Indicates that a live agent should be brought in - to handle the interaction with the user. In most cases, when - you set this flag to true, you would also want to set - end_interaction to true as well. Default is false. - end_interaction (bool): - Optional. Indicates that this intent ends an - interaction. Some integrations (e.g., Actions on - Google or Dialogflow phone gateway) use this - information to close interaction with an end - user. Default is false. - input_context_names (MutableSequence[str]): - Optional. The list of context names required for this intent - to be triggered. Format: - ``projects//agent/sessions/-/contexts/``. - events (MutableSequence[str]): - Optional. The collection of event names that - trigger the intent. If the collection of input - contexts is not empty, all of the contexts must - be present in the active user session for an - event to trigger this intent. Event names are - limited to 150 characters. - training_phrases (MutableSequence[google.cloud.dialogflow_v2.types.Intent.TrainingPhrase]): - Optional. The collection of examples that the - agent is trained on. - action (str): - Optional. The name of the action associated - with the intent. Note: The action name must not - contain whitespaces. - output_contexts (MutableSequence[google.cloud.dialogflow_v2.types.Context]): - Optional. The collection of contexts that are activated when - the intent is matched. Context messages in this collection - should not set the parameters field. Setting the - ``lifespan_count`` to 0 will reset the context when the - intent is matched. Format: - ``projects//agent/sessions/-/contexts/``. - reset_contexts (bool): - Optional. Indicates whether to delete all - contexts in the current session when this intent - is matched. - parameters (MutableSequence[google.cloud.dialogflow_v2.types.Intent.Parameter]): - Optional. The collection of parameters - associated with the intent. - messages (MutableSequence[google.cloud.dialogflow_v2.types.Intent.Message]): - Optional. The collection of rich messages corresponding to - the ``Response`` field in the Dialogflow console. - default_response_platforms (MutableSequence[google.cloud.dialogflow_v2.types.Intent.Message.Platform]): - Optional. The list of platforms for which the first - responses will be copied from the messages in - PLATFORM_UNSPECIFIED (i.e. default platform). - root_followup_intent_name (str): - Output only. Read-only. The unique identifier of the root - intent in the chain of followup intents. It identifies the - correct followup intents chain for this intent. We populate - this field only in the output. - - Format: ``projects//agent/intents/``. - parent_followup_intent_name (str): - Read-only after creation. The unique identifier of the - parent intent in the chain of followup intents. You can set - this field when creating an intent, for example with - [CreateIntent][google.cloud.dialogflow.v2.Intents.CreateIntent] - or - [BatchUpdateIntents][google.cloud.dialogflow.v2.Intents.BatchUpdateIntents], - in order to make this intent a followup intent. - - It identifies the parent followup intent. Format: - ``projects//agent/intents/``. - followup_intent_info (MutableSequence[google.cloud.dialogflow_v2.types.Intent.FollowupIntentInfo]): - Output only. Read-only. Information about all - followup intents that have this intent as a - direct or indirect parent. We populate this - field only in the output. - """ - class WebhookState(proto.Enum): - r"""Represents the different states that webhooks can be in. - - Values: - WEBHOOK_STATE_UNSPECIFIED (0): - Webhook is disabled in the agent and in the - intent. - WEBHOOK_STATE_ENABLED (1): - Webhook is enabled in the agent and in the - intent. - WEBHOOK_STATE_ENABLED_FOR_SLOT_FILLING (2): - Webhook is enabled in the agent and in the - intent. Also, each slot filling prompt is - forwarded to the webhook. - """ - WEBHOOK_STATE_UNSPECIFIED = 0 - WEBHOOK_STATE_ENABLED = 1 - WEBHOOK_STATE_ENABLED_FOR_SLOT_FILLING = 2 - - class TrainingPhrase(proto.Message): - r"""Represents an example that the agent is trained on. - - Attributes: - name (str): - Output only. The unique identifier of this - training phrase. - type_ (google.cloud.dialogflow_v2.types.Intent.TrainingPhrase.Type): - Required. The type of the training phrase. - parts (MutableSequence[google.cloud.dialogflow_v2.types.Intent.TrainingPhrase.Part]): - Required. The ordered list of training phrase parts. The - parts are concatenated in order to form the training phrase. - - Note: The API does not automatically annotate training - phrases like the Dialogflow Console does. - - Note: Do not forget to include whitespace at part - boundaries, so the training phrase is well formatted when - the parts are concatenated. - - If the training phrase does not need to be annotated with - parameters, you just need a single part with only the - [Part.text][google.cloud.dialogflow.v2.Intent.TrainingPhrase.Part.text] - field set. - - If you want to annotate the training phrase, you must create - multiple parts, where the fields of each part are populated - in one of two ways: - - - ``Part.text`` is set to a part of the phrase that has no - parameters. - - ``Part.text`` is set to a part of the phrase that you - want to annotate, and the ``entity_type``, ``alias``, and - ``user_defined`` fields are all set. - times_added_count (int): - Optional. Indicates how many times this - example was added to the intent. Each time a - developer adds an existing sample by editing an - intent or training, this counter is increased. - """ - class Type(proto.Enum): - r"""Represents different types of training phrases. - - Values: - TYPE_UNSPECIFIED (0): - Not specified. This value should never be - used. - EXAMPLE (1): - Examples do not contain @-prefixed entity - type names, but example parts can be annotated - with entity types. - TEMPLATE (2): - Templates are not annotated with entity - types, but they can contain @-prefixed entity - type names as substrings. Template mode has been - deprecated. Example mode is the only supported - way to create new training phrases. If you have - existing training phrases that you've created in - template mode, those will continue to work. - """ - TYPE_UNSPECIFIED = 0 - EXAMPLE = 1 - TEMPLATE = 2 - - class Part(proto.Message): - r"""Represents a part of a training phrase. - - Attributes: - text (str): - Required. The text for this part. - entity_type (str): - Optional. The entity type name prefixed with ``@``. This - field is required for annotated parts of the training - phrase. - alias (str): - Optional. The parameter name for the value - extracted from the annotated part of the - example. This field is required for annotated - parts of the training phrase. - user_defined (bool): - Optional. Indicates whether the text was - manually annotated. This field is set to true - when the Dialogflow Console is used to manually - annotate the part. When creating an annotated - part with the API, you must set this to true. - """ - - text: str = proto.Field( - proto.STRING, - number=1, - ) - entity_type: str = proto.Field( - proto.STRING, - number=2, - ) - alias: str = proto.Field( - proto.STRING, - number=3, - ) - user_defined: bool = proto.Field( - proto.BOOL, - number=4, - ) - - name: str = proto.Field( - proto.STRING, - number=1, - ) - type_: 'Intent.TrainingPhrase.Type' = proto.Field( - proto.ENUM, - number=2, - enum='Intent.TrainingPhrase.Type', - ) - parts: MutableSequence['Intent.TrainingPhrase.Part'] = proto.RepeatedField( - proto.MESSAGE, - number=3, - message='Intent.TrainingPhrase.Part', - ) - times_added_count: int = proto.Field( - proto.INT32, - number=4, - ) - - class Parameter(proto.Message): - r"""Represents intent parameters. - - Attributes: - name (str): - The unique identifier of this parameter. - display_name (str): - Required. The name of the parameter. - value (str): - Optional. The definition of the parameter value. It can be: - - - a constant string, - - a parameter value defined as ``$parameter_name``, - - an original parameter value defined as - ``$parameter_name.original``, - - a parameter value from some context defined as - ``#context_name.parameter_name``. - default_value (str): - Optional. The default value to use when the ``value`` yields - an empty result. Default values can be extracted from - contexts by using the following syntax: - ``#context_name.parameter_name``. - entity_type_display_name (str): - Optional. The name of the entity type, prefixed with ``@``, - that describes values of the parameter. If the parameter is - required, this must be provided. - mandatory (bool): - Optional. Indicates whether the parameter is - required. That is, whether the intent cannot be - completed without collecting the parameter - value. - prompts (MutableSequence[str]): - Optional. The collection of prompts that the - agent can present to the user in order to - collect a value for the parameter. - is_list (bool): - Optional. Indicates whether the parameter - represents a list of values. - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - display_name: str = proto.Field( - proto.STRING, - number=2, - ) - value: str = proto.Field( - proto.STRING, - number=3, - ) - default_value: str = proto.Field( - proto.STRING, - number=4, - ) - entity_type_display_name: str = proto.Field( - proto.STRING, - number=5, - ) - mandatory: bool = proto.Field( - proto.BOOL, - number=6, - ) - prompts: MutableSequence[str] = proto.RepeatedField( - proto.STRING, - number=7, - ) - is_list: bool = proto.Field( - proto.BOOL, - number=8, - ) - - class Message(proto.Message): - r"""A rich response message. Corresponds to the intent ``Response`` - field in the Dialogflow console. For more information, see `Rich - response - messages `__. - - This message has `oneof`_ fields (mutually exclusive fields). - For each oneof, at most one member field can be set at the same time. - Setting any member of the oneof automatically clears all other - members. - - .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields - - Attributes: - text (google.cloud.dialogflow_v2.types.Intent.Message.Text): - The text response. - - This field is a member of `oneof`_ ``message``. - image (google.cloud.dialogflow_v2.types.Intent.Message.Image): - The image response. - - This field is a member of `oneof`_ ``message``. - quick_replies (google.cloud.dialogflow_v2.types.Intent.Message.QuickReplies): - The quick replies response. - - This field is a member of `oneof`_ ``message``. - card (google.cloud.dialogflow_v2.types.Intent.Message.Card): - The card response. - - This field is a member of `oneof`_ ``message``. - payload (google.protobuf.struct_pb2.Struct): - A custom platform-specific response. - - This field is a member of `oneof`_ ``message``. - simple_responses (google.cloud.dialogflow_v2.types.Intent.Message.SimpleResponses): - The voice and text-only responses for Actions - on Google. - - This field is a member of `oneof`_ ``message``. - basic_card (google.cloud.dialogflow_v2.types.Intent.Message.BasicCard): - The basic card response for Actions on - Google. - - This field is a member of `oneof`_ ``message``. - suggestions (google.cloud.dialogflow_v2.types.Intent.Message.Suggestions): - The suggestion chips for Actions on Google. - - This field is a member of `oneof`_ ``message``. - link_out_suggestion (google.cloud.dialogflow_v2.types.Intent.Message.LinkOutSuggestion): - The link out suggestion chip for Actions on - Google. - - This field is a member of `oneof`_ ``message``. - list_select (google.cloud.dialogflow_v2.types.Intent.Message.ListSelect): - The list card response for Actions on Google. - - This field is a member of `oneof`_ ``message``. - carousel_select (google.cloud.dialogflow_v2.types.Intent.Message.CarouselSelect): - The carousel card response for Actions on - Google. - - This field is a member of `oneof`_ ``message``. - browse_carousel_card (google.cloud.dialogflow_v2.types.Intent.Message.BrowseCarouselCard): - Browse carousel card for Actions on Google. - - This field is a member of `oneof`_ ``message``. - table_card (google.cloud.dialogflow_v2.types.Intent.Message.TableCard): - Table card for Actions on Google. - - This field is a member of `oneof`_ ``message``. - media_content (google.cloud.dialogflow_v2.types.Intent.Message.MediaContent): - The media content card for Actions on Google. - - This field is a member of `oneof`_ ``message``. - platform (google.cloud.dialogflow_v2.types.Intent.Message.Platform): - Optional. The platform that this message is - intended for. - """ - class Platform(proto.Enum): - r"""The rich response message integration platform. See - `Integrations `__. - - Values: - PLATFORM_UNSPECIFIED (0): - Default platform. - FACEBOOK (1): - Facebook. - SLACK (2): - Slack. - TELEGRAM (3): - Telegram. - KIK (4): - Kik. - SKYPE (5): - Skype. - LINE (6): - Line. - VIBER (7): - Viber. - ACTIONS_ON_GOOGLE (8): - Google Assistant See `Dialogflow webhook - format `__ - GOOGLE_HANGOUTS (11): - Google Hangouts. - """ - PLATFORM_UNSPECIFIED = 0 - FACEBOOK = 1 - SLACK = 2 - TELEGRAM = 3 - KIK = 4 - SKYPE = 5 - LINE = 6 - VIBER = 7 - ACTIONS_ON_GOOGLE = 8 - GOOGLE_HANGOUTS = 11 - - class Text(proto.Message): - r"""The text response message. - - Attributes: - text (MutableSequence[str]): - Optional. The collection of the agent's - responses. - """ - - text: MutableSequence[str] = 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. - accessibility_text (str): - Optional. A text description of the image to - be used for accessibility, e.g., screen readers. - """ - - image_uri: str = proto.Field( - proto.STRING, - number=1, - ) - accessibility_text: str = 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 - quick replies. - quick_replies (MutableSequence[str]): - Optional. The collection of quick replies. - """ - - title: str = proto.Field( - proto.STRING, - number=1, - ) - quick_replies: MutableSequence[str] = proto.RepeatedField( - proto.STRING, - number=2, - ) - - class Card(proto.Message): - r"""The card response message. - - Attributes: - title (str): - Optional. The title of the card. - subtitle (str): - Optional. The subtitle of the card. - image_uri (str): - Optional. The public URI to an image file for - the card. - buttons (MutableSequence[google.cloud.dialogflow_v2.types.Intent.Message.Card.Button]): - Optional. The collection of card buttons. - """ - - class Button(proto.Message): - r"""Contains information about a button. - - Attributes: - text (str): - Optional. The text to show on the button. - postback (str): - Optional. The text to send back to the - Dialogflow API or a URI to open. - """ - - text: str = proto.Field( - proto.STRING, - number=1, - ) - postback: str = proto.Field( - proto.STRING, - number=2, - ) - - title: str = proto.Field( - proto.STRING, - number=1, - ) - subtitle: str = proto.Field( - proto.STRING, - number=2, - ) - image_uri: str = proto.Field( - proto.STRING, - number=3, - ) - buttons: MutableSequence['Intent.Message.Card.Button'] = 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 - text of the speech output. Mutually exclusive with ssml. - ssml (str): - One of text_to_speech or ssml must be provided. Structured - spoken response to the user in the SSML format. Mutually - exclusive with text_to_speech. - display_text (str): - Optional. The text to display. - """ - - text_to_speech: str = proto.Field( - proto.STRING, - number=1, - ) - ssml: str = proto.Field( - proto.STRING, - number=2, - ) - display_text: str = proto.Field( - proto.STRING, - number=3, - ) - - class SimpleResponses(proto.Message): - r"""The collection of simple response candidates. This message in - ``QueryResult.fulfillment_messages`` and - ``WebhookResponse.fulfillment_messages`` should contain only one - ``SimpleResponse``. - - Attributes: - simple_responses (MutableSequence[google.cloud.dialogflow_v2.types.Intent.Message.SimpleResponse]): - Required. The list of simple responses. - """ - - simple_responses: MutableSequence['Intent.Message.SimpleResponse'] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message='Intent.Message.SimpleResponse', - ) - - class BasicCard(proto.Message): - r"""The basic card message. Useful for displaying information. - - Attributes: - title (str): - Optional. The title of the card. - subtitle (str): - Optional. The subtitle of the card. - formatted_text (str): - Required, unless image is present. The body - text of the card. - image (google.cloud.dialogflow_v2.types.Intent.Message.Image): - Optional. The image for the card. - buttons (MutableSequence[google.cloud.dialogflow_v2.types.Intent.Message.BasicCard.Button]): - Optional. The collection of card buttons. - """ - - 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. - open_uri_action (google.cloud.dialogflow_v2.types.Intent.Message.BasicCard.Button.OpenUriAction): - Required. Action to take when a user taps on - the button. - """ - - class OpenUriAction(proto.Message): - r"""Opens the given URI. - - Attributes: - uri (str): - Required. The HTTP or HTTPS scheme URI. - """ - - uri: str = proto.Field( - proto.STRING, - number=1, - ) - - title: str = proto.Field( - proto.STRING, - number=1, - ) - open_uri_action: 'Intent.Message.BasicCard.Button.OpenUriAction' = proto.Field( - proto.MESSAGE, - number=2, - message='Intent.Message.BasicCard.Button.OpenUriAction', - ) - - title: str = proto.Field( - proto.STRING, - number=1, - ) - subtitle: str = proto.Field( - proto.STRING, - number=2, - ) - formatted_text: str = proto.Field( - proto.STRING, - number=3, - ) - image: 'Intent.Message.Image' = proto.Field( - proto.MESSAGE, - number=4, - message='Intent.Message.Image', - ) - buttons: MutableSequence['Intent.Message.BasicCard.Button'] = proto.RepeatedField( - proto.MESSAGE, - number=5, - message='Intent.Message.BasicCard.Button', - ) - - class Suggestion(proto.Message): - r"""The suggestion chip message that the user can tap to quickly - post a reply to the conversation. - - Attributes: - title (str): - Required. The text shown the in the - suggestion chip. - """ - - title: str = proto.Field( - proto.STRING, - number=1, - ) - - class Suggestions(proto.Message): - r"""The collection of suggestions. - - Attributes: - suggestions (MutableSequence[google.cloud.dialogflow_v2.types.Intent.Message.Suggestion]): - Required. The list of suggested replies. - """ - - suggestions: MutableSequence['Intent.Message.Suggestion'] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message='Intent.Message.Suggestion', - ) - - class LinkOutSuggestion(proto.Message): - r"""The suggestion chip message that allows the user to jump out - to the app or website associated with this agent. - - Attributes: - destination_name (str): - Required. The name of the app or site this - chip is linking to. - uri (str): - Required. The URI of the app or site to open - when the user taps the suggestion chip. - """ - - destination_name: str = proto.Field( - proto.STRING, - number=1, - ) - uri: str = 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. - items (MutableSequence[google.cloud.dialogflow_v2.types.Intent.Message.ListSelect.Item]): - Required. List items. - subtitle (str): - Optional. Subtitle of the list. - """ - - 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 - option. - title (str): - Required. The title of the list item. - description (str): - Optional. The main text describing the item. - image (google.cloud.dialogflow_v2.types.Intent.Message.Image): - Optional. The image to display. - """ - - info: 'Intent.Message.SelectItemInfo' = proto.Field( - proto.MESSAGE, - number=1, - message='Intent.Message.SelectItemInfo', - ) - title: str = proto.Field( - proto.STRING, - number=2, - ) - description: str = proto.Field( - proto.STRING, - number=3, - ) - image: 'Intent.Message.Image' = proto.Field( - proto.MESSAGE, - number=4, - message='Intent.Message.Image', - ) - - title: str = proto.Field( - proto.STRING, - number=1, - ) - items: MutableSequence['Intent.Message.ListSelect.Item'] = proto.RepeatedField( - proto.MESSAGE, - number=2, - message='Intent.Message.ListSelect.Item', - ) - subtitle: str = proto.Field( - proto.STRING, - number=3, - ) - - class CarouselSelect(proto.Message): - r"""The card for presenting a carousel of options to select from. - - Attributes: - items (MutableSequence[google.cloud.dialogflow_v2.types.Intent.Message.CarouselSelect.Item]): - Required. Carousel items. - """ - - 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 - item. - title (str): - Required. Title of the carousel item. - description (str): - Optional. The body text of the card. - image (google.cloud.dialogflow_v2.types.Intent.Message.Image): - Optional. The image to display. - """ - - info: 'Intent.Message.SelectItemInfo' = proto.Field( - proto.MESSAGE, - number=1, - message='Intent.Message.SelectItemInfo', - ) - title: str = proto.Field( - proto.STRING, - number=2, - ) - description: str = proto.Field( - proto.STRING, - number=3, - ) - image: 'Intent.Message.Image' = proto.Field( - proto.MESSAGE, - number=4, - message='Intent.Message.Image', - ) - - items: MutableSequence['Intent.Message.CarouselSelect.Item'] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message='Intent.Message.CarouselSelect.Item', - ) - - class SelectItemInfo(proto.Message): - r"""Additional info about the select item for when it is - triggered in a dialog. - - Attributes: - key (str): - Required. A unique key that will be sent back - to the agent if this response is given. - synonyms (MutableSequence[str]): - Optional. A list of synonyms that can also be - used to trigger this item in dialog. - """ - - key: str = proto.Field( - proto.STRING, - number=1, - ) - synonyms: MutableSequence[str] = 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 - (ie "audio"). - media_objects (MutableSequence[google.cloud.dialogflow_v2.types.Intent.Message.MediaContent.ResponseMediaObject]): - Required. List of media objects. - """ - class ResponseMediaType(proto.Enum): - r"""Format of response media type. - - Values: - RESPONSE_MEDIA_TYPE_UNSPECIFIED (0): - Unspecified. - AUDIO (1): - Response media type is audio. - """ - RESPONSE_MEDIA_TYPE_UNSPECIFIED = 0 - AUDIO = 1 - - class ResponseMediaObject(proto.Message): - r"""Response media object for media content card. - - This message has `oneof`_ fields (mutually exclusive fields). - For each oneof, at most one member field can be set at the same time. - Setting any member of the oneof automatically clears all other - members. - - .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields - - Attributes: - name (str): - Required. Name of media card. - description (str): - Optional. Description of media card. - large_image (google.cloud.dialogflow_v2.types.Intent.Message.Image): - Optional. Image to display above media - content. - - This field is a member of `oneof`_ ``image``. - icon (google.cloud.dialogflow_v2.types.Intent.Message.Image): - Optional. Icon to display above media - content. - - This field is a member of `oneof`_ ``image``. - content_url (str): - Required. Url where the media is stored. - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - description: str = proto.Field( - proto.STRING, - number=2, - ) - large_image: 'Intent.Message.Image' = proto.Field( - proto.MESSAGE, - number=3, - oneof='image', - message='Intent.Message.Image', - ) - icon: 'Intent.Message.Image' = proto.Field( - proto.MESSAGE, - number=4, - oneof='image', - message='Intent.Message.Image', - ) - content_url: str = proto.Field( - proto.STRING, - number=5, - ) - - media_type: 'Intent.Message.MediaContent.ResponseMediaType' = proto.Field( - proto.ENUM, - number=1, - enum='Intent.Message.MediaContent.ResponseMediaType', - ) - media_objects: MutableSequence['Intent.Message.MediaContent.ResponseMediaObject'] = proto.RepeatedField( - proto.MESSAGE, - number=2, - message='Intent.Message.MediaContent.ResponseMediaObject', - ) - - class BrowseCarouselCard(proto.Message): - r"""Browse Carousel Card for Actions on Google. - https://developers.google.com/actions/assistant/responses#browsing_carousel - - Attributes: - items (MutableSequence[google.cloud.dialogflow_v2.types.Intent.Message.BrowseCarouselCard.BrowseCarouselCardItem]): - Required. List of items in the Browse - Carousel Card. Minimum of two items, maximum of - ten. - image_display_options (google.cloud.dialogflow_v2.types.Intent.Message.BrowseCarouselCard.ImageDisplayOptions): - Optional. Settings for displaying the image. Applies to - every image in - [items][google.cloud.dialogflow.v2.Intent.Message.BrowseCarouselCard.items]. - """ - class ImageDisplayOptions(proto.Enum): - r"""Image display options for Actions on Google. This should be - used for when the image's aspect ratio does not match the image - container's aspect ratio. - - Values: - IMAGE_DISPLAY_OPTIONS_UNSPECIFIED (0): - Fill the gaps between the image and the image - container with gray bars. - GRAY (1): - Fill the gaps between the image and the image - container with gray bars. - WHITE (2): - Fill the gaps between the image and the image - container with white bars. - CROPPED (3): - Image is scaled such that the image width and - height match or exceed the container dimensions. - This may crop the top and bottom of the image if - the scaled image height is greater than the - container height, or crop the left and right of - the image if the scaled image width is greater - than the container width. This is similar to - "Zoom Mode" on a widescreen TV when playing a - 4:3 video. - BLURRED_BACKGROUND (4): - Pad the gaps between image and image frame - with a blurred copy of the same image. - """ - IMAGE_DISPLAY_OPTIONS_UNSPECIFIED = 0 - GRAY = 1 - WHITE = 2 - CROPPED = 3 - BLURRED_BACKGROUND = 4 - - 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. - title (str): - Required. Title of the carousel item. Maximum - of two lines of text. - description (str): - Optional. Description of the carousel item. - Maximum of four lines of text. - image (google.cloud.dialogflow_v2.types.Intent.Message.Image): - Optional. Hero image for the carousel item. - footer (str): - Optional. Text that appears at the bottom of - the Browse Carousel Card. Maximum of one line of - text. - """ - - class OpenUrlAction(proto.Message): - r"""Actions on Google action to open a given url. - - Attributes: - url (str): - Required. URL - url_type_hint (google.cloud.dialogflow_v2.types.Intent.Message.BrowseCarouselCard.BrowseCarouselCardItem.OpenUrlAction.UrlTypeHint): - Optional. Specifies the type of viewer that - is used when opening the URL. Defaults to - opening via web browser. - """ - class UrlTypeHint(proto.Enum): - r"""Type of the URI. - - Values: - URL_TYPE_HINT_UNSPECIFIED (0): - Unspecified - AMP_ACTION (1): - Url would be an amp action - AMP_CONTENT (2): - URL that points directly to AMP content, or - to a canonical URL which refers to AMP content - via . - """ - URL_TYPE_HINT_UNSPECIFIED = 0 - AMP_ACTION = 1 - AMP_CONTENT = 2 - - url: str = proto.Field( - proto.STRING, - number=1, - ) - url_type_hint: 'Intent.Message.BrowseCarouselCard.BrowseCarouselCardItem.OpenUrlAction.UrlTypeHint' = proto.Field( - proto.ENUM, - number=3, - enum='Intent.Message.BrowseCarouselCard.BrowseCarouselCardItem.OpenUrlAction.UrlTypeHint', - ) - - open_uri_action: 'Intent.Message.BrowseCarouselCard.BrowseCarouselCardItem.OpenUrlAction' = proto.Field( - proto.MESSAGE, - number=1, - message='Intent.Message.BrowseCarouselCard.BrowseCarouselCardItem.OpenUrlAction', - ) - title: str = proto.Field( - proto.STRING, - number=2, - ) - description: str = proto.Field( - proto.STRING, - number=3, - ) - image: 'Intent.Message.Image' = proto.Field( - proto.MESSAGE, - number=4, - message='Intent.Message.Image', - ) - footer: str = proto.Field( - proto.STRING, - number=5, - ) - - items: MutableSequence['Intent.Message.BrowseCarouselCard.BrowseCarouselCardItem'] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message='Intent.Message.BrowseCarouselCard.BrowseCarouselCardItem', - ) - image_display_options: 'Intent.Message.BrowseCarouselCard.ImageDisplayOptions' = proto.Field( - proto.ENUM, - number=2, - enum='Intent.Message.BrowseCarouselCard.ImageDisplayOptions', - ) - - class TableCard(proto.Message): - r"""Table card for Actions on Google. - - Attributes: - title (str): - Required. Title of the card. - subtitle (str): - Optional. Subtitle to the title. - image (google.cloud.dialogflow_v2.types.Intent.Message.Image): - Optional. Image which should be displayed on - the card. - column_properties (MutableSequence[google.cloud.dialogflow_v2.types.Intent.Message.ColumnProperties]): - Optional. Display properties for the columns - in this table. - rows (MutableSequence[google.cloud.dialogflow_v2.types.Intent.Message.TableCardRow]): - Optional. Rows in this table of data. - buttons (MutableSequence[google.cloud.dialogflow_v2.types.Intent.Message.BasicCard.Button]): - Optional. List of buttons for the card. - """ - - title: str = proto.Field( - proto.STRING, - number=1, - ) - subtitle: str = proto.Field( - proto.STRING, - number=2, - ) - image: 'Intent.Message.Image' = proto.Field( - proto.MESSAGE, - number=3, - message='Intent.Message.Image', - ) - column_properties: MutableSequence['Intent.Message.ColumnProperties'] = proto.RepeatedField( - proto.MESSAGE, - number=4, - message='Intent.Message.ColumnProperties', - ) - rows: MutableSequence['Intent.Message.TableCardRow'] = proto.RepeatedField( - proto.MESSAGE, - number=5, - message='Intent.Message.TableCardRow', - ) - buttons: MutableSequence['Intent.Message.BasicCard.Button'] = proto.RepeatedField( - proto.MESSAGE, - number=6, - message='Intent.Message.BasicCard.Button', - ) - - class ColumnProperties(proto.Message): - r"""Column properties for - [TableCard][google.cloud.dialogflow.v2.Intent.Message.TableCard]. - - Attributes: - header (str): - Required. Column heading. - horizontal_alignment (google.cloud.dialogflow_v2.types.Intent.Message.ColumnProperties.HorizontalAlignment): - Optional. Defines text alignment for all - cells in this column. - """ - class HorizontalAlignment(proto.Enum): - r"""Text alignments within a cell. - - Values: - HORIZONTAL_ALIGNMENT_UNSPECIFIED (0): - Text is aligned to the leading edge of the - column. - LEADING (1): - Text is aligned to the leading edge of the - column. - CENTER (2): - Text is centered in the column. - TRAILING (3): - Text is aligned to the trailing edge of the - column. - """ - HORIZONTAL_ALIGNMENT_UNSPECIFIED = 0 - LEADING = 1 - CENTER = 2 - TRAILING = 3 - - header: str = proto.Field( - proto.STRING, - number=1, - ) - horizontal_alignment: 'Intent.Message.ColumnProperties.HorizontalAlignment' = proto.Field( - proto.ENUM, - number=2, - enum='Intent.Message.ColumnProperties.HorizontalAlignment', - ) - - class TableCardRow(proto.Message): - r"""Row of - [TableCard][google.cloud.dialogflow.v2.Intent.Message.TableCard]. - - Attributes: - cells (MutableSequence[google.cloud.dialogflow_v2.types.Intent.Message.TableCardCell]): - Optional. List of cells that make up this - row. - divider_after (bool): - Optional. Whether to add a visual divider - after this row. - """ - - cells: MutableSequence['Intent.Message.TableCardCell'] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message='Intent.Message.TableCardCell', - ) - divider_after: bool = proto.Field( - proto.BOOL, - number=2, - ) - - class TableCardCell(proto.Message): - r"""Cell of - [TableCardRow][google.cloud.dialogflow.v2.Intent.Message.TableCardRow]. - - Attributes: - text (str): - Required. Text in this cell. - """ - - text: str = proto.Field( - proto.STRING, - number=1, - ) - - text: 'Intent.Message.Text' = proto.Field( - proto.MESSAGE, - number=1, - oneof='message', - message='Intent.Message.Text', - ) - image: 'Intent.Message.Image' = proto.Field( - proto.MESSAGE, - number=2, - oneof='message', - message='Intent.Message.Image', - ) - quick_replies: 'Intent.Message.QuickReplies' = proto.Field( - proto.MESSAGE, - number=3, - oneof='message', - message='Intent.Message.QuickReplies', - ) - card: 'Intent.Message.Card' = proto.Field( - proto.MESSAGE, - number=4, - oneof='message', - message='Intent.Message.Card', - ) - payload: struct_pb2.Struct = proto.Field( - proto.MESSAGE, - number=5, - oneof='message', - message=struct_pb2.Struct, - ) - simple_responses: 'Intent.Message.SimpleResponses' = proto.Field( - proto.MESSAGE, - number=7, - oneof='message', - message='Intent.Message.SimpleResponses', - ) - basic_card: 'Intent.Message.BasicCard' = proto.Field( - proto.MESSAGE, - number=8, - oneof='message', - message='Intent.Message.BasicCard', - ) - suggestions: 'Intent.Message.Suggestions' = proto.Field( - proto.MESSAGE, - number=9, - oneof='message', - message='Intent.Message.Suggestions', - ) - link_out_suggestion: 'Intent.Message.LinkOutSuggestion' = proto.Field( - proto.MESSAGE, - number=10, - oneof='message', - message='Intent.Message.LinkOutSuggestion', - ) - list_select: 'Intent.Message.ListSelect' = proto.Field( - proto.MESSAGE, - number=11, - oneof='message', - message='Intent.Message.ListSelect', - ) - carousel_select: 'Intent.Message.CarouselSelect' = proto.Field( - proto.MESSAGE, - number=12, - oneof='message', - message='Intent.Message.CarouselSelect', - ) - browse_carousel_card: 'Intent.Message.BrowseCarouselCard' = proto.Field( - proto.MESSAGE, - number=22, - oneof='message', - message='Intent.Message.BrowseCarouselCard', - ) - table_card: 'Intent.Message.TableCard' = proto.Field( - proto.MESSAGE, - number=23, - oneof='message', - message='Intent.Message.TableCard', - ) - media_content: 'Intent.Message.MediaContent' = proto.Field( - proto.MESSAGE, - number=24, - oneof='message', - message='Intent.Message.MediaContent', - ) - platform: 'Intent.Message.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: - ``projects//agent/intents/``. - parent_followup_intent_name (str): - The unique identifier of the followup intent's parent. - Format: ``projects//agent/intents/``. - """ - - followup_intent_name: str = proto.Field( - proto.STRING, - number=1, - ) - parent_followup_intent_name: str = proto.Field( - proto.STRING, - number=2, - ) - - name: str = proto.Field( - proto.STRING, - number=1, - ) - display_name: str = proto.Field( - proto.STRING, - number=2, - ) - webhook_state: WebhookState = proto.Field( - proto.ENUM, - number=6, - enum=WebhookState, - ) - priority: int = proto.Field( - proto.INT32, - number=3, - ) - is_fallback: bool = proto.Field( - proto.BOOL, - number=4, - ) - ml_disabled: bool = proto.Field( - proto.BOOL, - number=19, - ) - live_agent_handoff: bool = proto.Field( - proto.BOOL, - number=20, - ) - end_interaction: bool = proto.Field( - proto.BOOL, - number=21, - ) - input_context_names: MutableSequence[str] = proto.RepeatedField( - proto.STRING, - number=7, - ) - events: MutableSequence[str] = proto.RepeatedField( - proto.STRING, - number=8, - ) - training_phrases: MutableSequence[TrainingPhrase] = proto.RepeatedField( - proto.MESSAGE, - number=9, - message=TrainingPhrase, - ) - action: str = proto.Field( - proto.STRING, - number=10, - ) - output_contexts: MutableSequence[context.Context] = proto.RepeatedField( - proto.MESSAGE, - number=11, - message=context.Context, - ) - reset_contexts: bool = proto.Field( - proto.BOOL, - number=12, - ) - parameters: MutableSequence[Parameter] = proto.RepeatedField( - proto.MESSAGE, - number=13, - message=Parameter, - ) - messages: MutableSequence[Message] = proto.RepeatedField( - proto.MESSAGE, - number=14, - message=Message, - ) - default_response_platforms: MutableSequence[Message.Platform] = proto.RepeatedField( - proto.ENUM, - number=15, - enum=Message.Platform, - ) - root_followup_intent_name: str = proto.Field( - proto.STRING, - number=16, - ) - parent_followup_intent_name: str = proto.Field( - proto.STRING, - number=17, - ) - followup_intent_info: MutableSequence[FollowupIntentInfo] = proto.RepeatedField( - proto.MESSAGE, - number=18, - message=FollowupIntentInfo, - ) - - -class ListIntentsRequest(proto.Message): - r"""The request message for - [Intents.ListIntents][google.cloud.dialogflow.v2.Intents.ListIntents]. - - Attributes: - parent (str): - Required. The agent to list all intents from. Format: - ``projects//agent`` or - ``projects//locations//agent``. - - Alternatively, you can specify the environment to list - intents for. Format: - ``projects//agent/environments/`` - or - ``projects//locations//agent/environments/``. - Note: training phrases of the intents will not be returned - for non-draft environment. - language_code (str): - Optional. The language used to access language-specific - data. If not specified, the agent's default language is - used. For more information, see `Multilingual intent and - entity - data `__. - intent_view (google.cloud.dialogflow_v2.types.IntentView): - Optional. The resource view to apply to the - returned intent. - 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: str = proto.Field( - proto.STRING, - number=1, - ) - language_code: str = proto.Field( - proto.STRING, - number=2, - ) - intent_view: 'IntentView' = proto.Field( - proto.ENUM, - number=3, - enum='IntentView', - ) - page_size: int = proto.Field( - proto.INT32, - number=4, - ) - page_token: str = proto.Field( - proto.STRING, - number=5, - ) - - -class ListIntentsResponse(proto.Message): - r"""The response message for - [Intents.ListIntents][google.cloud.dialogflow.v2.Intents.ListIntents]. - - Attributes: - intents (MutableSequence[google.cloud.dialogflow_v2.types.Intent]): - The list of agent intents. 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 - - intents: MutableSequence['Intent'] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message='Intent', - ) - next_page_token: str = proto.Field( - proto.STRING, - number=2, - ) - - -class GetIntentRequest(proto.Message): - r"""The request message for - [Intents.GetIntent][google.cloud.dialogflow.v2.Intents.GetIntent]. - - Attributes: - name (str): - Required. The name of the intent. Format: - ``projects//agent/intents/``. - language_code (str): - Optional. The language used to access language-specific - data. If not specified, the agent's default language is - used. For more information, see `Multilingual intent and - entity - data `__. - intent_view (google.cloud.dialogflow_v2.types.IntentView): - Optional. The resource view to apply to the - returned intent. - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - language_code: str = proto.Field( - proto.STRING, - number=2, - ) - intent_view: 'IntentView' = proto.Field( - proto.ENUM, - number=3, - enum='IntentView', - ) - - -class CreateIntentRequest(proto.Message): - r"""The request message for - [Intents.CreateIntent][google.cloud.dialogflow.v2.Intents.CreateIntent]. - - Attributes: - parent (str): - Required. The agent to create a intent for. Format: - ``projects//agent``. - intent (google.cloud.dialogflow_v2.types.Intent): - Required. The intent to create. - language_code (str): - Optional. The language used to access language-specific - data. If not specified, the agent's default language is - used. For more information, see `Multilingual intent and - entity - data `__. - intent_view (google.cloud.dialogflow_v2.types.IntentView): - Optional. The resource view to apply to the - returned intent. - """ - - parent: str = proto.Field( - proto.STRING, - number=1, - ) - intent: 'Intent' = proto.Field( - proto.MESSAGE, - number=2, - message='Intent', - ) - language_code: str = proto.Field( - proto.STRING, - number=3, - ) - intent_view: 'IntentView' = proto.Field( - proto.ENUM, - number=4, - enum='IntentView', - ) - - -class UpdateIntentRequest(proto.Message): - r"""The request message for - [Intents.UpdateIntent][google.cloud.dialogflow.v2.Intents.UpdateIntent]. - - Attributes: - intent (google.cloud.dialogflow_v2.types.Intent): - Required. The intent to update. - language_code (str): - Optional. The language used to access language-specific - data. If not specified, the agent's default language is - used. For more information, see `Multilingual intent and - entity - data `__. - update_mask (google.protobuf.field_mask_pb2.FieldMask): - Optional. The mask to control which fields - get updated. - intent_view (google.cloud.dialogflow_v2.types.IntentView): - Optional. The resource view to apply to the - returned intent. - """ - - intent: 'Intent' = proto.Field( - proto.MESSAGE, - number=1, - message='Intent', - ) - language_code: str = proto.Field( - proto.STRING, - number=2, - ) - update_mask: field_mask_pb2.FieldMask = proto.Field( - proto.MESSAGE, - number=3, - message=field_mask_pb2.FieldMask, - ) - intent_view: 'IntentView' = proto.Field( - proto.ENUM, - number=4, - enum='IntentView', - ) - - -class DeleteIntentRequest(proto.Message): - r"""The request message for - [Intents.DeleteIntent][google.cloud.dialogflow.v2.Intents.DeleteIntent]. - - Attributes: - name (str): - Required. The name of the intent to delete. If this intent - has direct or indirect followup intents, we also delete - them. Format: - ``projects//agent/intents/``. - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - - -class BatchUpdateIntentsRequest(proto.Message): - r""" - - This message has `oneof`_ fields (mutually exclusive fields). - For each oneof, at most one member field can be set at the same time. - Setting any member of the oneof automatically clears all other - members. - - .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields - - Attributes: - parent (str): - Required. The name of the agent to update or create intents - in. Format: ``projects//agent``. - intent_batch_uri (str): - The URI to a Google Cloud Storage file - containing intents to update or create. The file - format can either be a serialized proto (of - IntentBatch type) or JSON object. Note: The URI - must start with "gs://". - - This field is a member of `oneof`_ ``intent_batch``. - intent_batch_inline (google.cloud.dialogflow_v2.types.IntentBatch): - The collection of intents to update or - create. - - This field is a member of `oneof`_ ``intent_batch``. - language_code (str): - Optional. The language used to access language-specific - data. If not specified, the agent's default language is - used. For more information, see `Multilingual intent and - entity - data `__. - update_mask (google.protobuf.field_mask_pb2.FieldMask): - Optional. The mask to control which fields - get updated. - intent_view (google.cloud.dialogflow_v2.types.IntentView): - Optional. The resource view to apply to the - returned intent. - """ - - parent: str = proto.Field( - proto.STRING, - number=1, - ) - intent_batch_uri: str = proto.Field( - proto.STRING, - number=2, - oneof='intent_batch', - ) - intent_batch_inline: 'IntentBatch' = proto.Field( - proto.MESSAGE, - number=3, - oneof='intent_batch', - message='IntentBatch', - ) - language_code: str = proto.Field( - proto.STRING, - number=4, - ) - update_mask: field_mask_pb2.FieldMask = proto.Field( - proto.MESSAGE, - number=5, - message=field_mask_pb2.FieldMask, - ) - intent_view: 'IntentView' = proto.Field( - proto.ENUM, - number=6, - enum='IntentView', - ) - - -class BatchUpdateIntentsResponse(proto.Message): - r"""The response message for - [Intents.BatchUpdateIntents][google.cloud.dialogflow.v2.Intents.BatchUpdateIntents]. - - Attributes: - intents (MutableSequence[google.cloud.dialogflow_v2.types.Intent]): - The collection of updated or created intents. - """ - - intents: MutableSequence['Intent'] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message='Intent', - ) - - -class BatchDeleteIntentsRequest(proto.Message): - r"""The request message for - [Intents.BatchDeleteIntents][google.cloud.dialogflow.v2.Intents.BatchDeleteIntents]. - - Attributes: - parent (str): - Required. The name of the agent to delete all entities types - for. Format: ``projects//agent``. - intents (MutableSequence[google.cloud.dialogflow_v2.types.Intent]): - Required. The collection of intents to delete. Only intent - ``name`` must be filled in. - """ - - parent: str = proto.Field( - proto.STRING, - number=1, - ) - intents: MutableSequence['Intent'] = 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 (MutableSequence[google.cloud.dialogflow_v2.types.Intent]): - A collection of intents. - """ - - intents: MutableSequence['Intent'] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message='Intent', - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v2/google/cloud/dialogflow_v2/types/knowledge_base.py b/owl-bot-staging/v2/google/cloud/dialogflow_v2/types/knowledge_base.py deleted file mode 100644 index 04657f00c..000000000 --- a/owl-bot-staging/v2/google/cloud/dialogflow_v2/types/knowledge_base.py +++ /dev/null @@ -1,262 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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 __future__ import annotations - -from typing import MutableMapping, MutableSequence - -import proto # type: ignore - -from google.protobuf import field_mask_pb2 # type: ignore - - -__protobuf__ = proto.module( - package='google.cloud.dialogflow.v2', - manifest={ - 'KnowledgeBase', - 'ListKnowledgeBasesRequest', - 'ListKnowledgeBasesResponse', - 'GetKnowledgeBaseRequest', - 'CreateKnowledgeBaseRequest', - 'DeleteKnowledgeBaseRequest', - 'UpdateKnowledgeBaseRequest', - }, -) - - -class KnowledgeBase(proto.Message): - r"""A knowledge base represents a collection of knowledge documents that - you provide to Dialogflow. Your knowledge documents contain - information that may be useful during conversations with end-users. - Some Dialogflow features use knowledge bases when looking for a - response to an end-user input. - - For more information, see the `knowledge base - guide `__. - - Note: The ``projects.agent.knowledgeBases`` resource is deprecated; - only use ``projects.knowledgeBases``. - - Attributes: - name (str): - The knowledge base resource name. The name must be empty - when creating a knowledge base. Format: - ``projects//locations//knowledgeBases/``. - display_name (str): - Required. The display name of the knowledge - base. The name must be 1024 bytes or less; - otherwise, the creation request fails. - language_code (str): - Language which represents the KnowledgeBase. - When the KnowledgeBase is created/updated, - expect this to be present for non en-us - languages. When unspecified, the default - language code en-us applies. - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - display_name: str = proto.Field( - proto.STRING, - number=2, - ) - language_code: str = proto.Field( - proto.STRING, - number=4, - ) - - -class ListKnowledgeBasesRequest(proto.Message): - r"""Request message for - [KnowledgeBases.ListKnowledgeBases][google.cloud.dialogflow.v2.KnowledgeBases.ListKnowledgeBases]. - - Attributes: - parent (str): - Required. The project to list of knowledge bases for. - Format: ``projects//locations/``. - page_size (int): - The maximum number of items to return in a - single page. By default 10 and at most 100. - page_token (str): - The next_page_token value returned from a previous list - request. - filter (str): - The filter expression used to filter knowledge bases - returned by the list method. The expression has the - following syntax: - - [AND ] ... - - The following fields and operators are supported: - - - display_name with has(:) operator - - language_code with equals(=) operator - - Examples: - - - 'language_code=en-us' matches knowledge bases with en-us - language code. - - 'display_name:articles' matches knowledge bases whose - display name contains "articles". - - 'display_name:"Best Articles"' matches knowledge bases - whose display name contains "Best Articles". - - 'language_code=en-gb AND display_name=articles' matches - all knowledge bases whose display name contains - "articles" and whose language code is "en-gb". - - Note: An empty filter string (i.e. "") is a no-op and will - result in no filtering. - - For more information about filtering, see `API - Filtering `__. - """ - - parent: str = proto.Field( - proto.STRING, - number=1, - ) - page_size: int = proto.Field( - proto.INT32, - number=2, - ) - page_token: str = proto.Field( - proto.STRING, - number=3, - ) - filter: str = proto.Field( - proto.STRING, - number=4, - ) - - -class ListKnowledgeBasesResponse(proto.Message): - r"""Response message for - [KnowledgeBases.ListKnowledgeBases][google.cloud.dialogflow.v2.KnowledgeBases.ListKnowledgeBases]. - - Attributes: - knowledge_bases (MutableSequence[google.cloud.dialogflow_v2.types.KnowledgeBase]): - The list of knowledge bases. - 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 - - knowledge_bases: MutableSequence['KnowledgeBase'] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message='KnowledgeBase', - ) - next_page_token: str = proto.Field( - proto.STRING, - number=2, - ) - - -class GetKnowledgeBaseRequest(proto.Message): - r"""Request message for - [KnowledgeBases.GetKnowledgeBase][google.cloud.dialogflow.v2.KnowledgeBases.GetKnowledgeBase]. - - Attributes: - name (str): - Required. The name of the knowledge base to retrieve. Format - ``projects//locations//knowledgeBases/``. - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - - -class CreateKnowledgeBaseRequest(proto.Message): - r"""Request message for - [KnowledgeBases.CreateKnowledgeBase][google.cloud.dialogflow.v2.KnowledgeBases.CreateKnowledgeBase]. - - Attributes: - parent (str): - Required. The project to create a knowledge base for. - Format: ``projects//locations/``. - knowledge_base (google.cloud.dialogflow_v2.types.KnowledgeBase): - Required. The knowledge base to create. - """ - - parent: str = proto.Field( - proto.STRING, - number=1, - ) - knowledge_base: 'KnowledgeBase' = proto.Field( - proto.MESSAGE, - number=2, - message='KnowledgeBase', - ) - - -class DeleteKnowledgeBaseRequest(proto.Message): - r"""Request message for - [KnowledgeBases.DeleteKnowledgeBase][google.cloud.dialogflow.v2.KnowledgeBases.DeleteKnowledgeBase]. - - Attributes: - name (str): - Required. The name of the knowledge base to delete. Format: - ``projects//locations//knowledgeBases/``. - force (bool): - Optional. Force deletes the knowledge base. - When set to true, any documents in the knowledge - base are also deleted. - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - force: bool = proto.Field( - proto.BOOL, - number=2, - ) - - -class UpdateKnowledgeBaseRequest(proto.Message): - r"""Request message for - [KnowledgeBases.UpdateKnowledgeBase][google.cloud.dialogflow.v2.KnowledgeBases.UpdateKnowledgeBase]. - - Attributes: - knowledge_base (google.cloud.dialogflow_v2.types.KnowledgeBase): - Required. The knowledge base to update. - update_mask (google.protobuf.field_mask_pb2.FieldMask): - Optional. Not specified means ``update all``. Currently, - only ``display_name`` can be updated, an InvalidArgument - will be returned for attempting to update other fields. - """ - - knowledge_base: 'KnowledgeBase' = proto.Field( - proto.MESSAGE, - number=1, - message='KnowledgeBase', - ) - update_mask: field_mask_pb2.FieldMask = proto.Field( - proto.MESSAGE, - number=2, - message=field_mask_pb2.FieldMask, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v2/google/cloud/dialogflow_v2/types/participant.py b/owl-bot-staging/v2/google/cloud/dialogflow_v2/types/participant.py deleted file mode 100644 index b33fd00e6..000000000 --- a/owl-bot-staging/v2/google/cloud/dialogflow_v2/types/participant.py +++ /dev/null @@ -1,1519 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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 __future__ import annotations - -from typing import MutableMapping, MutableSequence - -import proto # type: ignore - -from google.cloud.dialogflow_v2.types import audio_config as gcd_audio_config -from google.cloud.dialogflow_v2.types import session -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( - package='google.cloud.dialogflow.v2', - manifest={ - 'Participant', - 'Message', - 'CreateParticipantRequest', - 'GetParticipantRequest', - 'ListParticipantsRequest', - 'ListParticipantsResponse', - 'UpdateParticipantRequest', - 'AnalyzeContentRequest', - 'DtmfParameters', - 'AnalyzeContentResponse', - 'StreamingAnalyzeContentRequest', - 'StreamingAnalyzeContentResponse', - 'SuggestArticlesRequest', - 'SuggestArticlesResponse', - 'SuggestFaqAnswersRequest', - 'SuggestFaqAnswersResponse', - 'SuggestSmartRepliesRequest', - 'SuggestSmartRepliesResponse', - 'OutputAudio', - 'AutomatedAgentReply', - 'ArticleAnswer', - 'FaqAnswer', - 'SmartReplyAnswer', - 'SuggestionResult', - 'InputTextConfig', - 'AnnotatedMessagePart', - 'MessageAnnotation', - 'AssistQueryParameters', - }, -) - - -class Participant(proto.Message): - r"""Represents a conversation participant (human agent, virtual - agent, end-user). - - Attributes: - name (str): - Optional. The unique identifier of this participant. Format: - ``projects//locations//conversations//participants/``. - role (google.cloud.dialogflow_v2.types.Participant.Role): - Immutable. The role this participant plays in - the conversation. This field must be set during - participant creation and is then immutable. - sip_recording_media_label (str): - Optional. Label applied to streams - representing this participant in SIPREC XML - metadata and SDP. This is used to assign - transcriptions from that media stream to this - participant. This field can be updated. - obfuscated_external_user_id (str): - Optional. Obfuscated user id that should be associated with - the created participant. - - You can specify a user id as follows: - - 1. If you set this field in - [CreateParticipantRequest][google.cloud.dialogflow.v2.CreateParticipantRequest.participant] - or - [UpdateParticipantRequest][google.cloud.dialogflow.v2.UpdateParticipantRequest.participant], - Dialogflow adds the obfuscated user id with the - participant. - - 2. If you set this field in - [AnalyzeContent][google.cloud.dialogflow.v2.AnalyzeContentRequest.obfuscated_external_user_id] - or - [StreamingAnalyzeContent][google.cloud.dialogflow.v2.StreamingAnalyzeContentRequest.obfuscated_external_user_id], - Dialogflow will update - [Participant.obfuscated_external_user_id][google.cloud.dialogflow.v2.Participant.obfuscated_external_user_id]. - - Dialogflow returns an error if you try to add a user id for - a - non-[END_USER][google.cloud.dialogflow.v2.Participant.Role.END_USER] - participant. - - Dialogflow uses this user id for billing and measurement - purposes. For example, Dialogflow determines whether a user - in one conversation returned in a later conversation. - - Note: - - - Please never pass raw user ids to Dialogflow. Always - obfuscate your user id first. - - Dialogflow only accepts a UTF-8 encoded string, e.g., a - hex digest of a hash function like SHA-512. - - The length of the user id must be <= 256 characters. - documents_metadata_filters (MutableMapping[str, str]): - Optional. Key-value filters on the metadata of documents - returned by article suggestion. If specified, article - suggestion only returns suggested documents that match all - filters in their - [Document.metadata][google.cloud.dialogflow.v2.Document.metadata]. - Multiple values for a metadata key should be concatenated by - comma. For example, filters to match all documents that have - 'US' or 'CA' in their market metadata values and 'agent' in - their user metadata values will be - - :: - - documents_metadata_filters { - key: "market" - value: "US,CA" - } - documents_metadata_filters { - key: "user" - value: "agent" - } - """ - class Role(proto.Enum): - r"""Enumeration of the roles a participant can play in a - conversation. - - Values: - ROLE_UNSPECIFIED (0): - Participant role not set. - HUMAN_AGENT (1): - Participant is a human agent. - AUTOMATED_AGENT (2): - Participant is an automated agent, such as a - Dialogflow agent. - END_USER (3): - Participant is an end user that has called or - chatted with Dialogflow services. - """ - ROLE_UNSPECIFIED = 0 - HUMAN_AGENT = 1 - AUTOMATED_AGENT = 2 - END_USER = 3 - - name: str = proto.Field( - proto.STRING, - number=1, - ) - role: Role = proto.Field( - proto.ENUM, - number=2, - enum=Role, - ) - sip_recording_media_label: str = proto.Field( - proto.STRING, - number=6, - ) - obfuscated_external_user_id: str = proto.Field( - proto.STRING, - number=7, - ) - documents_metadata_filters: MutableMapping[str, str] = proto.MapField( - proto.STRING, - proto.STRING, - number=8, - ) - - -class Message(proto.Message): - r"""Represents a message posted into a conversation. - - Attributes: - name (str): - Optional. The unique identifier of the message. Format: - ``projects//locations//conversations//messages/``. - content (str): - Required. The message content. - language_code (str): - Optional. The message language. This should be a - `BCP-47 `__ - language tag. Example: "en-US". - participant (str): - Output only. The participant that sends this - message. - participant_role (google.cloud.dialogflow_v2.types.Participant.Role): - Output only. The role of the participant. - create_time (google.protobuf.timestamp_pb2.Timestamp): - Output only. The time when the message was - created in Contact Center AI. - send_time (google.protobuf.timestamp_pb2.Timestamp): - Optional. The time when the message was sent. - message_annotation (google.cloud.dialogflow_v2.types.MessageAnnotation): - Output only. The annotation for the message. - sentiment_analysis (google.cloud.dialogflow_v2.types.SentimentAnalysisResult): - Output only. The sentiment analysis result - for the message. - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - content: str = proto.Field( - proto.STRING, - number=2, - ) - language_code: str = proto.Field( - proto.STRING, - number=3, - ) - participant: str = proto.Field( - proto.STRING, - number=4, - ) - participant_role: 'Participant.Role' = proto.Field( - proto.ENUM, - number=5, - enum='Participant.Role', - ) - create_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=6, - message=timestamp_pb2.Timestamp, - ) - send_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=9, - message=timestamp_pb2.Timestamp, - ) - message_annotation: 'MessageAnnotation' = proto.Field( - proto.MESSAGE, - number=7, - message='MessageAnnotation', - ) - sentiment_analysis: session.SentimentAnalysisResult = proto.Field( - proto.MESSAGE, - number=8, - message=session.SentimentAnalysisResult, - ) - - -class CreateParticipantRequest(proto.Message): - r"""The request message for - [Participants.CreateParticipant][google.cloud.dialogflow.v2.Participants.CreateParticipant]. - - Attributes: - parent (str): - Required. Resource identifier of the conversation adding the - participant. Format: - ``projects//locations//conversations/``. - participant (google.cloud.dialogflow_v2.types.Participant): - Required. The participant to create. - """ - - parent: str = proto.Field( - proto.STRING, - number=1, - ) - participant: 'Participant' = proto.Field( - proto.MESSAGE, - number=2, - message='Participant', - ) - - -class GetParticipantRequest(proto.Message): - r"""The request message for - [Participants.GetParticipant][google.cloud.dialogflow.v2.Participants.GetParticipant]. - - Attributes: - name (str): - Required. The name of the participant. Format: - ``projects//locations//conversations//participants/``. - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - - -class ListParticipantsRequest(proto.Message): - r"""The request message for - [Participants.ListParticipants][google.cloud.dialogflow.v2.Participants.ListParticipants]. - - Attributes: - parent (str): - Required. The conversation to list all participants from. - Format: - ``projects//locations//conversations/``. - 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: str = proto.Field( - proto.STRING, - number=1, - ) - page_size: int = proto.Field( - proto.INT32, - number=2, - ) - page_token: str = proto.Field( - proto.STRING, - number=3, - ) - - -class ListParticipantsResponse(proto.Message): - r"""The response message for - [Participants.ListParticipants][google.cloud.dialogflow.v2.Participants.ListParticipants]. - - Attributes: - participants (MutableSequence[google.cloud.dialogflow_v2.types.Participant]): - The list of participants. There is 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 - - participants: MutableSequence['Participant'] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message='Participant', - ) - next_page_token: str = proto.Field( - proto.STRING, - number=2, - ) - - -class UpdateParticipantRequest(proto.Message): - r"""The request message for - [Participants.UpdateParticipant][google.cloud.dialogflow.v2.Participants.UpdateParticipant]. - - Attributes: - participant (google.cloud.dialogflow_v2.types.Participant): - Required. The participant to update. - update_mask (google.protobuf.field_mask_pb2.FieldMask): - Required. The mask to specify which fields to - update. - """ - - participant: 'Participant' = proto.Field( - proto.MESSAGE, - number=1, - message='Participant', - ) - update_mask: field_mask_pb2.FieldMask = proto.Field( - proto.MESSAGE, - number=2, - message=field_mask_pb2.FieldMask, - ) - - -class AnalyzeContentRequest(proto.Message): - r"""The request message for - [Participants.AnalyzeContent][google.cloud.dialogflow.v2.Participants.AnalyzeContent]. - - This message has `oneof`_ fields (mutually exclusive fields). - For each oneof, at most one member field can be set at the same time. - Setting any member of the oneof automatically clears all other - members. - - .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields - - Attributes: - participant (str): - Required. The name of the participant this text comes from. - Format: - ``projects//locations//conversations//participants/``. - text_input (google.cloud.dialogflow_v2.types.TextInput): - The natural language text to be processed. - - This field is a member of `oneof`_ ``input``. - event_input (google.cloud.dialogflow_v2.types.EventInput): - An input event to send to Dialogflow. - - This field is a member of `oneof`_ ``input``. - reply_audio_config (google.cloud.dialogflow_v2.types.OutputAudioConfig): - Speech synthesis configuration. - The speech synthesis settings for a virtual - agent that may be configured for the associated - conversation profile are not used when calling - AnalyzeContent. If this configuration is not - supplied, speech synthesis is disabled. - query_params (google.cloud.dialogflow_v2.types.QueryParameters): - Parameters for a Dialogflow virtual-agent - query. - assist_query_params (google.cloud.dialogflow_v2.types.AssistQueryParameters): - Parameters for a human assist query. - cx_parameters (google.protobuf.struct_pb2.Struct): - Additional parameters to be put into - Dialogflow CX session parameters. To remove a - parameter from the session, clients should - explicitly set the parameter value to null. - - Note: this field should only be used if you are - connecting to a Dialogflow CX agent. - request_id (str): - A unique identifier for this request. Restricted to 36 ASCII - characters. A random UUID is recommended. This request is - only idempotent if a ``request_id`` is provided. - """ - - participant: str = proto.Field( - proto.STRING, - number=1, - ) - text_input: session.TextInput = proto.Field( - proto.MESSAGE, - number=6, - oneof='input', - message=session.TextInput, - ) - event_input: session.EventInput = proto.Field( - proto.MESSAGE, - number=8, - oneof='input', - message=session.EventInput, - ) - reply_audio_config: gcd_audio_config.OutputAudioConfig = proto.Field( - proto.MESSAGE, - number=5, - message=gcd_audio_config.OutputAudioConfig, - ) - query_params: session.QueryParameters = proto.Field( - proto.MESSAGE, - number=9, - message=session.QueryParameters, - ) - assist_query_params: 'AssistQueryParameters' = proto.Field( - proto.MESSAGE, - number=14, - message='AssistQueryParameters', - ) - cx_parameters: struct_pb2.Struct = proto.Field( - proto.MESSAGE, - number=18, - message=struct_pb2.Struct, - ) - request_id: str = proto.Field( - proto.STRING, - number=11, - ) - - -class DtmfParameters(proto.Message): - r"""The message in the response that indicates the parameters of - DTMF. - - Attributes: - accepts_dtmf_input (bool): - Indicates whether DTMF input can be handled - in the next request. - """ - - accepts_dtmf_input: bool = proto.Field( - proto.BOOL, - number=1, - ) - - -class AnalyzeContentResponse(proto.Message): - r"""The response message for - [Participants.AnalyzeContent][google.cloud.dialogflow.v2.Participants.AnalyzeContent]. - - Attributes: - reply_text (str): - The output text content. - This field is set if the automated agent - responded with text to show to the user. - reply_audio (google.cloud.dialogflow_v2.types.OutputAudio): - The audio data bytes encoded as specified in the request. - This field is set if: - - - ``reply_audio_config`` was specified in the request, or - - The automated agent responded with audio to play to the - user. In such case, ``reply_audio.config`` contains - settings used to synthesize the speech. - - In some scenarios, multiple output audio fields may be - present in the response structure. In these cases, only the - top-most-level audio output has content. - automated_agent_reply (google.cloud.dialogflow_v2.types.AutomatedAgentReply): - Only set if a Dialogflow automated agent has responded. Note - that: - [AutomatedAgentReply.detect_intent_response.output_audio][] - and - [AutomatedAgentReply.detect_intent_response.output_audio_config][] - are always empty, use - [reply_audio][google.cloud.dialogflow.v2.AnalyzeContentResponse.reply_audio] - instead. - message (google.cloud.dialogflow_v2.types.Message): - Message analyzed by CCAI. - human_agent_suggestion_results (MutableSequence[google.cloud.dialogflow_v2.types.SuggestionResult]): - The suggestions for most recent human agent. The order is - the same as - [HumanAgentAssistantConfig.SuggestionConfig.feature_configs][google.cloud.dialogflow.v2.HumanAgentAssistantConfig.SuggestionConfig.feature_configs] - of - [HumanAgentAssistantConfig.human_agent_suggestion_config][google.cloud.dialogflow.v2.HumanAgentAssistantConfig.human_agent_suggestion_config]. - - Note that any failure of Agent Assist features will not lead - to the overall failure of an AnalyzeContent API call. - Instead, the features will fail silently with the error - field set in the corresponding SuggestionResult. - end_user_suggestion_results (MutableSequence[google.cloud.dialogflow_v2.types.SuggestionResult]): - The suggestions for end user. The order is the same as - [HumanAgentAssistantConfig.SuggestionConfig.feature_configs][google.cloud.dialogflow.v2.HumanAgentAssistantConfig.SuggestionConfig.feature_configs] - of - [HumanAgentAssistantConfig.end_user_suggestion_config][google.cloud.dialogflow.v2.HumanAgentAssistantConfig.end_user_suggestion_config]. - - Same as human_agent_suggestion_results, any failure of Agent - Assist features will not lead to the overall failure of an - AnalyzeContent API call. Instead, the features will fail - silently with the error field set in the corresponding - SuggestionResult. - dtmf_parameters (google.cloud.dialogflow_v2.types.DtmfParameters): - Indicates the parameters of DTMF. - """ - - reply_text: str = proto.Field( - proto.STRING, - number=1, - ) - reply_audio: 'OutputAudio' = proto.Field( - proto.MESSAGE, - number=2, - message='OutputAudio', - ) - automated_agent_reply: 'AutomatedAgentReply' = proto.Field( - proto.MESSAGE, - number=3, - message='AutomatedAgentReply', - ) - message: 'Message' = proto.Field( - proto.MESSAGE, - number=5, - message='Message', - ) - human_agent_suggestion_results: MutableSequence['SuggestionResult'] = proto.RepeatedField( - proto.MESSAGE, - number=6, - message='SuggestionResult', - ) - end_user_suggestion_results: MutableSequence['SuggestionResult'] = proto.RepeatedField( - proto.MESSAGE, - number=7, - message='SuggestionResult', - ) - dtmf_parameters: 'DtmfParameters' = proto.Field( - proto.MESSAGE, - number=9, - message='DtmfParameters', - ) - - -class StreamingAnalyzeContentRequest(proto.Message): - r"""The top-level message sent by the client to the - [Participants.StreamingAnalyzeContent][google.cloud.dialogflow.v2.Participants.StreamingAnalyzeContent] - method. - - Multiple request messages should be sent in order: - - 1. The first message must contain - [participant][google.cloud.dialogflow.v2.StreamingAnalyzeContentRequest.participant], - [config][google.cloud.dialogflow.v2.StreamingAnalyzeContentRequest.config] - and optionally - [query_params][google.cloud.dialogflow.v2.StreamingAnalyzeContentRequest.query_params]. - If you want to receive an audio response, it should also contain - [reply_audio_config][google.cloud.dialogflow.v2.StreamingAnalyzeContentRequest.reply_audio_config]. - The message must not contain - [input][google.cloud.dialogflow.v2.StreamingAnalyzeContentRequest.input]. - - 2. If - [config][google.cloud.dialogflow.v2.StreamingAnalyzeContentRequest.config] - in the first message was set to - [audio_config][google.cloud.dialogflow.v2.StreamingAnalyzeContentRequest.audio_config], - all subsequent messages must contain - [input_audio][google.cloud.dialogflow.v2.StreamingAnalyzeContentRequest.input_audio] - to continue with Speech recognition. However, note that: - - - Dialogflow will bill you for the audio so far. - - Dialogflow discards all Speech recognition results in favor of - the text input. - - 3. If - [StreamingAnalyzeContentRequest.config][google.cloud.dialogflow.v2.StreamingAnalyzeContentRequest.config] - in the first message was set to - [StreamingAnalyzeContentRequest.text_config][google.cloud.dialogflow.v2.StreamingAnalyzeContentRequest.text_config], - then the second message must contain only - [input_text][google.cloud.dialogflow.v2.StreamingAnalyzeContentRequest.input_text]. - Moreover, you must not send more than two messages. - - After you sent all input, you must half-close or abort the request - stream. - - This message has `oneof`_ fields (mutually exclusive fields). - For each oneof, at most one member field can be set at the same time. - Setting any member of the oneof automatically clears all other - members. - - .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields - - Attributes: - participant (str): - Required. The name of the participant this text comes from. - Format: - ``projects//locations//conversations//participants/``. - audio_config (google.cloud.dialogflow_v2.types.InputAudioConfig): - Instructs the speech recognizer how to - process the speech audio. - - This field is a member of `oneof`_ ``config``. - text_config (google.cloud.dialogflow_v2.types.InputTextConfig): - The natural language text to be processed. - - This field is a member of `oneof`_ ``config``. - reply_audio_config (google.cloud.dialogflow_v2.types.OutputAudioConfig): - Speech synthesis configuration. - The speech synthesis settings for a virtual - agent that may be configured for the associated - conversation profile are not used when calling - StreamingAnalyzeContent. If this configuration - is not supplied, speech synthesis is disabled. - input_audio (bytes): - The input audio content to be recognized. Must be sent if - ``audio_config`` is set in the first message. The complete - audio over all streaming messages must not exceed 1 minute. - - This field is a member of `oneof`_ ``input``. - input_text (str): - The UTF-8 encoded natural language text to be processed. - Must be sent if ``text_config`` is set in the first message. - Text length must not exceed 256 bytes for virtual agent - interactions. The ``input_text`` field can be only sent - once. - - This field is a member of `oneof`_ ``input``. - input_dtmf (google.cloud.dialogflow_v2.types.TelephonyDtmfEvents): - The DTMF digits used to invoke intent and - fill in parameter value. - This input is ignored if the previous response - indicated that DTMF input is not accepted. - - This field is a member of `oneof`_ ``input``. - query_params (google.cloud.dialogflow_v2.types.QueryParameters): - Parameters for a Dialogflow virtual-agent - query. - assist_query_params (google.cloud.dialogflow_v2.types.AssistQueryParameters): - Parameters for a human assist query. - cx_parameters (google.protobuf.struct_pb2.Struct): - Additional parameters to be put into - Dialogflow CX session parameters. To remove a - parameter from the session, clients should - explicitly set the parameter value to null. - - Note: this field should only be used if you are - connecting to a Dialogflow CX agent. - enable_partial_automated_agent_reply (bool): - Enable partial virtual agent responses. If this flag is not - enabled, response stream still contains only one final - response even if some ``Fulfillment``\ s in Dialogflow - virtual agent have been configured to return partial - responses. - """ - - participant: str = proto.Field( - proto.STRING, - number=1, - ) - audio_config: gcd_audio_config.InputAudioConfig = proto.Field( - proto.MESSAGE, - number=2, - oneof='config', - message=gcd_audio_config.InputAudioConfig, - ) - text_config: 'InputTextConfig' = proto.Field( - proto.MESSAGE, - number=3, - oneof='config', - message='InputTextConfig', - ) - reply_audio_config: gcd_audio_config.OutputAudioConfig = proto.Field( - proto.MESSAGE, - number=4, - message=gcd_audio_config.OutputAudioConfig, - ) - input_audio: bytes = proto.Field( - proto.BYTES, - number=5, - oneof='input', - ) - input_text: str = proto.Field( - proto.STRING, - number=6, - oneof='input', - ) - input_dtmf: gcd_audio_config.TelephonyDtmfEvents = proto.Field( - proto.MESSAGE, - number=9, - oneof='input', - message=gcd_audio_config.TelephonyDtmfEvents, - ) - query_params: session.QueryParameters = proto.Field( - proto.MESSAGE, - number=7, - message=session.QueryParameters, - ) - assist_query_params: 'AssistQueryParameters' = proto.Field( - proto.MESSAGE, - number=8, - message='AssistQueryParameters', - ) - cx_parameters: struct_pb2.Struct = proto.Field( - proto.MESSAGE, - number=13, - message=struct_pb2.Struct, - ) - enable_partial_automated_agent_reply: bool = proto.Field( - proto.BOOL, - number=12, - ) - - -class StreamingAnalyzeContentResponse(proto.Message): - r"""The top-level message returned from the ``StreamingAnalyzeContent`` - method. - - Multiple response messages can be returned in order: - - 1. If the input was set to streaming audio, the first one or more - messages contain ``recognition_result``. Each - ``recognition_result`` represents a more complete transcript of - what the user said. The last ``recognition_result`` has - ``is_final`` set to ``true``. - - 2. In virtual agent stage: if - ``enable_partial_automated_agent_reply`` is true, the following N - (currently 1 <= N <= 4) messages contain - ``automated_agent_reply`` and optionally ``reply_audio`` returned - by the virtual agent. The first (N-1) - ``automated_agent_reply``\ s will have - ``automated_agent_reply_type`` set to ``PARTIAL``. The last - ``automated_agent_reply`` has ``automated_agent_reply_type`` set - to ``FINAL``. If ``enable_partial_automated_agent_reply`` is not - enabled, response stream only contains the final reply. - - In human assist stage: the following N (N >= 1) messages contain - ``human_agent_suggestion_results``, - ``end_user_suggestion_results`` or ``message``. - - Attributes: - recognition_result (google.cloud.dialogflow_v2.types.StreamingRecognitionResult): - The result of speech recognition. - reply_text (str): - The output text content. - This field is set if an automated agent - responded with a text for the user. - reply_audio (google.cloud.dialogflow_v2.types.OutputAudio): - The audio data bytes encoded as specified in the request. - This field is set if: - - - The ``reply_audio_config`` field is specified in the - request. - - The automated agent, which this output comes from, - responded with audio. In such case, the - ``reply_audio.config`` field contains settings used to - synthesize the speech. - - In some scenarios, multiple output audio fields may be - present in the response structure. In these cases, only the - top-most-level audio output has content. - automated_agent_reply (google.cloud.dialogflow_v2.types.AutomatedAgentReply): - Only set if a Dialogflow automated agent has responded. Note - that: - [AutomatedAgentReply.detect_intent_response.output_audio][] - and - [AutomatedAgentReply.detect_intent_response.output_audio_config][] - are always empty, use - [reply_audio][google.cloud.dialogflow.v2.StreamingAnalyzeContentResponse.reply_audio] - instead. - message (google.cloud.dialogflow_v2.types.Message): - Message analyzed by CCAI. - human_agent_suggestion_results (MutableSequence[google.cloud.dialogflow_v2.types.SuggestionResult]): - The suggestions for most recent human agent. The order is - the same as - [HumanAgentAssistantConfig.SuggestionConfig.feature_configs][google.cloud.dialogflow.v2.HumanAgentAssistantConfig.SuggestionConfig.feature_configs] - of - [HumanAgentAssistantConfig.human_agent_suggestion_config][google.cloud.dialogflow.v2.HumanAgentAssistantConfig.human_agent_suggestion_config]. - end_user_suggestion_results (MutableSequence[google.cloud.dialogflow_v2.types.SuggestionResult]): - The suggestions for end user. The order is the same as - [HumanAgentAssistantConfig.SuggestionConfig.feature_configs][google.cloud.dialogflow.v2.HumanAgentAssistantConfig.SuggestionConfig.feature_configs] - of - [HumanAgentAssistantConfig.end_user_suggestion_config][google.cloud.dialogflow.v2.HumanAgentAssistantConfig.end_user_suggestion_config]. - dtmf_parameters (google.cloud.dialogflow_v2.types.DtmfParameters): - Indicates the parameters of DTMF. - """ - - recognition_result: session.StreamingRecognitionResult = proto.Field( - proto.MESSAGE, - number=1, - message=session.StreamingRecognitionResult, - ) - reply_text: str = proto.Field( - proto.STRING, - number=2, - ) - reply_audio: 'OutputAudio' = proto.Field( - proto.MESSAGE, - number=3, - message='OutputAudio', - ) - automated_agent_reply: 'AutomatedAgentReply' = proto.Field( - proto.MESSAGE, - number=4, - message='AutomatedAgentReply', - ) - message: 'Message' = proto.Field( - proto.MESSAGE, - number=6, - message='Message', - ) - human_agent_suggestion_results: MutableSequence['SuggestionResult'] = proto.RepeatedField( - proto.MESSAGE, - number=7, - message='SuggestionResult', - ) - end_user_suggestion_results: MutableSequence['SuggestionResult'] = proto.RepeatedField( - proto.MESSAGE, - number=8, - message='SuggestionResult', - ) - dtmf_parameters: 'DtmfParameters' = proto.Field( - proto.MESSAGE, - number=10, - message='DtmfParameters', - ) - - -class SuggestArticlesRequest(proto.Message): - r"""The request message for - [Participants.SuggestArticles][google.cloud.dialogflow.v2.Participants.SuggestArticles]. - - Attributes: - parent (str): - Required. The name of the participant to fetch suggestion - for. Format: - ``projects//locations//conversations//participants/``. - latest_message (str): - Optional. The name of the latest conversation message to - compile suggestion for. If empty, it will be the latest - message of the conversation. - - Format: - ``projects//locations//conversations//messages/``. - context_size (int): - Optional. Max number of messages prior to and including - [latest_message][google.cloud.dialogflow.v2.SuggestArticlesRequest.latest_message] - to use as context when compiling the suggestion. By default - 20 and at most 50. - assist_query_params (google.cloud.dialogflow_v2.types.AssistQueryParameters): - Parameters for a human assist query. - """ - - parent: str = proto.Field( - proto.STRING, - number=1, - ) - latest_message: str = proto.Field( - proto.STRING, - number=2, - ) - context_size: int = proto.Field( - proto.INT32, - number=3, - ) - assist_query_params: 'AssistQueryParameters' = proto.Field( - proto.MESSAGE, - number=4, - message='AssistQueryParameters', - ) - - -class SuggestArticlesResponse(proto.Message): - r"""The response message for - [Participants.SuggestArticles][google.cloud.dialogflow.v2.Participants.SuggestArticles]. - - Attributes: - article_answers (MutableSequence[google.cloud.dialogflow_v2.types.ArticleAnswer]): - Articles ordered by score in descending - order. - latest_message (str): - The name of the latest conversation message used to compile - suggestion for. - - Format: - ``projects//locations//conversations//messages/``. - context_size (int): - Number of messages prior to and including - [latest_message][google.cloud.dialogflow.v2.SuggestArticlesResponse.latest_message] - to compile the suggestion. It may be smaller than the - [SuggestArticlesRequest.context_size][google.cloud.dialogflow.v2.SuggestArticlesRequest.context_size] - field in the request if there aren't that many messages in - the conversation. - """ - - article_answers: MutableSequence['ArticleAnswer'] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message='ArticleAnswer', - ) - latest_message: str = proto.Field( - proto.STRING, - number=2, - ) - context_size: int = proto.Field( - proto.INT32, - number=3, - ) - - -class SuggestFaqAnswersRequest(proto.Message): - r"""The request message for - [Participants.SuggestFaqAnswers][google.cloud.dialogflow.v2.Participants.SuggestFaqAnswers]. - - Attributes: - parent (str): - Required. The name of the participant to fetch suggestion - for. Format: - ``projects//locations//conversations//participants/``. - latest_message (str): - Optional. The name of the latest conversation message to - compile suggestion for. If empty, it will be the latest - message of the conversation. - - Format: - ``projects//locations//conversations//messages/``. - context_size (int): - Optional. Max number of messages prior to and including - [latest_message] to use as context when compiling the - suggestion. By default 20 and at most 50. - assist_query_params (google.cloud.dialogflow_v2.types.AssistQueryParameters): - Parameters for a human assist query. - """ - - parent: str = proto.Field( - proto.STRING, - number=1, - ) - latest_message: str = proto.Field( - proto.STRING, - number=2, - ) - context_size: int = proto.Field( - proto.INT32, - number=3, - ) - assist_query_params: 'AssistQueryParameters' = proto.Field( - proto.MESSAGE, - number=4, - message='AssistQueryParameters', - ) - - -class SuggestFaqAnswersResponse(proto.Message): - r"""The request message for - [Participants.SuggestFaqAnswers][google.cloud.dialogflow.v2.Participants.SuggestFaqAnswers]. - - Attributes: - faq_answers (MutableSequence[google.cloud.dialogflow_v2.types.FaqAnswer]): - Answers extracted from FAQ documents. - latest_message (str): - The name of the latest conversation message used to compile - suggestion for. - - Format: - ``projects//locations//conversations//messages/``. - context_size (int): - Number of messages prior to and including - [latest_message][google.cloud.dialogflow.v2.SuggestFaqAnswersResponse.latest_message] - to compile the suggestion. It may be smaller than the - [SuggestFaqAnswersRequest.context_size][google.cloud.dialogflow.v2.SuggestFaqAnswersRequest.context_size] - field in the request if there aren't that many messages in - the conversation. - """ - - faq_answers: MutableSequence['FaqAnswer'] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message='FaqAnswer', - ) - latest_message: str = proto.Field( - proto.STRING, - number=2, - ) - context_size: int = proto.Field( - proto.INT32, - number=3, - ) - - -class SuggestSmartRepliesRequest(proto.Message): - r"""The request message for - [Participants.SuggestSmartReplies][google.cloud.dialogflow.v2.Participants.SuggestSmartReplies]. - - Attributes: - parent (str): - Required. The name of the participant to fetch suggestion - for. Format: - ``projects//locations//conversations//participants/``. - current_text_input (google.cloud.dialogflow_v2.types.TextInput): - The current natural language text segment to - compile suggestion for. This provides a way for - user to get follow up smart reply suggestion - after a smart reply selection, without sending a - text message. - latest_message (str): - The name of the latest conversation message to compile - suggestion for. If empty, it will be the latest message of - the conversation. - - Format: - ``projects//locations//conversations//messages/``. - context_size (int): - Max number of messages prior to and including - [latest_message] to use as context when compiling the - suggestion. By default 20 and at most 50. - """ - - parent: str = proto.Field( - proto.STRING, - number=1, - ) - current_text_input: session.TextInput = proto.Field( - proto.MESSAGE, - number=4, - message=session.TextInput, - ) - latest_message: str = proto.Field( - proto.STRING, - number=2, - ) - context_size: int = proto.Field( - proto.INT32, - number=3, - ) - - -class SuggestSmartRepliesResponse(proto.Message): - r"""The response message for - [Participants.SuggestSmartReplies][google.cloud.dialogflow.v2.Participants.SuggestSmartReplies]. - - Attributes: - smart_reply_answers (MutableSequence[google.cloud.dialogflow_v2.types.SmartReplyAnswer]): - Output only. Multiple reply options provided - by smart reply service. The order is based on - the rank of the model prediction. The maximum - number of the returned replies is set in - SmartReplyConfig. - latest_message (str): - The name of the latest conversation message used to compile - suggestion for. - - Format: - ``projects//locations//conversations//messages/``. - context_size (int): - Number of messages prior to and including - [latest_message][google.cloud.dialogflow.v2.SuggestSmartRepliesResponse.latest_message] - to compile the suggestion. It may be smaller than the - [SuggestSmartRepliesRequest.context_size][google.cloud.dialogflow.v2.SuggestSmartRepliesRequest.context_size] - field in the request if there aren't that many messages in - the conversation. - """ - - smart_reply_answers: MutableSequence['SmartReplyAnswer'] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message='SmartReplyAnswer', - ) - latest_message: str = proto.Field( - proto.STRING, - number=2, - ) - context_size: int = proto.Field( - proto.INT32, - number=3, - ) - - -class OutputAudio(proto.Message): - r"""Represents the natural language speech audio to be played to - the end user. - - Attributes: - config (google.cloud.dialogflow_v2.types.OutputAudioConfig): - Instructs the speech synthesizer how to - generate the speech audio. - audio (bytes): - The natural language speech audio. - """ - - config: gcd_audio_config.OutputAudioConfig = proto.Field( - proto.MESSAGE, - number=1, - message=gcd_audio_config.OutputAudioConfig, - ) - audio: bytes = 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 - [Sessions.DetectIntent][google.cloud.dialogflow.v2.Sessions.DetectIntent] - call. - automated_agent_reply_type (google.cloud.dialogflow_v2.types.AutomatedAgentReply.AutomatedAgentReplyType): - AutomatedAgentReply type. - allow_cancellation (bool): - Indicates whether the partial automated agent - reply is interruptible when a later reply - message arrives. e.g. if the agent specified - some music as partial response, it can be - cancelled. - cx_current_page (str): - The unique identifier of the current Dialogflow CX - conversation page. Format: - ``projects//locations//agents//flows//pages/``. - """ - class AutomatedAgentReplyType(proto.Enum): - r"""Represents different automated agent reply types. - - Values: - AUTOMATED_AGENT_REPLY_TYPE_UNSPECIFIED (0): - Not specified. This should never happen. - PARTIAL (1): - Partial reply. e.g. Aggregated responses in a - ``Fulfillment`` that enables ``return_partial_response`` can - be returned as partial reply. WARNING: partial reply is not - eligible for barge-in. - FINAL (2): - Final reply. - """ - AUTOMATED_AGENT_REPLY_TYPE_UNSPECIFIED = 0 - PARTIAL = 1 - FINAL = 2 - - detect_intent_response: session.DetectIntentResponse = proto.Field( - proto.MESSAGE, - number=1, - message=session.DetectIntentResponse, - ) - automated_agent_reply_type: AutomatedAgentReplyType = proto.Field( - proto.ENUM, - number=7, - enum=AutomatedAgentReplyType, - ) - allow_cancellation: bool = proto.Field( - proto.BOOL, - number=8, - ) - cx_current_page: str = proto.Field( - proto.STRING, - number=11, - ) - - -class ArticleAnswer(proto.Message): - r"""Represents article answer. - - Attributes: - title (str): - The article title. - uri (str): - The article URI. - snippets (MutableSequence[str]): - Article snippets. - confidence (float): - Article match confidence. - The system's confidence score that this article - is a good match for this conversation, as a - value from 0.0 (completely uncertain) to 1.0 - (completely certain). - metadata (MutableMapping[str, str]): - A map that contains metadata about the answer - and the document from which it originates. - answer_record (str): - The name of answer record, in the format of - "projects//locations//answerRecords/". - """ - - title: str = proto.Field( - proto.STRING, - number=1, - ) - uri: str = proto.Field( - proto.STRING, - number=2, - ) - snippets: MutableSequence[str] = proto.RepeatedField( - proto.STRING, - number=3, - ) - confidence: float = proto.Field( - proto.FLOAT, - number=4, - ) - metadata: MutableMapping[str, str] = proto.MapField( - proto.STRING, - proto.STRING, - number=5, - ) - answer_record: str = 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 - document. - confidence (float): - The system's confidence score that this - Knowledge answer is a good match for this - conversational query, range from 0.0 (completely - uncertain) to 1.0 (completely certain). - question (str): - The corresponding FAQ question. - source (str): - Indicates which Knowledge Document this answer was extracted - from. Format: - ``projects//locations//agent/knowledgeBases//documents/``. - metadata (MutableMapping[str, str]): - A map that contains metadata about the answer - and the document from which it originates. - answer_record (str): - The name of answer record, in the format of - "projects//locations//answerRecords/". - """ - - answer: str = proto.Field( - proto.STRING, - number=1, - ) - confidence: float = proto.Field( - proto.FLOAT, - number=2, - ) - question: str = proto.Field( - proto.STRING, - number=3, - ) - source: str = proto.Field( - proto.STRING, - number=4, - ) - metadata: MutableMapping[str, str] = proto.MapField( - proto.STRING, - proto.STRING, - number=5, - ) - answer_record: str = proto.Field( - proto.STRING, - number=6, - ) - - -class SmartReplyAnswer(proto.Message): - r"""Represents a smart reply answer. - - Attributes: - reply (str): - The content of the reply. - confidence (float): - Smart reply confidence. - The system's confidence score that this reply is - a good match for this conversation, as a value - from 0.0 (completely uncertain) to 1.0 - (completely certain). - answer_record (str): - The name of answer record, in the format of - "projects//locations//answerRecords/". - """ - - reply: str = proto.Field( - proto.STRING, - number=1, - ) - confidence: float = proto.Field( - proto.FLOAT, - number=2, - ) - answer_record: str = proto.Field( - proto.STRING, - number=3, - ) - - -class SuggestionResult(proto.Message): - r"""One response of different type of suggestion response which is used - in the response of - [Participants.AnalyzeContent][google.cloud.dialogflow.v2.Participants.AnalyzeContent] - and - [Participants.AnalyzeContent][google.cloud.dialogflow.v2.Participants.AnalyzeContent], - as well as - [HumanAgentAssistantEvent][google.cloud.dialogflow.v2.HumanAgentAssistantEvent]. - - This message has `oneof`_ fields (mutually exclusive fields). - For each oneof, at most one member field can be set at the same time. - Setting any member of the oneof automatically clears all other - members. - - .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields - - Attributes: - error (google.rpc.status_pb2.Status): - Error status if the request failed. - - This field is a member of `oneof`_ ``suggestion_response``. - suggest_articles_response (google.cloud.dialogflow_v2.types.SuggestArticlesResponse): - SuggestArticlesResponse if request is for - ARTICLE_SUGGESTION. - - This field is a member of `oneof`_ ``suggestion_response``. - suggest_faq_answers_response (google.cloud.dialogflow_v2.types.SuggestFaqAnswersResponse): - SuggestFaqAnswersResponse if request is for FAQ_ANSWER. - - This field is a member of `oneof`_ ``suggestion_response``. - suggest_smart_replies_response (google.cloud.dialogflow_v2.types.SuggestSmartRepliesResponse): - SuggestSmartRepliesResponse if request is for SMART_REPLY. - - This field is a member of `oneof`_ ``suggestion_response``. - """ - - error: status_pb2.Status = proto.Field( - proto.MESSAGE, - number=1, - oneof='suggestion_response', - message=status_pb2.Status, - ) - suggest_articles_response: 'SuggestArticlesResponse' = proto.Field( - proto.MESSAGE, - number=2, - oneof='suggestion_response', - message='SuggestArticlesResponse', - ) - suggest_faq_answers_response: 'SuggestFaqAnswersResponse' = proto.Field( - proto.MESSAGE, - number=3, - oneof='suggestion_response', - message='SuggestFaqAnswersResponse', - ) - suggest_smart_replies_response: 'SuggestSmartRepliesResponse' = proto.Field( - proto.MESSAGE, - number=4, - oneof='suggestion_response', - message='SuggestSmartRepliesResponse', - ) - - -class InputTextConfig(proto.Message): - r"""Defines the language used in the input text. - - Attributes: - language_code (str): - Required. The language of this conversational query. See - `Language - Support `__ - for a list of the currently supported language codes. - """ - - language_code: str = proto.Field( - proto.STRING, - number=1, - ) - - -class AnnotatedMessagePart(proto.Message): - r"""Represents a part of a message possibly annotated with an - entity. The part can be an entity or purely a part of the - message between two entities or message start/end. - - Attributes: - text (str): - A part of a message possibly annotated with - an entity. - entity_type (str): - The `Dialogflow system entity - type `__ - of this message part. If this is empty, Dialogflow could not - annotate the phrase part with a system entity. - formatted_value (google.protobuf.struct_pb2.Value): - The `Dialogflow system entity formatted - value `__ - of this message part. For example for a system entity of - type ``@sys.unit-currency``, this may contain: - - .. raw:: html - -
-                {
-                  "amount": 5,
-                  "currency": "USD"
-                }
-                
- """ - - text: str = proto.Field( - proto.STRING, - number=1, - ) - entity_type: str = proto.Field( - proto.STRING, - number=2, - ) - formatted_value: struct_pb2.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 (MutableSequence[google.cloud.dialogflow_v2.types.AnnotatedMessagePart]): - The collection of annotated message parts ordered by their - position in the message. You can recover the annotated - message by concatenating [AnnotatedMessagePart.text]. - contain_entities (bool): - Indicates whether the text message contains - entities. - """ - - parts: MutableSequence['AnnotatedMessagePart'] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message='AnnotatedMessagePart', - ) - contain_entities: bool = proto.Field( - proto.BOOL, - number=2, - ) - - -class AssistQueryParameters(proto.Message): - r"""Represents the parameters of human assist query. - - Attributes: - documents_metadata_filters (MutableMapping[str, str]): - Key-value filters on the metadata of documents returned by - article suggestion. If specified, article suggestion only - returns suggested documents that match all filters in their - [Document.metadata][google.cloud.dialogflow.v2.Document.metadata]. - Multiple values for a metadata key should be concatenated by - comma. For example, filters to match all documents that have - 'US' or 'CA' in their market metadata values and 'agent' in - their user metadata values will be - - :: - - documents_metadata_filters { - key: "market" - value: "US,CA" - } - documents_metadata_filters { - key: "user" - value: "agent" - } - """ - - documents_metadata_filters: MutableMapping[str, str] = proto.MapField( - proto.STRING, - proto.STRING, - number=1, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v2/google/cloud/dialogflow_v2/types/session.py b/owl-bot-staging/v2/google/cloud/dialogflow_v2/types/session.py deleted file mode 100644 index 4ef614b80..000000000 --- a/owl-bot-staging/v2/google/cloud/dialogflow_v2/types/session.py +++ /dev/null @@ -1,1042 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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 __future__ import annotations - -from typing import MutableMapping, MutableSequence - -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 # 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( - package='google.cloud.dialogflow.v2', - manifest={ - 'DetectIntentRequest', - 'DetectIntentResponse', - 'QueryParameters', - 'QueryInput', - 'QueryResult', - 'StreamingDetectIntentRequest', - 'StreamingDetectIntentResponse', - 'StreamingRecognitionResult', - 'TextInput', - 'EventInput', - 'SentimentAnalysisRequestConfig', - 'SentimentAnalysisResult', - 'Sentiment', - }, -) - - -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. - Format: - ``projects//agent/sessions/``, or - ``projects//agent/environments//users//sessions/``. - If ``Environment ID`` is not specified, we assume default - 'draft' environment (``Environment ID`` might be referred to - as environment name at some places). If ``User ID`` is not - specified, we are using "-". It's up to the API caller to - choose an appropriate ``Session ID`` and ``User Id``. They - can be a random number or some type of user and session - identifiers (preferably hashed). The length of the - ``Session ID`` and ``User ID`` must not exceed 36 - characters. - - For more information, see the `API interactions - guide `__. - - Note: Always use agent versions for production traffic. See - `Versions and - environments `__. - query_params (google.cloud.dialogflow_v2.types.QueryParameters): - The parameters of this query. - query_input (google.cloud.dialogflow_v2.types.QueryInput): - Required. The input specification. It can be - set to: - 1. an audio config - which instructs the speech recognizer how to - process the speech audio, - 2. a conversational query in the form of text, - or - 3. an event that specifies which intent to - trigger. - output_audio_config (google.cloud.dialogflow_v2.types.OutputAudioConfig): - Instructs the speech synthesizer how to - generate the output audio. If this field is not - set and agent-level speech synthesizer is not - configured, no output audio is generated. - output_audio_config_mask (google.protobuf.field_mask_pb2.FieldMask): - Mask for - [output_audio_config][google.cloud.dialogflow.v2.DetectIntentRequest.output_audio_config] - indicating which settings in this request-level config - should override speech synthesizer settings defined at - agent-level. - - If unspecified or empty, - [output_audio_config][google.cloud.dialogflow.v2.DetectIntentRequest.output_audio_config] - replaces the agent-level config in its entirety. - input_audio (bytes): - The natural language speech audio to be processed. This - field should be populated iff ``query_input`` is set to an - input audio config. A single request can contain up to 1 - minute of speech audio data. - """ - - session: str = proto.Field( - proto.STRING, - number=1, - ) - query_params: 'QueryParameters' = proto.Field( - proto.MESSAGE, - number=2, - message='QueryParameters', - ) - query_input: 'QueryInput' = proto.Field( - proto.MESSAGE, - number=3, - message='QueryInput', - ) - output_audio_config: gcd_audio_config.OutputAudioConfig = proto.Field( - proto.MESSAGE, - number=4, - message=gcd_audio_config.OutputAudioConfig, - ) - output_audio_config_mask: field_mask_pb2.FieldMask = proto.Field( - proto.MESSAGE, - number=7, - message=field_mask_pb2.FieldMask, - ) - input_audio: bytes = 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 - be used to locate a response in the training - example set or for reporting issues. - query_result (google.cloud.dialogflow_v2.types.QueryResult): - The selected results of the conversational query or event - processing. See ``alternative_query_results`` for additional - potential results. - webhook_status (google.rpc.status_pb2.Status): - Specifies the status of the webhook request. - output_audio (bytes): - The audio data bytes encoded as specified in the request. - Note: The output audio is generated based on the values of - default platform text responses found in the - ``query_result.fulfillment_messages`` field. If multiple - default text responses exist, they will be concatenated when - generating audio. If no default platform text responses - exist, the generated audio content will be empty. - - In some scenarios, multiple output audio fields may be - present in the response structure. In these cases, only the - top-most-level audio output has content. - output_audio_config (google.cloud.dialogflow_v2.types.OutputAudioConfig): - The config used by the speech synthesizer to - generate the output audio. - """ - - response_id: str = proto.Field( - proto.STRING, - number=1, - ) - query_result: 'QueryResult' = proto.Field( - proto.MESSAGE, - number=2, - message='QueryResult', - ) - webhook_status: status_pb2.Status = proto.Field( - proto.MESSAGE, - number=3, - message=status_pb2.Status, - ) - output_audio: bytes = proto.Field( - proto.BYTES, - number=4, - ) - output_audio_config: gcd_audio_config.OutputAudioConfig = proto.Field( - proto.MESSAGE, - number=6, - message=gcd_audio_config.OutputAudioConfig, - ) - - -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 - zone database `__, e.g., - America/New_York, Europe/Paris. If not provided, the time - zone specified in agent settings is used. - geo_location (google.type.latlng_pb2.LatLng): - The geo location of this conversational - query. - contexts (MutableSequence[google.cloud.dialogflow_v2.types.Context]): - The collection of contexts to be activated - before this query is executed. - reset_contexts (bool): - Specifies whether to delete all contexts in - the current session before the new ones are - activated. - session_entity_types (MutableSequence[google.cloud.dialogflow_v2.types.SessionEntityType]): - Additional session entity types to replace or - extend developer entity types with. The entity - synonyms apply to all languages and persist for - the session of this query. - payload (google.protobuf.struct_pb2.Struct): - This field can be used to pass custom data to your webhook. - Arbitrary JSON objects are supported. If supplied, the value - is used to populate the - ``WebhookRequest.original_detect_intent_request.payload`` - field sent to your webhook. - sentiment_analysis_request_config (google.cloud.dialogflow_v2.types.SentimentAnalysisRequestConfig): - Configures the type of sentiment analysis to - perform. If not provided, sentiment analysis is - not performed. - webhook_headers (MutableMapping[str, str]): - This field can be used to pass HTTP headers - for a webhook call. These headers will be sent - to webhook along with the headers that have been - configured through the Dialogflow web console. - The headers defined within this field will - overwrite the headers configured through the - Dialogflow console if there is a conflict. - Header names are case-insensitive. Google's - specified headers are not allowed. Including: - "Host", "Content-Length", "Connection", "From", - "User-Agent", "Accept-Encoding", - "If-Modified-Since", "If-None-Match", - "X-Forwarded-For", etc. - """ - - time_zone: str = proto.Field( - proto.STRING, - number=1, - ) - geo_location: latlng_pb2.LatLng = proto.Field( - proto.MESSAGE, - number=2, - message=latlng_pb2.LatLng, - ) - contexts: MutableSequence[context.Context] = proto.RepeatedField( - proto.MESSAGE, - number=3, - message=context.Context, - ) - reset_contexts: bool = proto.Field( - proto.BOOL, - number=4, - ) - session_entity_types: MutableSequence[session_entity_type.SessionEntityType] = proto.RepeatedField( - proto.MESSAGE, - number=5, - message=session_entity_type.SessionEntityType, - ) - payload: struct_pb2.Struct = proto.Field( - proto.MESSAGE, - number=6, - message=struct_pb2.Struct, - ) - sentiment_analysis_request_config: 'SentimentAnalysisRequestConfig' = proto.Field( - proto.MESSAGE, - number=10, - message='SentimentAnalysisRequestConfig', - ) - webhook_headers: MutableMapping[str, str] = proto.MapField( - proto.STRING, - proto.STRING, - number=14, - ) - - -class QueryInput(proto.Message): - r"""Represents the query input. It can contain either: - 1. An audio config which - instructs the speech recognizer how to process the speech - audio. - 2. A conversational query in the form of text,. - - 3. An event that specifies which intent to trigger. - - This message has `oneof`_ fields (mutually exclusive fields). - For each oneof, at most one member field can be set at the same time. - Setting any member of the oneof automatically clears all other - members. - - .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields - - Attributes: - audio_config (google.cloud.dialogflow_v2.types.InputAudioConfig): - Instructs the speech recognizer how to - process the speech audio. - - This field is a member of `oneof`_ ``input``. - text (google.cloud.dialogflow_v2.types.TextInput): - The natural language text to be processed. - Text length must not exceed 256 character for - virtual agent interactions. - - This field is a member of `oneof`_ ``input``. - event (google.cloud.dialogflow_v2.types.EventInput): - The event to be processed. - - This field is a member of `oneof`_ ``input``. - """ - - audio_config: gcd_audio_config.InputAudioConfig = proto.Field( - proto.MESSAGE, - number=1, - oneof='input', - message=gcd_audio_config.InputAudioConfig, - ) - text: 'TextInput' = proto.Field( - proto.MESSAGE, - number=2, - oneof='input', - message='TextInput', - ) - event: 'EventInput' = proto.Field( - proto.MESSAGE, - number=3, - oneof='input', - message='EventInput', - ) - - -class QueryResult(proto.Message): - r"""Represents the result of conversational query or event - processing. - - Attributes: - query_text (str): - The original conversational query text: - - - If natural language text was provided as input, - ``query_text`` contains a copy of the input. - - If natural language speech audio was provided as input, - ``query_text`` contains the speech recognition result. If - speech recognizer produced multiple alternatives, a - particular one is picked. - - If automatic spell correction is enabled, ``query_text`` - will contain the corrected user input. - language_code (str): - The language that was triggered during intent detection. See - `Language - Support `__ - for a list of the currently supported language codes. - speech_recognition_confidence (float): - The Speech recognition confidence between 0.0 - and 1.0. A higher number indicates an estimated - greater likelihood that the recognized words are - correct. The default of 0.0 is a sentinel value - indicating that confidence was not set. - - This field is not guaranteed to be accurate or - set. In particular this field isn't set for - StreamingDetectIntent since the streaming - endpoint has separate confidence estimates per - portion of the audio in - StreamingRecognitionResult. - action (str): - The action name from the matched intent. - parameters (google.protobuf.struct_pb2.Struct): - The collection of extracted parameters. - Depending on your protocol or client library - language, this is a map, associative array, - symbol table, dictionary, or JSON object - composed of a collection of (MapKey, MapValue) - pairs: - - MapKey type: string - - MapKey value: parameter name - - MapValue type: - - If parameter's entity type is a - composite entity: map - Else: depending on - parameter value type, could be one of string, - number, boolean, null, list or map - - MapValue value: - - If parameter's entity type is a - composite entity: map from composite - entity property names to property values - - Else: parameter value - all_required_params_present (bool): - This field is set to: - - - ``false`` if the matched intent has required parameters - and not all of the required parameter values have been - collected. - - ``true`` if all required parameter values have been - collected, or if the matched intent doesn't contain any - required parameters. - cancels_slot_filling (bool): - Indicates whether the conversational query triggers a - cancellation for slot filling. For more information, see the - `cancel slot filling - documentation `__. - fulfillment_text (str): - The text to be pronounced to the user or shown on the - screen. Note: This is a legacy field, - ``fulfillment_messages`` should be preferred. - fulfillment_messages (MutableSequence[google.cloud.dialogflow_v2.types.Intent.Message]): - The collection of rich messages to present to - the user. - webhook_source (str): - If the query was fulfilled by a webhook call, this field is - set to the value of the ``source`` field returned in the - webhook response. - webhook_payload (google.protobuf.struct_pb2.Struct): - If the query was fulfilled by a webhook call, this field is - set to the value of the ``payload`` field returned in the - webhook response. - output_contexts (MutableSequence[google.cloud.dialogflow_v2.types.Context]): - The collection of output contexts. If applicable, - ``output_contexts.parameters`` contains entries with name - ``.original`` containing the original - parameter values before the query. - intent (google.cloud.dialogflow_v2.types.Intent): - The intent that matched the conversational query. Some, not - all fields are filled in this message, including but not - limited to: ``name``, ``display_name``, ``end_interaction`` - and ``is_fallback``. - intent_detection_confidence (float): - The intent detection confidence. Values range from 0.0 - (completely uncertain) to 1.0 (completely certain). This - value is for informational purpose only and is only used to - help match the best intent within the classification - threshold. This value may change for the same end-user - expression at any time due to a model retraining or change - in implementation. If there are - ``multiple knowledge_answers`` messages, this value is set - to the greatest ``knowledgeAnswers.match_confidence`` value - in the list. - diagnostic_info (google.protobuf.struct_pb2.Struct): - Free-form diagnostic information for the - associated detect intent request. The fields of - this data can change without notice, so you - should not write code that depends on its - structure. - The data may contain: - - - webhook call latency - - webhook errors - sentiment_analysis_result (google.cloud.dialogflow_v2.types.SentimentAnalysisResult): - The sentiment analysis result, which depends on the - ``sentiment_analysis_request_config`` specified in the - request. - """ - - query_text: str = proto.Field( - proto.STRING, - number=1, - ) - language_code: str = proto.Field( - proto.STRING, - number=15, - ) - speech_recognition_confidence: float = proto.Field( - proto.FLOAT, - number=2, - ) - action: str = proto.Field( - proto.STRING, - number=3, - ) - parameters: struct_pb2.Struct = proto.Field( - proto.MESSAGE, - number=4, - message=struct_pb2.Struct, - ) - all_required_params_present: bool = proto.Field( - proto.BOOL, - number=5, - ) - cancels_slot_filling: bool = proto.Field( - proto.BOOL, - number=21, - ) - fulfillment_text: str = proto.Field( - proto.STRING, - number=6, - ) - fulfillment_messages: MutableSequence[gcd_intent.Intent.Message] = proto.RepeatedField( - proto.MESSAGE, - number=7, - message=gcd_intent.Intent.Message, - ) - webhook_source: str = proto.Field( - proto.STRING, - number=8, - ) - webhook_payload: struct_pb2.Struct = proto.Field( - proto.MESSAGE, - number=9, - message=struct_pb2.Struct, - ) - output_contexts: MutableSequence[context.Context] = proto.RepeatedField( - proto.MESSAGE, - number=10, - message=context.Context, - ) - intent: gcd_intent.Intent = proto.Field( - proto.MESSAGE, - number=11, - message=gcd_intent.Intent, - ) - intent_detection_confidence: float = proto.Field( - proto.FLOAT, - number=12, - ) - diagnostic_info: struct_pb2.Struct = proto.Field( - proto.MESSAGE, - number=14, - message=struct_pb2.Struct, - ) - sentiment_analysis_result: 'SentimentAnalysisResult' = proto.Field( - proto.MESSAGE, - number=17, - message='SentimentAnalysisResult', - ) - - -class StreamingDetectIntentRequest(proto.Message): - r"""The top-level message sent by the client to the - [Sessions.StreamingDetectIntent][google.cloud.dialogflow.v2.Sessions.StreamingDetectIntent] - method. - - Multiple request messages should be sent in order: - - 1. The first message must contain - [session][google.cloud.dialogflow.v2.StreamingDetectIntentRequest.session], - [query_input][google.cloud.dialogflow.v2.StreamingDetectIntentRequest.query_input] - plus optionally - [query_params][google.cloud.dialogflow.v2.StreamingDetectIntentRequest.query_params]. - If the client wants to receive an audio response, it should also - contain - [output_audio_config][google.cloud.dialogflow.v2.StreamingDetectIntentRequest.output_audio_config]. - The message must not contain - [input_audio][google.cloud.dialogflow.v2.StreamingDetectIntentRequest.input_audio]. - - 2. If - [query_input][google.cloud.dialogflow.v2.StreamingDetectIntentRequest.query_input] - was set to - [query_input.audio_config][google.cloud.dialogflow.v2.InputAudioConfig], - all subsequent messages must contain - [input_audio][google.cloud.dialogflow.v2.StreamingDetectIntentRequest.input_audio] - to continue with Speech recognition. If you decide to rather - detect an intent from text input after you already started Speech - recognition, please send a message with - [query_input.text][google.cloud.dialogflow.v2.QueryInput.text]. - - However, note that: - - - Dialogflow will bill you for the audio duration so far. - - Dialogflow discards all Speech recognition results in favor of - the input text. - - Dialogflow will use the language code from the first message. - - After you sent all input, you must half-close or abort the request - stream. - - Attributes: - session (str): - Required. The name of the session the query is sent to. - Format of the session name: - ``projects//agent/sessions/``, or - ``projects//agent/environments//users//sessions/``. - If ``Environment ID`` is not specified, we assume default - 'draft' environment. If ``User ID`` is not specified, we are - using "-". It's up to the API caller to choose an - appropriate ``Session ID`` and ``User Id``. They can be a - random number or some type of user and session identifiers - (preferably hashed). The length of the ``Session ID`` and - ``User ID`` must not exceed 36 characters. - - For more information, see the `API interactions - guide `__. - - Note: Always use agent versions for production traffic. See - `Versions and - environments `__. - query_params (google.cloud.dialogflow_v2.types.QueryParameters): - The parameters of this query. - query_input (google.cloud.dialogflow_v2.types.QueryInput): - Required. The input specification. It can be - set to: - 1. an audio config which instructs the speech - recognizer how to process the speech audio, - - 2. a conversational query in the form of text, - or - 3. an event that specifies which intent to - trigger. - single_utterance (bool): - Please use - [InputAudioConfig.single_utterance][google.cloud.dialogflow.v2.InputAudioConfig.single_utterance] - instead. If ``false`` (default), recognition does not cease - until the client closes the stream. If ``true``, the - recognizer will detect a single spoken utterance in input - audio. Recognition ceases when it detects the audio's voice - has stopped or paused. In this case, once a detected intent - is received, the client should close the stream and start a - new request with a new stream as needed. This setting is - ignored when ``query_input`` is a piece of text or an event. - output_audio_config (google.cloud.dialogflow_v2.types.OutputAudioConfig): - Instructs the speech synthesizer how to - generate the output audio. If this field is not - set and agent-level speech synthesizer is not - configured, no output audio is generated. - output_audio_config_mask (google.protobuf.field_mask_pb2.FieldMask): - Mask for - [output_audio_config][google.cloud.dialogflow.v2.StreamingDetectIntentRequest.output_audio_config] - indicating which settings in this request-level config - should override speech synthesizer settings defined at - agent-level. - - If unspecified or empty, - [output_audio_config][google.cloud.dialogflow.v2.StreamingDetectIntentRequest.output_audio_config] - replaces the agent-level config in its entirety. - input_audio (bytes): - The input audio content to be recognized. Must be sent if - ``query_input`` was set to a streaming input audio config. - The complete audio over all streaming messages must not - exceed 1 minute. - """ - - session: str = proto.Field( - proto.STRING, - number=1, - ) - query_params: 'QueryParameters' = proto.Field( - proto.MESSAGE, - number=2, - message='QueryParameters', - ) - query_input: 'QueryInput' = proto.Field( - proto.MESSAGE, - number=3, - message='QueryInput', - ) - single_utterance: bool = proto.Field( - proto.BOOL, - number=4, - ) - output_audio_config: gcd_audio_config.OutputAudioConfig = proto.Field( - proto.MESSAGE, - number=5, - message=gcd_audio_config.OutputAudioConfig, - ) - output_audio_config_mask: field_mask_pb2.FieldMask = proto.Field( - proto.MESSAGE, - number=7, - message=field_mask_pb2.FieldMask, - ) - input_audio: bytes = proto.Field( - proto.BYTES, - number=6, - ) - - -class StreamingDetectIntentResponse(proto.Message): - r"""The top-level message returned from the ``StreamingDetectIntent`` - method. - - Multiple response messages can be returned in order: - - 1. If the ``StreamingDetectIntentRequest.input_audio`` field was - set, the ``recognition_result`` field is populated for one or - more messages. See the - [StreamingRecognitionResult][google.cloud.dialogflow.v2.StreamingRecognitionResult] - message for details about the result message sequence. - - 2. The next message contains ``response_id``, ``query_result`` and - optionally ``webhook_status`` if a WebHook was called. - - Attributes: - response_id (str): - The unique identifier of the response. It can - be used to locate a response in the training - example set or for reporting issues. - recognition_result (google.cloud.dialogflow_v2.types.StreamingRecognitionResult): - The result of speech recognition. - query_result (google.cloud.dialogflow_v2.types.QueryResult): - The result of the conversational query or - event processing. - webhook_status (google.rpc.status_pb2.Status): - Specifies the status of the webhook request. - output_audio (bytes): - The audio data bytes encoded as specified in the request. - Note: The output audio is generated based on the values of - default platform text responses found in the - ``query_result.fulfillment_messages`` field. If multiple - default text responses exist, they will be concatenated when - generating audio. If no default platform text responses - exist, the generated audio content will be empty. - - In some scenarios, multiple output audio fields may be - present in the response structure. In these cases, only the - top-most-level audio output has content. - output_audio_config (google.cloud.dialogflow_v2.types.OutputAudioConfig): - The config used by the speech synthesizer to - generate the output audio. - """ - - response_id: str = proto.Field( - proto.STRING, - number=1, - ) - recognition_result: 'StreamingRecognitionResult' = proto.Field( - proto.MESSAGE, - number=2, - message='StreamingRecognitionResult', - ) - query_result: 'QueryResult' = proto.Field( - proto.MESSAGE, - number=3, - message='QueryResult', - ) - webhook_status: status_pb2.Status = proto.Field( - proto.MESSAGE, - number=4, - message=status_pb2.Status, - ) - output_audio: bytes = proto.Field( - proto.BYTES, - number=5, - ) - output_audio_config: gcd_audio_config.OutputAudioConfig = proto.Field( - proto.MESSAGE, - number=6, - message=gcd_audio_config.OutputAudioConfig, - ) - - -class StreamingRecognitionResult(proto.Message): - r"""Contains a speech recognition result corresponding to a portion of - the audio that is currently being processed or an indication that - this is the end of the single requested utterance. - - While end-user audio is being processed, Dialogflow sends a series - of results. Each result may contain a ``transcript`` value. A - transcript represents a portion of the utterance. While the - recognizer is processing audio, transcript values may be interim - values or finalized values. Once a transcript is finalized, the - ``is_final`` value is set to true and processing continues for the - next transcript. - - If - ``StreamingDetectIntentRequest.query_input.audio_config.single_utterance`` - was true, and the recognizer has completed processing audio, the - ``message_type`` value is set to \`END_OF_SINGLE_UTTERANCE and the - following (last) result contains the last finalized transcript. - - The complete end-user utterance is determined by concatenating the - finalized transcript values received for the series of results. - - In the following example, single utterance is enabled. In the case - where single utterance is not enabled, result 7 would not occur. - - :: - - Num | transcript | message_type | is_final - --- | ----------------------- | ----------------------- | -------- - 1 | "tube" | TRANSCRIPT | false - 2 | "to be a" | TRANSCRIPT | false - 3 | "to be" | TRANSCRIPT | false - 4 | "to be or not to be" | TRANSCRIPT | true - 5 | "that's" | TRANSCRIPT | false - 6 | "that is | TRANSCRIPT | false - 7 | unset | END_OF_SINGLE_UTTERANCE | unset - 8 | " that is the question" | TRANSCRIPT | true - - Concatenating the finalized transcripts with ``is_final`` set to - true, the complete utterance becomes "to be or not to be that is the - question". - - Attributes: - message_type (google.cloud.dialogflow_v2.types.StreamingRecognitionResult.MessageType): - Type of the result message. - transcript (str): - Transcript text representing the words that the user spoke. - Populated if and only if ``message_type`` = ``TRANSCRIPT``. - is_final (bool): - If ``false``, the ``StreamingRecognitionResult`` represents - an interim result that may change. If ``true``, the - recognizer will not return any further hypotheses about this - piece of the audio. May only be populated for - ``message_type`` = ``TRANSCRIPT``. - confidence (float): - The Speech confidence between 0.0 and 1.0 for the current - portion of audio. A higher number indicates an estimated - greater likelihood that the recognized words are correct. - The default of 0.0 is a sentinel value indicating that - confidence was not set. - - This field is typically only provided if ``is_final`` is - true and you should not rely on it being accurate or even - set. - speech_word_info (MutableSequence[google.cloud.dialogflow_v2.types.SpeechWordInfo]): - Word-specific information for the words recognized by Speech - in - [transcript][google.cloud.dialogflow.v2.StreamingRecognitionResult.transcript]. - Populated if and only if ``message_type`` = ``TRANSCRIPT`` - and [InputAudioConfig.enable_word_info] is set. - speech_end_offset (google.protobuf.duration_pb2.Duration): - Time offset of the end of this Speech recognition result - relative to the beginning of the audio. Only populated for - ``message_type`` = ``TRANSCRIPT``. - language_code (str): - Detected language code for the transcript. - """ - class MessageType(proto.Enum): - r"""Type of the response message. - - Values: - MESSAGE_TYPE_UNSPECIFIED (0): - Not specified. Should never be used. - TRANSCRIPT (1): - Message contains a (possibly partial) - transcript. - END_OF_SINGLE_UTTERANCE (2): - Event indicates that the server has detected the end of the - user's speech utterance and expects no additional inputs. - Therefore, the server will not process additional audio - (although it may subsequently return additional results). - The client should stop sending additional audio data, - half-close the gRPC connection, and wait for any additional - results until the server closes the gRPC connection. This - message is only sent if ``single_utterance`` was set to - ``true``, and is not used otherwise. - """ - MESSAGE_TYPE_UNSPECIFIED = 0 - TRANSCRIPT = 1 - END_OF_SINGLE_UTTERANCE = 2 - - message_type: MessageType = proto.Field( - proto.ENUM, - number=1, - enum=MessageType, - ) - transcript: str = proto.Field( - proto.STRING, - number=2, - ) - is_final: bool = proto.Field( - proto.BOOL, - number=3, - ) - confidence: float = proto.Field( - proto.FLOAT, - number=4, - ) - speech_word_info: MutableSequence[gcd_audio_config.SpeechWordInfo] = proto.RepeatedField( - proto.MESSAGE, - number=7, - message=gcd_audio_config.SpeechWordInfo, - ) - speech_end_offset: duration_pb2.Duration = proto.Field( - proto.MESSAGE, - number=8, - message=duration_pb2.Duration, - ) - language_code: str = proto.Field( - proto.STRING, - number=10, - ) - - -class TextInput(proto.Message): - r"""============================================================================ - Auxiliary proto messages. - - Represents the natural language text to be processed. - - Attributes: - text (str): - Required. The UTF-8 encoded natural language - text to be processed. Text length must not - exceed 256 characters for virtual agent - interactions. - language_code (str): - Required. The language of this conversational query. See - `Language - Support `__ - for a list of the currently supported language codes. Note - that queries in the same session do not necessarily need to - specify the same language. - """ - - text: str = proto.Field( - proto.STRING, - number=1, - ) - language_code: str = proto.Field( - proto.STRING, - number=2, - ) - - -class EventInput(proto.Message): - r"""Events allow for matching intents by event name instead of the - natural language input. For instance, input - ```` - can trigger a personalized welcome response. The parameter ``name`` - may be used by the agent in the response: - ``"Hello #welcome_event.name! What can I do for you today?"``. - - Attributes: - name (str): - Required. The unique identifier of the event. - parameters (google.protobuf.struct_pb2.Struct): - The collection of parameters associated with - the event. - Depending on your protocol or client library - language, this is a map, associative array, - symbol table, dictionary, or JSON object - composed of a collection of (MapKey, MapValue) - pairs: - - MapKey type: string - - MapKey value: parameter name - - MapValue type: - - If parameter's entity type is a - composite entity: map - Else: depending on - parameter value type, could be one of string, - number, boolean, null, list or map - - MapValue value: - - If parameter's entity type is a - composite entity: map from composite - entity property names to property values - - Else: parameter value - language_code (str): - Required. The language of this query. See `Language - Support `__ - for a list of the currently supported language codes. Note - that queries in the same session do not necessarily need to - specify the same language. - - This field is ignored when used in the context of a - [WebhookResponse.followup_event_input][google.cloud.dialogflow.v2.WebhookResponse.followup_event_input] - field, because the language was already defined in the - originating detect intent request. - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - parameters: struct_pb2.Struct = proto.Field( - proto.MESSAGE, - number=2, - message=struct_pb2.Struct, - ) - language_code: str = 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 - ``query_text``. If not provided, sentiment analysis is not - performed on ``query_text``. - """ - - analyze_query_text_sentiment: bool = proto.Field( - proto.BOOL, - number=1, - ) - - -class SentimentAnalysisResult(proto.Message): - r"""The result of sentiment analysis. Sentiment analysis inspects user - input and identifies the prevailing subjective opinion, especially - to determine a user's attitude as positive, negative, or neutral. - For [Participants.DetectIntent][], it needs to be configured in - [DetectIntentRequest.query_params][google.cloud.dialogflow.v2.DetectIntentRequest.query_params]. - For [Participants.StreamingDetectIntent][], it needs to be - configured in - [StreamingDetectIntentRequest.query_params][google.cloud.dialogflow.v2.StreamingDetectIntentRequest.query_params]. - And for - [Participants.AnalyzeContent][google.cloud.dialogflow.v2.Participants.AnalyzeContent] - and - [Participants.StreamingAnalyzeContent][google.cloud.dialogflow.v2.Participants.StreamingAnalyzeContent], - it needs to be configured in - [ConversationProfile.human_agent_assistant_config][google.cloud.dialogflow.v2.ConversationProfile.human_agent_assistant_config] - - Attributes: - query_text_sentiment (google.cloud.dialogflow_v2.types.Sentiment): - The sentiment analysis result for ``query_text``. - """ - - query_text_sentiment: 'Sentiment' = proto.Field( - proto.MESSAGE, - number=1, - message='Sentiment', - ) - - -class Sentiment(proto.Message): - r"""The sentiment, such as positive/negative feeling or association, for - a unit of analysis, such as the query text. See: - https://cloud.google.com/natural-language/docs/basics#interpreting_sentiment_analysis_values - for how to interpret the result. - - Attributes: - score (float): - Sentiment score between -1.0 (negative - sentiment) and 1.0 (positive sentiment). - magnitude (float): - A non-negative number in the [0, +inf) range, which - represents the absolute magnitude of sentiment, regardless - of score (positive or negative). - """ - - score: float = proto.Field( - proto.FLOAT, - number=1, - ) - magnitude: float = proto.Field( - proto.FLOAT, - number=2, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v2/google/cloud/dialogflow_v2/types/session_entity_type.py b/owl-bot-staging/v2/google/cloud/dialogflow_v2/types/session_entity_type.py deleted file mode 100644 index 63235ac97..000000000 --- a/owl-bot-staging/v2/google/cloud/dialogflow_v2/types/session_entity_type.py +++ /dev/null @@ -1,277 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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 __future__ import annotations - -from typing import MutableMapping, MutableSequence - -import proto # type: ignore - -from google.cloud.dialogflow_v2.types import entity_type -from google.protobuf import field_mask_pb2 # type: ignore - - -__protobuf__ = proto.module( - package='google.cloud.dialogflow.v2', - manifest={ - 'SessionEntityType', - 'ListSessionEntityTypesRequest', - 'ListSessionEntityTypesResponse', - 'GetSessionEntityTypeRequest', - 'CreateSessionEntityTypeRequest', - 'UpdateSessionEntityTypeRequest', - 'DeleteSessionEntityTypeRequest', - }, -) - - -class SessionEntityType(proto.Message): - r"""A session represents a conversation between a Dialogflow agent and - an end-user. You can create special entities, called session - entities, during a session. Session entities can extend or replace - custom entity types and only exist during the session that they were - created for. All session data, including session entities, is stored - by Dialogflow for 20 minutes. - - For more information, see the `session entity - guide `__. - - Attributes: - name (str): - Required. The unique identifier of this session entity type. - Format: - ``projects//agent/sessions//entityTypes/``, - or - ``projects//agent/environments//users//sessions//entityTypes/``. - If ``Environment ID`` is not specified, we assume default - 'draft' environment. If ``User ID`` is not specified, we - assume default '-' user. - - ```` must be the display name of - an existing entity type in the same agent that will be - overridden or supplemented. - entity_override_mode (google.cloud.dialogflow_v2.types.SessionEntityType.EntityOverrideMode): - Required. Indicates whether the additional - data should override or supplement the custom - entity type definition. - entities (MutableSequence[google.cloud.dialogflow_v2.types.EntityType.Entity]): - Required. The collection of entities - associated with this session entity type. - """ - class EntityOverrideMode(proto.Enum): - r"""The types of modifications for a session entity type. - - Values: - ENTITY_OVERRIDE_MODE_UNSPECIFIED (0): - Not specified. This value should be never - used. - ENTITY_OVERRIDE_MODE_OVERRIDE (1): - The collection of session entities overrides - the collection of entities in the corresponding - custom entity type. - ENTITY_OVERRIDE_MODE_SUPPLEMENT (2): - The collection of session entities extends the collection of - entities in the corresponding custom entity type. - - Note: Even in this override mode calls to - ``ListSessionEntityTypes``, ``GetSessionEntityType``, - ``CreateSessionEntityType`` and ``UpdateSessionEntityType`` - only return the additional entities added in this session - entity type. If you want to get the supplemented list, - please call - [EntityTypes.GetEntityType][google.cloud.dialogflow.v2.EntityTypes.GetEntityType] - on the custom entity type and merge. - """ - ENTITY_OVERRIDE_MODE_UNSPECIFIED = 0 - ENTITY_OVERRIDE_MODE_OVERRIDE = 1 - ENTITY_OVERRIDE_MODE_SUPPLEMENT = 2 - - name: str = proto.Field( - proto.STRING, - number=1, - ) - entity_override_mode: EntityOverrideMode = proto.Field( - proto.ENUM, - number=2, - enum=EntityOverrideMode, - ) - entities: MutableSequence[entity_type.EntityType.Entity] = proto.RepeatedField( - proto.MESSAGE, - number=3, - message=entity_type.EntityType.Entity, - ) - - -class ListSessionEntityTypesRequest(proto.Message): - r"""The request message for - [SessionEntityTypes.ListSessionEntityTypes][google.cloud.dialogflow.v2.SessionEntityTypes.ListSessionEntityTypes]. - - Attributes: - parent (str): - Required. The session to list all session entity types from. - Format: - ``projects//agent/sessions/`` or - ``projects//agent/environments//users// sessions/``. - If ``Environment ID`` is not specified, we assume default - 'draft' environment. If ``User ID`` is not specified, we - assume default '-' user. - 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: str = proto.Field( - proto.STRING, - number=1, - ) - page_size: int = proto.Field( - proto.INT32, - number=2, - ) - page_token: str = proto.Field( - proto.STRING, - number=3, - ) - - -class ListSessionEntityTypesResponse(proto.Message): - r"""The response message for - [SessionEntityTypes.ListSessionEntityTypes][google.cloud.dialogflow.v2.SessionEntityTypes.ListSessionEntityTypes]. - - Attributes: - session_entity_types (MutableSequence[google.cloud.dialogflow_v2.types.SessionEntityType]): - The list of session entity types. 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 - - session_entity_types: MutableSequence['SessionEntityType'] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message='SessionEntityType', - ) - next_page_token: str = proto.Field( - proto.STRING, - number=2, - ) - - -class GetSessionEntityTypeRequest(proto.Message): - r"""The request message for - [SessionEntityTypes.GetSessionEntityType][google.cloud.dialogflow.v2.SessionEntityTypes.GetSessionEntityType]. - - Attributes: - name (str): - Required. The name of the session entity type. Format: - ``projects//agent/sessions//entityTypes/`` - or - ``projects//agent/environments//users//sessions//entityTypes/``. - If ``Environment ID`` is not specified, we assume default - 'draft' environment. If ``User ID`` is not specified, we - assume default '-' user. - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - - -class CreateSessionEntityTypeRequest(proto.Message): - r"""The request message for - [SessionEntityTypes.CreateSessionEntityType][google.cloud.dialogflow.v2.SessionEntityTypes.CreateSessionEntityType]. - - Attributes: - parent (str): - Required. The session to create a session entity type for. - Format: - ``projects//agent/sessions/`` or - ``projects//agent/environments//users// sessions/``. - If ``Environment ID`` is not specified, we assume default - 'draft' environment. If ``User ID`` is not specified, we - assume default '-' user. - session_entity_type (google.cloud.dialogflow_v2.types.SessionEntityType): - Required. The session entity type to create. - """ - - parent: str = proto.Field( - proto.STRING, - number=1, - ) - session_entity_type: 'SessionEntityType' = proto.Field( - proto.MESSAGE, - number=2, - message='SessionEntityType', - ) - - -class UpdateSessionEntityTypeRequest(proto.Message): - r"""The request message for - [SessionEntityTypes.UpdateSessionEntityType][google.cloud.dialogflow.v2.SessionEntityTypes.UpdateSessionEntityType]. - - Attributes: - session_entity_type (google.cloud.dialogflow_v2.types.SessionEntityType): - Required. The session entity type to update. - update_mask (google.protobuf.field_mask_pb2.FieldMask): - Optional. The mask to control which fields - get updated. - """ - - session_entity_type: 'SessionEntityType' = proto.Field( - proto.MESSAGE, - number=1, - message='SessionEntityType', - ) - update_mask: field_mask_pb2.FieldMask = proto.Field( - proto.MESSAGE, - number=2, - message=field_mask_pb2.FieldMask, - ) - - -class DeleteSessionEntityTypeRequest(proto.Message): - r"""The request message for - [SessionEntityTypes.DeleteSessionEntityType][google.cloud.dialogflow.v2.SessionEntityTypes.DeleteSessionEntityType]. - - Attributes: - name (str): - Required. The name of the entity type to delete. Format: - ``projects//agent/sessions//entityTypes/`` - or - ``projects//agent/environments//users//sessions//entityTypes/``. - If ``Environment ID`` is not specified, we assume default - 'draft' environment. If ``User ID`` is not specified, we - assume default '-' user. - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v2/google/cloud/dialogflow_v2/types/validation_result.py b/owl-bot-staging/v2/google/cloud/dialogflow_v2/types/validation_result.py deleted file mode 100644 index 010e40386..000000000 --- a/owl-bot-staging/v2/google/cloud/dialogflow_v2/types/validation_result.py +++ /dev/null @@ -1,114 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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 __future__ import annotations - -from typing import MutableMapping, MutableSequence - -import proto # type: ignore - - -__protobuf__ = proto.module( - package='google.cloud.dialogflow.v2', - manifest={ - 'ValidationError', - 'ValidationResult', - }, -) - - -class ValidationError(proto.Message): - r"""Represents a single validation error. - - Attributes: - severity (google.cloud.dialogflow_v2.types.ValidationError.Severity): - The severity of the error. - entries (MutableSequence[str]): - The names of the entries that the error is - associated with. Format: - - - "projects//agent", if the error is - associated with the entire agent. - - "projects//agent/intents/", if the error is associated with certain - intents. - - "projects//agent/intents//trainingPhrases/", if - the error is associated with certain intent - training phrases. - "projects//agent/intents//parameters/", if the error is - associated with certain intent parameters. - - "projects//agent/entities/", if the error is associated with certain - entities. - error_message (str): - The detailed error message. - """ - class Severity(proto.Enum): - r"""Represents a level of severity. - - Values: - SEVERITY_UNSPECIFIED (0): - Not specified. This value should never be - used. - INFO (1): - The agent doesn't follow Dialogflow best - practices. - WARNING (2): - The agent may not behave as expected. - ERROR (3): - The agent may experience partial failures. - CRITICAL (4): - The agent may completely fail. - """ - SEVERITY_UNSPECIFIED = 0 - INFO = 1 - WARNING = 2 - ERROR = 3 - CRITICAL = 4 - - severity: Severity = proto.Field( - proto.ENUM, - number=1, - enum=Severity, - ) - entries: MutableSequence[str] = proto.RepeatedField( - proto.STRING, - number=3, - ) - error_message: str = proto.Field( - proto.STRING, - number=4, - ) - - -class ValidationResult(proto.Message): - r"""Represents the output of agent validation. - - Attributes: - validation_errors (MutableSequence[google.cloud.dialogflow_v2.types.ValidationError]): - Contains all validation errors. - """ - - validation_errors: MutableSequence['ValidationError'] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message='ValidationError', - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v2/google/cloud/dialogflow_v2/types/version.py b/owl-bot-staging/v2/google/cloud/dialogflow_v2/types/version.py deleted file mode 100644 index 41f93f691..000000000 --- a/owl-bot-staging/v2/google/cloud/dialogflow_v2/types/version.py +++ /dev/null @@ -1,281 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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 __future__ import annotations - -from typing import MutableMapping, MutableSequence - -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. - - Values: - VERSION_STATUS_UNSPECIFIED (0): - Not specified. This value is not used. - IN_PROGRESS (1): - Version is not ready to serve (e.g. training - is in progress). - READY (2): - Version is ready to serve. - FAILED (3): - Version training failed. - """ - VERSION_STATUS_UNSPECIFIED = 0 - IN_PROGRESS = 1 - READY = 2 - FAILED = 3 - - name: str = proto.Field( - proto.STRING, - number=1, - ) - description: str = proto.Field( - proto.STRING, - number=2, - ) - version_number: int = proto.Field( - proto.INT32, - number=3, - ) - create_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=4, - message=timestamp_pb2.Timestamp, - ) - status: VersionStatus = 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: str = proto.Field( - proto.STRING, - number=1, - ) - page_size: int = proto.Field( - proto.INT32, - number=2, - ) - page_token: str = 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 (MutableSequence[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: MutableSequence['Version'] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message='Version', - ) - next_page_token: str = 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: str = 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: str = proto.Field( - proto.STRING, - number=1, - ) - version: '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: 'Version' = proto.Field( - proto.MESSAGE, - number=1, - message='Version', - ) - update_mask: field_mask_pb2.FieldMask = 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: str = proto.Field( - proto.STRING, - number=1, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v2/google/cloud/dialogflow_v2/types/webhook.py b/owl-bot-staging/v2/google/cloud/dialogflow_v2/types/webhook.py deleted file mode 100644 index 2cf383737..000000000 --- a/owl-bot-staging/v2/google/cloud/dialogflow_v2/types/webhook.py +++ /dev/null @@ -1,235 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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 __future__ import annotations - -from typing import MutableMapping, MutableSequence - -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 # type: ignore - - -__protobuf__ = proto.module( - package='google.cloud.dialogflow.v2', - manifest={ - 'WebhookRequest', - 'WebhookResponse', - 'OriginalDetectIntentRequest', - }, -) - - -class WebhookRequest(proto.Message): - r"""The request message for a webhook call. - - Attributes: - session (str): - The unique identifier of detectIntent request session. Can - be used to identify end-user inside webhook implementation. - Format: - ``projects//agent/sessions/``, or - ``projects//agent/environments//users//sessions/``. - response_id (str): - The unique identifier of the response. Contains the same - value as ``[Streaming]DetectIntentResponse.response_id``. - query_result (google.cloud.dialogflow_v2.types.QueryResult): - The result of the conversational query or event processing. - Contains the same value as - ``[Streaming]DetectIntentResponse.query_result``. - original_detect_intent_request (google.cloud.dialogflow_v2.types.OriginalDetectIntentRequest): - Optional. The contents of the original request that was - passed to ``[Streaming]DetectIntent`` call. - """ - - session: str = proto.Field( - proto.STRING, - number=4, - ) - response_id: str = proto.Field( - proto.STRING, - number=1, - ) - query_result: gcd_session.QueryResult = proto.Field( - proto.MESSAGE, - number=2, - message=gcd_session.QueryResult, - ) - original_detect_intent_request: 'OriginalDetectIntentRequest' = proto.Field( - proto.MESSAGE, - number=3, - message='OriginalDetectIntentRequest', - ) - - -class WebhookResponse(proto.Message): - r"""The response message for a webhook call. - - This response is validated by the Dialogflow server. If validation - fails, an error will be returned in the - [QueryResult.diagnostic_info][google.cloud.dialogflow.v2.QueryResult.diagnostic_info] - field. Setting JSON fields to an empty value with the wrong type is - a common error. To avoid this error: - - - Use ``""`` for empty strings - - Use ``{}`` or ``null`` for empty objects - - Use ``[]`` or ``null`` for empty arrays - - For more information, see the `Protocol Buffers Language - Guide `__. - - Attributes: - fulfillment_text (str): - Optional. The text response message intended for the - end-user. It is recommended to use - ``fulfillment_messages.text.text[0]`` instead. When - provided, Dialogflow uses this field to populate - [QueryResult.fulfillment_text][google.cloud.dialogflow.v2.QueryResult.fulfillment_text] - sent to the integration or API caller. - fulfillment_messages (MutableSequence[google.cloud.dialogflow_v2.types.Intent.Message]): - Optional. The rich response messages intended for the - end-user. When provided, Dialogflow uses this field to - populate - [QueryResult.fulfillment_messages][google.cloud.dialogflow.v2.QueryResult.fulfillment_messages] - sent to the integration or API caller. - source (str): - Optional. A custom field used to identify the webhook - source. Arbitrary strings are supported. When provided, - Dialogflow uses this field to populate - [QueryResult.webhook_source][google.cloud.dialogflow.v2.QueryResult.webhook_source] - sent to the integration or API caller. - payload (google.protobuf.struct_pb2.Struct): - Optional. This field can be used to pass custom data from - your webhook to the integration or API caller. Arbitrary - JSON objects are supported. When provided, Dialogflow uses - this field to populate - [QueryResult.webhook_payload][google.cloud.dialogflow.v2.QueryResult.webhook_payload] - sent to the integration or API caller. This field is also - used by the `Google Assistant - integration `__ - for rich response messages. See the format definition at - `Google Assistant Dialogflow webhook - format `__ - output_contexts (MutableSequence[google.cloud.dialogflow_v2.types.Context]): - Optional. The collection of output contexts that will - overwrite currently active contexts for the session and - reset their lifespans. When provided, Dialogflow uses this - field to populate - [QueryResult.output_contexts][google.cloud.dialogflow.v2.QueryResult.output_contexts] - sent to the integration or API caller. - followup_event_input (google.cloud.dialogflow_v2.types.EventInput): - Optional. Invokes the supplied events. When this field is - set, Dialogflow ignores the ``fulfillment_text``, - ``fulfillment_messages``, and ``payload`` fields. - session_entity_types (MutableSequence[google.cloud.dialogflow_v2.types.SessionEntityType]): - Optional. Additional session entity types to replace or - extend developer entity types with. The entity synonyms - apply to all languages and persist for the session. Setting - this data from a webhook overwrites the session entity types - that have been set using ``detectIntent``, - ``streamingDetectIntent`` or - [SessionEntityType][google.cloud.dialogflow.v2.SessionEntityType] - management methods. - """ - - fulfillment_text: str = proto.Field( - proto.STRING, - number=1, - ) - fulfillment_messages: MutableSequence[intent.Intent.Message] = proto.RepeatedField( - proto.MESSAGE, - number=2, - message=intent.Intent.Message, - ) - source: str = proto.Field( - proto.STRING, - number=3, - ) - payload: struct_pb2.Struct = proto.Field( - proto.MESSAGE, - number=4, - message=struct_pb2.Struct, - ) - output_contexts: MutableSequence[context.Context] = proto.RepeatedField( - proto.MESSAGE, - number=5, - message=context.Context, - ) - followup_event_input: gcd_session.EventInput = proto.Field( - proto.MESSAGE, - number=6, - message=gcd_session.EventInput, - ) - session_entity_types: MutableSequence[session_entity_type.SessionEntityType] = proto.RepeatedField( - proto.MESSAGE, - number=10, - message=session_entity_type.SessionEntityType, - ) - - -class OriginalDetectIntentRequest(proto.Message): - r"""Represents the contents of the original request that was passed to - the ``[Streaming]DetectIntent`` call. - - Attributes: - source (str): - The source of this request, e.g., ``google``, ``facebook``, - ``slack``. It is set by Dialogflow-owned servers. - version (str): - Optional. The version of the protocol used - for this request. This field is AoG-specific. - payload (google.protobuf.struct_pb2.Struct): - Optional. This field is set to the value of the - ``QueryParameters.payload`` field passed in the request. - Some integrations that query a Dialogflow agent may provide - additional information in the payload. - - In particular, for the Dialogflow Phone Gateway integration, - this field has the form: - - .. raw:: html - -
{
-                 "telephony": {
-                   "caller_id": "+18558363987"
-                 }
-                }
- - Note: The caller ID field (``caller_id``) will be redacted - for Trial Edition agents and populated with the caller ID in - `E.164 format `__ for - Essentials Edition agents. - """ - - source: str = proto.Field( - proto.STRING, - number=1, - ) - version: str = proto.Field( - proto.STRING, - number=2, - ) - payload: struct_pb2.Struct = proto.Field( - proto.MESSAGE, - number=3, - message=struct_pb2.Struct, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v2/mypy.ini b/owl-bot-staging/v2/mypy.ini deleted file mode 100644 index 574c5aed3..000000000 --- a/owl-bot-staging/v2/mypy.ini +++ /dev/null @@ -1,3 +0,0 @@ -[mypy] -python_version = 3.7 -namespace_packages = True diff --git a/owl-bot-staging/v2/noxfile.py b/owl-bot-staging/v2/noxfile.py deleted file mode 100644 index a8e47e8c2..000000000 --- a/owl-bot-staging/v2/noxfile.py +++ /dev/null @@ -1,184 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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 pathlib -import shutil -import subprocess -import sys - - -import nox # type: ignore - -ALL_PYTHON = [ - "3.7", - "3.8", - "3.9", - "3.10", - "3.11", -] - -CURRENT_DIRECTORY = pathlib.Path(__file__).parent.absolute() - -LOWER_BOUND_CONSTRAINTS_FILE = CURRENT_DIRECTORY / "constraints.txt" -PACKAGE_NAME = subprocess.check_output([sys.executable, "setup.py", "--name"], encoding="utf-8") - -BLACK_VERSION = "black==22.3.0" -BLACK_PATHS = ["docs", "google", "tests", "samples", "noxfile.py", "setup.py"] -DEFAULT_PYTHON_VERSION = "3.11" - -nox.sessions = [ - "unit", - "cover", - "mypy", - "check_lower_bounds" - # exclude update_lower_bounds from default - "docs", - "blacken", - "lint", - "lint_setup_py", -] - -@nox.session(python=ALL_PYTHON) -def unit(session): - """Run the unit test suite.""" - - session.install('coverage', 'pytest', 'pytest-cov', 'pytest-asyncio', 'asyncmock; python_version < "3.8"') - session.install('-e', '.') - - session.run( - 'py.test', - '--quiet', - '--cov=google/cloud/dialogflow_v2/', - '--cov=tests/', - '--cov-config=.coveragerc', - '--cov-report=term', - '--cov-report=html', - os.path.join('tests', 'unit', ''.join(session.posargs)) - ) - - -@nox.session(python=DEFAULT_PYTHON_VERSION) -def cover(session): - """Run the final coverage report. - This outputs the coverage report aggregating coverage from the unit - test runs (not system test runs), and then erases coverage data. - """ - session.install("coverage", "pytest-cov") - session.run("coverage", "report", "--show-missing", "--fail-under=100") - - session.run("coverage", "erase") - - -@nox.session(python=ALL_PYTHON) -def mypy(session): - """Run the type checker.""" - session.install( - 'mypy', - 'types-requests', - 'types-protobuf' - ) - session.install('.') - session.run( - 'mypy', - '--explicit-package-bases', - 'google', - ) - - -@nox.session -def update_lower_bounds(session): - """Update lower bounds in constraints.txt to match setup.py""" - session.install('google-cloud-testutils') - session.install('.') - - session.run( - 'lower-bound-checker', - 'update', - '--package-name', - PACKAGE_NAME, - '--constraints-file', - str(LOWER_BOUND_CONSTRAINTS_FILE), - ) - - -@nox.session -def check_lower_bounds(session): - """Check lower bounds in setup.py are reflected in constraints file""" - session.install('google-cloud-testutils') - session.install('.') - - session.run( - 'lower-bound-checker', - 'check', - '--package-name', - PACKAGE_NAME, - '--constraints-file', - str(LOWER_BOUND_CONSTRAINTS_FILE), - ) - -@nox.session(python=DEFAULT_PYTHON_VERSION) -def docs(session): - """Build the docs for this library.""" - - session.install("-e", ".") - session.install("sphinx==4.0.1", "alabaster", "recommonmark") - - shutil.rmtree(os.path.join("docs", "_build"), ignore_errors=True) - session.run( - "sphinx-build", - "-W", # warnings as errors - "-T", # show full traceback on exception - "-N", # no colors - "-b", - "html", - "-d", - os.path.join("docs", "_build", "doctrees", ""), - os.path.join("docs", ""), - os.path.join("docs", "_build", "html", ""), - ) - - -@nox.session(python=DEFAULT_PYTHON_VERSION) -def lint(session): - """Run linters. - - Returns a failure if the linters find linting errors or sufficiently - serious code quality issues. - """ - session.install("flake8", BLACK_VERSION) - session.run( - "black", - "--check", - *BLACK_PATHS, - ) - session.run("flake8", "google", "tests", "samples") - - -@nox.session(python=DEFAULT_PYTHON_VERSION) -def blacken(session): - """Run black. Format code to uniform standard.""" - session.install(BLACK_VERSION) - session.run( - "black", - *BLACK_PATHS, - ) - - -@nox.session(python=DEFAULT_PYTHON_VERSION) -def lint_setup_py(session): - """Verify that setup.py is valid (including RST check).""" - session.install("docutils", "pygments") - session.run("python", "setup.py", "check", "--restructuredtext", "--strict") diff --git a/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_agents_delete_agent_async.py b/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_agents_delete_agent_async.py deleted file mode 100644 index b1720dfe6..000000000 --- a/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_agents_delete_agent_async.py +++ /dev/null @@ -1,50 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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. -# -# Generated code. DO NOT EDIT! -# -# Snippet for DeleteAgent -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-dialogflow - - -# [START dialogflow_v2_generated_Agents_DeleteAgent_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import dialogflow_v2 - - -async def sample_delete_agent(): - # Create a client - client = dialogflow_v2.AgentsAsyncClient() - - # Initialize request argument(s) - request = dialogflow_v2.DeleteAgentRequest( - parent="parent_value", - ) - - # Make the request - await client.delete_agent(request=request) - - -# [END dialogflow_v2_generated_Agents_DeleteAgent_async] diff --git a/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_agents_delete_agent_sync.py b/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_agents_delete_agent_sync.py deleted file mode 100644 index cdaf06329..000000000 --- a/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_agents_delete_agent_sync.py +++ /dev/null @@ -1,50 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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. -# -# Generated code. DO NOT EDIT! -# -# Snippet for DeleteAgent -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-dialogflow - - -# [START dialogflow_v2_generated_Agents_DeleteAgent_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import dialogflow_v2 - - -def sample_delete_agent(): - # Create a client - client = dialogflow_v2.AgentsClient() - - # Initialize request argument(s) - request = dialogflow_v2.DeleteAgentRequest( - parent="parent_value", - ) - - # Make the request - client.delete_agent(request=request) - - -# [END dialogflow_v2_generated_Agents_DeleteAgent_sync] diff --git a/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_agents_export_agent_async.py b/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_agents_export_agent_async.py deleted file mode 100644 index d6d2572cf..000000000 --- a/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_agents_export_agent_async.py +++ /dev/null @@ -1,57 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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. -# -# Generated code. DO NOT EDIT! -# -# Snippet for ExportAgent -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-dialogflow - - -# [START dialogflow_v2_generated_Agents_ExportAgent_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import dialogflow_v2 - - -async def sample_export_agent(): - # Create a client - client = dialogflow_v2.AgentsAsyncClient() - - # Initialize request argument(s) - request = dialogflow_v2.ExportAgentRequest( - parent="parent_value", - agent_uri="agent_uri_value", - ) - - # Make the request - operation = client.export_agent(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - -# [END dialogflow_v2_generated_Agents_ExportAgent_async] diff --git a/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_agents_export_agent_sync.py b/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_agents_export_agent_sync.py deleted file mode 100644 index a30e991d7..000000000 --- a/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_agents_export_agent_sync.py +++ /dev/null @@ -1,57 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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. -# -# Generated code. DO NOT EDIT! -# -# Snippet for ExportAgent -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-dialogflow - - -# [START dialogflow_v2_generated_Agents_ExportAgent_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import dialogflow_v2 - - -def sample_export_agent(): - # Create a client - client = dialogflow_v2.AgentsClient() - - # Initialize request argument(s) - request = dialogflow_v2.ExportAgentRequest( - parent="parent_value", - agent_uri="agent_uri_value", - ) - - # Make the request - operation = client.export_agent(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - -# [END dialogflow_v2_generated_Agents_ExportAgent_sync] diff --git a/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_agents_get_agent_async.py b/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_agents_get_agent_async.py deleted file mode 100644 index 586fbb434..000000000 --- a/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_agents_get_agent_async.py +++ /dev/null @@ -1,52 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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. -# -# Generated code. DO NOT EDIT! -# -# Snippet for GetAgent -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-dialogflow - - -# [START dialogflow_v2_generated_Agents_GetAgent_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import dialogflow_v2 - - -async def sample_get_agent(): - # Create a client - client = dialogflow_v2.AgentsAsyncClient() - - # Initialize request argument(s) - request = dialogflow_v2.GetAgentRequest( - parent="parent_value", - ) - - # Make the request - response = await client.get_agent(request=request) - - # Handle the response - print(response) - -# [END dialogflow_v2_generated_Agents_GetAgent_async] diff --git a/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_agents_get_agent_sync.py b/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_agents_get_agent_sync.py deleted file mode 100644 index d47cd8e7f..000000000 --- a/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_agents_get_agent_sync.py +++ /dev/null @@ -1,52 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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. -# -# Generated code. DO NOT EDIT! -# -# Snippet for GetAgent -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-dialogflow - - -# [START dialogflow_v2_generated_Agents_GetAgent_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import dialogflow_v2 - - -def sample_get_agent(): - # Create a client - client = dialogflow_v2.AgentsClient() - - # Initialize request argument(s) - request = dialogflow_v2.GetAgentRequest( - parent="parent_value", - ) - - # Make the request - response = client.get_agent(request=request) - - # Handle the response - print(response) - -# [END dialogflow_v2_generated_Agents_GetAgent_sync] diff --git a/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_agents_get_validation_result_async.py b/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_agents_get_validation_result_async.py deleted file mode 100644 index ad40d98cc..000000000 --- a/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_agents_get_validation_result_async.py +++ /dev/null @@ -1,52 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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. -# -# Generated code. DO NOT EDIT! -# -# Snippet for GetValidationResult -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-dialogflow - - -# [START dialogflow_v2_generated_Agents_GetValidationResult_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import dialogflow_v2 - - -async def sample_get_validation_result(): - # Create a client - client = dialogflow_v2.AgentsAsyncClient() - - # Initialize request argument(s) - request = dialogflow_v2.GetValidationResultRequest( - parent="parent_value", - ) - - # Make the request - response = await client.get_validation_result(request=request) - - # Handle the response - print(response) - -# [END dialogflow_v2_generated_Agents_GetValidationResult_async] diff --git a/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_agents_get_validation_result_sync.py b/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_agents_get_validation_result_sync.py deleted file mode 100644 index 1a7410122..000000000 --- a/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_agents_get_validation_result_sync.py +++ /dev/null @@ -1,52 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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. -# -# Generated code. DO NOT EDIT! -# -# Snippet for GetValidationResult -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-dialogflow - - -# [START dialogflow_v2_generated_Agents_GetValidationResult_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import dialogflow_v2 - - -def sample_get_validation_result(): - # Create a client - client = dialogflow_v2.AgentsClient() - - # Initialize request argument(s) - request = dialogflow_v2.GetValidationResultRequest( - parent="parent_value", - ) - - # Make the request - response = client.get_validation_result(request=request) - - # Handle the response - print(response) - -# [END dialogflow_v2_generated_Agents_GetValidationResult_sync] diff --git a/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_agents_import_agent_async.py b/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_agents_import_agent_async.py deleted file mode 100644 index c594d17db..000000000 --- a/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_agents_import_agent_async.py +++ /dev/null @@ -1,57 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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. -# -# Generated code. DO NOT EDIT! -# -# Snippet for ImportAgent -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-dialogflow - - -# [START dialogflow_v2_generated_Agents_ImportAgent_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import dialogflow_v2 - - -async def sample_import_agent(): - # Create a client - client = dialogflow_v2.AgentsAsyncClient() - - # Initialize request argument(s) - request = dialogflow_v2.ImportAgentRequest( - agent_uri="agent_uri_value", - parent="parent_value", - ) - - # Make the request - operation = client.import_agent(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - -# [END dialogflow_v2_generated_Agents_ImportAgent_async] diff --git a/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_agents_import_agent_sync.py b/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_agents_import_agent_sync.py deleted file mode 100644 index daf93bbc3..000000000 --- a/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_agents_import_agent_sync.py +++ /dev/null @@ -1,57 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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. -# -# Generated code. DO NOT EDIT! -# -# Snippet for ImportAgent -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-dialogflow - - -# [START dialogflow_v2_generated_Agents_ImportAgent_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import dialogflow_v2 - - -def sample_import_agent(): - # Create a client - client = dialogflow_v2.AgentsClient() - - # Initialize request argument(s) - request = dialogflow_v2.ImportAgentRequest( - agent_uri="agent_uri_value", - parent="parent_value", - ) - - # Make the request - operation = client.import_agent(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - -# [END dialogflow_v2_generated_Agents_ImportAgent_sync] diff --git a/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_agents_restore_agent_async.py b/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_agents_restore_agent_async.py deleted file mode 100644 index 50a371adc..000000000 --- a/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_agents_restore_agent_async.py +++ /dev/null @@ -1,57 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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. -# -# Generated code. DO NOT EDIT! -# -# Snippet for RestoreAgent -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-dialogflow - - -# [START dialogflow_v2_generated_Agents_RestoreAgent_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import dialogflow_v2 - - -async def sample_restore_agent(): - # Create a client - client = dialogflow_v2.AgentsAsyncClient() - - # Initialize request argument(s) - request = dialogflow_v2.RestoreAgentRequest( - agent_uri="agent_uri_value", - parent="parent_value", - ) - - # Make the request - operation = client.restore_agent(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - -# [END dialogflow_v2_generated_Agents_RestoreAgent_async] diff --git a/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_agents_restore_agent_sync.py b/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_agents_restore_agent_sync.py deleted file mode 100644 index 3dbab5e48..000000000 --- a/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_agents_restore_agent_sync.py +++ /dev/null @@ -1,57 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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. -# -# Generated code. DO NOT EDIT! -# -# Snippet for RestoreAgent -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-dialogflow - - -# [START dialogflow_v2_generated_Agents_RestoreAgent_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import dialogflow_v2 - - -def sample_restore_agent(): - # Create a client - client = dialogflow_v2.AgentsClient() - - # Initialize request argument(s) - request = dialogflow_v2.RestoreAgentRequest( - agent_uri="agent_uri_value", - parent="parent_value", - ) - - # Make the request - operation = client.restore_agent(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - -# [END dialogflow_v2_generated_Agents_RestoreAgent_sync] diff --git a/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_agents_search_agents_async.py b/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_agents_search_agents_async.py deleted file mode 100644 index 785888393..000000000 --- a/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_agents_search_agents_async.py +++ /dev/null @@ -1,53 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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. -# -# Generated code. DO NOT EDIT! -# -# Snippet for SearchAgents -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-dialogflow - - -# [START dialogflow_v2_generated_Agents_SearchAgents_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import dialogflow_v2 - - -async def sample_search_agents(): - # Create a client - client = dialogflow_v2.AgentsAsyncClient() - - # Initialize request argument(s) - request = dialogflow_v2.SearchAgentsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.search_agents(request=request) - - # Handle the response - async for response in page_result: - print(response) - -# [END dialogflow_v2_generated_Agents_SearchAgents_async] diff --git a/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_agents_search_agents_sync.py b/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_agents_search_agents_sync.py deleted file mode 100644 index 618afc8b8..000000000 --- a/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_agents_search_agents_sync.py +++ /dev/null @@ -1,53 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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. -# -# Generated code. DO NOT EDIT! -# -# Snippet for SearchAgents -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-dialogflow - - -# [START dialogflow_v2_generated_Agents_SearchAgents_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import dialogflow_v2 - - -def sample_search_agents(): - # Create a client - client = dialogflow_v2.AgentsClient() - - # Initialize request argument(s) - request = dialogflow_v2.SearchAgentsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.search_agents(request=request) - - # Handle the response - for response in page_result: - print(response) - -# [END dialogflow_v2_generated_Agents_SearchAgents_sync] diff --git a/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_agents_set_agent_async.py b/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_agents_set_agent_async.py deleted file mode 100644 index 537865dab..000000000 --- a/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_agents_set_agent_async.py +++ /dev/null @@ -1,58 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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. -# -# Generated code. DO NOT EDIT! -# -# Snippet for SetAgent -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-dialogflow - - -# [START dialogflow_v2_generated_Agents_SetAgent_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import dialogflow_v2 - - -async def sample_set_agent(): - # Create a client - client = dialogflow_v2.AgentsAsyncClient() - - # Initialize request argument(s) - agent = dialogflow_v2.Agent() - agent.parent = "parent_value" - agent.display_name = "display_name_value" - agent.default_language_code = "default_language_code_value" - agent.time_zone = "time_zone_value" - - request = dialogflow_v2.SetAgentRequest( - agent=agent, - ) - - # Make the request - response = await client.set_agent(request=request) - - # Handle the response - print(response) - -# [END dialogflow_v2_generated_Agents_SetAgent_async] diff --git a/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_agents_set_agent_sync.py b/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_agents_set_agent_sync.py deleted file mode 100644 index 1097964a0..000000000 --- a/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_agents_set_agent_sync.py +++ /dev/null @@ -1,58 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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. -# -# Generated code. DO NOT EDIT! -# -# Snippet for SetAgent -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-dialogflow - - -# [START dialogflow_v2_generated_Agents_SetAgent_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import dialogflow_v2 - - -def sample_set_agent(): - # Create a client - client = dialogflow_v2.AgentsClient() - - # Initialize request argument(s) - agent = dialogflow_v2.Agent() - agent.parent = "parent_value" - agent.display_name = "display_name_value" - agent.default_language_code = "default_language_code_value" - agent.time_zone = "time_zone_value" - - request = dialogflow_v2.SetAgentRequest( - agent=agent, - ) - - # Make the request - response = client.set_agent(request=request) - - # Handle the response - print(response) - -# [END dialogflow_v2_generated_Agents_SetAgent_sync] diff --git a/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_agents_train_agent_async.py b/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_agents_train_agent_async.py deleted file mode 100644 index 841058307..000000000 --- a/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_agents_train_agent_async.py +++ /dev/null @@ -1,56 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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. -# -# Generated code. DO NOT EDIT! -# -# Snippet for TrainAgent -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-dialogflow - - -# [START dialogflow_v2_generated_Agents_TrainAgent_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import dialogflow_v2 - - -async def sample_train_agent(): - # Create a client - client = dialogflow_v2.AgentsAsyncClient() - - # Initialize request argument(s) - request = dialogflow_v2.TrainAgentRequest( - parent="parent_value", - ) - - # Make the request - operation = client.train_agent(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - -# [END dialogflow_v2_generated_Agents_TrainAgent_async] diff --git a/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_agents_train_agent_sync.py b/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_agents_train_agent_sync.py deleted file mode 100644 index 7df9178c4..000000000 --- a/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_agents_train_agent_sync.py +++ /dev/null @@ -1,56 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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. -# -# Generated code. DO NOT EDIT! -# -# Snippet for TrainAgent -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-dialogflow - - -# [START dialogflow_v2_generated_Agents_TrainAgent_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import dialogflow_v2 - - -def sample_train_agent(): - # Create a client - client = dialogflow_v2.AgentsClient() - - # Initialize request argument(s) - request = dialogflow_v2.TrainAgentRequest( - parent="parent_value", - ) - - # Make the request - operation = client.train_agent(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - -# [END dialogflow_v2_generated_Agents_TrainAgent_sync] diff --git a/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_answer_records_list_answer_records_async.py b/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_answer_records_list_answer_records_async.py deleted file mode 100644 index da2a6d5ed..000000000 --- a/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_answer_records_list_answer_records_async.py +++ /dev/null @@ -1,53 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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. -# -# Generated code. DO NOT EDIT! -# -# Snippet for ListAnswerRecords -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-dialogflow - - -# [START dialogflow_v2_generated_AnswerRecords_ListAnswerRecords_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import dialogflow_v2 - - -async def sample_list_answer_records(): - # Create a client - client = dialogflow_v2.AnswerRecordsAsyncClient() - - # Initialize request argument(s) - request = dialogflow_v2.ListAnswerRecordsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_answer_records(request=request) - - # Handle the response - async for response in page_result: - print(response) - -# [END dialogflow_v2_generated_AnswerRecords_ListAnswerRecords_async] diff --git a/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_answer_records_list_answer_records_sync.py b/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_answer_records_list_answer_records_sync.py deleted file mode 100644 index bece3997f..000000000 --- a/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_answer_records_list_answer_records_sync.py +++ /dev/null @@ -1,53 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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. -# -# Generated code. DO NOT EDIT! -# -# Snippet for ListAnswerRecords -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-dialogflow - - -# [START dialogflow_v2_generated_AnswerRecords_ListAnswerRecords_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import dialogflow_v2 - - -def sample_list_answer_records(): - # Create a client - client = dialogflow_v2.AnswerRecordsClient() - - # Initialize request argument(s) - request = dialogflow_v2.ListAnswerRecordsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_answer_records(request=request) - - # Handle the response - for response in page_result: - print(response) - -# [END dialogflow_v2_generated_AnswerRecords_ListAnswerRecords_sync] diff --git a/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_answer_records_update_answer_record_async.py b/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_answer_records_update_answer_record_async.py deleted file mode 100644 index eca9f7445..000000000 --- a/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_answer_records_update_answer_record_async.py +++ /dev/null @@ -1,51 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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. -# -# Generated code. DO NOT EDIT! -# -# Snippet for UpdateAnswerRecord -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-dialogflow - - -# [START dialogflow_v2_generated_AnswerRecords_UpdateAnswerRecord_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import dialogflow_v2 - - -async def sample_update_answer_record(): - # Create a client - client = dialogflow_v2.AnswerRecordsAsyncClient() - - # Initialize request argument(s) - request = dialogflow_v2.UpdateAnswerRecordRequest( - ) - - # Make the request - response = await client.update_answer_record(request=request) - - # Handle the response - print(response) - -# [END dialogflow_v2_generated_AnswerRecords_UpdateAnswerRecord_async] diff --git a/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_answer_records_update_answer_record_sync.py b/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_answer_records_update_answer_record_sync.py deleted file mode 100644 index 2dc299413..000000000 --- a/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_answer_records_update_answer_record_sync.py +++ /dev/null @@ -1,51 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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. -# -# Generated code. DO NOT EDIT! -# -# Snippet for UpdateAnswerRecord -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-dialogflow - - -# [START dialogflow_v2_generated_AnswerRecords_UpdateAnswerRecord_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import dialogflow_v2 - - -def sample_update_answer_record(): - # Create a client - client = dialogflow_v2.AnswerRecordsClient() - - # Initialize request argument(s) - request = dialogflow_v2.UpdateAnswerRecordRequest( - ) - - # Make the request - response = client.update_answer_record(request=request) - - # Handle the response - print(response) - -# [END dialogflow_v2_generated_AnswerRecords_UpdateAnswerRecord_sync] diff --git a/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_contexts_create_context_async.py b/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_contexts_create_context_async.py deleted file mode 100644 index e2b2d81b5..000000000 --- a/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_contexts_create_context_async.py +++ /dev/null @@ -1,56 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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. -# -# Generated code. DO NOT EDIT! -# -# Snippet for CreateContext -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-dialogflow - - -# [START dialogflow_v2_generated_Contexts_CreateContext_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import dialogflow_v2 - - -async def sample_create_context(): - # Create a client - client = dialogflow_v2.ContextsAsyncClient() - - # Initialize request argument(s) - context = dialogflow_v2.Context() - context.name = "name_value" - - request = dialogflow_v2.CreateContextRequest( - parent="parent_value", - context=context, - ) - - # Make the request - response = await client.create_context(request=request) - - # Handle the response - print(response) - -# [END dialogflow_v2_generated_Contexts_CreateContext_async] diff --git a/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_contexts_create_context_sync.py b/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_contexts_create_context_sync.py deleted file mode 100644 index cda6f8dbc..000000000 --- a/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_contexts_create_context_sync.py +++ /dev/null @@ -1,56 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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. -# -# Generated code. DO NOT EDIT! -# -# Snippet for CreateContext -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-dialogflow - - -# [START dialogflow_v2_generated_Contexts_CreateContext_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import dialogflow_v2 - - -def sample_create_context(): - # Create a client - client = dialogflow_v2.ContextsClient() - - # Initialize request argument(s) - context = dialogflow_v2.Context() - context.name = "name_value" - - request = dialogflow_v2.CreateContextRequest( - parent="parent_value", - context=context, - ) - - # Make the request - response = client.create_context(request=request) - - # Handle the response - print(response) - -# [END dialogflow_v2_generated_Contexts_CreateContext_sync] diff --git a/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_contexts_delete_all_contexts_async.py b/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_contexts_delete_all_contexts_async.py deleted file mode 100644 index e05187c31..000000000 --- a/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_contexts_delete_all_contexts_async.py +++ /dev/null @@ -1,50 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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. -# -# Generated code. DO NOT EDIT! -# -# Snippet for DeleteAllContexts -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-dialogflow - - -# [START dialogflow_v2_generated_Contexts_DeleteAllContexts_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import dialogflow_v2 - - -async def sample_delete_all_contexts(): - # Create a client - client = dialogflow_v2.ContextsAsyncClient() - - # Initialize request argument(s) - request = dialogflow_v2.DeleteAllContextsRequest( - parent="parent_value", - ) - - # Make the request - await client.delete_all_contexts(request=request) - - -# [END dialogflow_v2_generated_Contexts_DeleteAllContexts_async] diff --git a/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_contexts_delete_all_contexts_sync.py b/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_contexts_delete_all_contexts_sync.py deleted file mode 100644 index b1111db2c..000000000 --- a/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_contexts_delete_all_contexts_sync.py +++ /dev/null @@ -1,50 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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. -# -# Generated code. DO NOT EDIT! -# -# Snippet for DeleteAllContexts -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-dialogflow - - -# [START dialogflow_v2_generated_Contexts_DeleteAllContexts_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import dialogflow_v2 - - -def sample_delete_all_contexts(): - # Create a client - client = dialogflow_v2.ContextsClient() - - # Initialize request argument(s) - request = dialogflow_v2.DeleteAllContextsRequest( - parent="parent_value", - ) - - # Make the request - client.delete_all_contexts(request=request) - - -# [END dialogflow_v2_generated_Contexts_DeleteAllContexts_sync] diff --git a/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_contexts_delete_context_async.py b/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_contexts_delete_context_async.py deleted file mode 100644 index 33a5eaa7e..000000000 --- a/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_contexts_delete_context_async.py +++ /dev/null @@ -1,50 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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. -# -# Generated code. DO NOT EDIT! -# -# Snippet for DeleteContext -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-dialogflow - - -# [START dialogflow_v2_generated_Contexts_DeleteContext_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import dialogflow_v2 - - -async def sample_delete_context(): - # Create a client - client = dialogflow_v2.ContextsAsyncClient() - - # Initialize request argument(s) - request = dialogflow_v2.DeleteContextRequest( - name="name_value", - ) - - # Make the request - await client.delete_context(request=request) - - -# [END dialogflow_v2_generated_Contexts_DeleteContext_async] diff --git a/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_contexts_delete_context_sync.py b/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_contexts_delete_context_sync.py deleted file mode 100644 index fc244f00a..000000000 --- a/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_contexts_delete_context_sync.py +++ /dev/null @@ -1,50 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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. -# -# Generated code. DO NOT EDIT! -# -# Snippet for DeleteContext -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-dialogflow - - -# [START dialogflow_v2_generated_Contexts_DeleteContext_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import dialogflow_v2 - - -def sample_delete_context(): - # Create a client - client = dialogflow_v2.ContextsClient() - - # Initialize request argument(s) - request = dialogflow_v2.DeleteContextRequest( - name="name_value", - ) - - # Make the request - client.delete_context(request=request) - - -# [END dialogflow_v2_generated_Contexts_DeleteContext_sync] diff --git a/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_contexts_get_context_async.py b/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_contexts_get_context_async.py deleted file mode 100644 index d0c0d14ec..000000000 --- a/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_contexts_get_context_async.py +++ /dev/null @@ -1,52 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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. -# -# Generated code. DO NOT EDIT! -# -# Snippet for GetContext -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-dialogflow - - -# [START dialogflow_v2_generated_Contexts_GetContext_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import dialogflow_v2 - - -async def sample_get_context(): - # Create a client - client = dialogflow_v2.ContextsAsyncClient() - - # Initialize request argument(s) - request = dialogflow_v2.GetContextRequest( - name="name_value", - ) - - # Make the request - response = await client.get_context(request=request) - - # Handle the response - print(response) - -# [END dialogflow_v2_generated_Contexts_GetContext_async] diff --git a/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_contexts_get_context_sync.py b/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_contexts_get_context_sync.py deleted file mode 100644 index 8a3e5420d..000000000 --- a/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_contexts_get_context_sync.py +++ /dev/null @@ -1,52 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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. -# -# Generated code. DO NOT EDIT! -# -# Snippet for GetContext -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-dialogflow - - -# [START dialogflow_v2_generated_Contexts_GetContext_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import dialogflow_v2 - - -def sample_get_context(): - # Create a client - client = dialogflow_v2.ContextsClient() - - # Initialize request argument(s) - request = dialogflow_v2.GetContextRequest( - name="name_value", - ) - - # Make the request - response = client.get_context(request=request) - - # Handle the response - print(response) - -# [END dialogflow_v2_generated_Contexts_GetContext_sync] diff --git a/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_contexts_list_contexts_async.py b/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_contexts_list_contexts_async.py deleted file mode 100644 index 8b33f3d9d..000000000 --- a/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_contexts_list_contexts_async.py +++ /dev/null @@ -1,53 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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. -# -# Generated code. DO NOT EDIT! -# -# Snippet for ListContexts -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-dialogflow - - -# [START dialogflow_v2_generated_Contexts_ListContexts_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import dialogflow_v2 - - -async def sample_list_contexts(): - # Create a client - client = dialogflow_v2.ContextsAsyncClient() - - # Initialize request argument(s) - request = dialogflow_v2.ListContextsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_contexts(request=request) - - # Handle the response - async for response in page_result: - print(response) - -# [END dialogflow_v2_generated_Contexts_ListContexts_async] diff --git a/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_contexts_list_contexts_sync.py b/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_contexts_list_contexts_sync.py deleted file mode 100644 index 68f04249b..000000000 --- a/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_contexts_list_contexts_sync.py +++ /dev/null @@ -1,53 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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. -# -# Generated code. DO NOT EDIT! -# -# Snippet for ListContexts -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-dialogflow - - -# [START dialogflow_v2_generated_Contexts_ListContexts_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import dialogflow_v2 - - -def sample_list_contexts(): - # Create a client - client = dialogflow_v2.ContextsClient() - - # Initialize request argument(s) - request = dialogflow_v2.ListContextsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_contexts(request=request) - - # Handle the response - for response in page_result: - print(response) - -# [END dialogflow_v2_generated_Contexts_ListContexts_sync] diff --git a/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_contexts_update_context_async.py b/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_contexts_update_context_async.py deleted file mode 100644 index 8f0976083..000000000 --- a/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_contexts_update_context_async.py +++ /dev/null @@ -1,55 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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. -# -# Generated code. DO NOT EDIT! -# -# Snippet for UpdateContext -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-dialogflow - - -# [START dialogflow_v2_generated_Contexts_UpdateContext_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import dialogflow_v2 - - -async def sample_update_context(): - # Create a client - client = dialogflow_v2.ContextsAsyncClient() - - # Initialize request argument(s) - context = dialogflow_v2.Context() - context.name = "name_value" - - request = dialogflow_v2.UpdateContextRequest( - context=context, - ) - - # Make the request - response = await client.update_context(request=request) - - # Handle the response - print(response) - -# [END dialogflow_v2_generated_Contexts_UpdateContext_async] diff --git a/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_contexts_update_context_sync.py b/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_contexts_update_context_sync.py deleted file mode 100644 index 10519b6cd..000000000 --- a/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_contexts_update_context_sync.py +++ /dev/null @@ -1,55 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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. -# -# Generated code. DO NOT EDIT! -# -# Snippet for UpdateContext -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-dialogflow - - -# [START dialogflow_v2_generated_Contexts_UpdateContext_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import dialogflow_v2 - - -def sample_update_context(): - # Create a client - client = dialogflow_v2.ContextsClient() - - # Initialize request argument(s) - context = dialogflow_v2.Context() - context.name = "name_value" - - request = dialogflow_v2.UpdateContextRequest( - context=context, - ) - - # Make the request - response = client.update_context(request=request) - - # Handle the response - print(response) - -# [END dialogflow_v2_generated_Contexts_UpdateContext_sync] diff --git a/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_conversation_datasets_create_conversation_dataset_async.py b/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_conversation_datasets_create_conversation_dataset_async.py deleted file mode 100644 index eee486b64..000000000 --- a/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_conversation_datasets_create_conversation_dataset_async.py +++ /dev/null @@ -1,60 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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. -# -# Generated code. DO NOT EDIT! -# -# Snippet for CreateConversationDataset -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-dialogflow - - -# [START dialogflow_v2_generated_ConversationDatasets_CreateConversationDataset_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import dialogflow_v2 - - -async def sample_create_conversation_dataset(): - # Create a client - client = dialogflow_v2.ConversationDatasetsAsyncClient() - - # Initialize request argument(s) - conversation_dataset = dialogflow_v2.ConversationDataset() - conversation_dataset.display_name = "display_name_value" - - request = dialogflow_v2.CreateConversationDatasetRequest( - parent="parent_value", - conversation_dataset=conversation_dataset, - ) - - # Make the request - operation = client.create_conversation_dataset(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - -# [END dialogflow_v2_generated_ConversationDatasets_CreateConversationDataset_async] diff --git a/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_conversation_datasets_create_conversation_dataset_sync.py b/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_conversation_datasets_create_conversation_dataset_sync.py deleted file mode 100644 index f6ca4b244..000000000 --- a/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_conversation_datasets_create_conversation_dataset_sync.py +++ /dev/null @@ -1,60 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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. -# -# Generated code. DO NOT EDIT! -# -# Snippet for CreateConversationDataset -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-dialogflow - - -# [START dialogflow_v2_generated_ConversationDatasets_CreateConversationDataset_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import dialogflow_v2 - - -def sample_create_conversation_dataset(): - # Create a client - client = dialogflow_v2.ConversationDatasetsClient() - - # Initialize request argument(s) - conversation_dataset = dialogflow_v2.ConversationDataset() - conversation_dataset.display_name = "display_name_value" - - request = dialogflow_v2.CreateConversationDatasetRequest( - parent="parent_value", - conversation_dataset=conversation_dataset, - ) - - # Make the request - operation = client.create_conversation_dataset(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - -# [END dialogflow_v2_generated_ConversationDatasets_CreateConversationDataset_sync] diff --git a/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_conversation_datasets_delete_conversation_dataset_async.py b/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_conversation_datasets_delete_conversation_dataset_async.py deleted file mode 100644 index ff3dc6334..000000000 --- a/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_conversation_datasets_delete_conversation_dataset_async.py +++ /dev/null @@ -1,56 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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. -# -# Generated code. DO NOT EDIT! -# -# Snippet for DeleteConversationDataset -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-dialogflow - - -# [START dialogflow_v2_generated_ConversationDatasets_DeleteConversationDataset_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import dialogflow_v2 - - -async def sample_delete_conversation_dataset(): - # Create a client - client = dialogflow_v2.ConversationDatasetsAsyncClient() - - # Initialize request argument(s) - request = dialogflow_v2.DeleteConversationDatasetRequest( - name="name_value", - ) - - # Make the request - operation = client.delete_conversation_dataset(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - -# [END dialogflow_v2_generated_ConversationDatasets_DeleteConversationDataset_async] diff --git a/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_conversation_datasets_delete_conversation_dataset_sync.py b/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_conversation_datasets_delete_conversation_dataset_sync.py deleted file mode 100644 index 2d433389f..000000000 --- a/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_conversation_datasets_delete_conversation_dataset_sync.py +++ /dev/null @@ -1,56 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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. -# -# Generated code. DO NOT EDIT! -# -# Snippet for DeleteConversationDataset -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-dialogflow - - -# [START dialogflow_v2_generated_ConversationDatasets_DeleteConversationDataset_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import dialogflow_v2 - - -def sample_delete_conversation_dataset(): - # Create a client - client = dialogflow_v2.ConversationDatasetsClient() - - # Initialize request argument(s) - request = dialogflow_v2.DeleteConversationDatasetRequest( - name="name_value", - ) - - # Make the request - operation = client.delete_conversation_dataset(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - -# [END dialogflow_v2_generated_ConversationDatasets_DeleteConversationDataset_sync] diff --git a/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_conversation_datasets_get_conversation_dataset_async.py b/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_conversation_datasets_get_conversation_dataset_async.py deleted file mode 100644 index 2bdce7d10..000000000 --- a/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_conversation_datasets_get_conversation_dataset_async.py +++ /dev/null @@ -1,52 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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. -# -# Generated code. DO NOT EDIT! -# -# Snippet for GetConversationDataset -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-dialogflow - - -# [START dialogflow_v2_generated_ConversationDatasets_GetConversationDataset_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import dialogflow_v2 - - -async def sample_get_conversation_dataset(): - # Create a client - client = dialogflow_v2.ConversationDatasetsAsyncClient() - - # Initialize request argument(s) - request = dialogflow_v2.GetConversationDatasetRequest( - name="name_value", - ) - - # Make the request - response = await client.get_conversation_dataset(request=request) - - # Handle the response - print(response) - -# [END dialogflow_v2_generated_ConversationDatasets_GetConversationDataset_async] diff --git a/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_conversation_datasets_get_conversation_dataset_sync.py b/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_conversation_datasets_get_conversation_dataset_sync.py deleted file mode 100644 index a1adb1c55..000000000 --- a/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_conversation_datasets_get_conversation_dataset_sync.py +++ /dev/null @@ -1,52 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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. -# -# Generated code. DO NOT EDIT! -# -# Snippet for GetConversationDataset -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-dialogflow - - -# [START dialogflow_v2_generated_ConversationDatasets_GetConversationDataset_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import dialogflow_v2 - - -def sample_get_conversation_dataset(): - # Create a client - client = dialogflow_v2.ConversationDatasetsClient() - - # Initialize request argument(s) - request = dialogflow_v2.GetConversationDatasetRequest( - name="name_value", - ) - - # Make the request - response = client.get_conversation_dataset(request=request) - - # Handle the response - print(response) - -# [END dialogflow_v2_generated_ConversationDatasets_GetConversationDataset_sync] diff --git a/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_conversation_datasets_import_conversation_data_async.py b/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_conversation_datasets_import_conversation_data_async.py deleted file mode 100644 index 59d1ebd6c..000000000 --- a/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_conversation_datasets_import_conversation_data_async.py +++ /dev/null @@ -1,60 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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. -# -# Generated code. DO NOT EDIT! -# -# Snippet for ImportConversationData -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-dialogflow - - -# [START dialogflow_v2_generated_ConversationDatasets_ImportConversationData_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import dialogflow_v2 - - -async def sample_import_conversation_data(): - # Create a client - client = dialogflow_v2.ConversationDatasetsAsyncClient() - - # Initialize request argument(s) - input_config = dialogflow_v2.InputConfig() - input_config.gcs_source.uris = ['uris_value1', 'uris_value2'] - - request = dialogflow_v2.ImportConversationDataRequest( - name="name_value", - input_config=input_config, - ) - - # Make the request - operation = client.import_conversation_data(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - -# [END dialogflow_v2_generated_ConversationDatasets_ImportConversationData_async] diff --git a/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_conversation_datasets_import_conversation_data_sync.py b/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_conversation_datasets_import_conversation_data_sync.py deleted file mode 100644 index 5a3ca0653..000000000 --- a/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_conversation_datasets_import_conversation_data_sync.py +++ /dev/null @@ -1,60 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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. -# -# Generated code. DO NOT EDIT! -# -# Snippet for ImportConversationData -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-dialogflow - - -# [START dialogflow_v2_generated_ConversationDatasets_ImportConversationData_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import dialogflow_v2 - - -def sample_import_conversation_data(): - # Create a client - client = dialogflow_v2.ConversationDatasetsClient() - - # Initialize request argument(s) - input_config = dialogflow_v2.InputConfig() - input_config.gcs_source.uris = ['uris_value1', 'uris_value2'] - - request = dialogflow_v2.ImportConversationDataRequest( - name="name_value", - input_config=input_config, - ) - - # Make the request - operation = client.import_conversation_data(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - -# [END dialogflow_v2_generated_ConversationDatasets_ImportConversationData_sync] diff --git a/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_conversation_datasets_list_conversation_datasets_async.py b/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_conversation_datasets_list_conversation_datasets_async.py deleted file mode 100644 index 10b0d8152..000000000 --- a/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_conversation_datasets_list_conversation_datasets_async.py +++ /dev/null @@ -1,53 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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. -# -# Generated code. DO NOT EDIT! -# -# Snippet for ListConversationDatasets -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-dialogflow - - -# [START dialogflow_v2_generated_ConversationDatasets_ListConversationDatasets_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import dialogflow_v2 - - -async def sample_list_conversation_datasets(): - # Create a client - client = dialogflow_v2.ConversationDatasetsAsyncClient() - - # Initialize request argument(s) - request = dialogflow_v2.ListConversationDatasetsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_conversation_datasets(request=request) - - # Handle the response - async for response in page_result: - print(response) - -# [END dialogflow_v2_generated_ConversationDatasets_ListConversationDatasets_async] diff --git a/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_conversation_datasets_list_conversation_datasets_sync.py b/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_conversation_datasets_list_conversation_datasets_sync.py deleted file mode 100644 index 39697ec8b..000000000 --- a/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_conversation_datasets_list_conversation_datasets_sync.py +++ /dev/null @@ -1,53 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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. -# -# Generated code. DO NOT EDIT! -# -# Snippet for ListConversationDatasets -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-dialogflow - - -# [START dialogflow_v2_generated_ConversationDatasets_ListConversationDatasets_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import dialogflow_v2 - - -def sample_list_conversation_datasets(): - # Create a client - client = dialogflow_v2.ConversationDatasetsClient() - - # Initialize request argument(s) - request = dialogflow_v2.ListConversationDatasetsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_conversation_datasets(request=request) - - # Handle the response - for response in page_result: - print(response) - -# [END dialogflow_v2_generated_ConversationDatasets_ListConversationDatasets_sync] diff --git a/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_conversation_models_create_conversation_model_async.py b/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_conversation_models_create_conversation_model_async.py deleted file mode 100644 index c86dc38a8..000000000 --- a/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_conversation_models_create_conversation_model_async.py +++ /dev/null @@ -1,60 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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. -# -# Generated code. DO NOT EDIT! -# -# Snippet for CreateConversationModel -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-dialogflow - - -# [START dialogflow_v2_generated_ConversationModels_CreateConversationModel_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import dialogflow_v2 - - -async def sample_create_conversation_model(): - # Create a client - client = dialogflow_v2.ConversationModelsAsyncClient() - - # Initialize request argument(s) - conversation_model = dialogflow_v2.ConversationModel() - conversation_model.display_name = "display_name_value" - conversation_model.datasets.dataset = "dataset_value" - - request = dialogflow_v2.CreateConversationModelRequest( - conversation_model=conversation_model, - ) - - # Make the request - operation = client.create_conversation_model(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - -# [END dialogflow_v2_generated_ConversationModels_CreateConversationModel_async] diff --git a/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_conversation_models_create_conversation_model_evaluation_async.py b/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_conversation_models_create_conversation_model_evaluation_async.py deleted file mode 100644 index 002b800c0..000000000 --- a/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_conversation_models_create_conversation_model_evaluation_async.py +++ /dev/null @@ -1,56 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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. -# -# Generated code. DO NOT EDIT! -# -# Snippet for CreateConversationModelEvaluation -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-dialogflow - - -# [START dialogflow_v2_generated_ConversationModels_CreateConversationModelEvaluation_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import dialogflow_v2 - - -async def sample_create_conversation_model_evaluation(): - # Create a client - client = dialogflow_v2.ConversationModelsAsyncClient() - - # Initialize request argument(s) - request = dialogflow_v2.CreateConversationModelEvaluationRequest( - parent="parent_value", - ) - - # Make the request - operation = client.create_conversation_model_evaluation(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - -# [END dialogflow_v2_generated_ConversationModels_CreateConversationModelEvaluation_async] diff --git a/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_conversation_models_create_conversation_model_evaluation_sync.py b/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_conversation_models_create_conversation_model_evaluation_sync.py deleted file mode 100644 index 5b53f0f14..000000000 --- a/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_conversation_models_create_conversation_model_evaluation_sync.py +++ /dev/null @@ -1,56 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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. -# -# Generated code. DO NOT EDIT! -# -# Snippet for CreateConversationModelEvaluation -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-dialogflow - - -# [START dialogflow_v2_generated_ConversationModels_CreateConversationModelEvaluation_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import dialogflow_v2 - - -def sample_create_conversation_model_evaluation(): - # Create a client - client = dialogflow_v2.ConversationModelsClient() - - # Initialize request argument(s) - request = dialogflow_v2.CreateConversationModelEvaluationRequest( - parent="parent_value", - ) - - # Make the request - operation = client.create_conversation_model_evaluation(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - -# [END dialogflow_v2_generated_ConversationModels_CreateConversationModelEvaluation_sync] diff --git a/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_conversation_models_create_conversation_model_sync.py b/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_conversation_models_create_conversation_model_sync.py deleted file mode 100644 index fd5a425ce..000000000 --- a/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_conversation_models_create_conversation_model_sync.py +++ /dev/null @@ -1,60 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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. -# -# Generated code. DO NOT EDIT! -# -# Snippet for CreateConversationModel -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-dialogflow - - -# [START dialogflow_v2_generated_ConversationModels_CreateConversationModel_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import dialogflow_v2 - - -def sample_create_conversation_model(): - # Create a client - client = dialogflow_v2.ConversationModelsClient() - - # Initialize request argument(s) - conversation_model = dialogflow_v2.ConversationModel() - conversation_model.display_name = "display_name_value" - conversation_model.datasets.dataset = "dataset_value" - - request = dialogflow_v2.CreateConversationModelRequest( - conversation_model=conversation_model, - ) - - # Make the request - operation = client.create_conversation_model(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - -# [END dialogflow_v2_generated_ConversationModels_CreateConversationModel_sync] diff --git a/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_conversation_models_delete_conversation_model_async.py b/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_conversation_models_delete_conversation_model_async.py deleted file mode 100644 index a257e1e67..000000000 --- a/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_conversation_models_delete_conversation_model_async.py +++ /dev/null @@ -1,56 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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. -# -# Generated code. DO NOT EDIT! -# -# Snippet for DeleteConversationModel -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-dialogflow - - -# [START dialogflow_v2_generated_ConversationModels_DeleteConversationModel_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import dialogflow_v2 - - -async def sample_delete_conversation_model(): - # Create a client - client = dialogflow_v2.ConversationModelsAsyncClient() - - # Initialize request argument(s) - request = dialogflow_v2.DeleteConversationModelRequest( - name="name_value", - ) - - # Make the request - operation = client.delete_conversation_model(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - -# [END dialogflow_v2_generated_ConversationModels_DeleteConversationModel_async] diff --git a/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_conversation_models_delete_conversation_model_sync.py b/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_conversation_models_delete_conversation_model_sync.py deleted file mode 100644 index 4432e749f..000000000 --- a/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_conversation_models_delete_conversation_model_sync.py +++ /dev/null @@ -1,56 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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. -# -# Generated code. DO NOT EDIT! -# -# Snippet for DeleteConversationModel -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-dialogflow - - -# [START dialogflow_v2_generated_ConversationModels_DeleteConversationModel_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import dialogflow_v2 - - -def sample_delete_conversation_model(): - # Create a client - client = dialogflow_v2.ConversationModelsClient() - - # Initialize request argument(s) - request = dialogflow_v2.DeleteConversationModelRequest( - name="name_value", - ) - - # Make the request - operation = client.delete_conversation_model(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - -# [END dialogflow_v2_generated_ConversationModels_DeleteConversationModel_sync] diff --git a/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_conversation_models_deploy_conversation_model_async.py b/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_conversation_models_deploy_conversation_model_async.py deleted file mode 100644 index b234b6376..000000000 --- a/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_conversation_models_deploy_conversation_model_async.py +++ /dev/null @@ -1,56 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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. -# -# Generated code. DO NOT EDIT! -# -# Snippet for DeployConversationModel -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-dialogflow - - -# [START dialogflow_v2_generated_ConversationModels_DeployConversationModel_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import dialogflow_v2 - - -async def sample_deploy_conversation_model(): - # Create a client - client = dialogflow_v2.ConversationModelsAsyncClient() - - # Initialize request argument(s) - request = dialogflow_v2.DeployConversationModelRequest( - name="name_value", - ) - - # Make the request - operation = client.deploy_conversation_model(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - -# [END dialogflow_v2_generated_ConversationModels_DeployConversationModel_async] diff --git a/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_conversation_models_deploy_conversation_model_sync.py b/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_conversation_models_deploy_conversation_model_sync.py deleted file mode 100644 index ff3df0819..000000000 --- a/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_conversation_models_deploy_conversation_model_sync.py +++ /dev/null @@ -1,56 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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. -# -# Generated code. DO NOT EDIT! -# -# Snippet for DeployConversationModel -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-dialogflow - - -# [START dialogflow_v2_generated_ConversationModels_DeployConversationModel_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import dialogflow_v2 - - -def sample_deploy_conversation_model(): - # Create a client - client = dialogflow_v2.ConversationModelsClient() - - # Initialize request argument(s) - request = dialogflow_v2.DeployConversationModelRequest( - name="name_value", - ) - - # Make the request - operation = client.deploy_conversation_model(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - -# [END dialogflow_v2_generated_ConversationModels_DeployConversationModel_sync] diff --git a/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_conversation_models_get_conversation_model_async.py b/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_conversation_models_get_conversation_model_async.py deleted file mode 100644 index 6fb15bea7..000000000 --- a/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_conversation_models_get_conversation_model_async.py +++ /dev/null @@ -1,52 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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. -# -# Generated code. DO NOT EDIT! -# -# Snippet for GetConversationModel -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-dialogflow - - -# [START dialogflow_v2_generated_ConversationModels_GetConversationModel_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import dialogflow_v2 - - -async def sample_get_conversation_model(): - # Create a client - client = dialogflow_v2.ConversationModelsAsyncClient() - - # Initialize request argument(s) - request = dialogflow_v2.GetConversationModelRequest( - name="name_value", - ) - - # Make the request - response = await client.get_conversation_model(request=request) - - # Handle the response - print(response) - -# [END dialogflow_v2_generated_ConversationModels_GetConversationModel_async] diff --git a/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_conversation_models_get_conversation_model_evaluation_async.py b/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_conversation_models_get_conversation_model_evaluation_async.py deleted file mode 100644 index 42c16c161..000000000 --- a/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_conversation_models_get_conversation_model_evaluation_async.py +++ /dev/null @@ -1,52 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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. -# -# Generated code. DO NOT EDIT! -# -# Snippet for GetConversationModelEvaluation -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-dialogflow - - -# [START dialogflow_v2_generated_ConversationModels_GetConversationModelEvaluation_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import dialogflow_v2 - - -async def sample_get_conversation_model_evaluation(): - # Create a client - client = dialogflow_v2.ConversationModelsAsyncClient() - - # Initialize request argument(s) - request = dialogflow_v2.GetConversationModelEvaluationRequest( - name="name_value", - ) - - # Make the request - response = await client.get_conversation_model_evaluation(request=request) - - # Handle the response - print(response) - -# [END dialogflow_v2_generated_ConversationModels_GetConversationModelEvaluation_async] diff --git a/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_conversation_models_get_conversation_model_evaluation_sync.py b/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_conversation_models_get_conversation_model_evaluation_sync.py deleted file mode 100644 index c1a3e68ca..000000000 --- a/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_conversation_models_get_conversation_model_evaluation_sync.py +++ /dev/null @@ -1,52 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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. -# -# Generated code. DO NOT EDIT! -# -# Snippet for GetConversationModelEvaluation -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-dialogflow - - -# [START dialogflow_v2_generated_ConversationModels_GetConversationModelEvaluation_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import dialogflow_v2 - - -def sample_get_conversation_model_evaluation(): - # Create a client - client = dialogflow_v2.ConversationModelsClient() - - # Initialize request argument(s) - request = dialogflow_v2.GetConversationModelEvaluationRequest( - name="name_value", - ) - - # Make the request - response = client.get_conversation_model_evaluation(request=request) - - # Handle the response - print(response) - -# [END dialogflow_v2_generated_ConversationModels_GetConversationModelEvaluation_sync] diff --git a/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_conversation_models_get_conversation_model_sync.py b/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_conversation_models_get_conversation_model_sync.py deleted file mode 100644 index 495024914..000000000 --- a/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_conversation_models_get_conversation_model_sync.py +++ /dev/null @@ -1,52 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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. -# -# Generated code. DO NOT EDIT! -# -# Snippet for GetConversationModel -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-dialogflow - - -# [START dialogflow_v2_generated_ConversationModels_GetConversationModel_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import dialogflow_v2 - - -def sample_get_conversation_model(): - # Create a client - client = dialogflow_v2.ConversationModelsClient() - - # Initialize request argument(s) - request = dialogflow_v2.GetConversationModelRequest( - name="name_value", - ) - - # Make the request - response = client.get_conversation_model(request=request) - - # Handle the response - print(response) - -# [END dialogflow_v2_generated_ConversationModels_GetConversationModel_sync] diff --git a/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_conversation_models_list_conversation_model_evaluations_async.py b/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_conversation_models_list_conversation_model_evaluations_async.py deleted file mode 100644 index b394c9f8f..000000000 --- a/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_conversation_models_list_conversation_model_evaluations_async.py +++ /dev/null @@ -1,53 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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. -# -# Generated code. DO NOT EDIT! -# -# Snippet for ListConversationModelEvaluations -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-dialogflow - - -# [START dialogflow_v2_generated_ConversationModels_ListConversationModelEvaluations_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import dialogflow_v2 - - -async def sample_list_conversation_model_evaluations(): - # Create a client - client = dialogflow_v2.ConversationModelsAsyncClient() - - # Initialize request argument(s) - request = dialogflow_v2.ListConversationModelEvaluationsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_conversation_model_evaluations(request=request) - - # Handle the response - async for response in page_result: - print(response) - -# [END dialogflow_v2_generated_ConversationModels_ListConversationModelEvaluations_async] diff --git a/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_conversation_models_list_conversation_model_evaluations_sync.py b/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_conversation_models_list_conversation_model_evaluations_sync.py deleted file mode 100644 index ab7bd21d9..000000000 --- a/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_conversation_models_list_conversation_model_evaluations_sync.py +++ /dev/null @@ -1,53 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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. -# -# Generated code. DO NOT EDIT! -# -# Snippet for ListConversationModelEvaluations -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-dialogflow - - -# [START dialogflow_v2_generated_ConversationModels_ListConversationModelEvaluations_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import dialogflow_v2 - - -def sample_list_conversation_model_evaluations(): - # Create a client - client = dialogflow_v2.ConversationModelsClient() - - # Initialize request argument(s) - request = dialogflow_v2.ListConversationModelEvaluationsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_conversation_model_evaluations(request=request) - - # Handle the response - for response in page_result: - print(response) - -# [END dialogflow_v2_generated_ConversationModels_ListConversationModelEvaluations_sync] diff --git a/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_conversation_models_list_conversation_models_async.py b/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_conversation_models_list_conversation_models_async.py deleted file mode 100644 index e222baea8..000000000 --- a/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_conversation_models_list_conversation_models_async.py +++ /dev/null @@ -1,53 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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. -# -# Generated code. DO NOT EDIT! -# -# Snippet for ListConversationModels -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-dialogflow - - -# [START dialogflow_v2_generated_ConversationModels_ListConversationModels_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import dialogflow_v2 - - -async def sample_list_conversation_models(): - # Create a client - client = dialogflow_v2.ConversationModelsAsyncClient() - - # Initialize request argument(s) - request = dialogflow_v2.ListConversationModelsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_conversation_models(request=request) - - # Handle the response - async for response in page_result: - print(response) - -# [END dialogflow_v2_generated_ConversationModels_ListConversationModels_async] diff --git a/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_conversation_models_list_conversation_models_sync.py b/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_conversation_models_list_conversation_models_sync.py deleted file mode 100644 index b161675e5..000000000 --- a/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_conversation_models_list_conversation_models_sync.py +++ /dev/null @@ -1,53 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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. -# -# Generated code. DO NOT EDIT! -# -# Snippet for ListConversationModels -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-dialogflow - - -# [START dialogflow_v2_generated_ConversationModels_ListConversationModels_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import dialogflow_v2 - - -def sample_list_conversation_models(): - # Create a client - client = dialogflow_v2.ConversationModelsClient() - - # Initialize request argument(s) - request = dialogflow_v2.ListConversationModelsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_conversation_models(request=request) - - # Handle the response - for response in page_result: - print(response) - -# [END dialogflow_v2_generated_ConversationModels_ListConversationModels_sync] diff --git a/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_conversation_models_undeploy_conversation_model_async.py b/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_conversation_models_undeploy_conversation_model_async.py deleted file mode 100644 index f04ccb26a..000000000 --- a/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_conversation_models_undeploy_conversation_model_async.py +++ /dev/null @@ -1,56 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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. -# -# Generated code. DO NOT EDIT! -# -# Snippet for UndeployConversationModel -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-dialogflow - - -# [START dialogflow_v2_generated_ConversationModels_UndeployConversationModel_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import dialogflow_v2 - - -async def sample_undeploy_conversation_model(): - # Create a client - client = dialogflow_v2.ConversationModelsAsyncClient() - - # Initialize request argument(s) - request = dialogflow_v2.UndeployConversationModelRequest( - name="name_value", - ) - - # Make the request - operation = client.undeploy_conversation_model(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - -# [END dialogflow_v2_generated_ConversationModels_UndeployConversationModel_async] diff --git a/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_conversation_models_undeploy_conversation_model_sync.py b/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_conversation_models_undeploy_conversation_model_sync.py deleted file mode 100644 index c386985ff..000000000 --- a/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_conversation_models_undeploy_conversation_model_sync.py +++ /dev/null @@ -1,56 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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. -# -# Generated code. DO NOT EDIT! -# -# Snippet for UndeployConversationModel -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-dialogflow - - -# [START dialogflow_v2_generated_ConversationModels_UndeployConversationModel_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import dialogflow_v2 - - -def sample_undeploy_conversation_model(): - # Create a client - client = dialogflow_v2.ConversationModelsClient() - - # Initialize request argument(s) - request = dialogflow_v2.UndeployConversationModelRequest( - name="name_value", - ) - - # Make the request - operation = client.undeploy_conversation_model(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - -# [END dialogflow_v2_generated_ConversationModels_UndeployConversationModel_sync] diff --git a/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_conversation_profiles_clear_suggestion_feature_config_async.py b/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_conversation_profiles_clear_suggestion_feature_config_async.py deleted file mode 100644 index c86f384f5..000000000 --- a/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_conversation_profiles_clear_suggestion_feature_config_async.py +++ /dev/null @@ -1,58 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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. -# -# Generated code. DO NOT EDIT! -# -# Snippet for ClearSuggestionFeatureConfig -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-dialogflow - - -# [START dialogflow_v2_generated_ConversationProfiles_ClearSuggestionFeatureConfig_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import dialogflow_v2 - - -async def sample_clear_suggestion_feature_config(): - # Create a client - client = dialogflow_v2.ConversationProfilesAsyncClient() - - # Initialize request argument(s) - request = dialogflow_v2.ClearSuggestionFeatureConfigRequest( - conversation_profile="conversation_profile_value", - participant_role="END_USER", - suggestion_feature_type="SMART_REPLY", - ) - - # Make the request - operation = client.clear_suggestion_feature_config(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - -# [END dialogflow_v2_generated_ConversationProfiles_ClearSuggestionFeatureConfig_async] diff --git a/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_conversation_profiles_clear_suggestion_feature_config_sync.py b/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_conversation_profiles_clear_suggestion_feature_config_sync.py deleted file mode 100644 index b61ca4441..000000000 --- a/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_conversation_profiles_clear_suggestion_feature_config_sync.py +++ /dev/null @@ -1,58 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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. -# -# Generated code. DO NOT EDIT! -# -# Snippet for ClearSuggestionFeatureConfig -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-dialogflow - - -# [START dialogflow_v2_generated_ConversationProfiles_ClearSuggestionFeatureConfig_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import dialogflow_v2 - - -def sample_clear_suggestion_feature_config(): - # Create a client - client = dialogflow_v2.ConversationProfilesClient() - - # Initialize request argument(s) - request = dialogflow_v2.ClearSuggestionFeatureConfigRequest( - conversation_profile="conversation_profile_value", - participant_role="END_USER", - suggestion_feature_type="SMART_REPLY", - ) - - # Make the request - operation = client.clear_suggestion_feature_config(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - -# [END dialogflow_v2_generated_ConversationProfiles_ClearSuggestionFeatureConfig_sync] diff --git a/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_conversation_profiles_create_conversation_profile_async.py b/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_conversation_profiles_create_conversation_profile_async.py deleted file mode 100644 index 86401f4b6..000000000 --- a/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_conversation_profiles_create_conversation_profile_async.py +++ /dev/null @@ -1,56 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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. -# -# Generated code. DO NOT EDIT! -# -# Snippet for CreateConversationProfile -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-dialogflow - - -# [START dialogflow_v2_generated_ConversationProfiles_CreateConversationProfile_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import dialogflow_v2 - - -async def sample_create_conversation_profile(): - # Create a client - client = dialogflow_v2.ConversationProfilesAsyncClient() - - # Initialize request argument(s) - conversation_profile = dialogflow_v2.ConversationProfile() - conversation_profile.display_name = "display_name_value" - - request = dialogflow_v2.CreateConversationProfileRequest( - parent="parent_value", - conversation_profile=conversation_profile, - ) - - # Make the request - response = await client.create_conversation_profile(request=request) - - # Handle the response - print(response) - -# [END dialogflow_v2_generated_ConversationProfiles_CreateConversationProfile_async] diff --git a/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_conversation_profiles_create_conversation_profile_sync.py b/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_conversation_profiles_create_conversation_profile_sync.py deleted file mode 100644 index 746be660d..000000000 --- a/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_conversation_profiles_create_conversation_profile_sync.py +++ /dev/null @@ -1,56 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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. -# -# Generated code. DO NOT EDIT! -# -# Snippet for CreateConversationProfile -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-dialogflow - - -# [START dialogflow_v2_generated_ConversationProfiles_CreateConversationProfile_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import dialogflow_v2 - - -def sample_create_conversation_profile(): - # Create a client - client = dialogflow_v2.ConversationProfilesClient() - - # Initialize request argument(s) - conversation_profile = dialogflow_v2.ConversationProfile() - conversation_profile.display_name = "display_name_value" - - request = dialogflow_v2.CreateConversationProfileRequest( - parent="parent_value", - conversation_profile=conversation_profile, - ) - - # Make the request - response = client.create_conversation_profile(request=request) - - # Handle the response - print(response) - -# [END dialogflow_v2_generated_ConversationProfiles_CreateConversationProfile_sync] diff --git a/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_conversation_profiles_delete_conversation_profile_async.py b/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_conversation_profiles_delete_conversation_profile_async.py deleted file mode 100644 index 2d529e3a1..000000000 --- a/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_conversation_profiles_delete_conversation_profile_async.py +++ /dev/null @@ -1,50 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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. -# -# Generated code. DO NOT EDIT! -# -# Snippet for DeleteConversationProfile -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-dialogflow - - -# [START dialogflow_v2_generated_ConversationProfiles_DeleteConversationProfile_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import dialogflow_v2 - - -async def sample_delete_conversation_profile(): - # Create a client - client = dialogflow_v2.ConversationProfilesAsyncClient() - - # Initialize request argument(s) - request = dialogflow_v2.DeleteConversationProfileRequest( - name="name_value", - ) - - # Make the request - await client.delete_conversation_profile(request=request) - - -# [END dialogflow_v2_generated_ConversationProfiles_DeleteConversationProfile_async] diff --git a/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_conversation_profiles_delete_conversation_profile_sync.py b/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_conversation_profiles_delete_conversation_profile_sync.py deleted file mode 100644 index ac2062299..000000000 --- a/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_conversation_profiles_delete_conversation_profile_sync.py +++ /dev/null @@ -1,50 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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. -# -# Generated code. DO NOT EDIT! -# -# Snippet for DeleteConversationProfile -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-dialogflow - - -# [START dialogflow_v2_generated_ConversationProfiles_DeleteConversationProfile_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import dialogflow_v2 - - -def sample_delete_conversation_profile(): - # Create a client - client = dialogflow_v2.ConversationProfilesClient() - - # Initialize request argument(s) - request = dialogflow_v2.DeleteConversationProfileRequest( - name="name_value", - ) - - # Make the request - client.delete_conversation_profile(request=request) - - -# [END dialogflow_v2_generated_ConversationProfiles_DeleteConversationProfile_sync] diff --git a/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_conversation_profiles_get_conversation_profile_async.py b/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_conversation_profiles_get_conversation_profile_async.py deleted file mode 100644 index 5c50bbd50..000000000 --- a/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_conversation_profiles_get_conversation_profile_async.py +++ /dev/null @@ -1,52 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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. -# -# Generated code. DO NOT EDIT! -# -# Snippet for GetConversationProfile -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-dialogflow - - -# [START dialogflow_v2_generated_ConversationProfiles_GetConversationProfile_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import dialogflow_v2 - - -async def sample_get_conversation_profile(): - # Create a client - client = dialogflow_v2.ConversationProfilesAsyncClient() - - # Initialize request argument(s) - request = dialogflow_v2.GetConversationProfileRequest( - name="name_value", - ) - - # Make the request - response = await client.get_conversation_profile(request=request) - - # Handle the response - print(response) - -# [END dialogflow_v2_generated_ConversationProfiles_GetConversationProfile_async] diff --git a/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_conversation_profiles_get_conversation_profile_sync.py b/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_conversation_profiles_get_conversation_profile_sync.py deleted file mode 100644 index 2cbead0d4..000000000 --- a/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_conversation_profiles_get_conversation_profile_sync.py +++ /dev/null @@ -1,52 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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. -# -# Generated code. DO NOT EDIT! -# -# Snippet for GetConversationProfile -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-dialogflow - - -# [START dialogflow_v2_generated_ConversationProfiles_GetConversationProfile_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import dialogflow_v2 - - -def sample_get_conversation_profile(): - # Create a client - client = dialogflow_v2.ConversationProfilesClient() - - # Initialize request argument(s) - request = dialogflow_v2.GetConversationProfileRequest( - name="name_value", - ) - - # Make the request - response = client.get_conversation_profile(request=request) - - # Handle the response - print(response) - -# [END dialogflow_v2_generated_ConversationProfiles_GetConversationProfile_sync] diff --git a/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_conversation_profiles_list_conversation_profiles_async.py b/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_conversation_profiles_list_conversation_profiles_async.py deleted file mode 100644 index ef1e07266..000000000 --- a/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_conversation_profiles_list_conversation_profiles_async.py +++ /dev/null @@ -1,53 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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. -# -# Generated code. DO NOT EDIT! -# -# Snippet for ListConversationProfiles -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-dialogflow - - -# [START dialogflow_v2_generated_ConversationProfiles_ListConversationProfiles_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import dialogflow_v2 - - -async def sample_list_conversation_profiles(): - # Create a client - client = dialogflow_v2.ConversationProfilesAsyncClient() - - # Initialize request argument(s) - request = dialogflow_v2.ListConversationProfilesRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_conversation_profiles(request=request) - - # Handle the response - async for response in page_result: - print(response) - -# [END dialogflow_v2_generated_ConversationProfiles_ListConversationProfiles_async] diff --git a/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_conversation_profiles_list_conversation_profiles_sync.py b/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_conversation_profiles_list_conversation_profiles_sync.py deleted file mode 100644 index c146ff188..000000000 --- a/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_conversation_profiles_list_conversation_profiles_sync.py +++ /dev/null @@ -1,53 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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. -# -# Generated code. DO NOT EDIT! -# -# Snippet for ListConversationProfiles -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-dialogflow - - -# [START dialogflow_v2_generated_ConversationProfiles_ListConversationProfiles_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import dialogflow_v2 - - -def sample_list_conversation_profiles(): - # Create a client - client = dialogflow_v2.ConversationProfilesClient() - - # Initialize request argument(s) - request = dialogflow_v2.ListConversationProfilesRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_conversation_profiles(request=request) - - # Handle the response - for response in page_result: - print(response) - -# [END dialogflow_v2_generated_ConversationProfiles_ListConversationProfiles_sync] diff --git a/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_conversation_profiles_set_suggestion_feature_config_async.py b/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_conversation_profiles_set_suggestion_feature_config_async.py deleted file mode 100644 index 948f43b4b..000000000 --- a/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_conversation_profiles_set_suggestion_feature_config_async.py +++ /dev/null @@ -1,57 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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. -# -# Generated code. DO NOT EDIT! -# -# Snippet for SetSuggestionFeatureConfig -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-dialogflow - - -# [START dialogflow_v2_generated_ConversationProfiles_SetSuggestionFeatureConfig_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import dialogflow_v2 - - -async def sample_set_suggestion_feature_config(): - # Create a client - client = dialogflow_v2.ConversationProfilesAsyncClient() - - # Initialize request argument(s) - request = dialogflow_v2.SetSuggestionFeatureConfigRequest( - conversation_profile="conversation_profile_value", - participant_role="END_USER", - ) - - # Make the request - operation = client.set_suggestion_feature_config(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - -# [END dialogflow_v2_generated_ConversationProfiles_SetSuggestionFeatureConfig_async] diff --git a/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_conversation_profiles_set_suggestion_feature_config_sync.py b/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_conversation_profiles_set_suggestion_feature_config_sync.py deleted file mode 100644 index 5cf4b7604..000000000 --- a/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_conversation_profiles_set_suggestion_feature_config_sync.py +++ /dev/null @@ -1,57 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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. -# -# Generated code. DO NOT EDIT! -# -# Snippet for SetSuggestionFeatureConfig -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-dialogflow - - -# [START dialogflow_v2_generated_ConversationProfiles_SetSuggestionFeatureConfig_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import dialogflow_v2 - - -def sample_set_suggestion_feature_config(): - # Create a client - client = dialogflow_v2.ConversationProfilesClient() - - # Initialize request argument(s) - request = dialogflow_v2.SetSuggestionFeatureConfigRequest( - conversation_profile="conversation_profile_value", - participant_role="END_USER", - ) - - # Make the request - operation = client.set_suggestion_feature_config(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - -# [END dialogflow_v2_generated_ConversationProfiles_SetSuggestionFeatureConfig_sync] diff --git a/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_conversation_profiles_update_conversation_profile_async.py b/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_conversation_profiles_update_conversation_profile_async.py deleted file mode 100644 index cdc7a825f..000000000 --- a/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_conversation_profiles_update_conversation_profile_async.py +++ /dev/null @@ -1,55 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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. -# -# Generated code. DO NOT EDIT! -# -# Snippet for UpdateConversationProfile -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-dialogflow - - -# [START dialogflow_v2_generated_ConversationProfiles_UpdateConversationProfile_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import dialogflow_v2 - - -async def sample_update_conversation_profile(): - # Create a client - client = dialogflow_v2.ConversationProfilesAsyncClient() - - # Initialize request argument(s) - conversation_profile = dialogflow_v2.ConversationProfile() - conversation_profile.display_name = "display_name_value" - - request = dialogflow_v2.UpdateConversationProfileRequest( - conversation_profile=conversation_profile, - ) - - # Make the request - response = await client.update_conversation_profile(request=request) - - # Handle the response - print(response) - -# [END dialogflow_v2_generated_ConversationProfiles_UpdateConversationProfile_async] diff --git a/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_conversation_profiles_update_conversation_profile_sync.py b/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_conversation_profiles_update_conversation_profile_sync.py deleted file mode 100644 index ae1e1075c..000000000 --- a/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_conversation_profiles_update_conversation_profile_sync.py +++ /dev/null @@ -1,55 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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. -# -# Generated code. DO NOT EDIT! -# -# Snippet for UpdateConversationProfile -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-dialogflow - - -# [START dialogflow_v2_generated_ConversationProfiles_UpdateConversationProfile_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import dialogflow_v2 - - -def sample_update_conversation_profile(): - # Create a client - client = dialogflow_v2.ConversationProfilesClient() - - # Initialize request argument(s) - conversation_profile = dialogflow_v2.ConversationProfile() - conversation_profile.display_name = "display_name_value" - - request = dialogflow_v2.UpdateConversationProfileRequest( - conversation_profile=conversation_profile, - ) - - # Make the request - response = client.update_conversation_profile(request=request) - - # Handle the response - print(response) - -# [END dialogflow_v2_generated_ConversationProfiles_UpdateConversationProfile_sync] diff --git a/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_conversations_complete_conversation_async.py b/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_conversations_complete_conversation_async.py deleted file mode 100644 index 8e76c4bba..000000000 --- a/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_conversations_complete_conversation_async.py +++ /dev/null @@ -1,52 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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. -# -# Generated code. DO NOT EDIT! -# -# Snippet for CompleteConversation -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-dialogflow - - -# [START dialogflow_v2_generated_Conversations_CompleteConversation_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import dialogflow_v2 - - -async def sample_complete_conversation(): - # Create a client - client = dialogflow_v2.ConversationsAsyncClient() - - # Initialize request argument(s) - request = dialogflow_v2.CompleteConversationRequest( - name="name_value", - ) - - # Make the request - response = await client.complete_conversation(request=request) - - # Handle the response - print(response) - -# [END dialogflow_v2_generated_Conversations_CompleteConversation_async] diff --git a/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_conversations_complete_conversation_sync.py b/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_conversations_complete_conversation_sync.py deleted file mode 100644 index cbce9abb0..000000000 --- a/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_conversations_complete_conversation_sync.py +++ /dev/null @@ -1,52 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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. -# -# Generated code. DO NOT EDIT! -# -# Snippet for CompleteConversation -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-dialogflow - - -# [START dialogflow_v2_generated_Conversations_CompleteConversation_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import dialogflow_v2 - - -def sample_complete_conversation(): - # Create a client - client = dialogflow_v2.ConversationsClient() - - # Initialize request argument(s) - request = dialogflow_v2.CompleteConversationRequest( - name="name_value", - ) - - # Make the request - response = client.complete_conversation(request=request) - - # Handle the response - print(response) - -# [END dialogflow_v2_generated_Conversations_CompleteConversation_sync] diff --git a/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_conversations_create_conversation_async.py b/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_conversations_create_conversation_async.py deleted file mode 100644 index b1dda04f5..000000000 --- a/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_conversations_create_conversation_async.py +++ /dev/null @@ -1,56 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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. -# -# Generated code. DO NOT EDIT! -# -# Snippet for CreateConversation -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-dialogflow - - -# [START dialogflow_v2_generated_Conversations_CreateConversation_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import dialogflow_v2 - - -async def sample_create_conversation(): - # Create a client - client = dialogflow_v2.ConversationsAsyncClient() - - # Initialize request argument(s) - conversation = dialogflow_v2.Conversation() - conversation.conversation_profile = "conversation_profile_value" - - request = dialogflow_v2.CreateConversationRequest( - parent="parent_value", - conversation=conversation, - ) - - # Make the request - response = await client.create_conversation(request=request) - - # Handle the response - print(response) - -# [END dialogflow_v2_generated_Conversations_CreateConversation_async] diff --git a/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_conversations_create_conversation_sync.py b/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_conversations_create_conversation_sync.py deleted file mode 100644 index 18007f565..000000000 --- a/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_conversations_create_conversation_sync.py +++ /dev/null @@ -1,56 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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. -# -# Generated code. DO NOT EDIT! -# -# Snippet for CreateConversation -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-dialogflow - - -# [START dialogflow_v2_generated_Conversations_CreateConversation_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import dialogflow_v2 - - -def sample_create_conversation(): - # Create a client - client = dialogflow_v2.ConversationsClient() - - # Initialize request argument(s) - conversation = dialogflow_v2.Conversation() - conversation.conversation_profile = "conversation_profile_value" - - request = dialogflow_v2.CreateConversationRequest( - parent="parent_value", - conversation=conversation, - ) - - # Make the request - response = client.create_conversation(request=request) - - # Handle the response - print(response) - -# [END dialogflow_v2_generated_Conversations_CreateConversation_sync] diff --git a/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_conversations_get_conversation_async.py b/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_conversations_get_conversation_async.py deleted file mode 100644 index 524f40d13..000000000 --- a/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_conversations_get_conversation_async.py +++ /dev/null @@ -1,52 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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. -# -# Generated code. DO NOT EDIT! -# -# Snippet for GetConversation -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-dialogflow - - -# [START dialogflow_v2_generated_Conversations_GetConversation_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import dialogflow_v2 - - -async def sample_get_conversation(): - # Create a client - client = dialogflow_v2.ConversationsAsyncClient() - - # Initialize request argument(s) - request = dialogflow_v2.GetConversationRequest( - name="name_value", - ) - - # Make the request - response = await client.get_conversation(request=request) - - # Handle the response - print(response) - -# [END dialogflow_v2_generated_Conversations_GetConversation_async] diff --git a/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_conversations_get_conversation_sync.py b/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_conversations_get_conversation_sync.py deleted file mode 100644 index 9adc2c939..000000000 --- a/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_conversations_get_conversation_sync.py +++ /dev/null @@ -1,52 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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. -# -# Generated code. DO NOT EDIT! -# -# Snippet for GetConversation -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-dialogflow - - -# [START dialogflow_v2_generated_Conversations_GetConversation_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import dialogflow_v2 - - -def sample_get_conversation(): - # Create a client - client = dialogflow_v2.ConversationsClient() - - # Initialize request argument(s) - request = dialogflow_v2.GetConversationRequest( - name="name_value", - ) - - # Make the request - response = client.get_conversation(request=request) - - # Handle the response - print(response) - -# [END dialogflow_v2_generated_Conversations_GetConversation_sync] diff --git a/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_conversations_list_conversations_async.py b/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_conversations_list_conversations_async.py deleted file mode 100644 index b45c9fb4f..000000000 --- a/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_conversations_list_conversations_async.py +++ /dev/null @@ -1,53 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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. -# -# Generated code. DO NOT EDIT! -# -# Snippet for ListConversations -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-dialogflow - - -# [START dialogflow_v2_generated_Conversations_ListConversations_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import dialogflow_v2 - - -async def sample_list_conversations(): - # Create a client - client = dialogflow_v2.ConversationsAsyncClient() - - # Initialize request argument(s) - request = dialogflow_v2.ListConversationsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_conversations(request=request) - - # Handle the response - async for response in page_result: - print(response) - -# [END dialogflow_v2_generated_Conversations_ListConversations_async] diff --git a/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_conversations_list_conversations_sync.py b/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_conversations_list_conversations_sync.py deleted file mode 100644 index ac64eba36..000000000 --- a/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_conversations_list_conversations_sync.py +++ /dev/null @@ -1,53 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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. -# -# Generated code. DO NOT EDIT! -# -# Snippet for ListConversations -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-dialogflow - - -# [START dialogflow_v2_generated_Conversations_ListConversations_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import dialogflow_v2 - - -def sample_list_conversations(): - # Create a client - client = dialogflow_v2.ConversationsClient() - - # Initialize request argument(s) - request = dialogflow_v2.ListConversationsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_conversations(request=request) - - # Handle the response - for response in page_result: - print(response) - -# [END dialogflow_v2_generated_Conversations_ListConversations_sync] diff --git a/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_conversations_list_messages_async.py b/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_conversations_list_messages_async.py deleted file mode 100644 index 546511ed8..000000000 --- a/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_conversations_list_messages_async.py +++ /dev/null @@ -1,53 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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. -# -# Generated code. DO NOT EDIT! -# -# Snippet for ListMessages -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-dialogflow - - -# [START dialogflow_v2_generated_Conversations_ListMessages_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import dialogflow_v2 - - -async def sample_list_messages(): - # Create a client - client = dialogflow_v2.ConversationsAsyncClient() - - # Initialize request argument(s) - request = dialogflow_v2.ListMessagesRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_messages(request=request) - - # Handle the response - async for response in page_result: - print(response) - -# [END dialogflow_v2_generated_Conversations_ListMessages_async] diff --git a/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_conversations_list_messages_sync.py b/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_conversations_list_messages_sync.py deleted file mode 100644 index 03b964449..000000000 --- a/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_conversations_list_messages_sync.py +++ /dev/null @@ -1,53 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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. -# -# Generated code. DO NOT EDIT! -# -# Snippet for ListMessages -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-dialogflow - - -# [START dialogflow_v2_generated_Conversations_ListMessages_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import dialogflow_v2 - - -def sample_list_messages(): - # Create a client - client = dialogflow_v2.ConversationsClient() - - # Initialize request argument(s) - request = dialogflow_v2.ListMessagesRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_messages(request=request) - - # Handle the response - for response in page_result: - print(response) - -# [END dialogflow_v2_generated_Conversations_ListMessages_sync] diff --git a/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_conversations_suggest_conversation_summary_async.py b/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_conversations_suggest_conversation_summary_async.py deleted file mode 100644 index f36e6a5ea..000000000 --- a/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_conversations_suggest_conversation_summary_async.py +++ /dev/null @@ -1,52 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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. -# -# Generated code. DO NOT EDIT! -# -# Snippet for SuggestConversationSummary -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-dialogflow - - -# [START dialogflow_v2_generated_Conversations_SuggestConversationSummary_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import dialogflow_v2 - - -async def sample_suggest_conversation_summary(): - # Create a client - client = dialogflow_v2.ConversationsAsyncClient() - - # Initialize request argument(s) - request = dialogflow_v2.SuggestConversationSummaryRequest( - conversation="conversation_value", - ) - - # Make the request - response = await client.suggest_conversation_summary(request=request) - - # Handle the response - print(response) - -# [END dialogflow_v2_generated_Conversations_SuggestConversationSummary_async] diff --git a/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_conversations_suggest_conversation_summary_sync.py b/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_conversations_suggest_conversation_summary_sync.py deleted file mode 100644 index 7f6e8701e..000000000 --- a/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_conversations_suggest_conversation_summary_sync.py +++ /dev/null @@ -1,52 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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. -# -# Generated code. DO NOT EDIT! -# -# Snippet for SuggestConversationSummary -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-dialogflow - - -# [START dialogflow_v2_generated_Conversations_SuggestConversationSummary_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import dialogflow_v2 - - -def sample_suggest_conversation_summary(): - # Create a client - client = dialogflow_v2.ConversationsClient() - - # Initialize request argument(s) - request = dialogflow_v2.SuggestConversationSummaryRequest( - conversation="conversation_value", - ) - - # Make the request - response = client.suggest_conversation_summary(request=request) - - # Handle the response - print(response) - -# [END dialogflow_v2_generated_Conversations_SuggestConversationSummary_sync] diff --git a/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_documents_create_document_async.py b/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_documents_create_document_async.py deleted file mode 100644 index d809d1592..000000000 --- a/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_documents_create_document_async.py +++ /dev/null @@ -1,63 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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. -# -# Generated code. DO NOT EDIT! -# -# Snippet for CreateDocument -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-dialogflow - - -# [START dialogflow_v2_generated_Documents_CreateDocument_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import dialogflow_v2 - - -async def sample_create_document(): - # Create a client - client = dialogflow_v2.DocumentsAsyncClient() - - # Initialize request argument(s) - document = dialogflow_v2.Document() - document.content_uri = "content_uri_value" - document.display_name = "display_name_value" - document.mime_type = "mime_type_value" - document.knowledge_types = ['AGENT_FACING_SMART_REPLY'] - - request = dialogflow_v2.CreateDocumentRequest( - parent="parent_value", - document=document, - ) - - # Make the request - operation = client.create_document(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - -# [END dialogflow_v2_generated_Documents_CreateDocument_async] diff --git a/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_documents_create_document_sync.py b/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_documents_create_document_sync.py deleted file mode 100644 index 70d4a9cdf..000000000 --- a/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_documents_create_document_sync.py +++ /dev/null @@ -1,63 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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. -# -# Generated code. DO NOT EDIT! -# -# Snippet for CreateDocument -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-dialogflow - - -# [START dialogflow_v2_generated_Documents_CreateDocument_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import dialogflow_v2 - - -def sample_create_document(): - # Create a client - client = dialogflow_v2.DocumentsClient() - - # Initialize request argument(s) - document = dialogflow_v2.Document() - document.content_uri = "content_uri_value" - document.display_name = "display_name_value" - document.mime_type = "mime_type_value" - document.knowledge_types = ['AGENT_FACING_SMART_REPLY'] - - request = dialogflow_v2.CreateDocumentRequest( - parent="parent_value", - document=document, - ) - - # Make the request - operation = client.create_document(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - -# [END dialogflow_v2_generated_Documents_CreateDocument_sync] diff --git a/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_documents_delete_document_async.py b/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_documents_delete_document_async.py deleted file mode 100644 index f132dc3cb..000000000 --- a/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_documents_delete_document_async.py +++ /dev/null @@ -1,56 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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. -# -# Generated code. DO NOT EDIT! -# -# Snippet for DeleteDocument -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-dialogflow - - -# [START dialogflow_v2_generated_Documents_DeleteDocument_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import dialogflow_v2 - - -async def sample_delete_document(): - # Create a client - client = dialogflow_v2.DocumentsAsyncClient() - - # Initialize request argument(s) - request = dialogflow_v2.DeleteDocumentRequest( - name="name_value", - ) - - # Make the request - operation = client.delete_document(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - -# [END dialogflow_v2_generated_Documents_DeleteDocument_async] diff --git a/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_documents_delete_document_sync.py b/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_documents_delete_document_sync.py deleted file mode 100644 index 29308bfa3..000000000 --- a/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_documents_delete_document_sync.py +++ /dev/null @@ -1,56 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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. -# -# Generated code. DO NOT EDIT! -# -# Snippet for DeleteDocument -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-dialogflow - - -# [START dialogflow_v2_generated_Documents_DeleteDocument_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import dialogflow_v2 - - -def sample_delete_document(): - # Create a client - client = dialogflow_v2.DocumentsClient() - - # Initialize request argument(s) - request = dialogflow_v2.DeleteDocumentRequest( - name="name_value", - ) - - # Make the request - operation = client.delete_document(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - -# [END dialogflow_v2_generated_Documents_DeleteDocument_sync] diff --git a/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_documents_export_document_async.py b/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_documents_export_document_async.py deleted file mode 100644 index 4819de9e7..000000000 --- a/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_documents_export_document_async.py +++ /dev/null @@ -1,56 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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. -# -# Generated code. DO NOT EDIT! -# -# Snippet for ExportDocument -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-dialogflow - - -# [START dialogflow_v2_generated_Documents_ExportDocument_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import dialogflow_v2 - - -async def sample_export_document(): - # Create a client - client = dialogflow_v2.DocumentsAsyncClient() - - # Initialize request argument(s) - request = dialogflow_v2.ExportDocumentRequest( - name="name_value", - ) - - # Make the request - operation = client.export_document(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - -# [END dialogflow_v2_generated_Documents_ExportDocument_async] diff --git a/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_documents_export_document_sync.py b/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_documents_export_document_sync.py deleted file mode 100644 index 7e95abd6b..000000000 --- a/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_documents_export_document_sync.py +++ /dev/null @@ -1,56 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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. -# -# Generated code. DO NOT EDIT! -# -# Snippet for ExportDocument -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-dialogflow - - -# [START dialogflow_v2_generated_Documents_ExportDocument_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import dialogflow_v2 - - -def sample_export_document(): - # Create a client - client = dialogflow_v2.DocumentsClient() - - # Initialize request argument(s) - request = dialogflow_v2.ExportDocumentRequest( - name="name_value", - ) - - # Make the request - operation = client.export_document(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - -# [END dialogflow_v2_generated_Documents_ExportDocument_sync] diff --git a/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_documents_get_document_async.py b/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_documents_get_document_async.py deleted file mode 100644 index b3f049ea0..000000000 --- a/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_documents_get_document_async.py +++ /dev/null @@ -1,52 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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. -# -# Generated code. DO NOT EDIT! -# -# Snippet for GetDocument -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-dialogflow - - -# [START dialogflow_v2_generated_Documents_GetDocument_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import dialogflow_v2 - - -async def sample_get_document(): - # Create a client - client = dialogflow_v2.DocumentsAsyncClient() - - # Initialize request argument(s) - request = dialogflow_v2.GetDocumentRequest( - name="name_value", - ) - - # Make the request - response = await client.get_document(request=request) - - # Handle the response - print(response) - -# [END dialogflow_v2_generated_Documents_GetDocument_async] diff --git a/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_documents_get_document_sync.py b/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_documents_get_document_sync.py deleted file mode 100644 index 6889bea12..000000000 --- a/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_documents_get_document_sync.py +++ /dev/null @@ -1,52 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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. -# -# Generated code. DO NOT EDIT! -# -# Snippet for GetDocument -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-dialogflow - - -# [START dialogflow_v2_generated_Documents_GetDocument_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import dialogflow_v2 - - -def sample_get_document(): - # Create a client - client = dialogflow_v2.DocumentsClient() - - # Initialize request argument(s) - request = dialogflow_v2.GetDocumentRequest( - name="name_value", - ) - - # Make the request - response = client.get_document(request=request) - - # Handle the response - print(response) - -# [END dialogflow_v2_generated_Documents_GetDocument_sync] diff --git a/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_documents_import_documents_async.py b/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_documents_import_documents_async.py deleted file mode 100644 index 37441b731..000000000 --- a/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_documents_import_documents_async.py +++ /dev/null @@ -1,65 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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. -# -# Generated code. DO NOT EDIT! -# -# Snippet for ImportDocuments -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-dialogflow - - -# [START dialogflow_v2_generated_Documents_ImportDocuments_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import dialogflow_v2 - - -async def sample_import_documents(): - # Create a client - client = dialogflow_v2.DocumentsAsyncClient() - - # Initialize request argument(s) - gcs_source = dialogflow_v2.GcsSources() - gcs_source.uris = ['uris_value1', 'uris_value2'] - - document_template = dialogflow_v2.ImportDocumentTemplate() - document_template.mime_type = "mime_type_value" - document_template.knowledge_types = ['AGENT_FACING_SMART_REPLY'] - - request = dialogflow_v2.ImportDocumentsRequest( - gcs_source=gcs_source, - parent="parent_value", - document_template=document_template, - ) - - # Make the request - operation = client.import_documents(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - -# [END dialogflow_v2_generated_Documents_ImportDocuments_async] diff --git a/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_documents_import_documents_sync.py b/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_documents_import_documents_sync.py deleted file mode 100644 index 7cf8582e8..000000000 --- a/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_documents_import_documents_sync.py +++ /dev/null @@ -1,65 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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. -# -# Generated code. DO NOT EDIT! -# -# Snippet for ImportDocuments -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-dialogflow - - -# [START dialogflow_v2_generated_Documents_ImportDocuments_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import dialogflow_v2 - - -def sample_import_documents(): - # Create a client - client = dialogflow_v2.DocumentsClient() - - # Initialize request argument(s) - gcs_source = dialogflow_v2.GcsSources() - gcs_source.uris = ['uris_value1', 'uris_value2'] - - document_template = dialogflow_v2.ImportDocumentTemplate() - document_template.mime_type = "mime_type_value" - document_template.knowledge_types = ['AGENT_FACING_SMART_REPLY'] - - request = dialogflow_v2.ImportDocumentsRequest( - gcs_source=gcs_source, - parent="parent_value", - document_template=document_template, - ) - - # Make the request - operation = client.import_documents(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - -# [END dialogflow_v2_generated_Documents_ImportDocuments_sync] diff --git a/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_documents_list_documents_async.py b/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_documents_list_documents_async.py deleted file mode 100644 index ae74e62b2..000000000 --- a/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_documents_list_documents_async.py +++ /dev/null @@ -1,53 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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. -# -# Generated code. DO NOT EDIT! -# -# Snippet for ListDocuments -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-dialogflow - - -# [START dialogflow_v2_generated_Documents_ListDocuments_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import dialogflow_v2 - - -async def sample_list_documents(): - # Create a client - client = dialogflow_v2.DocumentsAsyncClient() - - # Initialize request argument(s) - request = dialogflow_v2.ListDocumentsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_documents(request=request) - - # Handle the response - async for response in page_result: - print(response) - -# [END dialogflow_v2_generated_Documents_ListDocuments_async] diff --git a/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_documents_list_documents_sync.py b/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_documents_list_documents_sync.py deleted file mode 100644 index 794475166..000000000 --- a/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_documents_list_documents_sync.py +++ /dev/null @@ -1,53 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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. -# -# Generated code. DO NOT EDIT! -# -# Snippet for ListDocuments -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-dialogflow - - -# [START dialogflow_v2_generated_Documents_ListDocuments_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import dialogflow_v2 - - -def sample_list_documents(): - # Create a client - client = dialogflow_v2.DocumentsClient() - - # Initialize request argument(s) - request = dialogflow_v2.ListDocumentsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_documents(request=request) - - # Handle the response - for response in page_result: - print(response) - -# [END dialogflow_v2_generated_Documents_ListDocuments_sync] diff --git a/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_documents_reload_document_async.py b/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_documents_reload_document_async.py deleted file mode 100644 index 32406990c..000000000 --- a/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_documents_reload_document_async.py +++ /dev/null @@ -1,57 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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. -# -# Generated code. DO NOT EDIT! -# -# Snippet for ReloadDocument -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-dialogflow - - -# [START dialogflow_v2_generated_Documents_ReloadDocument_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import dialogflow_v2 - - -async def sample_reload_document(): - # Create a client - client = dialogflow_v2.DocumentsAsyncClient() - - # Initialize request argument(s) - request = dialogflow_v2.ReloadDocumentRequest( - content_uri="content_uri_value", - name="name_value", - ) - - # Make the request - operation = client.reload_document(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - -# [END dialogflow_v2_generated_Documents_ReloadDocument_async] diff --git a/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_documents_reload_document_sync.py b/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_documents_reload_document_sync.py deleted file mode 100644 index 5adf2120f..000000000 --- a/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_documents_reload_document_sync.py +++ /dev/null @@ -1,57 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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. -# -# Generated code. DO NOT EDIT! -# -# Snippet for ReloadDocument -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-dialogflow - - -# [START dialogflow_v2_generated_Documents_ReloadDocument_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import dialogflow_v2 - - -def sample_reload_document(): - # Create a client - client = dialogflow_v2.DocumentsClient() - - # Initialize request argument(s) - request = dialogflow_v2.ReloadDocumentRequest( - content_uri="content_uri_value", - name="name_value", - ) - - # Make the request - operation = client.reload_document(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - -# [END dialogflow_v2_generated_Documents_ReloadDocument_sync] diff --git a/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_documents_update_document_async.py b/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_documents_update_document_async.py deleted file mode 100644 index 39affbf2d..000000000 --- a/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_documents_update_document_async.py +++ /dev/null @@ -1,62 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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. -# -# Generated code. DO NOT EDIT! -# -# Snippet for UpdateDocument -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-dialogflow - - -# [START dialogflow_v2_generated_Documents_UpdateDocument_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import dialogflow_v2 - - -async def sample_update_document(): - # Create a client - client = dialogflow_v2.DocumentsAsyncClient() - - # Initialize request argument(s) - document = dialogflow_v2.Document() - document.content_uri = "content_uri_value" - document.display_name = "display_name_value" - document.mime_type = "mime_type_value" - document.knowledge_types = ['AGENT_FACING_SMART_REPLY'] - - request = dialogflow_v2.UpdateDocumentRequest( - document=document, - ) - - # Make the request - operation = client.update_document(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - -# [END dialogflow_v2_generated_Documents_UpdateDocument_async] diff --git a/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_documents_update_document_sync.py b/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_documents_update_document_sync.py deleted file mode 100644 index df546764f..000000000 --- a/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_documents_update_document_sync.py +++ /dev/null @@ -1,62 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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. -# -# Generated code. DO NOT EDIT! -# -# Snippet for UpdateDocument -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-dialogflow - - -# [START dialogflow_v2_generated_Documents_UpdateDocument_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import dialogflow_v2 - - -def sample_update_document(): - # Create a client - client = dialogflow_v2.DocumentsClient() - - # Initialize request argument(s) - document = dialogflow_v2.Document() - document.content_uri = "content_uri_value" - document.display_name = "display_name_value" - document.mime_type = "mime_type_value" - document.knowledge_types = ['AGENT_FACING_SMART_REPLY'] - - request = dialogflow_v2.UpdateDocumentRequest( - document=document, - ) - - # Make the request - operation = client.update_document(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - -# [END dialogflow_v2_generated_Documents_UpdateDocument_sync] diff --git a/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_entity_types_batch_create_entities_async.py b/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_entity_types_batch_create_entities_async.py deleted file mode 100644 index d23dfdd26..000000000 --- a/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_entity_types_batch_create_entities_async.py +++ /dev/null @@ -1,61 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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. -# -# Generated code. DO NOT EDIT! -# -# Snippet for BatchCreateEntities -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-dialogflow - - -# [START dialogflow_v2_generated_EntityTypes_BatchCreateEntities_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import dialogflow_v2 - - -async def sample_batch_create_entities(): - # Create a client - client = dialogflow_v2.EntityTypesAsyncClient() - - # Initialize request argument(s) - entities = dialogflow_v2.Entity() - entities.value = "value_value" - entities.synonyms = ['synonyms_value1', 'synonyms_value2'] - - request = dialogflow_v2.BatchCreateEntitiesRequest( - parent="parent_value", - entities=entities, - ) - - # Make the request - operation = client.batch_create_entities(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - -# [END dialogflow_v2_generated_EntityTypes_BatchCreateEntities_async] diff --git a/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_entity_types_batch_create_entities_sync.py b/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_entity_types_batch_create_entities_sync.py deleted file mode 100644 index 8611dc976..000000000 --- a/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_entity_types_batch_create_entities_sync.py +++ /dev/null @@ -1,61 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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. -# -# Generated code. DO NOT EDIT! -# -# Snippet for BatchCreateEntities -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-dialogflow - - -# [START dialogflow_v2_generated_EntityTypes_BatchCreateEntities_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import dialogflow_v2 - - -def sample_batch_create_entities(): - # Create a client - client = dialogflow_v2.EntityTypesClient() - - # Initialize request argument(s) - entities = dialogflow_v2.Entity() - entities.value = "value_value" - entities.synonyms = ['synonyms_value1', 'synonyms_value2'] - - request = dialogflow_v2.BatchCreateEntitiesRequest( - parent="parent_value", - entities=entities, - ) - - # Make the request - operation = client.batch_create_entities(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - -# [END dialogflow_v2_generated_EntityTypes_BatchCreateEntities_sync] diff --git a/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_entity_types_batch_delete_entities_async.py b/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_entity_types_batch_delete_entities_async.py deleted file mode 100644 index 46c1ae69f..000000000 --- a/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_entity_types_batch_delete_entities_async.py +++ /dev/null @@ -1,57 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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. -# -# Generated code. DO NOT EDIT! -# -# Snippet for BatchDeleteEntities -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-dialogflow - - -# [START dialogflow_v2_generated_EntityTypes_BatchDeleteEntities_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import dialogflow_v2 - - -async def sample_batch_delete_entities(): - # Create a client - client = dialogflow_v2.EntityTypesAsyncClient() - - # Initialize request argument(s) - request = dialogflow_v2.BatchDeleteEntitiesRequest( - parent="parent_value", - entity_values=['entity_values_value1', 'entity_values_value2'], - ) - - # Make the request - operation = client.batch_delete_entities(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - -# [END dialogflow_v2_generated_EntityTypes_BatchDeleteEntities_async] diff --git a/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_entity_types_batch_delete_entities_sync.py b/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_entity_types_batch_delete_entities_sync.py deleted file mode 100644 index d76b852ab..000000000 --- a/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_entity_types_batch_delete_entities_sync.py +++ /dev/null @@ -1,57 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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. -# -# Generated code. DO NOT EDIT! -# -# Snippet for BatchDeleteEntities -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-dialogflow - - -# [START dialogflow_v2_generated_EntityTypes_BatchDeleteEntities_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import dialogflow_v2 - - -def sample_batch_delete_entities(): - # Create a client - client = dialogflow_v2.EntityTypesClient() - - # Initialize request argument(s) - request = dialogflow_v2.BatchDeleteEntitiesRequest( - parent="parent_value", - entity_values=['entity_values_value1', 'entity_values_value2'], - ) - - # Make the request - operation = client.batch_delete_entities(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - -# [END dialogflow_v2_generated_EntityTypes_BatchDeleteEntities_sync] diff --git a/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_entity_types_batch_delete_entity_types_async.py b/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_entity_types_batch_delete_entity_types_async.py deleted file mode 100644 index d232ddfc0..000000000 --- a/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_entity_types_batch_delete_entity_types_async.py +++ /dev/null @@ -1,57 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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. -# -# Generated code. DO NOT EDIT! -# -# Snippet for BatchDeleteEntityTypes -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-dialogflow - - -# [START dialogflow_v2_generated_EntityTypes_BatchDeleteEntityTypes_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import dialogflow_v2 - - -async def sample_batch_delete_entity_types(): - # Create a client - client = dialogflow_v2.EntityTypesAsyncClient() - - # Initialize request argument(s) - request = dialogflow_v2.BatchDeleteEntityTypesRequest( - parent="parent_value", - entity_type_names=['entity_type_names_value1', 'entity_type_names_value2'], - ) - - # Make the request - operation = client.batch_delete_entity_types(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - -# [END dialogflow_v2_generated_EntityTypes_BatchDeleteEntityTypes_async] diff --git a/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_entity_types_batch_delete_entity_types_sync.py b/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_entity_types_batch_delete_entity_types_sync.py deleted file mode 100644 index b0479ad11..000000000 --- a/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_entity_types_batch_delete_entity_types_sync.py +++ /dev/null @@ -1,57 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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. -# -# Generated code. DO NOT EDIT! -# -# Snippet for BatchDeleteEntityTypes -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-dialogflow - - -# [START dialogflow_v2_generated_EntityTypes_BatchDeleteEntityTypes_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import dialogflow_v2 - - -def sample_batch_delete_entity_types(): - # Create a client - client = dialogflow_v2.EntityTypesClient() - - # Initialize request argument(s) - request = dialogflow_v2.BatchDeleteEntityTypesRequest( - parent="parent_value", - entity_type_names=['entity_type_names_value1', 'entity_type_names_value2'], - ) - - # Make the request - operation = client.batch_delete_entity_types(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - -# [END dialogflow_v2_generated_EntityTypes_BatchDeleteEntityTypes_sync] diff --git a/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_entity_types_batch_update_entities_async.py b/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_entity_types_batch_update_entities_async.py deleted file mode 100644 index c56ab79aa..000000000 --- a/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_entity_types_batch_update_entities_async.py +++ /dev/null @@ -1,61 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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. -# -# Generated code. DO NOT EDIT! -# -# Snippet for BatchUpdateEntities -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-dialogflow - - -# [START dialogflow_v2_generated_EntityTypes_BatchUpdateEntities_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import dialogflow_v2 - - -async def sample_batch_update_entities(): - # Create a client - client = dialogflow_v2.EntityTypesAsyncClient() - - # Initialize request argument(s) - entities = dialogflow_v2.Entity() - entities.value = "value_value" - entities.synonyms = ['synonyms_value1', 'synonyms_value2'] - - request = dialogflow_v2.BatchUpdateEntitiesRequest( - parent="parent_value", - entities=entities, - ) - - # Make the request - operation = client.batch_update_entities(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - -# [END dialogflow_v2_generated_EntityTypes_BatchUpdateEntities_async] diff --git a/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_entity_types_batch_update_entities_sync.py b/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_entity_types_batch_update_entities_sync.py deleted file mode 100644 index 5505597b8..000000000 --- a/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_entity_types_batch_update_entities_sync.py +++ /dev/null @@ -1,61 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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. -# -# Generated code. DO NOT EDIT! -# -# Snippet for BatchUpdateEntities -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-dialogflow - - -# [START dialogflow_v2_generated_EntityTypes_BatchUpdateEntities_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import dialogflow_v2 - - -def sample_batch_update_entities(): - # Create a client - client = dialogflow_v2.EntityTypesClient() - - # Initialize request argument(s) - entities = dialogflow_v2.Entity() - entities.value = "value_value" - entities.synonyms = ['synonyms_value1', 'synonyms_value2'] - - request = dialogflow_v2.BatchUpdateEntitiesRequest( - parent="parent_value", - entities=entities, - ) - - # Make the request - operation = client.batch_update_entities(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - -# [END dialogflow_v2_generated_EntityTypes_BatchUpdateEntities_sync] diff --git a/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_entity_types_batch_update_entity_types_async.py b/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_entity_types_batch_update_entity_types_async.py deleted file mode 100644 index e63430028..000000000 --- a/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_entity_types_batch_update_entity_types_async.py +++ /dev/null @@ -1,57 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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. -# -# Generated code. DO NOT EDIT! -# -# Snippet for BatchUpdateEntityTypes -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-dialogflow - - -# [START dialogflow_v2_generated_EntityTypes_BatchUpdateEntityTypes_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import dialogflow_v2 - - -async def sample_batch_update_entity_types(): - # Create a client - client = dialogflow_v2.EntityTypesAsyncClient() - - # Initialize request argument(s) - request = dialogflow_v2.BatchUpdateEntityTypesRequest( - entity_type_batch_uri="entity_type_batch_uri_value", - parent="parent_value", - ) - - # Make the request - operation = client.batch_update_entity_types(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - -# [END dialogflow_v2_generated_EntityTypes_BatchUpdateEntityTypes_async] diff --git a/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_entity_types_batch_update_entity_types_sync.py b/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_entity_types_batch_update_entity_types_sync.py deleted file mode 100644 index 2676ff062..000000000 --- a/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_entity_types_batch_update_entity_types_sync.py +++ /dev/null @@ -1,57 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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. -# -# Generated code. DO NOT EDIT! -# -# Snippet for BatchUpdateEntityTypes -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-dialogflow - - -# [START dialogflow_v2_generated_EntityTypes_BatchUpdateEntityTypes_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import dialogflow_v2 - - -def sample_batch_update_entity_types(): - # Create a client - client = dialogflow_v2.EntityTypesClient() - - # Initialize request argument(s) - request = dialogflow_v2.BatchUpdateEntityTypesRequest( - entity_type_batch_uri="entity_type_batch_uri_value", - parent="parent_value", - ) - - # Make the request - operation = client.batch_update_entity_types(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - -# [END dialogflow_v2_generated_EntityTypes_BatchUpdateEntityTypes_sync] diff --git a/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_entity_types_create_entity_type_async.py b/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_entity_types_create_entity_type_async.py deleted file mode 100644 index 9d54836c7..000000000 --- a/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_entity_types_create_entity_type_async.py +++ /dev/null @@ -1,57 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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. -# -# Generated code. DO NOT EDIT! -# -# Snippet for CreateEntityType -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-dialogflow - - -# [START dialogflow_v2_generated_EntityTypes_CreateEntityType_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import dialogflow_v2 - - -async def sample_create_entity_type(): - # Create a client - client = dialogflow_v2.EntityTypesAsyncClient() - - # Initialize request argument(s) - entity_type = dialogflow_v2.EntityType() - entity_type.display_name = "display_name_value" - entity_type.kind = "KIND_REGEXP" - - request = dialogflow_v2.CreateEntityTypeRequest( - parent="parent_value", - entity_type=entity_type, - ) - - # Make the request - response = await client.create_entity_type(request=request) - - # Handle the response - print(response) - -# [END dialogflow_v2_generated_EntityTypes_CreateEntityType_async] diff --git a/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_entity_types_create_entity_type_sync.py b/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_entity_types_create_entity_type_sync.py deleted file mode 100644 index 9fe8e9ee4..000000000 --- a/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_entity_types_create_entity_type_sync.py +++ /dev/null @@ -1,57 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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. -# -# Generated code. DO NOT EDIT! -# -# Snippet for CreateEntityType -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-dialogflow - - -# [START dialogflow_v2_generated_EntityTypes_CreateEntityType_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import dialogflow_v2 - - -def sample_create_entity_type(): - # Create a client - client = dialogflow_v2.EntityTypesClient() - - # Initialize request argument(s) - entity_type = dialogflow_v2.EntityType() - entity_type.display_name = "display_name_value" - entity_type.kind = "KIND_REGEXP" - - request = dialogflow_v2.CreateEntityTypeRequest( - parent="parent_value", - entity_type=entity_type, - ) - - # Make the request - response = client.create_entity_type(request=request) - - # Handle the response - print(response) - -# [END dialogflow_v2_generated_EntityTypes_CreateEntityType_sync] diff --git a/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_entity_types_delete_entity_type_async.py b/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_entity_types_delete_entity_type_async.py deleted file mode 100644 index e05705038..000000000 --- a/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_entity_types_delete_entity_type_async.py +++ /dev/null @@ -1,50 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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. -# -# Generated code. DO NOT EDIT! -# -# Snippet for DeleteEntityType -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-dialogflow - - -# [START dialogflow_v2_generated_EntityTypes_DeleteEntityType_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import dialogflow_v2 - - -async def sample_delete_entity_type(): - # Create a client - client = dialogflow_v2.EntityTypesAsyncClient() - - # Initialize request argument(s) - request = dialogflow_v2.DeleteEntityTypeRequest( - name="name_value", - ) - - # Make the request - await client.delete_entity_type(request=request) - - -# [END dialogflow_v2_generated_EntityTypes_DeleteEntityType_async] diff --git a/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_entity_types_delete_entity_type_sync.py b/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_entity_types_delete_entity_type_sync.py deleted file mode 100644 index 31e564cc9..000000000 --- a/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_entity_types_delete_entity_type_sync.py +++ /dev/null @@ -1,50 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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. -# -# Generated code. DO NOT EDIT! -# -# Snippet for DeleteEntityType -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-dialogflow - - -# [START dialogflow_v2_generated_EntityTypes_DeleteEntityType_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import dialogflow_v2 - - -def sample_delete_entity_type(): - # Create a client - client = dialogflow_v2.EntityTypesClient() - - # Initialize request argument(s) - request = dialogflow_v2.DeleteEntityTypeRequest( - name="name_value", - ) - - # Make the request - client.delete_entity_type(request=request) - - -# [END dialogflow_v2_generated_EntityTypes_DeleteEntityType_sync] diff --git a/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_entity_types_get_entity_type_async.py b/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_entity_types_get_entity_type_async.py deleted file mode 100644 index 582cc5d88..000000000 --- a/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_entity_types_get_entity_type_async.py +++ /dev/null @@ -1,52 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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. -# -# Generated code. DO NOT EDIT! -# -# Snippet for GetEntityType -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-dialogflow - - -# [START dialogflow_v2_generated_EntityTypes_GetEntityType_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import dialogflow_v2 - - -async def sample_get_entity_type(): - # Create a client - client = dialogflow_v2.EntityTypesAsyncClient() - - # Initialize request argument(s) - request = dialogflow_v2.GetEntityTypeRequest( - name="name_value", - ) - - # Make the request - response = await client.get_entity_type(request=request) - - # Handle the response - print(response) - -# [END dialogflow_v2_generated_EntityTypes_GetEntityType_async] diff --git a/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_entity_types_get_entity_type_sync.py b/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_entity_types_get_entity_type_sync.py deleted file mode 100644 index ba8abfec2..000000000 --- a/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_entity_types_get_entity_type_sync.py +++ /dev/null @@ -1,52 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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. -# -# Generated code. DO NOT EDIT! -# -# Snippet for GetEntityType -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-dialogflow - - -# [START dialogflow_v2_generated_EntityTypes_GetEntityType_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import dialogflow_v2 - - -def sample_get_entity_type(): - # Create a client - client = dialogflow_v2.EntityTypesClient() - - # Initialize request argument(s) - request = dialogflow_v2.GetEntityTypeRequest( - name="name_value", - ) - - # Make the request - response = client.get_entity_type(request=request) - - # Handle the response - print(response) - -# [END dialogflow_v2_generated_EntityTypes_GetEntityType_sync] diff --git a/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_entity_types_list_entity_types_async.py b/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_entity_types_list_entity_types_async.py deleted file mode 100644 index 5caa10c8f..000000000 --- a/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_entity_types_list_entity_types_async.py +++ /dev/null @@ -1,53 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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. -# -# Generated code. DO NOT EDIT! -# -# Snippet for ListEntityTypes -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-dialogflow - - -# [START dialogflow_v2_generated_EntityTypes_ListEntityTypes_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import dialogflow_v2 - - -async def sample_list_entity_types(): - # Create a client - client = dialogflow_v2.EntityTypesAsyncClient() - - # Initialize request argument(s) - request = dialogflow_v2.ListEntityTypesRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_entity_types(request=request) - - # Handle the response - async for response in page_result: - print(response) - -# [END dialogflow_v2_generated_EntityTypes_ListEntityTypes_async] diff --git a/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_entity_types_list_entity_types_sync.py b/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_entity_types_list_entity_types_sync.py deleted file mode 100644 index 066ea18f7..000000000 --- a/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_entity_types_list_entity_types_sync.py +++ /dev/null @@ -1,53 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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. -# -# Generated code. DO NOT EDIT! -# -# Snippet for ListEntityTypes -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-dialogflow - - -# [START dialogflow_v2_generated_EntityTypes_ListEntityTypes_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import dialogflow_v2 - - -def sample_list_entity_types(): - # Create a client - client = dialogflow_v2.EntityTypesClient() - - # Initialize request argument(s) - request = dialogflow_v2.ListEntityTypesRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_entity_types(request=request) - - # Handle the response - for response in page_result: - print(response) - -# [END dialogflow_v2_generated_EntityTypes_ListEntityTypes_sync] diff --git a/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_entity_types_update_entity_type_async.py b/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_entity_types_update_entity_type_async.py deleted file mode 100644 index b3971416b..000000000 --- a/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_entity_types_update_entity_type_async.py +++ /dev/null @@ -1,56 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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. -# -# Generated code. DO NOT EDIT! -# -# Snippet for UpdateEntityType -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-dialogflow - - -# [START dialogflow_v2_generated_EntityTypes_UpdateEntityType_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import dialogflow_v2 - - -async def sample_update_entity_type(): - # Create a client - client = dialogflow_v2.EntityTypesAsyncClient() - - # Initialize request argument(s) - entity_type = dialogflow_v2.EntityType() - entity_type.display_name = "display_name_value" - entity_type.kind = "KIND_REGEXP" - - request = dialogflow_v2.UpdateEntityTypeRequest( - entity_type=entity_type, - ) - - # Make the request - response = await client.update_entity_type(request=request) - - # Handle the response - print(response) - -# [END dialogflow_v2_generated_EntityTypes_UpdateEntityType_async] diff --git a/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_entity_types_update_entity_type_sync.py b/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_entity_types_update_entity_type_sync.py deleted file mode 100644 index a09b2ee2e..000000000 --- a/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_entity_types_update_entity_type_sync.py +++ /dev/null @@ -1,56 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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. -# -# Generated code. DO NOT EDIT! -# -# Snippet for UpdateEntityType -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-dialogflow - - -# [START dialogflow_v2_generated_EntityTypes_UpdateEntityType_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import dialogflow_v2 - - -def sample_update_entity_type(): - # Create a client - client = dialogflow_v2.EntityTypesClient() - - # Initialize request argument(s) - entity_type = dialogflow_v2.EntityType() - entity_type.display_name = "display_name_value" - entity_type.kind = "KIND_REGEXP" - - request = dialogflow_v2.UpdateEntityTypeRequest( - entity_type=entity_type, - ) - - # Make the request - response = client.update_entity_type(request=request) - - # Handle the response - print(response) - -# [END dialogflow_v2_generated_EntityTypes_UpdateEntityType_sync] diff --git a/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_environments_create_environment_async.py b/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_environments_create_environment_async.py deleted file mode 100644 index 5f798a369..000000000 --- a/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_environments_create_environment_async.py +++ /dev/null @@ -1,53 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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. -# -# Generated code. DO NOT EDIT! -# -# Snippet for CreateEnvironment -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-dialogflow - - -# [START dialogflow_v2_generated_Environments_CreateEnvironment_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import dialogflow_v2 - - -async def sample_create_environment(): - # Create a client - client = dialogflow_v2.EnvironmentsAsyncClient() - - # Initialize request argument(s) - request = dialogflow_v2.CreateEnvironmentRequest( - parent="parent_value", - environment_id="environment_id_value", - ) - - # Make the request - response = await client.create_environment(request=request) - - # Handle the response - print(response) - -# [END dialogflow_v2_generated_Environments_CreateEnvironment_async] diff --git a/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_environments_create_environment_sync.py b/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_environments_create_environment_sync.py deleted file mode 100644 index 2d932f808..000000000 --- a/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_environments_create_environment_sync.py +++ /dev/null @@ -1,53 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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. -# -# Generated code. DO NOT EDIT! -# -# Snippet for CreateEnvironment -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-dialogflow - - -# [START dialogflow_v2_generated_Environments_CreateEnvironment_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import dialogflow_v2 - - -def sample_create_environment(): - # Create a client - client = dialogflow_v2.EnvironmentsClient() - - # Initialize request argument(s) - request = dialogflow_v2.CreateEnvironmentRequest( - parent="parent_value", - environment_id="environment_id_value", - ) - - # Make the request - response = client.create_environment(request=request) - - # Handle the response - print(response) - -# [END dialogflow_v2_generated_Environments_CreateEnvironment_sync] diff --git a/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_environments_delete_environment_async.py b/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_environments_delete_environment_async.py deleted file mode 100644 index cb75f4afc..000000000 --- a/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_environments_delete_environment_async.py +++ /dev/null @@ -1,50 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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. -# -# Generated code. DO NOT EDIT! -# -# Snippet for DeleteEnvironment -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-dialogflow - - -# [START dialogflow_v2_generated_Environments_DeleteEnvironment_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import dialogflow_v2 - - -async def sample_delete_environment(): - # Create a client - client = dialogflow_v2.EnvironmentsAsyncClient() - - # Initialize request argument(s) - request = dialogflow_v2.DeleteEnvironmentRequest( - name="name_value", - ) - - # Make the request - await client.delete_environment(request=request) - - -# [END dialogflow_v2_generated_Environments_DeleteEnvironment_async] diff --git a/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_environments_delete_environment_sync.py b/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_environments_delete_environment_sync.py deleted file mode 100644 index f223802ce..000000000 --- a/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_environments_delete_environment_sync.py +++ /dev/null @@ -1,50 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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. -# -# Generated code. DO NOT EDIT! -# -# Snippet for DeleteEnvironment -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-dialogflow - - -# [START dialogflow_v2_generated_Environments_DeleteEnvironment_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import dialogflow_v2 - - -def sample_delete_environment(): - # Create a client - client = dialogflow_v2.EnvironmentsClient() - - # Initialize request argument(s) - request = dialogflow_v2.DeleteEnvironmentRequest( - name="name_value", - ) - - # Make the request - client.delete_environment(request=request) - - -# [END dialogflow_v2_generated_Environments_DeleteEnvironment_sync] diff --git a/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_environments_get_environment_async.py b/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_environments_get_environment_async.py deleted file mode 100644 index 52ffb4fe9..000000000 --- a/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_environments_get_environment_async.py +++ /dev/null @@ -1,52 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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. -# -# Generated code. DO NOT EDIT! -# -# Snippet for GetEnvironment -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-dialogflow - - -# [START dialogflow_v2_generated_Environments_GetEnvironment_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import dialogflow_v2 - - -async def sample_get_environment(): - # Create a client - client = dialogflow_v2.EnvironmentsAsyncClient() - - # Initialize request argument(s) - request = dialogflow_v2.GetEnvironmentRequest( - name="name_value", - ) - - # Make the request - response = await client.get_environment(request=request) - - # Handle the response - print(response) - -# [END dialogflow_v2_generated_Environments_GetEnvironment_async] diff --git a/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_environments_get_environment_history_async.py b/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_environments_get_environment_history_async.py deleted file mode 100644 index d57018069..000000000 --- a/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_environments_get_environment_history_async.py +++ /dev/null @@ -1,53 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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. -# -# Generated code. DO NOT EDIT! -# -# Snippet for GetEnvironmentHistory -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-dialogflow - - -# [START dialogflow_v2_generated_Environments_GetEnvironmentHistory_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import dialogflow_v2 - - -async def sample_get_environment_history(): - # Create a client - client = dialogflow_v2.EnvironmentsAsyncClient() - - # Initialize request argument(s) - request = dialogflow_v2.GetEnvironmentHistoryRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.get_environment_history(request=request) - - # Handle the response - async for response in page_result: - print(response) - -# [END dialogflow_v2_generated_Environments_GetEnvironmentHistory_async] diff --git a/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_environments_get_environment_history_sync.py b/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_environments_get_environment_history_sync.py deleted file mode 100644 index 8edfe697e..000000000 --- a/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_environments_get_environment_history_sync.py +++ /dev/null @@ -1,53 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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. -# -# Generated code. DO NOT EDIT! -# -# Snippet for GetEnvironmentHistory -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-dialogflow - - -# [START dialogflow_v2_generated_Environments_GetEnvironmentHistory_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import dialogflow_v2 - - -def sample_get_environment_history(): - # Create a client - client = dialogflow_v2.EnvironmentsClient() - - # Initialize request argument(s) - request = dialogflow_v2.GetEnvironmentHistoryRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.get_environment_history(request=request) - - # Handle the response - for response in page_result: - print(response) - -# [END dialogflow_v2_generated_Environments_GetEnvironmentHistory_sync] diff --git a/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_environments_get_environment_sync.py b/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_environments_get_environment_sync.py deleted file mode 100644 index 6d88526d0..000000000 --- a/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_environments_get_environment_sync.py +++ /dev/null @@ -1,52 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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. -# -# Generated code. DO NOT EDIT! -# -# Snippet for GetEnvironment -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-dialogflow - - -# [START dialogflow_v2_generated_Environments_GetEnvironment_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import dialogflow_v2 - - -def sample_get_environment(): - # Create a client - client = dialogflow_v2.EnvironmentsClient() - - # Initialize request argument(s) - request = dialogflow_v2.GetEnvironmentRequest( - name="name_value", - ) - - # Make the request - response = client.get_environment(request=request) - - # Handle the response - print(response) - -# [END dialogflow_v2_generated_Environments_GetEnvironment_sync] diff --git a/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_environments_list_environments_async.py b/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_environments_list_environments_async.py deleted file mode 100644 index 66b5daa8b..000000000 --- a/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_environments_list_environments_async.py +++ /dev/null @@ -1,53 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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. -# -# Generated code. DO NOT EDIT! -# -# Snippet for ListEnvironments -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-dialogflow - - -# [START dialogflow_v2_generated_Environments_ListEnvironments_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import dialogflow_v2 - - -async def sample_list_environments(): - # Create a client - client = dialogflow_v2.EnvironmentsAsyncClient() - - # Initialize request argument(s) - request = dialogflow_v2.ListEnvironmentsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_environments(request=request) - - # Handle the response - async for response in page_result: - print(response) - -# [END dialogflow_v2_generated_Environments_ListEnvironments_async] diff --git a/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_environments_list_environments_sync.py b/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_environments_list_environments_sync.py deleted file mode 100644 index 29596e5c0..000000000 --- a/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_environments_list_environments_sync.py +++ /dev/null @@ -1,53 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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. -# -# Generated code. DO NOT EDIT! -# -# Snippet for ListEnvironments -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-dialogflow - - -# [START dialogflow_v2_generated_Environments_ListEnvironments_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import dialogflow_v2 - - -def sample_list_environments(): - # Create a client - client = dialogflow_v2.EnvironmentsClient() - - # Initialize request argument(s) - request = dialogflow_v2.ListEnvironmentsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_environments(request=request) - - # Handle the response - for response in page_result: - print(response) - -# [END dialogflow_v2_generated_Environments_ListEnvironments_sync] diff --git a/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_environments_update_environment_async.py b/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_environments_update_environment_async.py deleted file mode 100644 index fa631366b..000000000 --- a/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_environments_update_environment_async.py +++ /dev/null @@ -1,51 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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. -# -# Generated code. DO NOT EDIT! -# -# Snippet for UpdateEnvironment -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-dialogflow - - -# [START dialogflow_v2_generated_Environments_UpdateEnvironment_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import dialogflow_v2 - - -async def sample_update_environment(): - # Create a client - client = dialogflow_v2.EnvironmentsAsyncClient() - - # Initialize request argument(s) - request = dialogflow_v2.UpdateEnvironmentRequest( - ) - - # Make the request - response = await client.update_environment(request=request) - - # Handle the response - print(response) - -# [END dialogflow_v2_generated_Environments_UpdateEnvironment_async] diff --git a/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_environments_update_environment_sync.py b/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_environments_update_environment_sync.py deleted file mode 100644 index c1390683c..000000000 --- a/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_environments_update_environment_sync.py +++ /dev/null @@ -1,51 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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. -# -# Generated code. DO NOT EDIT! -# -# Snippet for UpdateEnvironment -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-dialogflow - - -# [START dialogflow_v2_generated_Environments_UpdateEnvironment_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import dialogflow_v2 - - -def sample_update_environment(): - # Create a client - client = dialogflow_v2.EnvironmentsClient() - - # Initialize request argument(s) - request = dialogflow_v2.UpdateEnvironmentRequest( - ) - - # Make the request - response = client.update_environment(request=request) - - # Handle the response - print(response) - -# [END dialogflow_v2_generated_Environments_UpdateEnvironment_sync] diff --git a/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_fulfillments_get_fulfillment_async.py b/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_fulfillments_get_fulfillment_async.py deleted file mode 100644 index eae72292f..000000000 --- a/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_fulfillments_get_fulfillment_async.py +++ /dev/null @@ -1,52 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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. -# -# Generated code. DO NOT EDIT! -# -# Snippet for GetFulfillment -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-dialogflow - - -# [START dialogflow_v2_generated_Fulfillments_GetFulfillment_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import dialogflow_v2 - - -async def sample_get_fulfillment(): - # Create a client - client = dialogflow_v2.FulfillmentsAsyncClient() - - # Initialize request argument(s) - request = dialogflow_v2.GetFulfillmentRequest( - name="name_value", - ) - - # Make the request - response = await client.get_fulfillment(request=request) - - # Handle the response - print(response) - -# [END dialogflow_v2_generated_Fulfillments_GetFulfillment_async] diff --git a/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_fulfillments_get_fulfillment_sync.py b/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_fulfillments_get_fulfillment_sync.py deleted file mode 100644 index a852d4faf..000000000 --- a/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_fulfillments_get_fulfillment_sync.py +++ /dev/null @@ -1,52 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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. -# -# Generated code. DO NOT EDIT! -# -# Snippet for GetFulfillment -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-dialogflow - - -# [START dialogflow_v2_generated_Fulfillments_GetFulfillment_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import dialogflow_v2 - - -def sample_get_fulfillment(): - # Create a client - client = dialogflow_v2.FulfillmentsClient() - - # Initialize request argument(s) - request = dialogflow_v2.GetFulfillmentRequest( - name="name_value", - ) - - # Make the request - response = client.get_fulfillment(request=request) - - # Handle the response - print(response) - -# [END dialogflow_v2_generated_Fulfillments_GetFulfillment_sync] diff --git a/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_fulfillments_update_fulfillment_async.py b/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_fulfillments_update_fulfillment_async.py deleted file mode 100644 index e4794941a..000000000 --- a/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_fulfillments_update_fulfillment_async.py +++ /dev/null @@ -1,56 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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. -# -# Generated code. DO NOT EDIT! -# -# Snippet for UpdateFulfillment -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-dialogflow - - -# [START dialogflow_v2_generated_Fulfillments_UpdateFulfillment_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import dialogflow_v2 - - -async def sample_update_fulfillment(): - # Create a client - client = dialogflow_v2.FulfillmentsAsyncClient() - - # Initialize request argument(s) - fulfillment = dialogflow_v2.Fulfillment() - fulfillment.generic_web_service.uri = "uri_value" - fulfillment.name = "name_value" - - request = dialogflow_v2.UpdateFulfillmentRequest( - fulfillment=fulfillment, - ) - - # Make the request - response = await client.update_fulfillment(request=request) - - # Handle the response - print(response) - -# [END dialogflow_v2_generated_Fulfillments_UpdateFulfillment_async] diff --git a/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_fulfillments_update_fulfillment_sync.py b/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_fulfillments_update_fulfillment_sync.py deleted file mode 100644 index 9cbbeb9a1..000000000 --- a/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_fulfillments_update_fulfillment_sync.py +++ /dev/null @@ -1,56 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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. -# -# Generated code. DO NOT EDIT! -# -# Snippet for UpdateFulfillment -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-dialogflow - - -# [START dialogflow_v2_generated_Fulfillments_UpdateFulfillment_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import dialogflow_v2 - - -def sample_update_fulfillment(): - # Create a client - client = dialogflow_v2.FulfillmentsClient() - - # Initialize request argument(s) - fulfillment = dialogflow_v2.Fulfillment() - fulfillment.generic_web_service.uri = "uri_value" - fulfillment.name = "name_value" - - request = dialogflow_v2.UpdateFulfillmentRequest( - fulfillment=fulfillment, - ) - - # Make the request - response = client.update_fulfillment(request=request) - - # Handle the response - print(response) - -# [END dialogflow_v2_generated_Fulfillments_UpdateFulfillment_sync] diff --git a/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_intents_batch_delete_intents_async.py b/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_intents_batch_delete_intents_async.py deleted file mode 100644 index 3ce966dce..000000000 --- a/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_intents_batch_delete_intents_async.py +++ /dev/null @@ -1,60 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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. -# -# Generated code. DO NOT EDIT! -# -# Snippet for BatchDeleteIntents -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-dialogflow - - -# [START dialogflow_v2_generated_Intents_BatchDeleteIntents_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import dialogflow_v2 - - -async def sample_batch_delete_intents(): - # Create a client - client = dialogflow_v2.IntentsAsyncClient() - - # Initialize request argument(s) - intents = dialogflow_v2.Intent() - intents.display_name = "display_name_value" - - request = dialogflow_v2.BatchDeleteIntentsRequest( - parent="parent_value", - intents=intents, - ) - - # Make the request - operation = client.batch_delete_intents(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - -# [END dialogflow_v2_generated_Intents_BatchDeleteIntents_async] diff --git a/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_intents_batch_delete_intents_sync.py b/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_intents_batch_delete_intents_sync.py deleted file mode 100644 index 26afc51ae..000000000 --- a/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_intents_batch_delete_intents_sync.py +++ /dev/null @@ -1,60 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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. -# -# Generated code. DO NOT EDIT! -# -# Snippet for BatchDeleteIntents -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-dialogflow - - -# [START dialogflow_v2_generated_Intents_BatchDeleteIntents_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import dialogflow_v2 - - -def sample_batch_delete_intents(): - # Create a client - client = dialogflow_v2.IntentsClient() - - # Initialize request argument(s) - intents = dialogflow_v2.Intent() - intents.display_name = "display_name_value" - - request = dialogflow_v2.BatchDeleteIntentsRequest( - parent="parent_value", - intents=intents, - ) - - # Make the request - operation = client.batch_delete_intents(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - -# [END dialogflow_v2_generated_Intents_BatchDeleteIntents_sync] diff --git a/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_intents_batch_update_intents_async.py b/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_intents_batch_update_intents_async.py deleted file mode 100644 index 16530d1bb..000000000 --- a/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_intents_batch_update_intents_async.py +++ /dev/null @@ -1,57 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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. -# -# Generated code. DO NOT EDIT! -# -# Snippet for BatchUpdateIntents -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-dialogflow - - -# [START dialogflow_v2_generated_Intents_BatchUpdateIntents_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import dialogflow_v2 - - -async def sample_batch_update_intents(): - # Create a client - client = dialogflow_v2.IntentsAsyncClient() - - # Initialize request argument(s) - request = dialogflow_v2.BatchUpdateIntentsRequest( - intent_batch_uri="intent_batch_uri_value", - parent="parent_value", - ) - - # Make the request - operation = client.batch_update_intents(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - -# [END dialogflow_v2_generated_Intents_BatchUpdateIntents_async] diff --git a/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_intents_batch_update_intents_sync.py b/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_intents_batch_update_intents_sync.py deleted file mode 100644 index fd9c104c0..000000000 --- a/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_intents_batch_update_intents_sync.py +++ /dev/null @@ -1,57 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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. -# -# Generated code. DO NOT EDIT! -# -# Snippet for BatchUpdateIntents -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-dialogflow - - -# [START dialogflow_v2_generated_Intents_BatchUpdateIntents_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import dialogflow_v2 - - -def sample_batch_update_intents(): - # Create a client - client = dialogflow_v2.IntentsClient() - - # Initialize request argument(s) - request = dialogflow_v2.BatchUpdateIntentsRequest( - intent_batch_uri="intent_batch_uri_value", - parent="parent_value", - ) - - # Make the request - operation = client.batch_update_intents(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - -# [END dialogflow_v2_generated_Intents_BatchUpdateIntents_sync] diff --git a/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_intents_create_intent_async.py b/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_intents_create_intent_async.py deleted file mode 100644 index 0786d9ee4..000000000 --- a/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_intents_create_intent_async.py +++ /dev/null @@ -1,56 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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. -# -# Generated code. DO NOT EDIT! -# -# Snippet for CreateIntent -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-dialogflow - - -# [START dialogflow_v2_generated_Intents_CreateIntent_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import dialogflow_v2 - - -async def sample_create_intent(): - # Create a client - client = dialogflow_v2.IntentsAsyncClient() - - # Initialize request argument(s) - intent = dialogflow_v2.Intent() - intent.display_name = "display_name_value" - - request = dialogflow_v2.CreateIntentRequest( - parent="parent_value", - intent=intent, - ) - - # Make the request - response = await client.create_intent(request=request) - - # Handle the response - print(response) - -# [END dialogflow_v2_generated_Intents_CreateIntent_async] diff --git a/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_intents_create_intent_sync.py b/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_intents_create_intent_sync.py deleted file mode 100644 index 449dddb33..000000000 --- a/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_intents_create_intent_sync.py +++ /dev/null @@ -1,56 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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. -# -# Generated code. DO NOT EDIT! -# -# Snippet for CreateIntent -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-dialogflow - - -# [START dialogflow_v2_generated_Intents_CreateIntent_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import dialogflow_v2 - - -def sample_create_intent(): - # Create a client - client = dialogflow_v2.IntentsClient() - - # Initialize request argument(s) - intent = dialogflow_v2.Intent() - intent.display_name = "display_name_value" - - request = dialogflow_v2.CreateIntentRequest( - parent="parent_value", - intent=intent, - ) - - # Make the request - response = client.create_intent(request=request) - - # Handle the response - print(response) - -# [END dialogflow_v2_generated_Intents_CreateIntent_sync] diff --git a/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_intents_delete_intent_async.py b/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_intents_delete_intent_async.py deleted file mode 100644 index f739d5b46..000000000 --- a/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_intents_delete_intent_async.py +++ /dev/null @@ -1,50 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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. -# -# Generated code. DO NOT EDIT! -# -# Snippet for DeleteIntent -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-dialogflow - - -# [START dialogflow_v2_generated_Intents_DeleteIntent_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import dialogflow_v2 - - -async def sample_delete_intent(): - # Create a client - client = dialogflow_v2.IntentsAsyncClient() - - # Initialize request argument(s) - request = dialogflow_v2.DeleteIntentRequest( - name="name_value", - ) - - # Make the request - await client.delete_intent(request=request) - - -# [END dialogflow_v2_generated_Intents_DeleteIntent_async] diff --git a/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_intents_delete_intent_sync.py b/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_intents_delete_intent_sync.py deleted file mode 100644 index 6573381f9..000000000 --- a/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_intents_delete_intent_sync.py +++ /dev/null @@ -1,50 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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. -# -# Generated code. DO NOT EDIT! -# -# Snippet for DeleteIntent -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-dialogflow - - -# [START dialogflow_v2_generated_Intents_DeleteIntent_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import dialogflow_v2 - - -def sample_delete_intent(): - # Create a client - client = dialogflow_v2.IntentsClient() - - # Initialize request argument(s) - request = dialogflow_v2.DeleteIntentRequest( - name="name_value", - ) - - # Make the request - client.delete_intent(request=request) - - -# [END dialogflow_v2_generated_Intents_DeleteIntent_sync] diff --git a/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_intents_get_intent_async.py b/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_intents_get_intent_async.py deleted file mode 100644 index f5ae8d571..000000000 --- a/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_intents_get_intent_async.py +++ /dev/null @@ -1,52 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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. -# -# Generated code. DO NOT EDIT! -# -# Snippet for GetIntent -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-dialogflow - - -# [START dialogflow_v2_generated_Intents_GetIntent_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import dialogflow_v2 - - -async def sample_get_intent(): - # Create a client - client = dialogflow_v2.IntentsAsyncClient() - - # Initialize request argument(s) - request = dialogflow_v2.GetIntentRequest( - name="name_value", - ) - - # Make the request - response = await client.get_intent(request=request) - - # Handle the response - print(response) - -# [END dialogflow_v2_generated_Intents_GetIntent_async] diff --git a/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_intents_get_intent_sync.py b/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_intents_get_intent_sync.py deleted file mode 100644 index 0ed7c7ae1..000000000 --- a/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_intents_get_intent_sync.py +++ /dev/null @@ -1,52 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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. -# -# Generated code. DO NOT EDIT! -# -# Snippet for GetIntent -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-dialogflow - - -# [START dialogflow_v2_generated_Intents_GetIntent_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import dialogflow_v2 - - -def sample_get_intent(): - # Create a client - client = dialogflow_v2.IntentsClient() - - # Initialize request argument(s) - request = dialogflow_v2.GetIntentRequest( - name="name_value", - ) - - # Make the request - response = client.get_intent(request=request) - - # Handle the response - print(response) - -# [END dialogflow_v2_generated_Intents_GetIntent_sync] diff --git a/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_intents_list_intents_async.py b/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_intents_list_intents_async.py deleted file mode 100644 index ed764e293..000000000 --- a/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_intents_list_intents_async.py +++ /dev/null @@ -1,53 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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. -# -# Generated code. DO NOT EDIT! -# -# Snippet for ListIntents -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-dialogflow - - -# [START dialogflow_v2_generated_Intents_ListIntents_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import dialogflow_v2 - - -async def sample_list_intents(): - # Create a client - client = dialogflow_v2.IntentsAsyncClient() - - # Initialize request argument(s) - request = dialogflow_v2.ListIntentsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_intents(request=request) - - # Handle the response - async for response in page_result: - print(response) - -# [END dialogflow_v2_generated_Intents_ListIntents_async] diff --git a/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_intents_list_intents_sync.py b/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_intents_list_intents_sync.py deleted file mode 100644 index 1aa147048..000000000 --- a/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_intents_list_intents_sync.py +++ /dev/null @@ -1,53 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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. -# -# Generated code. DO NOT EDIT! -# -# Snippet for ListIntents -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-dialogflow - - -# [START dialogflow_v2_generated_Intents_ListIntents_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import dialogflow_v2 - - -def sample_list_intents(): - # Create a client - client = dialogflow_v2.IntentsClient() - - # Initialize request argument(s) - request = dialogflow_v2.ListIntentsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_intents(request=request) - - # Handle the response - for response in page_result: - print(response) - -# [END dialogflow_v2_generated_Intents_ListIntents_sync] diff --git a/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_intents_update_intent_async.py b/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_intents_update_intent_async.py deleted file mode 100644 index 6bffbb542..000000000 --- a/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_intents_update_intent_async.py +++ /dev/null @@ -1,55 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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. -# -# Generated code. DO NOT EDIT! -# -# Snippet for UpdateIntent -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-dialogflow - - -# [START dialogflow_v2_generated_Intents_UpdateIntent_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import dialogflow_v2 - - -async def sample_update_intent(): - # Create a client - client = dialogflow_v2.IntentsAsyncClient() - - # Initialize request argument(s) - intent = dialogflow_v2.Intent() - intent.display_name = "display_name_value" - - request = dialogflow_v2.UpdateIntentRequest( - intent=intent, - ) - - # Make the request - response = await client.update_intent(request=request) - - # Handle the response - print(response) - -# [END dialogflow_v2_generated_Intents_UpdateIntent_async] diff --git a/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_intents_update_intent_sync.py b/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_intents_update_intent_sync.py deleted file mode 100644 index d98a21023..000000000 --- a/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_intents_update_intent_sync.py +++ /dev/null @@ -1,55 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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. -# -# Generated code. DO NOT EDIT! -# -# Snippet for UpdateIntent -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-dialogflow - - -# [START dialogflow_v2_generated_Intents_UpdateIntent_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import dialogflow_v2 - - -def sample_update_intent(): - # Create a client - client = dialogflow_v2.IntentsClient() - - # Initialize request argument(s) - intent = dialogflow_v2.Intent() - intent.display_name = "display_name_value" - - request = dialogflow_v2.UpdateIntentRequest( - intent=intent, - ) - - # Make the request - response = client.update_intent(request=request) - - # Handle the response - print(response) - -# [END dialogflow_v2_generated_Intents_UpdateIntent_sync] diff --git a/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_knowledge_bases_create_knowledge_base_async.py b/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_knowledge_bases_create_knowledge_base_async.py deleted file mode 100644 index ea4f1cd65..000000000 --- a/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_knowledge_bases_create_knowledge_base_async.py +++ /dev/null @@ -1,56 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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. -# -# Generated code. DO NOT EDIT! -# -# Snippet for CreateKnowledgeBase -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-dialogflow - - -# [START dialogflow_v2_generated_KnowledgeBases_CreateKnowledgeBase_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import dialogflow_v2 - - -async def sample_create_knowledge_base(): - # Create a client - client = dialogflow_v2.KnowledgeBasesAsyncClient() - - # Initialize request argument(s) - knowledge_base = dialogflow_v2.KnowledgeBase() - knowledge_base.display_name = "display_name_value" - - request = dialogflow_v2.CreateKnowledgeBaseRequest( - parent="parent_value", - knowledge_base=knowledge_base, - ) - - # Make the request - response = await client.create_knowledge_base(request=request) - - # Handle the response - print(response) - -# [END dialogflow_v2_generated_KnowledgeBases_CreateKnowledgeBase_async] diff --git a/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_knowledge_bases_create_knowledge_base_sync.py b/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_knowledge_bases_create_knowledge_base_sync.py deleted file mode 100644 index 5bdcc96c3..000000000 --- a/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_knowledge_bases_create_knowledge_base_sync.py +++ /dev/null @@ -1,56 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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. -# -# Generated code. DO NOT EDIT! -# -# Snippet for CreateKnowledgeBase -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-dialogflow - - -# [START dialogflow_v2_generated_KnowledgeBases_CreateKnowledgeBase_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import dialogflow_v2 - - -def sample_create_knowledge_base(): - # Create a client - client = dialogflow_v2.KnowledgeBasesClient() - - # Initialize request argument(s) - knowledge_base = dialogflow_v2.KnowledgeBase() - knowledge_base.display_name = "display_name_value" - - request = dialogflow_v2.CreateKnowledgeBaseRequest( - parent="parent_value", - knowledge_base=knowledge_base, - ) - - # Make the request - response = client.create_knowledge_base(request=request) - - # Handle the response - print(response) - -# [END dialogflow_v2_generated_KnowledgeBases_CreateKnowledgeBase_sync] diff --git a/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_knowledge_bases_delete_knowledge_base_async.py b/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_knowledge_bases_delete_knowledge_base_async.py deleted file mode 100644 index 51591e8d7..000000000 --- a/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_knowledge_bases_delete_knowledge_base_async.py +++ /dev/null @@ -1,50 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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. -# -# Generated code. DO NOT EDIT! -# -# Snippet for DeleteKnowledgeBase -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-dialogflow - - -# [START dialogflow_v2_generated_KnowledgeBases_DeleteKnowledgeBase_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import dialogflow_v2 - - -async def sample_delete_knowledge_base(): - # Create a client - client = dialogflow_v2.KnowledgeBasesAsyncClient() - - # Initialize request argument(s) - request = dialogflow_v2.DeleteKnowledgeBaseRequest( - name="name_value", - ) - - # Make the request - await client.delete_knowledge_base(request=request) - - -# [END dialogflow_v2_generated_KnowledgeBases_DeleteKnowledgeBase_async] diff --git a/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_knowledge_bases_delete_knowledge_base_sync.py b/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_knowledge_bases_delete_knowledge_base_sync.py deleted file mode 100644 index 73c7bbfbf..000000000 --- a/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_knowledge_bases_delete_knowledge_base_sync.py +++ /dev/null @@ -1,50 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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. -# -# Generated code. DO NOT EDIT! -# -# Snippet for DeleteKnowledgeBase -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-dialogflow - - -# [START dialogflow_v2_generated_KnowledgeBases_DeleteKnowledgeBase_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import dialogflow_v2 - - -def sample_delete_knowledge_base(): - # Create a client - client = dialogflow_v2.KnowledgeBasesClient() - - # Initialize request argument(s) - request = dialogflow_v2.DeleteKnowledgeBaseRequest( - name="name_value", - ) - - # Make the request - client.delete_knowledge_base(request=request) - - -# [END dialogflow_v2_generated_KnowledgeBases_DeleteKnowledgeBase_sync] diff --git a/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_knowledge_bases_get_knowledge_base_async.py b/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_knowledge_bases_get_knowledge_base_async.py deleted file mode 100644 index fb84ce092..000000000 --- a/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_knowledge_bases_get_knowledge_base_async.py +++ /dev/null @@ -1,52 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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. -# -# Generated code. DO NOT EDIT! -# -# Snippet for GetKnowledgeBase -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-dialogflow - - -# [START dialogflow_v2_generated_KnowledgeBases_GetKnowledgeBase_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import dialogflow_v2 - - -async def sample_get_knowledge_base(): - # Create a client - client = dialogflow_v2.KnowledgeBasesAsyncClient() - - # Initialize request argument(s) - request = dialogflow_v2.GetKnowledgeBaseRequest( - name="name_value", - ) - - # Make the request - response = await client.get_knowledge_base(request=request) - - # Handle the response - print(response) - -# [END dialogflow_v2_generated_KnowledgeBases_GetKnowledgeBase_async] diff --git a/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_knowledge_bases_get_knowledge_base_sync.py b/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_knowledge_bases_get_knowledge_base_sync.py deleted file mode 100644 index 85158d2a9..000000000 --- a/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_knowledge_bases_get_knowledge_base_sync.py +++ /dev/null @@ -1,52 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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. -# -# Generated code. DO NOT EDIT! -# -# Snippet for GetKnowledgeBase -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-dialogflow - - -# [START dialogflow_v2_generated_KnowledgeBases_GetKnowledgeBase_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import dialogflow_v2 - - -def sample_get_knowledge_base(): - # Create a client - client = dialogflow_v2.KnowledgeBasesClient() - - # Initialize request argument(s) - request = dialogflow_v2.GetKnowledgeBaseRequest( - name="name_value", - ) - - # Make the request - response = client.get_knowledge_base(request=request) - - # Handle the response - print(response) - -# [END dialogflow_v2_generated_KnowledgeBases_GetKnowledgeBase_sync] diff --git a/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_knowledge_bases_list_knowledge_bases_async.py b/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_knowledge_bases_list_knowledge_bases_async.py deleted file mode 100644 index d6aa8ab0c..000000000 --- a/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_knowledge_bases_list_knowledge_bases_async.py +++ /dev/null @@ -1,53 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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. -# -# Generated code. DO NOT EDIT! -# -# Snippet for ListKnowledgeBases -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-dialogflow - - -# [START dialogflow_v2_generated_KnowledgeBases_ListKnowledgeBases_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import dialogflow_v2 - - -async def sample_list_knowledge_bases(): - # Create a client - client = dialogflow_v2.KnowledgeBasesAsyncClient() - - # Initialize request argument(s) - request = dialogflow_v2.ListKnowledgeBasesRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_knowledge_bases(request=request) - - # Handle the response - async for response in page_result: - print(response) - -# [END dialogflow_v2_generated_KnowledgeBases_ListKnowledgeBases_async] diff --git a/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_knowledge_bases_list_knowledge_bases_sync.py b/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_knowledge_bases_list_knowledge_bases_sync.py deleted file mode 100644 index 5029e4718..000000000 --- a/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_knowledge_bases_list_knowledge_bases_sync.py +++ /dev/null @@ -1,53 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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. -# -# Generated code. DO NOT EDIT! -# -# Snippet for ListKnowledgeBases -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-dialogflow - - -# [START dialogflow_v2_generated_KnowledgeBases_ListKnowledgeBases_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import dialogflow_v2 - - -def sample_list_knowledge_bases(): - # Create a client - client = dialogflow_v2.KnowledgeBasesClient() - - # Initialize request argument(s) - request = dialogflow_v2.ListKnowledgeBasesRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_knowledge_bases(request=request) - - # Handle the response - for response in page_result: - print(response) - -# [END dialogflow_v2_generated_KnowledgeBases_ListKnowledgeBases_sync] diff --git a/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_knowledge_bases_update_knowledge_base_async.py b/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_knowledge_bases_update_knowledge_base_async.py deleted file mode 100644 index 53b88fec8..000000000 --- a/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_knowledge_bases_update_knowledge_base_async.py +++ /dev/null @@ -1,55 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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. -# -# Generated code. DO NOT EDIT! -# -# Snippet for UpdateKnowledgeBase -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-dialogflow - - -# [START dialogflow_v2_generated_KnowledgeBases_UpdateKnowledgeBase_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import dialogflow_v2 - - -async def sample_update_knowledge_base(): - # Create a client - client = dialogflow_v2.KnowledgeBasesAsyncClient() - - # Initialize request argument(s) - knowledge_base = dialogflow_v2.KnowledgeBase() - knowledge_base.display_name = "display_name_value" - - request = dialogflow_v2.UpdateKnowledgeBaseRequest( - knowledge_base=knowledge_base, - ) - - # Make the request - response = await client.update_knowledge_base(request=request) - - # Handle the response - print(response) - -# [END dialogflow_v2_generated_KnowledgeBases_UpdateKnowledgeBase_async] diff --git a/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_knowledge_bases_update_knowledge_base_sync.py b/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_knowledge_bases_update_knowledge_base_sync.py deleted file mode 100644 index b3a04ca3b..000000000 --- a/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_knowledge_bases_update_knowledge_base_sync.py +++ /dev/null @@ -1,55 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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. -# -# Generated code. DO NOT EDIT! -# -# Snippet for UpdateKnowledgeBase -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-dialogflow - - -# [START dialogflow_v2_generated_KnowledgeBases_UpdateKnowledgeBase_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import dialogflow_v2 - - -def sample_update_knowledge_base(): - # Create a client - client = dialogflow_v2.KnowledgeBasesClient() - - # Initialize request argument(s) - knowledge_base = dialogflow_v2.KnowledgeBase() - knowledge_base.display_name = "display_name_value" - - request = dialogflow_v2.UpdateKnowledgeBaseRequest( - knowledge_base=knowledge_base, - ) - - # Make the request - response = client.update_knowledge_base(request=request) - - # Handle the response - print(response) - -# [END dialogflow_v2_generated_KnowledgeBases_UpdateKnowledgeBase_sync] diff --git a/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_participants_analyze_content_async.py b/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_participants_analyze_content_async.py deleted file mode 100644 index 61b6086bf..000000000 --- a/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_participants_analyze_content_async.py +++ /dev/null @@ -1,57 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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. -# -# Generated code. DO NOT EDIT! -# -# Snippet for AnalyzeContent -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-dialogflow - - -# [START dialogflow_v2_generated_Participants_AnalyzeContent_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import dialogflow_v2 - - -async def sample_analyze_content(): - # Create a client - client = dialogflow_v2.ParticipantsAsyncClient() - - # Initialize request argument(s) - text_input = dialogflow_v2.TextInput() - text_input.text = "text_value" - text_input.language_code = "language_code_value" - - request = dialogflow_v2.AnalyzeContentRequest( - text_input=text_input, - participant="participant_value", - ) - - # Make the request - response = await client.analyze_content(request=request) - - # Handle the response - print(response) - -# [END dialogflow_v2_generated_Participants_AnalyzeContent_async] diff --git a/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_participants_analyze_content_sync.py b/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_participants_analyze_content_sync.py deleted file mode 100644 index ccfc75b63..000000000 --- a/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_participants_analyze_content_sync.py +++ /dev/null @@ -1,57 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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. -# -# Generated code. DO NOT EDIT! -# -# Snippet for AnalyzeContent -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-dialogflow - - -# [START dialogflow_v2_generated_Participants_AnalyzeContent_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import dialogflow_v2 - - -def sample_analyze_content(): - # Create a client - client = dialogflow_v2.ParticipantsClient() - - # Initialize request argument(s) - text_input = dialogflow_v2.TextInput() - text_input.text = "text_value" - text_input.language_code = "language_code_value" - - request = dialogflow_v2.AnalyzeContentRequest( - text_input=text_input, - participant="participant_value", - ) - - # Make the request - response = client.analyze_content(request=request) - - # Handle the response - print(response) - -# [END dialogflow_v2_generated_Participants_AnalyzeContent_sync] diff --git a/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_participants_create_participant_async.py b/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_participants_create_participant_async.py deleted file mode 100644 index 454d8593c..000000000 --- a/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_participants_create_participant_async.py +++ /dev/null @@ -1,52 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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. -# -# Generated code. DO NOT EDIT! -# -# Snippet for CreateParticipant -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-dialogflow - - -# [START dialogflow_v2_generated_Participants_CreateParticipant_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import dialogflow_v2 - - -async def sample_create_participant(): - # Create a client - client = dialogflow_v2.ParticipantsAsyncClient() - - # Initialize request argument(s) - request = dialogflow_v2.CreateParticipantRequest( - parent="parent_value", - ) - - # Make the request - response = await client.create_participant(request=request) - - # Handle the response - print(response) - -# [END dialogflow_v2_generated_Participants_CreateParticipant_async] diff --git a/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_participants_create_participant_sync.py b/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_participants_create_participant_sync.py deleted file mode 100644 index fa4c448c7..000000000 --- a/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_participants_create_participant_sync.py +++ /dev/null @@ -1,52 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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. -# -# Generated code. DO NOT EDIT! -# -# Snippet for CreateParticipant -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-dialogflow - - -# [START dialogflow_v2_generated_Participants_CreateParticipant_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import dialogflow_v2 - - -def sample_create_participant(): - # Create a client - client = dialogflow_v2.ParticipantsClient() - - # Initialize request argument(s) - request = dialogflow_v2.CreateParticipantRequest( - parent="parent_value", - ) - - # Make the request - response = client.create_participant(request=request) - - # Handle the response - print(response) - -# [END dialogflow_v2_generated_Participants_CreateParticipant_sync] diff --git a/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_participants_get_participant_async.py b/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_participants_get_participant_async.py deleted file mode 100644 index f43fda23d..000000000 --- a/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_participants_get_participant_async.py +++ /dev/null @@ -1,52 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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. -# -# Generated code. DO NOT EDIT! -# -# Snippet for GetParticipant -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-dialogflow - - -# [START dialogflow_v2_generated_Participants_GetParticipant_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import dialogflow_v2 - - -async def sample_get_participant(): - # Create a client - client = dialogflow_v2.ParticipantsAsyncClient() - - # Initialize request argument(s) - request = dialogflow_v2.GetParticipantRequest( - name="name_value", - ) - - # Make the request - response = await client.get_participant(request=request) - - # Handle the response - print(response) - -# [END dialogflow_v2_generated_Participants_GetParticipant_async] diff --git a/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_participants_get_participant_sync.py b/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_participants_get_participant_sync.py deleted file mode 100644 index 203c24463..000000000 --- a/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_participants_get_participant_sync.py +++ /dev/null @@ -1,52 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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. -# -# Generated code. DO NOT EDIT! -# -# Snippet for GetParticipant -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-dialogflow - - -# [START dialogflow_v2_generated_Participants_GetParticipant_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import dialogflow_v2 - - -def sample_get_participant(): - # Create a client - client = dialogflow_v2.ParticipantsClient() - - # Initialize request argument(s) - request = dialogflow_v2.GetParticipantRequest( - name="name_value", - ) - - # Make the request - response = client.get_participant(request=request) - - # Handle the response - print(response) - -# [END dialogflow_v2_generated_Participants_GetParticipant_sync] diff --git a/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_participants_list_participants_async.py b/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_participants_list_participants_async.py deleted file mode 100644 index e8bcdf30d..000000000 --- a/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_participants_list_participants_async.py +++ /dev/null @@ -1,53 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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. -# -# Generated code. DO NOT EDIT! -# -# Snippet for ListParticipants -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-dialogflow - - -# [START dialogflow_v2_generated_Participants_ListParticipants_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import dialogflow_v2 - - -async def sample_list_participants(): - # Create a client - client = dialogflow_v2.ParticipantsAsyncClient() - - # Initialize request argument(s) - request = dialogflow_v2.ListParticipantsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_participants(request=request) - - # Handle the response - async for response in page_result: - print(response) - -# [END dialogflow_v2_generated_Participants_ListParticipants_async] diff --git a/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_participants_list_participants_sync.py b/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_participants_list_participants_sync.py deleted file mode 100644 index 73c915c61..000000000 --- a/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_participants_list_participants_sync.py +++ /dev/null @@ -1,53 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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. -# -# Generated code. DO NOT EDIT! -# -# Snippet for ListParticipants -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-dialogflow - - -# [START dialogflow_v2_generated_Participants_ListParticipants_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import dialogflow_v2 - - -def sample_list_participants(): - # Create a client - client = dialogflow_v2.ParticipantsClient() - - # Initialize request argument(s) - request = dialogflow_v2.ListParticipantsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_participants(request=request) - - # Handle the response - for response in page_result: - print(response) - -# [END dialogflow_v2_generated_Participants_ListParticipants_sync] diff --git a/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_participants_streaming_analyze_content_async.py b/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_participants_streaming_analyze_content_async.py deleted file mode 100644 index 443179bf8..000000000 --- a/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_participants_streaming_analyze_content_async.py +++ /dev/null @@ -1,64 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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. -# -# Generated code. DO NOT EDIT! -# -# Snippet for StreamingAnalyzeContent -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-dialogflow - - -# [START dialogflow_v2_generated_Participants_StreamingAnalyzeContent_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import dialogflow_v2 - - -async def sample_streaming_analyze_content(): - # Create a client - client = dialogflow_v2.ParticipantsAsyncClient() - - # Initialize request argument(s) - request = dialogflow_v2.StreamingAnalyzeContentRequest( - input_audio=b'input_audio_blob', - participant="participant_value", - ) - - # This method expects an iterator which contains - # 'dialogflow_v2.StreamingAnalyzeContentRequest' objects - # Here we create a generator that yields a single `request` for - # demonstrative purposes. - requests = [request] - - def request_generator(): - for request in requests: - yield request - - # Make the request - stream = await client.streaming_analyze_content(requests=request_generator()) - - # Handle the response - async for response in stream: - print(response) - -# [END dialogflow_v2_generated_Participants_StreamingAnalyzeContent_async] diff --git a/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_participants_streaming_analyze_content_sync.py b/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_participants_streaming_analyze_content_sync.py deleted file mode 100644 index bd3b91a32..000000000 --- a/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_participants_streaming_analyze_content_sync.py +++ /dev/null @@ -1,64 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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. -# -# Generated code. DO NOT EDIT! -# -# Snippet for StreamingAnalyzeContent -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-dialogflow - - -# [START dialogflow_v2_generated_Participants_StreamingAnalyzeContent_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import dialogflow_v2 - - -def sample_streaming_analyze_content(): - # Create a client - client = dialogflow_v2.ParticipantsClient() - - # Initialize request argument(s) - request = dialogflow_v2.StreamingAnalyzeContentRequest( - input_audio=b'input_audio_blob', - participant="participant_value", - ) - - # This method expects an iterator which contains - # 'dialogflow_v2.StreamingAnalyzeContentRequest' objects - # Here we create a generator that yields a single `request` for - # demonstrative purposes. - requests = [request] - - def request_generator(): - for request in requests: - yield request - - # Make the request - stream = client.streaming_analyze_content(requests=request_generator()) - - # Handle the response - for response in stream: - print(response) - -# [END dialogflow_v2_generated_Participants_StreamingAnalyzeContent_sync] diff --git a/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_participants_suggest_articles_async.py b/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_participants_suggest_articles_async.py deleted file mode 100644 index b9d5d3664..000000000 --- a/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_participants_suggest_articles_async.py +++ /dev/null @@ -1,52 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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. -# -# Generated code. DO NOT EDIT! -# -# Snippet for SuggestArticles -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-dialogflow - - -# [START dialogflow_v2_generated_Participants_SuggestArticles_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import dialogflow_v2 - - -async def sample_suggest_articles(): - # Create a client - client = dialogflow_v2.ParticipantsAsyncClient() - - # Initialize request argument(s) - request = dialogflow_v2.SuggestArticlesRequest( - parent="parent_value", - ) - - # Make the request - response = await client.suggest_articles(request=request) - - # Handle the response - print(response) - -# [END dialogflow_v2_generated_Participants_SuggestArticles_async] diff --git a/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_participants_suggest_articles_sync.py b/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_participants_suggest_articles_sync.py deleted file mode 100644 index 2d14d2dac..000000000 --- a/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_participants_suggest_articles_sync.py +++ /dev/null @@ -1,52 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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. -# -# Generated code. DO NOT EDIT! -# -# Snippet for SuggestArticles -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-dialogflow - - -# [START dialogflow_v2_generated_Participants_SuggestArticles_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import dialogflow_v2 - - -def sample_suggest_articles(): - # Create a client - client = dialogflow_v2.ParticipantsClient() - - # Initialize request argument(s) - request = dialogflow_v2.SuggestArticlesRequest( - parent="parent_value", - ) - - # Make the request - response = client.suggest_articles(request=request) - - # Handle the response - print(response) - -# [END dialogflow_v2_generated_Participants_SuggestArticles_sync] diff --git a/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_participants_suggest_faq_answers_async.py b/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_participants_suggest_faq_answers_async.py deleted file mode 100644 index 08a012865..000000000 --- a/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_participants_suggest_faq_answers_async.py +++ /dev/null @@ -1,52 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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. -# -# Generated code. DO NOT EDIT! -# -# Snippet for SuggestFaqAnswers -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-dialogflow - - -# [START dialogflow_v2_generated_Participants_SuggestFaqAnswers_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import dialogflow_v2 - - -async def sample_suggest_faq_answers(): - # Create a client - client = dialogflow_v2.ParticipantsAsyncClient() - - # Initialize request argument(s) - request = dialogflow_v2.SuggestFaqAnswersRequest( - parent="parent_value", - ) - - # Make the request - response = await client.suggest_faq_answers(request=request) - - # Handle the response - print(response) - -# [END dialogflow_v2_generated_Participants_SuggestFaqAnswers_async] diff --git a/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_participants_suggest_faq_answers_sync.py b/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_participants_suggest_faq_answers_sync.py deleted file mode 100644 index 74dd76ccb..000000000 --- a/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_participants_suggest_faq_answers_sync.py +++ /dev/null @@ -1,52 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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. -# -# Generated code. DO NOT EDIT! -# -# Snippet for SuggestFaqAnswers -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-dialogflow - - -# [START dialogflow_v2_generated_Participants_SuggestFaqAnswers_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import dialogflow_v2 - - -def sample_suggest_faq_answers(): - # Create a client - client = dialogflow_v2.ParticipantsClient() - - # Initialize request argument(s) - request = dialogflow_v2.SuggestFaqAnswersRequest( - parent="parent_value", - ) - - # Make the request - response = client.suggest_faq_answers(request=request) - - # Handle the response - print(response) - -# [END dialogflow_v2_generated_Participants_SuggestFaqAnswers_sync] diff --git a/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_participants_suggest_smart_replies_async.py b/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_participants_suggest_smart_replies_async.py deleted file mode 100644 index 03491e918..000000000 --- a/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_participants_suggest_smart_replies_async.py +++ /dev/null @@ -1,52 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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. -# -# Generated code. DO NOT EDIT! -# -# Snippet for SuggestSmartReplies -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-dialogflow - - -# [START dialogflow_v2_generated_Participants_SuggestSmartReplies_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import dialogflow_v2 - - -async def sample_suggest_smart_replies(): - # Create a client - client = dialogflow_v2.ParticipantsAsyncClient() - - # Initialize request argument(s) - request = dialogflow_v2.SuggestSmartRepliesRequest( - parent="parent_value", - ) - - # Make the request - response = await client.suggest_smart_replies(request=request) - - # Handle the response - print(response) - -# [END dialogflow_v2_generated_Participants_SuggestSmartReplies_async] diff --git a/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_participants_suggest_smart_replies_sync.py b/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_participants_suggest_smart_replies_sync.py deleted file mode 100644 index 05e565aff..000000000 --- a/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_participants_suggest_smart_replies_sync.py +++ /dev/null @@ -1,52 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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. -# -# Generated code. DO NOT EDIT! -# -# Snippet for SuggestSmartReplies -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-dialogflow - - -# [START dialogflow_v2_generated_Participants_SuggestSmartReplies_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import dialogflow_v2 - - -def sample_suggest_smart_replies(): - # Create a client - client = dialogflow_v2.ParticipantsClient() - - # Initialize request argument(s) - request = dialogflow_v2.SuggestSmartRepliesRequest( - parent="parent_value", - ) - - # Make the request - response = client.suggest_smart_replies(request=request) - - # Handle the response - print(response) - -# [END dialogflow_v2_generated_Participants_SuggestSmartReplies_sync] diff --git a/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_participants_update_participant_async.py b/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_participants_update_participant_async.py deleted file mode 100644 index 6e6ec0e86..000000000 --- a/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_participants_update_participant_async.py +++ /dev/null @@ -1,51 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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. -# -# Generated code. DO NOT EDIT! -# -# Snippet for UpdateParticipant -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-dialogflow - - -# [START dialogflow_v2_generated_Participants_UpdateParticipant_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import dialogflow_v2 - - -async def sample_update_participant(): - # Create a client - client = dialogflow_v2.ParticipantsAsyncClient() - - # Initialize request argument(s) - request = dialogflow_v2.UpdateParticipantRequest( - ) - - # Make the request - response = await client.update_participant(request=request) - - # Handle the response - print(response) - -# [END dialogflow_v2_generated_Participants_UpdateParticipant_async] diff --git a/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_participants_update_participant_sync.py b/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_participants_update_participant_sync.py deleted file mode 100644 index 6ff5a4d16..000000000 --- a/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_participants_update_participant_sync.py +++ /dev/null @@ -1,51 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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. -# -# Generated code. DO NOT EDIT! -# -# Snippet for UpdateParticipant -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-dialogflow - - -# [START dialogflow_v2_generated_Participants_UpdateParticipant_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import dialogflow_v2 - - -def sample_update_participant(): - # Create a client - client = dialogflow_v2.ParticipantsClient() - - # Initialize request argument(s) - request = dialogflow_v2.UpdateParticipantRequest( - ) - - # Make the request - response = client.update_participant(request=request) - - # Handle the response - print(response) - -# [END dialogflow_v2_generated_Participants_UpdateParticipant_sync] diff --git a/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_session_entity_types_create_session_entity_type_async.py b/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_session_entity_types_create_session_entity_type_async.py deleted file mode 100644 index 118348e87..000000000 --- a/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_session_entity_types_create_session_entity_type_async.py +++ /dev/null @@ -1,59 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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. -# -# Generated code. DO NOT EDIT! -# -# Snippet for CreateSessionEntityType -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-dialogflow - - -# [START dialogflow_v2_generated_SessionEntityTypes_CreateSessionEntityType_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import dialogflow_v2 - - -async def sample_create_session_entity_type(): - # Create a client - client = dialogflow_v2.SessionEntityTypesAsyncClient() - - # Initialize request argument(s) - session_entity_type = dialogflow_v2.SessionEntityType() - session_entity_type.name = "name_value" - session_entity_type.entity_override_mode = "ENTITY_OVERRIDE_MODE_SUPPLEMENT" - session_entity_type.entities.value = "value_value" - session_entity_type.entities.synonyms = ['synonyms_value1', 'synonyms_value2'] - - request = dialogflow_v2.CreateSessionEntityTypeRequest( - parent="parent_value", - session_entity_type=session_entity_type, - ) - - # Make the request - response = await client.create_session_entity_type(request=request) - - # Handle the response - print(response) - -# [END dialogflow_v2_generated_SessionEntityTypes_CreateSessionEntityType_async] diff --git a/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_session_entity_types_create_session_entity_type_sync.py b/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_session_entity_types_create_session_entity_type_sync.py deleted file mode 100644 index 6da1d80e9..000000000 --- a/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_session_entity_types_create_session_entity_type_sync.py +++ /dev/null @@ -1,59 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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. -# -# Generated code. DO NOT EDIT! -# -# Snippet for CreateSessionEntityType -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-dialogflow - - -# [START dialogflow_v2_generated_SessionEntityTypes_CreateSessionEntityType_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import dialogflow_v2 - - -def sample_create_session_entity_type(): - # Create a client - client = dialogflow_v2.SessionEntityTypesClient() - - # Initialize request argument(s) - session_entity_type = dialogflow_v2.SessionEntityType() - session_entity_type.name = "name_value" - session_entity_type.entity_override_mode = "ENTITY_OVERRIDE_MODE_SUPPLEMENT" - session_entity_type.entities.value = "value_value" - session_entity_type.entities.synonyms = ['synonyms_value1', 'synonyms_value2'] - - request = dialogflow_v2.CreateSessionEntityTypeRequest( - parent="parent_value", - session_entity_type=session_entity_type, - ) - - # Make the request - response = client.create_session_entity_type(request=request) - - # Handle the response - print(response) - -# [END dialogflow_v2_generated_SessionEntityTypes_CreateSessionEntityType_sync] diff --git a/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_session_entity_types_delete_session_entity_type_async.py b/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_session_entity_types_delete_session_entity_type_async.py deleted file mode 100644 index 0f255fb95..000000000 --- a/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_session_entity_types_delete_session_entity_type_async.py +++ /dev/null @@ -1,50 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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. -# -# Generated code. DO NOT EDIT! -# -# Snippet for DeleteSessionEntityType -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-dialogflow - - -# [START dialogflow_v2_generated_SessionEntityTypes_DeleteSessionEntityType_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import dialogflow_v2 - - -async def sample_delete_session_entity_type(): - # Create a client - client = dialogflow_v2.SessionEntityTypesAsyncClient() - - # Initialize request argument(s) - request = dialogflow_v2.DeleteSessionEntityTypeRequest( - name="name_value", - ) - - # Make the request - await client.delete_session_entity_type(request=request) - - -# [END dialogflow_v2_generated_SessionEntityTypes_DeleteSessionEntityType_async] diff --git a/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_session_entity_types_delete_session_entity_type_sync.py b/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_session_entity_types_delete_session_entity_type_sync.py deleted file mode 100644 index 20b0deaee..000000000 --- a/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_session_entity_types_delete_session_entity_type_sync.py +++ /dev/null @@ -1,50 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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. -# -# Generated code. DO NOT EDIT! -# -# Snippet for DeleteSessionEntityType -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-dialogflow - - -# [START dialogflow_v2_generated_SessionEntityTypes_DeleteSessionEntityType_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import dialogflow_v2 - - -def sample_delete_session_entity_type(): - # Create a client - client = dialogflow_v2.SessionEntityTypesClient() - - # Initialize request argument(s) - request = dialogflow_v2.DeleteSessionEntityTypeRequest( - name="name_value", - ) - - # Make the request - client.delete_session_entity_type(request=request) - - -# [END dialogflow_v2_generated_SessionEntityTypes_DeleteSessionEntityType_sync] diff --git a/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_session_entity_types_get_session_entity_type_async.py b/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_session_entity_types_get_session_entity_type_async.py deleted file mode 100644 index 10420c60c..000000000 --- a/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_session_entity_types_get_session_entity_type_async.py +++ /dev/null @@ -1,52 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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. -# -# Generated code. DO NOT EDIT! -# -# Snippet for GetSessionEntityType -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-dialogflow - - -# [START dialogflow_v2_generated_SessionEntityTypes_GetSessionEntityType_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import dialogflow_v2 - - -async def sample_get_session_entity_type(): - # Create a client - client = dialogflow_v2.SessionEntityTypesAsyncClient() - - # Initialize request argument(s) - request = dialogflow_v2.GetSessionEntityTypeRequest( - name="name_value", - ) - - # Make the request - response = await client.get_session_entity_type(request=request) - - # Handle the response - print(response) - -# [END dialogflow_v2_generated_SessionEntityTypes_GetSessionEntityType_async] diff --git a/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_session_entity_types_get_session_entity_type_sync.py b/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_session_entity_types_get_session_entity_type_sync.py deleted file mode 100644 index c96b5dfb4..000000000 --- a/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_session_entity_types_get_session_entity_type_sync.py +++ /dev/null @@ -1,52 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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. -# -# Generated code. DO NOT EDIT! -# -# Snippet for GetSessionEntityType -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-dialogflow - - -# [START dialogflow_v2_generated_SessionEntityTypes_GetSessionEntityType_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import dialogflow_v2 - - -def sample_get_session_entity_type(): - # Create a client - client = dialogflow_v2.SessionEntityTypesClient() - - # Initialize request argument(s) - request = dialogflow_v2.GetSessionEntityTypeRequest( - name="name_value", - ) - - # Make the request - response = client.get_session_entity_type(request=request) - - # Handle the response - print(response) - -# [END dialogflow_v2_generated_SessionEntityTypes_GetSessionEntityType_sync] diff --git a/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_session_entity_types_list_session_entity_types_async.py b/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_session_entity_types_list_session_entity_types_async.py deleted file mode 100644 index 2d5baceb4..000000000 --- a/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_session_entity_types_list_session_entity_types_async.py +++ /dev/null @@ -1,53 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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. -# -# Generated code. DO NOT EDIT! -# -# Snippet for ListSessionEntityTypes -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-dialogflow - - -# [START dialogflow_v2_generated_SessionEntityTypes_ListSessionEntityTypes_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import dialogflow_v2 - - -async def sample_list_session_entity_types(): - # Create a client - client = dialogflow_v2.SessionEntityTypesAsyncClient() - - # Initialize request argument(s) - request = dialogflow_v2.ListSessionEntityTypesRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_session_entity_types(request=request) - - # Handle the response - async for response in page_result: - print(response) - -# [END dialogflow_v2_generated_SessionEntityTypes_ListSessionEntityTypes_async] diff --git a/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_session_entity_types_list_session_entity_types_sync.py b/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_session_entity_types_list_session_entity_types_sync.py deleted file mode 100644 index 1ff1bce9b..000000000 --- a/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_session_entity_types_list_session_entity_types_sync.py +++ /dev/null @@ -1,53 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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. -# -# Generated code. DO NOT EDIT! -# -# Snippet for ListSessionEntityTypes -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-dialogflow - - -# [START dialogflow_v2_generated_SessionEntityTypes_ListSessionEntityTypes_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import dialogflow_v2 - - -def sample_list_session_entity_types(): - # Create a client - client = dialogflow_v2.SessionEntityTypesClient() - - # Initialize request argument(s) - request = dialogflow_v2.ListSessionEntityTypesRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_session_entity_types(request=request) - - # Handle the response - for response in page_result: - print(response) - -# [END dialogflow_v2_generated_SessionEntityTypes_ListSessionEntityTypes_sync] diff --git a/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_session_entity_types_update_session_entity_type_async.py b/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_session_entity_types_update_session_entity_type_async.py deleted file mode 100644 index 33241c796..000000000 --- a/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_session_entity_types_update_session_entity_type_async.py +++ /dev/null @@ -1,58 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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. -# -# Generated code. DO NOT EDIT! -# -# Snippet for UpdateSessionEntityType -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-dialogflow - - -# [START dialogflow_v2_generated_SessionEntityTypes_UpdateSessionEntityType_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import dialogflow_v2 - - -async def sample_update_session_entity_type(): - # Create a client - client = dialogflow_v2.SessionEntityTypesAsyncClient() - - # Initialize request argument(s) - session_entity_type = dialogflow_v2.SessionEntityType() - session_entity_type.name = "name_value" - session_entity_type.entity_override_mode = "ENTITY_OVERRIDE_MODE_SUPPLEMENT" - session_entity_type.entities.value = "value_value" - session_entity_type.entities.synonyms = ['synonyms_value1', 'synonyms_value2'] - - request = dialogflow_v2.UpdateSessionEntityTypeRequest( - session_entity_type=session_entity_type, - ) - - # Make the request - response = await client.update_session_entity_type(request=request) - - # Handle the response - print(response) - -# [END dialogflow_v2_generated_SessionEntityTypes_UpdateSessionEntityType_async] diff --git a/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_session_entity_types_update_session_entity_type_sync.py b/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_session_entity_types_update_session_entity_type_sync.py deleted file mode 100644 index b2a9628e3..000000000 --- a/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_session_entity_types_update_session_entity_type_sync.py +++ /dev/null @@ -1,58 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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. -# -# Generated code. DO NOT EDIT! -# -# Snippet for UpdateSessionEntityType -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-dialogflow - - -# [START dialogflow_v2_generated_SessionEntityTypes_UpdateSessionEntityType_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import dialogflow_v2 - - -def sample_update_session_entity_type(): - # Create a client - client = dialogflow_v2.SessionEntityTypesClient() - - # Initialize request argument(s) - session_entity_type = dialogflow_v2.SessionEntityType() - session_entity_type.name = "name_value" - session_entity_type.entity_override_mode = "ENTITY_OVERRIDE_MODE_SUPPLEMENT" - session_entity_type.entities.value = "value_value" - session_entity_type.entities.synonyms = ['synonyms_value1', 'synonyms_value2'] - - request = dialogflow_v2.UpdateSessionEntityTypeRequest( - session_entity_type=session_entity_type, - ) - - # Make the request - response = client.update_session_entity_type(request=request) - - # Handle the response - print(response) - -# [END dialogflow_v2_generated_SessionEntityTypes_UpdateSessionEntityType_sync] diff --git a/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_sessions_detect_intent_async.py b/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_sessions_detect_intent_async.py deleted file mode 100644 index 1157564f6..000000000 --- a/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_sessions_detect_intent_async.py +++ /dev/null @@ -1,52 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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. -# -# Generated code. DO NOT EDIT! -# -# Snippet for DetectIntent -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-dialogflow - - -# [START dialogflow_v2_generated_Sessions_DetectIntent_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import dialogflow_v2 - - -async def sample_detect_intent(): - # Create a client - client = dialogflow_v2.SessionsAsyncClient() - - # Initialize request argument(s) - request = dialogflow_v2.DetectIntentRequest( - session="session_value", - ) - - # Make the request - response = await client.detect_intent(request=request) - - # Handle the response - print(response) - -# [END dialogflow_v2_generated_Sessions_DetectIntent_async] diff --git a/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_sessions_detect_intent_sync.py b/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_sessions_detect_intent_sync.py deleted file mode 100644 index 8a781d227..000000000 --- a/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_sessions_detect_intent_sync.py +++ /dev/null @@ -1,52 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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. -# -# Generated code. DO NOT EDIT! -# -# Snippet for DetectIntent -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-dialogflow - - -# [START dialogflow_v2_generated_Sessions_DetectIntent_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import dialogflow_v2 - - -def sample_detect_intent(): - # Create a client - client = dialogflow_v2.SessionsClient() - - # Initialize request argument(s) - request = dialogflow_v2.DetectIntentRequest( - session="session_value", - ) - - # Make the request - response = client.detect_intent(request=request) - - # Handle the response - print(response) - -# [END dialogflow_v2_generated_Sessions_DetectIntent_sync] diff --git a/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_sessions_streaming_detect_intent_async.py b/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_sessions_streaming_detect_intent_async.py deleted file mode 100644 index a33d7da10..000000000 --- a/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_sessions_streaming_detect_intent_async.py +++ /dev/null @@ -1,63 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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. -# -# Generated code. DO NOT EDIT! -# -# Snippet for StreamingDetectIntent -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-dialogflow - - -# [START dialogflow_v2_generated_Sessions_StreamingDetectIntent_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import dialogflow_v2 - - -async def sample_streaming_detect_intent(): - # Create a client - client = dialogflow_v2.SessionsAsyncClient() - - # Initialize request argument(s) - request = dialogflow_v2.StreamingDetectIntentRequest( - session="session_value", - ) - - # This method expects an iterator which contains - # 'dialogflow_v2.StreamingDetectIntentRequest' objects - # Here we create a generator that yields a single `request` for - # demonstrative purposes. - requests = [request] - - def request_generator(): - for request in requests: - yield request - - # Make the request - stream = await client.streaming_detect_intent(requests=request_generator()) - - # Handle the response - async for response in stream: - print(response) - -# [END dialogflow_v2_generated_Sessions_StreamingDetectIntent_async] diff --git a/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_sessions_streaming_detect_intent_sync.py b/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_sessions_streaming_detect_intent_sync.py deleted file mode 100644 index e0885ac7c..000000000 --- a/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_sessions_streaming_detect_intent_sync.py +++ /dev/null @@ -1,63 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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. -# -# Generated code. DO NOT EDIT! -# -# Snippet for StreamingDetectIntent -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-dialogflow - - -# [START dialogflow_v2_generated_Sessions_StreamingDetectIntent_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import dialogflow_v2 - - -def sample_streaming_detect_intent(): - # Create a client - client = dialogflow_v2.SessionsClient() - - # Initialize request argument(s) - request = dialogflow_v2.StreamingDetectIntentRequest( - session="session_value", - ) - - # This method expects an iterator which contains - # 'dialogflow_v2.StreamingDetectIntentRequest' objects - # Here we create a generator that yields a single `request` for - # demonstrative purposes. - requests = [request] - - def request_generator(): - for request in requests: - yield request - - # Make the request - stream = client.streaming_detect_intent(requests=request_generator()) - - # Handle the response - for response in stream: - print(response) - -# [END dialogflow_v2_generated_Sessions_StreamingDetectIntent_sync] diff --git a/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_versions_create_version_async.py b/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_versions_create_version_async.py deleted file mode 100644 index c79bbed4e..000000000 --- a/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_versions_create_version_async.py +++ /dev/null @@ -1,52 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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. -# -# Generated code. DO NOT EDIT! -# -# Snippet for CreateVersion -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-dialogflow - - -# [START dialogflow_v2_generated_Versions_CreateVersion_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import dialogflow_v2 - - -async def sample_create_version(): - # Create a client - client = dialogflow_v2.VersionsAsyncClient() - - # Initialize request argument(s) - request = dialogflow_v2.CreateVersionRequest( - parent="parent_value", - ) - - # Make the request - response = await client.create_version(request=request) - - # Handle the response - print(response) - -# [END dialogflow_v2_generated_Versions_CreateVersion_async] diff --git a/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_versions_create_version_sync.py b/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_versions_create_version_sync.py deleted file mode 100644 index 7463be086..000000000 --- a/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_versions_create_version_sync.py +++ /dev/null @@ -1,52 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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. -# -# Generated code. DO NOT EDIT! -# -# Snippet for CreateVersion -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-dialogflow - - -# [START dialogflow_v2_generated_Versions_CreateVersion_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import dialogflow_v2 - - -def sample_create_version(): - # Create a client - client = dialogflow_v2.VersionsClient() - - # Initialize request argument(s) - request = dialogflow_v2.CreateVersionRequest( - parent="parent_value", - ) - - # Make the request - response = client.create_version(request=request) - - # Handle the response - print(response) - -# [END dialogflow_v2_generated_Versions_CreateVersion_sync] diff --git a/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_versions_delete_version_async.py b/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_versions_delete_version_async.py deleted file mode 100644 index a421789c7..000000000 --- a/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_versions_delete_version_async.py +++ /dev/null @@ -1,50 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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. -# -# Generated code. DO NOT EDIT! -# -# Snippet for DeleteVersion -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-dialogflow - - -# [START dialogflow_v2_generated_Versions_DeleteVersion_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import dialogflow_v2 - - -async def sample_delete_version(): - # Create a client - client = dialogflow_v2.VersionsAsyncClient() - - # Initialize request argument(s) - request = dialogflow_v2.DeleteVersionRequest( - name="name_value", - ) - - # Make the request - await client.delete_version(request=request) - - -# [END dialogflow_v2_generated_Versions_DeleteVersion_async] diff --git a/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_versions_delete_version_sync.py b/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_versions_delete_version_sync.py deleted file mode 100644 index 4a7a8bc7e..000000000 --- a/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_versions_delete_version_sync.py +++ /dev/null @@ -1,50 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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. -# -# Generated code. DO NOT EDIT! -# -# Snippet for DeleteVersion -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-dialogflow - - -# [START dialogflow_v2_generated_Versions_DeleteVersion_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import dialogflow_v2 - - -def sample_delete_version(): - # Create a client - client = dialogflow_v2.VersionsClient() - - # Initialize request argument(s) - request = dialogflow_v2.DeleteVersionRequest( - name="name_value", - ) - - # Make the request - client.delete_version(request=request) - - -# [END dialogflow_v2_generated_Versions_DeleteVersion_sync] diff --git a/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_versions_get_version_async.py b/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_versions_get_version_async.py deleted file mode 100644 index 0db5b1a9f..000000000 --- a/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_versions_get_version_async.py +++ /dev/null @@ -1,52 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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. -# -# Generated code. DO NOT EDIT! -# -# Snippet for GetVersion -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-dialogflow - - -# [START dialogflow_v2_generated_Versions_GetVersion_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import dialogflow_v2 - - -async def sample_get_version(): - # Create a client - client = dialogflow_v2.VersionsAsyncClient() - - # Initialize request argument(s) - request = dialogflow_v2.GetVersionRequest( - name="name_value", - ) - - # Make the request - response = await client.get_version(request=request) - - # Handle the response - print(response) - -# [END dialogflow_v2_generated_Versions_GetVersion_async] diff --git a/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_versions_get_version_sync.py b/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_versions_get_version_sync.py deleted file mode 100644 index d19dd8228..000000000 --- a/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_versions_get_version_sync.py +++ /dev/null @@ -1,52 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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. -# -# Generated code. DO NOT EDIT! -# -# Snippet for GetVersion -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-dialogflow - - -# [START dialogflow_v2_generated_Versions_GetVersion_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import dialogflow_v2 - - -def sample_get_version(): - # Create a client - client = dialogflow_v2.VersionsClient() - - # Initialize request argument(s) - request = dialogflow_v2.GetVersionRequest( - name="name_value", - ) - - # Make the request - response = client.get_version(request=request) - - # Handle the response - print(response) - -# [END dialogflow_v2_generated_Versions_GetVersion_sync] diff --git a/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_versions_list_versions_async.py b/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_versions_list_versions_async.py deleted file mode 100644 index 2ad8a6ad3..000000000 --- a/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_versions_list_versions_async.py +++ /dev/null @@ -1,53 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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. -# -# Generated code. DO NOT EDIT! -# -# Snippet for ListVersions -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-dialogflow - - -# [START dialogflow_v2_generated_Versions_ListVersions_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import dialogflow_v2 - - -async def sample_list_versions(): - # Create a client - client = dialogflow_v2.VersionsAsyncClient() - - # Initialize request argument(s) - request = dialogflow_v2.ListVersionsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_versions(request=request) - - # Handle the response - async for response in page_result: - print(response) - -# [END dialogflow_v2_generated_Versions_ListVersions_async] diff --git a/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_versions_list_versions_sync.py b/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_versions_list_versions_sync.py deleted file mode 100644 index fcfc1ccbe..000000000 --- a/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_versions_list_versions_sync.py +++ /dev/null @@ -1,53 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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. -# -# Generated code. DO NOT EDIT! -# -# Snippet for ListVersions -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-dialogflow - - -# [START dialogflow_v2_generated_Versions_ListVersions_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import dialogflow_v2 - - -def sample_list_versions(): - # Create a client - client = dialogflow_v2.VersionsClient() - - # Initialize request argument(s) - request = dialogflow_v2.ListVersionsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_versions(request=request) - - # Handle the response - for response in page_result: - print(response) - -# [END dialogflow_v2_generated_Versions_ListVersions_sync] diff --git a/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_versions_update_version_async.py b/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_versions_update_version_async.py deleted file mode 100644 index dc4e672dd..000000000 --- a/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_versions_update_version_async.py +++ /dev/null @@ -1,51 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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. -# -# Generated code. DO NOT EDIT! -# -# Snippet for UpdateVersion -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-dialogflow - - -# [START dialogflow_v2_generated_Versions_UpdateVersion_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import dialogflow_v2 - - -async def sample_update_version(): - # Create a client - client = dialogflow_v2.VersionsAsyncClient() - - # Initialize request argument(s) - request = dialogflow_v2.UpdateVersionRequest( - ) - - # Make the request - response = await client.update_version(request=request) - - # Handle the response - print(response) - -# [END dialogflow_v2_generated_Versions_UpdateVersion_async] diff --git a/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_versions_update_version_sync.py b/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_versions_update_version_sync.py deleted file mode 100644 index ebbd4dbc5..000000000 --- a/owl-bot-staging/v2/samples/generated_samples/dialogflow_v2_generated_versions_update_version_sync.py +++ /dev/null @@ -1,51 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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. -# -# Generated code. DO NOT EDIT! -# -# Snippet for UpdateVersion -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-dialogflow - - -# [START dialogflow_v2_generated_Versions_UpdateVersion_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import dialogflow_v2 - - -def sample_update_version(): - # Create a client - client = dialogflow_v2.VersionsClient() - - # Initialize request argument(s) - request = dialogflow_v2.UpdateVersionRequest( - ) - - # Make the request - response = client.update_version(request=request) - - # Handle the response - print(response) - -# [END dialogflow_v2_generated_Versions_UpdateVersion_sync] diff --git a/owl-bot-staging/v2/samples/generated_samples/snippet_metadata_google.cloud.dialogflow.v2.json b/owl-bot-staging/v2/samples/generated_samples/snippet_metadata_google.cloud.dialogflow.v2.json deleted file mode 100644 index d2844dc00..000000000 --- a/owl-bot-staging/v2/samples/generated_samples/snippet_metadata_google.cloud.dialogflow.v2.json +++ /dev/null @@ -1,16802 +0,0 @@ -{ - "clientLibrary": { - "apis": [ - { - "id": "google.cloud.dialogflow.v2", - "version": "v2" - } - ], - "language": "PYTHON", - "name": "google-cloud-dialogflow", - "version": "0.1.0" - }, - "snippets": [ - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.dialogflow_v2.AgentsAsyncClient", - "shortName": "AgentsAsyncClient" - }, - "fullName": "google.cloud.dialogflow_v2.AgentsAsyncClient.delete_agent", - "method": { - "fullName": "google.cloud.dialogflow.v2.Agents.DeleteAgent", - "service": { - "fullName": "google.cloud.dialogflow.v2.Agents", - "shortName": "Agents" - }, - "shortName": "DeleteAgent" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.dialogflow_v2.types.DeleteAgentRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "shortName": "delete_agent" - }, - "description": "Sample for DeleteAgent", - "file": "dialogflow_v2_generated_agents_delete_agent_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "dialogflow_v2_generated_Agents_DeleteAgent_async", - "segments": [ - { - "end": 49, - "start": 27, - "type": "FULL" - }, - { - "end": 49, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 50, - "type": "RESPONSE_HANDLING" - } - ], - "title": "dialogflow_v2_generated_agents_delete_agent_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.dialogflow_v2.AgentsClient", - "shortName": "AgentsClient" - }, - "fullName": "google.cloud.dialogflow_v2.AgentsClient.delete_agent", - "method": { - "fullName": "google.cloud.dialogflow.v2.Agents.DeleteAgent", - "service": { - "fullName": "google.cloud.dialogflow.v2.Agents", - "shortName": "Agents" - }, - "shortName": "DeleteAgent" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.dialogflow_v2.types.DeleteAgentRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "shortName": "delete_agent" - }, - "description": "Sample for DeleteAgent", - "file": "dialogflow_v2_generated_agents_delete_agent_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "dialogflow_v2_generated_Agents_DeleteAgent_sync", - "segments": [ - { - "end": 49, - "start": 27, - "type": "FULL" - }, - { - "end": 49, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 50, - "type": "RESPONSE_HANDLING" - } - ], - "title": "dialogflow_v2_generated_agents_delete_agent_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.dialogflow_v2.AgentsAsyncClient", - "shortName": "AgentsAsyncClient" - }, - "fullName": "google.cloud.dialogflow_v2.AgentsAsyncClient.export_agent", - "method": { - "fullName": "google.cloud.dialogflow.v2.Agents.ExportAgent", - "service": { - "fullName": "google.cloud.dialogflow.v2.Agents", - "shortName": "Agents" - }, - "shortName": "ExportAgent" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.dialogflow_v2.types.ExportAgentRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.api_core.operation_async.AsyncOperation", - "shortName": "export_agent" - }, - "description": "Sample for ExportAgent", - "file": "dialogflow_v2_generated_agents_export_agent_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "dialogflow_v2_generated_Agents_ExportAgent_async", - "segments": [ - { - "end": 56, - "start": 27, - "type": "FULL" - }, - { - "end": 56, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 46, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 53, - "start": 47, - "type": "REQUEST_EXECUTION" - }, - { - "end": 57, - "start": 54, - "type": "RESPONSE_HANDLING" - } - ], - "title": "dialogflow_v2_generated_agents_export_agent_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.dialogflow_v2.AgentsClient", - "shortName": "AgentsClient" - }, - "fullName": "google.cloud.dialogflow_v2.AgentsClient.export_agent", - "method": { - "fullName": "google.cloud.dialogflow.v2.Agents.ExportAgent", - "service": { - "fullName": "google.cloud.dialogflow.v2.Agents", - "shortName": "Agents" - }, - "shortName": "ExportAgent" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.dialogflow_v2.types.ExportAgentRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.api_core.operation.Operation", - "shortName": "export_agent" - }, - "description": "Sample for ExportAgent", - "file": "dialogflow_v2_generated_agents_export_agent_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "dialogflow_v2_generated_Agents_ExportAgent_sync", - "segments": [ - { - "end": 56, - "start": 27, - "type": "FULL" - }, - { - "end": 56, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 46, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 53, - "start": 47, - "type": "REQUEST_EXECUTION" - }, - { - "end": 57, - "start": 54, - "type": "RESPONSE_HANDLING" - } - ], - "title": "dialogflow_v2_generated_agents_export_agent_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.dialogflow_v2.AgentsAsyncClient", - "shortName": "AgentsAsyncClient" - }, - "fullName": "google.cloud.dialogflow_v2.AgentsAsyncClient.get_agent", - "method": { - "fullName": "google.cloud.dialogflow.v2.Agents.GetAgent", - "service": { - "fullName": "google.cloud.dialogflow.v2.Agents", - "shortName": "Agents" - }, - "shortName": "GetAgent" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.dialogflow_v2.types.GetAgentRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.dialogflow_v2.types.Agent", - "shortName": "get_agent" - }, - "description": "Sample for GetAgent", - "file": "dialogflow_v2_generated_agents_get_agent_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "dialogflow_v2_generated_Agents_GetAgent_async", - "segments": [ - { - "end": 51, - "start": 27, - "type": "FULL" - }, - { - "end": 51, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 48, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 52, - "start": 49, - "type": "RESPONSE_HANDLING" - } - ], - "title": "dialogflow_v2_generated_agents_get_agent_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.dialogflow_v2.AgentsClient", - "shortName": "AgentsClient" - }, - "fullName": "google.cloud.dialogflow_v2.AgentsClient.get_agent", - "method": { - "fullName": "google.cloud.dialogflow.v2.Agents.GetAgent", - "service": { - "fullName": "google.cloud.dialogflow.v2.Agents", - "shortName": "Agents" - }, - "shortName": "GetAgent" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.dialogflow_v2.types.GetAgentRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.dialogflow_v2.types.Agent", - "shortName": "get_agent" - }, - "description": "Sample for GetAgent", - "file": "dialogflow_v2_generated_agents_get_agent_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "dialogflow_v2_generated_Agents_GetAgent_sync", - "segments": [ - { - "end": 51, - "start": 27, - "type": "FULL" - }, - { - "end": 51, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 48, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 52, - "start": 49, - "type": "RESPONSE_HANDLING" - } - ], - "title": "dialogflow_v2_generated_agents_get_agent_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.dialogflow_v2.AgentsAsyncClient", - "shortName": "AgentsAsyncClient" - }, - "fullName": "google.cloud.dialogflow_v2.AgentsAsyncClient.get_validation_result", - "method": { - "fullName": "google.cloud.dialogflow.v2.Agents.GetValidationResult", - "service": { - "fullName": "google.cloud.dialogflow.v2.Agents", - "shortName": "Agents" - }, - "shortName": "GetValidationResult" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.dialogflow_v2.types.GetValidationResultRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.dialogflow_v2.types.ValidationResult", - "shortName": "get_validation_result" - }, - "description": "Sample for GetValidationResult", - "file": "dialogflow_v2_generated_agents_get_validation_result_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "dialogflow_v2_generated_Agents_GetValidationResult_async", - "segments": [ - { - "end": 51, - "start": 27, - "type": "FULL" - }, - { - "end": 51, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 48, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 52, - "start": 49, - "type": "RESPONSE_HANDLING" - } - ], - "title": "dialogflow_v2_generated_agents_get_validation_result_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.dialogflow_v2.AgentsClient", - "shortName": "AgentsClient" - }, - "fullName": "google.cloud.dialogflow_v2.AgentsClient.get_validation_result", - "method": { - "fullName": "google.cloud.dialogflow.v2.Agents.GetValidationResult", - "service": { - "fullName": "google.cloud.dialogflow.v2.Agents", - "shortName": "Agents" - }, - "shortName": "GetValidationResult" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.dialogflow_v2.types.GetValidationResultRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.dialogflow_v2.types.ValidationResult", - "shortName": "get_validation_result" - }, - "description": "Sample for GetValidationResult", - "file": "dialogflow_v2_generated_agents_get_validation_result_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "dialogflow_v2_generated_Agents_GetValidationResult_sync", - "segments": [ - { - "end": 51, - "start": 27, - "type": "FULL" - }, - { - "end": 51, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 48, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 52, - "start": 49, - "type": "RESPONSE_HANDLING" - } - ], - "title": "dialogflow_v2_generated_agents_get_validation_result_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.dialogflow_v2.AgentsAsyncClient", - "shortName": "AgentsAsyncClient" - }, - "fullName": "google.cloud.dialogflow_v2.AgentsAsyncClient.import_agent", - "method": { - "fullName": "google.cloud.dialogflow.v2.Agents.ImportAgent", - "service": { - "fullName": "google.cloud.dialogflow.v2.Agents", - "shortName": "Agents" - }, - "shortName": "ImportAgent" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.dialogflow_v2.types.ImportAgentRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.api_core.operation_async.AsyncOperation", - "shortName": "import_agent" - }, - "description": "Sample for ImportAgent", - "file": "dialogflow_v2_generated_agents_import_agent_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "dialogflow_v2_generated_Agents_ImportAgent_async", - "segments": [ - { - "end": 56, - "start": 27, - "type": "FULL" - }, - { - "end": 56, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 46, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 53, - "start": 47, - "type": "REQUEST_EXECUTION" - }, - { - "end": 57, - "start": 54, - "type": "RESPONSE_HANDLING" - } - ], - "title": "dialogflow_v2_generated_agents_import_agent_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.dialogflow_v2.AgentsClient", - "shortName": "AgentsClient" - }, - "fullName": "google.cloud.dialogflow_v2.AgentsClient.import_agent", - "method": { - "fullName": "google.cloud.dialogflow.v2.Agents.ImportAgent", - "service": { - "fullName": "google.cloud.dialogflow.v2.Agents", - "shortName": "Agents" - }, - "shortName": "ImportAgent" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.dialogflow_v2.types.ImportAgentRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.api_core.operation.Operation", - "shortName": "import_agent" - }, - "description": "Sample for ImportAgent", - "file": "dialogflow_v2_generated_agents_import_agent_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "dialogflow_v2_generated_Agents_ImportAgent_sync", - "segments": [ - { - "end": 56, - "start": 27, - "type": "FULL" - }, - { - "end": 56, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 46, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 53, - "start": 47, - "type": "REQUEST_EXECUTION" - }, - { - "end": 57, - "start": 54, - "type": "RESPONSE_HANDLING" - } - ], - "title": "dialogflow_v2_generated_agents_import_agent_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.dialogflow_v2.AgentsAsyncClient", - "shortName": "AgentsAsyncClient" - }, - "fullName": "google.cloud.dialogflow_v2.AgentsAsyncClient.restore_agent", - "method": { - "fullName": "google.cloud.dialogflow.v2.Agents.RestoreAgent", - "service": { - "fullName": "google.cloud.dialogflow.v2.Agents", - "shortName": "Agents" - }, - "shortName": "RestoreAgent" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.dialogflow_v2.types.RestoreAgentRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.api_core.operation_async.AsyncOperation", - "shortName": "restore_agent" - }, - "description": "Sample for RestoreAgent", - "file": "dialogflow_v2_generated_agents_restore_agent_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "dialogflow_v2_generated_Agents_RestoreAgent_async", - "segments": [ - { - "end": 56, - "start": 27, - "type": "FULL" - }, - { - "end": 56, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 46, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 53, - "start": 47, - "type": "REQUEST_EXECUTION" - }, - { - "end": 57, - "start": 54, - "type": "RESPONSE_HANDLING" - } - ], - "title": "dialogflow_v2_generated_agents_restore_agent_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.dialogflow_v2.AgentsClient", - "shortName": "AgentsClient" - }, - "fullName": "google.cloud.dialogflow_v2.AgentsClient.restore_agent", - "method": { - "fullName": "google.cloud.dialogflow.v2.Agents.RestoreAgent", - "service": { - "fullName": "google.cloud.dialogflow.v2.Agents", - "shortName": "Agents" - }, - "shortName": "RestoreAgent" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.dialogflow_v2.types.RestoreAgentRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.api_core.operation.Operation", - "shortName": "restore_agent" - }, - "description": "Sample for RestoreAgent", - "file": "dialogflow_v2_generated_agents_restore_agent_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "dialogflow_v2_generated_Agents_RestoreAgent_sync", - "segments": [ - { - "end": 56, - "start": 27, - "type": "FULL" - }, - { - "end": 56, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 46, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 53, - "start": 47, - "type": "REQUEST_EXECUTION" - }, - { - "end": 57, - "start": 54, - "type": "RESPONSE_HANDLING" - } - ], - "title": "dialogflow_v2_generated_agents_restore_agent_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.dialogflow_v2.AgentsAsyncClient", - "shortName": "AgentsAsyncClient" - }, - "fullName": "google.cloud.dialogflow_v2.AgentsAsyncClient.search_agents", - "method": { - "fullName": "google.cloud.dialogflow.v2.Agents.SearchAgents", - "service": { - "fullName": "google.cloud.dialogflow.v2.Agents", - "shortName": "Agents" - }, - "shortName": "SearchAgents" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.dialogflow_v2.types.SearchAgentsRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.dialogflow_v2.services.agents.pagers.SearchAgentsAsyncPager", - "shortName": "search_agents" - }, - "description": "Sample for SearchAgents", - "file": "dialogflow_v2_generated_agents_search_agents_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "dialogflow_v2_generated_Agents_SearchAgents_async", - "segments": [ - { - "end": 52, - "start": 27, - "type": "FULL" - }, - { - "end": 52, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 48, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 53, - "start": 49, - "type": "RESPONSE_HANDLING" - } - ], - "title": "dialogflow_v2_generated_agents_search_agents_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.dialogflow_v2.AgentsClient", - "shortName": "AgentsClient" - }, - "fullName": "google.cloud.dialogflow_v2.AgentsClient.search_agents", - "method": { - "fullName": "google.cloud.dialogflow.v2.Agents.SearchAgents", - "service": { - "fullName": "google.cloud.dialogflow.v2.Agents", - "shortName": "Agents" - }, - "shortName": "SearchAgents" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.dialogflow_v2.types.SearchAgentsRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.dialogflow_v2.services.agents.pagers.SearchAgentsPager", - "shortName": "search_agents" - }, - "description": "Sample for SearchAgents", - "file": "dialogflow_v2_generated_agents_search_agents_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "dialogflow_v2_generated_Agents_SearchAgents_sync", - "segments": [ - { - "end": 52, - "start": 27, - "type": "FULL" - }, - { - "end": 52, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 48, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 53, - "start": 49, - "type": "RESPONSE_HANDLING" - } - ], - "title": "dialogflow_v2_generated_agents_search_agents_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.dialogflow_v2.AgentsAsyncClient", - "shortName": "AgentsAsyncClient" - }, - "fullName": "google.cloud.dialogflow_v2.AgentsAsyncClient.set_agent", - "method": { - "fullName": "google.cloud.dialogflow.v2.Agents.SetAgent", - "service": { - "fullName": "google.cloud.dialogflow.v2.Agents", - "shortName": "Agents" - }, - "shortName": "SetAgent" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.dialogflow_v2.types.SetAgentRequest" - }, - { - "name": "agent", - "type": "google.cloud.dialogflow_v2.types.Agent" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.dialogflow_v2.types.Agent", - "shortName": "set_agent" - }, - "description": "Sample for SetAgent", - "file": "dialogflow_v2_generated_agents_set_agent_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "dialogflow_v2_generated_Agents_SetAgent_async", - "segments": [ - { - "end": 57, - "start": 27, - "type": "FULL" - }, - { - "end": 57, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 51, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 54, - "start": 52, - "type": "REQUEST_EXECUTION" - }, - { - "end": 58, - "start": 55, - "type": "RESPONSE_HANDLING" - } - ], - "title": "dialogflow_v2_generated_agents_set_agent_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.dialogflow_v2.AgentsClient", - "shortName": "AgentsClient" - }, - "fullName": "google.cloud.dialogflow_v2.AgentsClient.set_agent", - "method": { - "fullName": "google.cloud.dialogflow.v2.Agents.SetAgent", - "service": { - "fullName": "google.cloud.dialogflow.v2.Agents", - "shortName": "Agents" - }, - "shortName": "SetAgent" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.dialogflow_v2.types.SetAgentRequest" - }, - { - "name": "agent", - "type": "google.cloud.dialogflow_v2.types.Agent" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.dialogflow_v2.types.Agent", - "shortName": "set_agent" - }, - "description": "Sample for SetAgent", - "file": "dialogflow_v2_generated_agents_set_agent_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "dialogflow_v2_generated_Agents_SetAgent_sync", - "segments": [ - { - "end": 57, - "start": 27, - "type": "FULL" - }, - { - "end": 57, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 51, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 54, - "start": 52, - "type": "REQUEST_EXECUTION" - }, - { - "end": 58, - "start": 55, - "type": "RESPONSE_HANDLING" - } - ], - "title": "dialogflow_v2_generated_agents_set_agent_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.dialogflow_v2.AgentsAsyncClient", - "shortName": "AgentsAsyncClient" - }, - "fullName": "google.cloud.dialogflow_v2.AgentsAsyncClient.train_agent", - "method": { - "fullName": "google.cloud.dialogflow.v2.Agents.TrainAgent", - "service": { - "fullName": "google.cloud.dialogflow.v2.Agents", - "shortName": "Agents" - }, - "shortName": "TrainAgent" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.dialogflow_v2.types.TrainAgentRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.api_core.operation_async.AsyncOperation", - "shortName": "train_agent" - }, - "description": "Sample for TrainAgent", - "file": "dialogflow_v2_generated_agents_train_agent_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "dialogflow_v2_generated_Agents_TrainAgent_async", - "segments": [ - { - "end": 55, - "start": 27, - "type": "FULL" - }, - { - "end": 55, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 52, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 56, - "start": 53, - "type": "RESPONSE_HANDLING" - } - ], - "title": "dialogflow_v2_generated_agents_train_agent_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.dialogflow_v2.AgentsClient", - "shortName": "AgentsClient" - }, - "fullName": "google.cloud.dialogflow_v2.AgentsClient.train_agent", - "method": { - "fullName": "google.cloud.dialogflow.v2.Agents.TrainAgent", - "service": { - "fullName": "google.cloud.dialogflow.v2.Agents", - "shortName": "Agents" - }, - "shortName": "TrainAgent" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.dialogflow_v2.types.TrainAgentRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.api_core.operation.Operation", - "shortName": "train_agent" - }, - "description": "Sample for TrainAgent", - "file": "dialogflow_v2_generated_agents_train_agent_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "dialogflow_v2_generated_Agents_TrainAgent_sync", - "segments": [ - { - "end": 55, - "start": 27, - "type": "FULL" - }, - { - "end": 55, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 52, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 56, - "start": 53, - "type": "RESPONSE_HANDLING" - } - ], - "title": "dialogflow_v2_generated_agents_train_agent_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.dialogflow_v2.AnswerRecordsAsyncClient", - "shortName": "AnswerRecordsAsyncClient" - }, - "fullName": "google.cloud.dialogflow_v2.AnswerRecordsAsyncClient.list_answer_records", - "method": { - "fullName": "google.cloud.dialogflow.v2.AnswerRecords.ListAnswerRecords", - "service": { - "fullName": "google.cloud.dialogflow.v2.AnswerRecords", - "shortName": "AnswerRecords" - }, - "shortName": "ListAnswerRecords" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.dialogflow_v2.types.ListAnswerRecordsRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.dialogflow_v2.services.answer_records.pagers.ListAnswerRecordsAsyncPager", - "shortName": "list_answer_records" - }, - "description": "Sample for ListAnswerRecords", - "file": "dialogflow_v2_generated_answer_records_list_answer_records_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "dialogflow_v2_generated_AnswerRecords_ListAnswerRecords_async", - "segments": [ - { - "end": 52, - "start": 27, - "type": "FULL" - }, - { - "end": 52, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 48, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 53, - "start": 49, - "type": "RESPONSE_HANDLING" - } - ], - "title": "dialogflow_v2_generated_answer_records_list_answer_records_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.dialogflow_v2.AnswerRecordsClient", - "shortName": "AnswerRecordsClient" - }, - "fullName": "google.cloud.dialogflow_v2.AnswerRecordsClient.list_answer_records", - "method": { - "fullName": "google.cloud.dialogflow.v2.AnswerRecords.ListAnswerRecords", - "service": { - "fullName": "google.cloud.dialogflow.v2.AnswerRecords", - "shortName": "AnswerRecords" - }, - "shortName": "ListAnswerRecords" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.dialogflow_v2.types.ListAnswerRecordsRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.dialogflow_v2.services.answer_records.pagers.ListAnswerRecordsPager", - "shortName": "list_answer_records" - }, - "description": "Sample for ListAnswerRecords", - "file": "dialogflow_v2_generated_answer_records_list_answer_records_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "dialogflow_v2_generated_AnswerRecords_ListAnswerRecords_sync", - "segments": [ - { - "end": 52, - "start": 27, - "type": "FULL" - }, - { - "end": 52, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 48, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 53, - "start": 49, - "type": "RESPONSE_HANDLING" - } - ], - "title": "dialogflow_v2_generated_answer_records_list_answer_records_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.dialogflow_v2.AnswerRecordsAsyncClient", - "shortName": "AnswerRecordsAsyncClient" - }, - "fullName": "google.cloud.dialogflow_v2.AnswerRecordsAsyncClient.update_answer_record", - "method": { - "fullName": "google.cloud.dialogflow.v2.AnswerRecords.UpdateAnswerRecord", - "service": { - "fullName": "google.cloud.dialogflow.v2.AnswerRecords", - "shortName": "AnswerRecords" - }, - "shortName": "UpdateAnswerRecord" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.dialogflow_v2.types.UpdateAnswerRecordRequest" - }, - { - "name": "answer_record", - "type": "google.cloud.dialogflow_v2.types.AnswerRecord" - }, - { - "name": "update_mask", - "type": "google.protobuf.field_mask_pb2.FieldMask" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.dialogflow_v2.types.AnswerRecord", - "shortName": "update_answer_record" - }, - "description": "Sample for UpdateAnswerRecord", - "file": "dialogflow_v2_generated_answer_records_update_answer_record_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "dialogflow_v2_generated_AnswerRecords_UpdateAnswerRecord_async", - "segments": [ - { - "end": 50, - "start": 27, - "type": "FULL" - }, - { - "end": 50, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 44, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 47, - "start": 45, - "type": "REQUEST_EXECUTION" - }, - { - "end": 51, - "start": 48, - "type": "RESPONSE_HANDLING" - } - ], - "title": "dialogflow_v2_generated_answer_records_update_answer_record_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.dialogflow_v2.AnswerRecordsClient", - "shortName": "AnswerRecordsClient" - }, - "fullName": "google.cloud.dialogflow_v2.AnswerRecordsClient.update_answer_record", - "method": { - "fullName": "google.cloud.dialogflow.v2.AnswerRecords.UpdateAnswerRecord", - "service": { - "fullName": "google.cloud.dialogflow.v2.AnswerRecords", - "shortName": "AnswerRecords" - }, - "shortName": "UpdateAnswerRecord" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.dialogflow_v2.types.UpdateAnswerRecordRequest" - }, - { - "name": "answer_record", - "type": "google.cloud.dialogflow_v2.types.AnswerRecord" - }, - { - "name": "update_mask", - "type": "google.protobuf.field_mask_pb2.FieldMask" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.dialogflow_v2.types.AnswerRecord", - "shortName": "update_answer_record" - }, - "description": "Sample for UpdateAnswerRecord", - "file": "dialogflow_v2_generated_answer_records_update_answer_record_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "dialogflow_v2_generated_AnswerRecords_UpdateAnswerRecord_sync", - "segments": [ - { - "end": 50, - "start": 27, - "type": "FULL" - }, - { - "end": 50, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 44, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 47, - "start": 45, - "type": "REQUEST_EXECUTION" - }, - { - "end": 51, - "start": 48, - "type": "RESPONSE_HANDLING" - } - ], - "title": "dialogflow_v2_generated_answer_records_update_answer_record_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.dialogflow_v2.ContextsAsyncClient", - "shortName": "ContextsAsyncClient" - }, - "fullName": "google.cloud.dialogflow_v2.ContextsAsyncClient.create_context", - "method": { - "fullName": "google.cloud.dialogflow.v2.Contexts.CreateContext", - "service": { - "fullName": "google.cloud.dialogflow.v2.Contexts", - "shortName": "Contexts" - }, - "shortName": "CreateContext" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.dialogflow_v2.types.CreateContextRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "context", - "type": "google.cloud.dialogflow_v2.types.Context" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.dialogflow_v2.types.Context", - "shortName": "create_context" - }, - "description": "Sample for CreateContext", - "file": "dialogflow_v2_generated_contexts_create_context_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "dialogflow_v2_generated_Contexts_CreateContext_async", - "segments": [ - { - "end": 55, - "start": 27, - "type": "FULL" - }, - { - "end": 55, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 49, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 52, - "start": 50, - "type": "REQUEST_EXECUTION" - }, - { - "end": 56, - "start": 53, - "type": "RESPONSE_HANDLING" - } - ], - "title": "dialogflow_v2_generated_contexts_create_context_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.dialogflow_v2.ContextsClient", - "shortName": "ContextsClient" - }, - "fullName": "google.cloud.dialogflow_v2.ContextsClient.create_context", - "method": { - "fullName": "google.cloud.dialogflow.v2.Contexts.CreateContext", - "service": { - "fullName": "google.cloud.dialogflow.v2.Contexts", - "shortName": "Contexts" - }, - "shortName": "CreateContext" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.dialogflow_v2.types.CreateContextRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "context", - "type": "google.cloud.dialogflow_v2.types.Context" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.dialogflow_v2.types.Context", - "shortName": "create_context" - }, - "description": "Sample for CreateContext", - "file": "dialogflow_v2_generated_contexts_create_context_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "dialogflow_v2_generated_Contexts_CreateContext_sync", - "segments": [ - { - "end": 55, - "start": 27, - "type": "FULL" - }, - { - "end": 55, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 49, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 52, - "start": 50, - "type": "REQUEST_EXECUTION" - }, - { - "end": 56, - "start": 53, - "type": "RESPONSE_HANDLING" - } - ], - "title": "dialogflow_v2_generated_contexts_create_context_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.dialogflow_v2.ContextsAsyncClient", - "shortName": "ContextsAsyncClient" - }, - "fullName": "google.cloud.dialogflow_v2.ContextsAsyncClient.delete_all_contexts", - "method": { - "fullName": "google.cloud.dialogflow.v2.Contexts.DeleteAllContexts", - "service": { - "fullName": "google.cloud.dialogflow.v2.Contexts", - "shortName": "Contexts" - }, - "shortName": "DeleteAllContexts" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.dialogflow_v2.types.DeleteAllContextsRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "shortName": "delete_all_contexts" - }, - "description": "Sample for DeleteAllContexts", - "file": "dialogflow_v2_generated_contexts_delete_all_contexts_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "dialogflow_v2_generated_Contexts_DeleteAllContexts_async", - "segments": [ - { - "end": 49, - "start": 27, - "type": "FULL" - }, - { - "end": 49, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 50, - "type": "RESPONSE_HANDLING" - } - ], - "title": "dialogflow_v2_generated_contexts_delete_all_contexts_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.dialogflow_v2.ContextsClient", - "shortName": "ContextsClient" - }, - "fullName": "google.cloud.dialogflow_v2.ContextsClient.delete_all_contexts", - "method": { - "fullName": "google.cloud.dialogflow.v2.Contexts.DeleteAllContexts", - "service": { - "fullName": "google.cloud.dialogflow.v2.Contexts", - "shortName": "Contexts" - }, - "shortName": "DeleteAllContexts" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.dialogflow_v2.types.DeleteAllContextsRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "shortName": "delete_all_contexts" - }, - "description": "Sample for DeleteAllContexts", - "file": "dialogflow_v2_generated_contexts_delete_all_contexts_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "dialogflow_v2_generated_Contexts_DeleteAllContexts_sync", - "segments": [ - { - "end": 49, - "start": 27, - "type": "FULL" - }, - { - "end": 49, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 50, - "type": "RESPONSE_HANDLING" - } - ], - "title": "dialogflow_v2_generated_contexts_delete_all_contexts_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.dialogflow_v2.ContextsAsyncClient", - "shortName": "ContextsAsyncClient" - }, - "fullName": "google.cloud.dialogflow_v2.ContextsAsyncClient.delete_context", - "method": { - "fullName": "google.cloud.dialogflow.v2.Contexts.DeleteContext", - "service": { - "fullName": "google.cloud.dialogflow.v2.Contexts", - "shortName": "Contexts" - }, - "shortName": "DeleteContext" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.dialogflow_v2.types.DeleteContextRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "shortName": "delete_context" - }, - "description": "Sample for DeleteContext", - "file": "dialogflow_v2_generated_contexts_delete_context_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "dialogflow_v2_generated_Contexts_DeleteContext_async", - "segments": [ - { - "end": 49, - "start": 27, - "type": "FULL" - }, - { - "end": 49, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 50, - "type": "RESPONSE_HANDLING" - } - ], - "title": "dialogflow_v2_generated_contexts_delete_context_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.dialogflow_v2.ContextsClient", - "shortName": "ContextsClient" - }, - "fullName": "google.cloud.dialogflow_v2.ContextsClient.delete_context", - "method": { - "fullName": "google.cloud.dialogflow.v2.Contexts.DeleteContext", - "service": { - "fullName": "google.cloud.dialogflow.v2.Contexts", - "shortName": "Contexts" - }, - "shortName": "DeleteContext" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.dialogflow_v2.types.DeleteContextRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "shortName": "delete_context" - }, - "description": "Sample for DeleteContext", - "file": "dialogflow_v2_generated_contexts_delete_context_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "dialogflow_v2_generated_Contexts_DeleteContext_sync", - "segments": [ - { - "end": 49, - "start": 27, - "type": "FULL" - }, - { - "end": 49, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 50, - "type": "RESPONSE_HANDLING" - } - ], - "title": "dialogflow_v2_generated_contexts_delete_context_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.dialogflow_v2.ContextsAsyncClient", - "shortName": "ContextsAsyncClient" - }, - "fullName": "google.cloud.dialogflow_v2.ContextsAsyncClient.get_context", - "method": { - "fullName": "google.cloud.dialogflow.v2.Contexts.GetContext", - "service": { - "fullName": "google.cloud.dialogflow.v2.Contexts", - "shortName": "Contexts" - }, - "shortName": "GetContext" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.dialogflow_v2.types.GetContextRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.dialogflow_v2.types.Context", - "shortName": "get_context" - }, - "description": "Sample for GetContext", - "file": "dialogflow_v2_generated_contexts_get_context_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "dialogflow_v2_generated_Contexts_GetContext_async", - "segments": [ - { - "end": 51, - "start": 27, - "type": "FULL" - }, - { - "end": 51, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 48, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 52, - "start": 49, - "type": "RESPONSE_HANDLING" - } - ], - "title": "dialogflow_v2_generated_contexts_get_context_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.dialogflow_v2.ContextsClient", - "shortName": "ContextsClient" - }, - "fullName": "google.cloud.dialogflow_v2.ContextsClient.get_context", - "method": { - "fullName": "google.cloud.dialogflow.v2.Contexts.GetContext", - "service": { - "fullName": "google.cloud.dialogflow.v2.Contexts", - "shortName": "Contexts" - }, - "shortName": "GetContext" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.dialogflow_v2.types.GetContextRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.dialogflow_v2.types.Context", - "shortName": "get_context" - }, - "description": "Sample for GetContext", - "file": "dialogflow_v2_generated_contexts_get_context_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "dialogflow_v2_generated_Contexts_GetContext_sync", - "segments": [ - { - "end": 51, - "start": 27, - "type": "FULL" - }, - { - "end": 51, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 48, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 52, - "start": 49, - "type": "RESPONSE_HANDLING" - } - ], - "title": "dialogflow_v2_generated_contexts_get_context_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.dialogflow_v2.ContextsAsyncClient", - "shortName": "ContextsAsyncClient" - }, - "fullName": "google.cloud.dialogflow_v2.ContextsAsyncClient.list_contexts", - "method": { - "fullName": "google.cloud.dialogflow.v2.Contexts.ListContexts", - "service": { - "fullName": "google.cloud.dialogflow.v2.Contexts", - "shortName": "Contexts" - }, - "shortName": "ListContexts" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.dialogflow_v2.types.ListContextsRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.dialogflow_v2.services.contexts.pagers.ListContextsAsyncPager", - "shortName": "list_contexts" - }, - "description": "Sample for ListContexts", - "file": "dialogflow_v2_generated_contexts_list_contexts_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "dialogflow_v2_generated_Contexts_ListContexts_async", - "segments": [ - { - "end": 52, - "start": 27, - "type": "FULL" - }, - { - "end": 52, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 48, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 53, - "start": 49, - "type": "RESPONSE_HANDLING" - } - ], - "title": "dialogflow_v2_generated_contexts_list_contexts_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.dialogflow_v2.ContextsClient", - "shortName": "ContextsClient" - }, - "fullName": "google.cloud.dialogflow_v2.ContextsClient.list_contexts", - "method": { - "fullName": "google.cloud.dialogflow.v2.Contexts.ListContexts", - "service": { - "fullName": "google.cloud.dialogflow.v2.Contexts", - "shortName": "Contexts" - }, - "shortName": "ListContexts" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.dialogflow_v2.types.ListContextsRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.dialogflow_v2.services.contexts.pagers.ListContextsPager", - "shortName": "list_contexts" - }, - "description": "Sample for ListContexts", - "file": "dialogflow_v2_generated_contexts_list_contexts_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "dialogflow_v2_generated_Contexts_ListContexts_sync", - "segments": [ - { - "end": 52, - "start": 27, - "type": "FULL" - }, - { - "end": 52, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 48, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 53, - "start": 49, - "type": "RESPONSE_HANDLING" - } - ], - "title": "dialogflow_v2_generated_contexts_list_contexts_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.dialogflow_v2.ContextsAsyncClient", - "shortName": "ContextsAsyncClient" - }, - "fullName": "google.cloud.dialogflow_v2.ContextsAsyncClient.update_context", - "method": { - "fullName": "google.cloud.dialogflow.v2.Contexts.UpdateContext", - "service": { - "fullName": "google.cloud.dialogflow.v2.Contexts", - "shortName": "Contexts" - }, - "shortName": "UpdateContext" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.dialogflow_v2.types.UpdateContextRequest" - }, - { - "name": "context", - "type": "google.cloud.dialogflow_v2.types.Context" - }, - { - "name": "update_mask", - "type": "google.protobuf.field_mask_pb2.FieldMask" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.dialogflow_v2.types.Context", - "shortName": "update_context" - }, - "description": "Sample for UpdateContext", - "file": "dialogflow_v2_generated_contexts_update_context_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "dialogflow_v2_generated_Contexts_UpdateContext_async", - "segments": [ - { - "end": 54, - "start": 27, - "type": "FULL" - }, - { - "end": 54, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 48, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 51, - "start": 49, - "type": "REQUEST_EXECUTION" - }, - { - "end": 55, - "start": 52, - "type": "RESPONSE_HANDLING" - } - ], - "title": "dialogflow_v2_generated_contexts_update_context_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.dialogflow_v2.ContextsClient", - "shortName": "ContextsClient" - }, - "fullName": "google.cloud.dialogflow_v2.ContextsClient.update_context", - "method": { - "fullName": "google.cloud.dialogflow.v2.Contexts.UpdateContext", - "service": { - "fullName": "google.cloud.dialogflow.v2.Contexts", - "shortName": "Contexts" - }, - "shortName": "UpdateContext" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.dialogflow_v2.types.UpdateContextRequest" - }, - { - "name": "context", - "type": "google.cloud.dialogflow_v2.types.Context" - }, - { - "name": "update_mask", - "type": "google.protobuf.field_mask_pb2.FieldMask" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.dialogflow_v2.types.Context", - "shortName": "update_context" - }, - "description": "Sample for UpdateContext", - "file": "dialogflow_v2_generated_contexts_update_context_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "dialogflow_v2_generated_Contexts_UpdateContext_sync", - "segments": [ - { - "end": 54, - "start": 27, - "type": "FULL" - }, - { - "end": 54, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 48, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 51, - "start": 49, - "type": "REQUEST_EXECUTION" - }, - { - "end": 55, - "start": 52, - "type": "RESPONSE_HANDLING" - } - ], - "title": "dialogflow_v2_generated_contexts_update_context_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.dialogflow_v2.ConversationDatasetsAsyncClient", - "shortName": "ConversationDatasetsAsyncClient" - }, - "fullName": "google.cloud.dialogflow_v2.ConversationDatasetsAsyncClient.create_conversation_dataset", - "method": { - "fullName": "google.cloud.dialogflow.v2.ConversationDatasets.CreateConversationDataset", - "service": { - "fullName": "google.cloud.dialogflow.v2.ConversationDatasets", - "shortName": "ConversationDatasets" - }, - "shortName": "CreateConversationDataset" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.dialogflow_v2.types.CreateConversationDatasetRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "conversation_dataset", - "type": "google.cloud.dialogflow_v2.types.ConversationDataset" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.api_core.operation_async.AsyncOperation", - "shortName": "create_conversation_dataset" - }, - "description": "Sample for CreateConversationDataset", - "file": "dialogflow_v2_generated_conversation_datasets_create_conversation_dataset_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "dialogflow_v2_generated_ConversationDatasets_CreateConversationDataset_async", - "segments": [ - { - "end": 59, - "start": 27, - "type": "FULL" - }, - { - "end": 59, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 49, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 56, - "start": 50, - "type": "REQUEST_EXECUTION" - }, - { - "end": 60, - "start": 57, - "type": "RESPONSE_HANDLING" - } - ], - "title": "dialogflow_v2_generated_conversation_datasets_create_conversation_dataset_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.dialogflow_v2.ConversationDatasetsClient", - "shortName": "ConversationDatasetsClient" - }, - "fullName": "google.cloud.dialogflow_v2.ConversationDatasetsClient.create_conversation_dataset", - "method": { - "fullName": "google.cloud.dialogflow.v2.ConversationDatasets.CreateConversationDataset", - "service": { - "fullName": "google.cloud.dialogflow.v2.ConversationDatasets", - "shortName": "ConversationDatasets" - }, - "shortName": "CreateConversationDataset" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.dialogflow_v2.types.CreateConversationDatasetRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "conversation_dataset", - "type": "google.cloud.dialogflow_v2.types.ConversationDataset" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.api_core.operation.Operation", - "shortName": "create_conversation_dataset" - }, - "description": "Sample for CreateConversationDataset", - "file": "dialogflow_v2_generated_conversation_datasets_create_conversation_dataset_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "dialogflow_v2_generated_ConversationDatasets_CreateConversationDataset_sync", - "segments": [ - { - "end": 59, - "start": 27, - "type": "FULL" - }, - { - "end": 59, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 49, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 56, - "start": 50, - "type": "REQUEST_EXECUTION" - }, - { - "end": 60, - "start": 57, - "type": "RESPONSE_HANDLING" - } - ], - "title": "dialogflow_v2_generated_conversation_datasets_create_conversation_dataset_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.dialogflow_v2.ConversationDatasetsAsyncClient", - "shortName": "ConversationDatasetsAsyncClient" - }, - "fullName": "google.cloud.dialogflow_v2.ConversationDatasetsAsyncClient.delete_conversation_dataset", - "method": { - "fullName": "google.cloud.dialogflow.v2.ConversationDatasets.DeleteConversationDataset", - "service": { - "fullName": "google.cloud.dialogflow.v2.ConversationDatasets", - "shortName": "ConversationDatasets" - }, - "shortName": "DeleteConversationDataset" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.dialogflow_v2.types.DeleteConversationDatasetRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.api_core.operation_async.AsyncOperation", - "shortName": "delete_conversation_dataset" - }, - "description": "Sample for DeleteConversationDataset", - "file": "dialogflow_v2_generated_conversation_datasets_delete_conversation_dataset_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "dialogflow_v2_generated_ConversationDatasets_DeleteConversationDataset_async", - "segments": [ - { - "end": 55, - "start": 27, - "type": "FULL" - }, - { - "end": 55, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 52, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 56, - "start": 53, - "type": "RESPONSE_HANDLING" - } - ], - "title": "dialogflow_v2_generated_conversation_datasets_delete_conversation_dataset_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.dialogflow_v2.ConversationDatasetsClient", - "shortName": "ConversationDatasetsClient" - }, - "fullName": "google.cloud.dialogflow_v2.ConversationDatasetsClient.delete_conversation_dataset", - "method": { - "fullName": "google.cloud.dialogflow.v2.ConversationDatasets.DeleteConversationDataset", - "service": { - "fullName": "google.cloud.dialogflow.v2.ConversationDatasets", - "shortName": "ConversationDatasets" - }, - "shortName": "DeleteConversationDataset" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.dialogflow_v2.types.DeleteConversationDatasetRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.api_core.operation.Operation", - "shortName": "delete_conversation_dataset" - }, - "description": "Sample for DeleteConversationDataset", - "file": "dialogflow_v2_generated_conversation_datasets_delete_conversation_dataset_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "dialogflow_v2_generated_ConversationDatasets_DeleteConversationDataset_sync", - "segments": [ - { - "end": 55, - "start": 27, - "type": "FULL" - }, - { - "end": 55, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 52, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 56, - "start": 53, - "type": "RESPONSE_HANDLING" - } - ], - "title": "dialogflow_v2_generated_conversation_datasets_delete_conversation_dataset_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.dialogflow_v2.ConversationDatasetsAsyncClient", - "shortName": "ConversationDatasetsAsyncClient" - }, - "fullName": "google.cloud.dialogflow_v2.ConversationDatasetsAsyncClient.get_conversation_dataset", - "method": { - "fullName": "google.cloud.dialogflow.v2.ConversationDatasets.GetConversationDataset", - "service": { - "fullName": "google.cloud.dialogflow.v2.ConversationDatasets", - "shortName": "ConversationDatasets" - }, - "shortName": "GetConversationDataset" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.dialogflow_v2.types.GetConversationDatasetRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.dialogflow_v2.types.ConversationDataset", - "shortName": "get_conversation_dataset" - }, - "description": "Sample for GetConversationDataset", - "file": "dialogflow_v2_generated_conversation_datasets_get_conversation_dataset_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "dialogflow_v2_generated_ConversationDatasets_GetConversationDataset_async", - "segments": [ - { - "end": 51, - "start": 27, - "type": "FULL" - }, - { - "end": 51, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 48, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 52, - "start": 49, - "type": "RESPONSE_HANDLING" - } - ], - "title": "dialogflow_v2_generated_conversation_datasets_get_conversation_dataset_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.dialogflow_v2.ConversationDatasetsClient", - "shortName": "ConversationDatasetsClient" - }, - "fullName": "google.cloud.dialogflow_v2.ConversationDatasetsClient.get_conversation_dataset", - "method": { - "fullName": "google.cloud.dialogflow.v2.ConversationDatasets.GetConversationDataset", - "service": { - "fullName": "google.cloud.dialogflow.v2.ConversationDatasets", - "shortName": "ConversationDatasets" - }, - "shortName": "GetConversationDataset" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.dialogflow_v2.types.GetConversationDatasetRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.dialogflow_v2.types.ConversationDataset", - "shortName": "get_conversation_dataset" - }, - "description": "Sample for GetConversationDataset", - "file": "dialogflow_v2_generated_conversation_datasets_get_conversation_dataset_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "dialogflow_v2_generated_ConversationDatasets_GetConversationDataset_sync", - "segments": [ - { - "end": 51, - "start": 27, - "type": "FULL" - }, - { - "end": 51, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 48, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 52, - "start": 49, - "type": "RESPONSE_HANDLING" - } - ], - "title": "dialogflow_v2_generated_conversation_datasets_get_conversation_dataset_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.dialogflow_v2.ConversationDatasetsAsyncClient", - "shortName": "ConversationDatasetsAsyncClient" - }, - "fullName": "google.cloud.dialogflow_v2.ConversationDatasetsAsyncClient.import_conversation_data", - "method": { - "fullName": "google.cloud.dialogflow.v2.ConversationDatasets.ImportConversationData", - "service": { - "fullName": "google.cloud.dialogflow.v2.ConversationDatasets", - "shortName": "ConversationDatasets" - }, - "shortName": "ImportConversationData" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.dialogflow_v2.types.ImportConversationDataRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.api_core.operation_async.AsyncOperation", - "shortName": "import_conversation_data" - }, - "description": "Sample for ImportConversationData", - "file": "dialogflow_v2_generated_conversation_datasets_import_conversation_data_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "dialogflow_v2_generated_ConversationDatasets_ImportConversationData_async", - "segments": [ - { - "end": 59, - "start": 27, - "type": "FULL" - }, - { - "end": 59, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 49, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 56, - "start": 50, - "type": "REQUEST_EXECUTION" - }, - { - "end": 60, - "start": 57, - "type": "RESPONSE_HANDLING" - } - ], - "title": "dialogflow_v2_generated_conversation_datasets_import_conversation_data_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.dialogflow_v2.ConversationDatasetsClient", - "shortName": "ConversationDatasetsClient" - }, - "fullName": "google.cloud.dialogflow_v2.ConversationDatasetsClient.import_conversation_data", - "method": { - "fullName": "google.cloud.dialogflow.v2.ConversationDatasets.ImportConversationData", - "service": { - "fullName": "google.cloud.dialogflow.v2.ConversationDatasets", - "shortName": "ConversationDatasets" - }, - "shortName": "ImportConversationData" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.dialogflow_v2.types.ImportConversationDataRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.api_core.operation.Operation", - "shortName": "import_conversation_data" - }, - "description": "Sample for ImportConversationData", - "file": "dialogflow_v2_generated_conversation_datasets_import_conversation_data_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "dialogflow_v2_generated_ConversationDatasets_ImportConversationData_sync", - "segments": [ - { - "end": 59, - "start": 27, - "type": "FULL" - }, - { - "end": 59, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 49, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 56, - "start": 50, - "type": "REQUEST_EXECUTION" - }, - { - "end": 60, - "start": 57, - "type": "RESPONSE_HANDLING" - } - ], - "title": "dialogflow_v2_generated_conversation_datasets_import_conversation_data_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.dialogflow_v2.ConversationDatasetsAsyncClient", - "shortName": "ConversationDatasetsAsyncClient" - }, - "fullName": "google.cloud.dialogflow_v2.ConversationDatasetsAsyncClient.list_conversation_datasets", - "method": { - "fullName": "google.cloud.dialogflow.v2.ConversationDatasets.ListConversationDatasets", - "service": { - "fullName": "google.cloud.dialogflow.v2.ConversationDatasets", - "shortName": "ConversationDatasets" - }, - "shortName": "ListConversationDatasets" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.dialogflow_v2.types.ListConversationDatasetsRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.dialogflow_v2.services.conversation_datasets.pagers.ListConversationDatasetsAsyncPager", - "shortName": "list_conversation_datasets" - }, - "description": "Sample for ListConversationDatasets", - "file": "dialogflow_v2_generated_conversation_datasets_list_conversation_datasets_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "dialogflow_v2_generated_ConversationDatasets_ListConversationDatasets_async", - "segments": [ - { - "end": 52, - "start": 27, - "type": "FULL" - }, - { - "end": 52, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 48, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 53, - "start": 49, - "type": "RESPONSE_HANDLING" - } - ], - "title": "dialogflow_v2_generated_conversation_datasets_list_conversation_datasets_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.dialogflow_v2.ConversationDatasetsClient", - "shortName": "ConversationDatasetsClient" - }, - "fullName": "google.cloud.dialogflow_v2.ConversationDatasetsClient.list_conversation_datasets", - "method": { - "fullName": "google.cloud.dialogflow.v2.ConversationDatasets.ListConversationDatasets", - "service": { - "fullName": "google.cloud.dialogflow.v2.ConversationDatasets", - "shortName": "ConversationDatasets" - }, - "shortName": "ListConversationDatasets" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.dialogflow_v2.types.ListConversationDatasetsRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.dialogflow_v2.services.conversation_datasets.pagers.ListConversationDatasetsPager", - "shortName": "list_conversation_datasets" - }, - "description": "Sample for ListConversationDatasets", - "file": "dialogflow_v2_generated_conversation_datasets_list_conversation_datasets_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "dialogflow_v2_generated_ConversationDatasets_ListConversationDatasets_sync", - "segments": [ - { - "end": 52, - "start": 27, - "type": "FULL" - }, - { - "end": 52, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 48, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 53, - "start": 49, - "type": "RESPONSE_HANDLING" - } - ], - "title": "dialogflow_v2_generated_conversation_datasets_list_conversation_datasets_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.dialogflow_v2.ConversationModelsAsyncClient", - "shortName": "ConversationModelsAsyncClient" - }, - "fullName": "google.cloud.dialogflow_v2.ConversationModelsAsyncClient.create_conversation_model_evaluation", - "method": { - "fullName": "google.cloud.dialogflow.v2.ConversationModels.CreateConversationModelEvaluation", - "service": { - "fullName": "google.cloud.dialogflow.v2.ConversationModels", - "shortName": "ConversationModels" - }, - "shortName": "CreateConversationModelEvaluation" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.dialogflow_v2.types.CreateConversationModelEvaluationRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "conversation_model_evaluation", - "type": "google.cloud.dialogflow_v2.types.ConversationModelEvaluation" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.api_core.operation_async.AsyncOperation", - "shortName": "create_conversation_model_evaluation" - }, - "description": "Sample for CreateConversationModelEvaluation", - "file": "dialogflow_v2_generated_conversation_models_create_conversation_model_evaluation_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "dialogflow_v2_generated_ConversationModels_CreateConversationModelEvaluation_async", - "segments": [ - { - "end": 55, - "start": 27, - "type": "FULL" - }, - { - "end": 55, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 52, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 56, - "start": 53, - "type": "RESPONSE_HANDLING" - } - ], - "title": "dialogflow_v2_generated_conversation_models_create_conversation_model_evaluation_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.dialogflow_v2.ConversationModelsClient", - "shortName": "ConversationModelsClient" - }, - "fullName": "google.cloud.dialogflow_v2.ConversationModelsClient.create_conversation_model_evaluation", - "method": { - "fullName": "google.cloud.dialogflow.v2.ConversationModels.CreateConversationModelEvaluation", - "service": { - "fullName": "google.cloud.dialogflow.v2.ConversationModels", - "shortName": "ConversationModels" - }, - "shortName": "CreateConversationModelEvaluation" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.dialogflow_v2.types.CreateConversationModelEvaluationRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "conversation_model_evaluation", - "type": "google.cloud.dialogflow_v2.types.ConversationModelEvaluation" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.api_core.operation.Operation", - "shortName": "create_conversation_model_evaluation" - }, - "description": "Sample for CreateConversationModelEvaluation", - "file": "dialogflow_v2_generated_conversation_models_create_conversation_model_evaluation_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "dialogflow_v2_generated_ConversationModels_CreateConversationModelEvaluation_sync", - "segments": [ - { - "end": 55, - "start": 27, - "type": "FULL" - }, - { - "end": 55, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 52, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 56, - "start": 53, - "type": "RESPONSE_HANDLING" - } - ], - "title": "dialogflow_v2_generated_conversation_models_create_conversation_model_evaluation_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.dialogflow_v2.ConversationModelsAsyncClient", - "shortName": "ConversationModelsAsyncClient" - }, - "fullName": "google.cloud.dialogflow_v2.ConversationModelsAsyncClient.create_conversation_model", - "method": { - "fullName": "google.cloud.dialogflow.v2.ConversationModels.CreateConversationModel", - "service": { - "fullName": "google.cloud.dialogflow.v2.ConversationModels", - "shortName": "ConversationModels" - }, - "shortName": "CreateConversationModel" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.dialogflow_v2.types.CreateConversationModelRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "conversation_model", - "type": "google.cloud.dialogflow_v2.types.ConversationModel" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.api_core.operation_async.AsyncOperation", - "shortName": "create_conversation_model" - }, - "description": "Sample for CreateConversationModel", - "file": "dialogflow_v2_generated_conversation_models_create_conversation_model_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "dialogflow_v2_generated_ConversationModels_CreateConversationModel_async", - "segments": [ - { - "end": 59, - "start": 27, - "type": "FULL" - }, - { - "end": 59, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 49, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 56, - "start": 50, - "type": "REQUEST_EXECUTION" - }, - { - "end": 60, - "start": 57, - "type": "RESPONSE_HANDLING" - } - ], - "title": "dialogflow_v2_generated_conversation_models_create_conversation_model_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.dialogflow_v2.ConversationModelsClient", - "shortName": "ConversationModelsClient" - }, - "fullName": "google.cloud.dialogflow_v2.ConversationModelsClient.create_conversation_model", - "method": { - "fullName": "google.cloud.dialogflow.v2.ConversationModels.CreateConversationModel", - "service": { - "fullName": "google.cloud.dialogflow.v2.ConversationModels", - "shortName": "ConversationModels" - }, - "shortName": "CreateConversationModel" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.dialogflow_v2.types.CreateConversationModelRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "conversation_model", - "type": "google.cloud.dialogflow_v2.types.ConversationModel" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.api_core.operation.Operation", - "shortName": "create_conversation_model" - }, - "description": "Sample for CreateConversationModel", - "file": "dialogflow_v2_generated_conversation_models_create_conversation_model_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "dialogflow_v2_generated_ConversationModels_CreateConversationModel_sync", - "segments": [ - { - "end": 59, - "start": 27, - "type": "FULL" - }, - { - "end": 59, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 49, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 56, - "start": 50, - "type": "REQUEST_EXECUTION" - }, - { - "end": 60, - "start": 57, - "type": "RESPONSE_HANDLING" - } - ], - "title": "dialogflow_v2_generated_conversation_models_create_conversation_model_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.dialogflow_v2.ConversationModelsAsyncClient", - "shortName": "ConversationModelsAsyncClient" - }, - "fullName": "google.cloud.dialogflow_v2.ConversationModelsAsyncClient.delete_conversation_model", - "method": { - "fullName": "google.cloud.dialogflow.v2.ConversationModels.DeleteConversationModel", - "service": { - "fullName": "google.cloud.dialogflow.v2.ConversationModels", - "shortName": "ConversationModels" - }, - "shortName": "DeleteConversationModel" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.dialogflow_v2.types.DeleteConversationModelRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.api_core.operation_async.AsyncOperation", - "shortName": "delete_conversation_model" - }, - "description": "Sample for DeleteConversationModel", - "file": "dialogflow_v2_generated_conversation_models_delete_conversation_model_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "dialogflow_v2_generated_ConversationModels_DeleteConversationModel_async", - "segments": [ - { - "end": 55, - "start": 27, - "type": "FULL" - }, - { - "end": 55, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 52, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 56, - "start": 53, - "type": "RESPONSE_HANDLING" - } - ], - "title": "dialogflow_v2_generated_conversation_models_delete_conversation_model_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.dialogflow_v2.ConversationModelsClient", - "shortName": "ConversationModelsClient" - }, - "fullName": "google.cloud.dialogflow_v2.ConversationModelsClient.delete_conversation_model", - "method": { - "fullName": "google.cloud.dialogflow.v2.ConversationModels.DeleteConversationModel", - "service": { - "fullName": "google.cloud.dialogflow.v2.ConversationModels", - "shortName": "ConversationModels" - }, - "shortName": "DeleteConversationModel" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.dialogflow_v2.types.DeleteConversationModelRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.api_core.operation.Operation", - "shortName": "delete_conversation_model" - }, - "description": "Sample for DeleteConversationModel", - "file": "dialogflow_v2_generated_conversation_models_delete_conversation_model_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "dialogflow_v2_generated_ConversationModels_DeleteConversationModel_sync", - "segments": [ - { - "end": 55, - "start": 27, - "type": "FULL" - }, - { - "end": 55, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 52, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 56, - "start": 53, - "type": "RESPONSE_HANDLING" - } - ], - "title": "dialogflow_v2_generated_conversation_models_delete_conversation_model_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.dialogflow_v2.ConversationModelsAsyncClient", - "shortName": "ConversationModelsAsyncClient" - }, - "fullName": "google.cloud.dialogflow_v2.ConversationModelsAsyncClient.deploy_conversation_model", - "method": { - "fullName": "google.cloud.dialogflow.v2.ConversationModels.DeployConversationModel", - "service": { - "fullName": "google.cloud.dialogflow.v2.ConversationModels", - "shortName": "ConversationModels" - }, - "shortName": "DeployConversationModel" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.dialogflow_v2.types.DeployConversationModelRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.api_core.operation_async.AsyncOperation", - "shortName": "deploy_conversation_model" - }, - "description": "Sample for DeployConversationModel", - "file": "dialogflow_v2_generated_conversation_models_deploy_conversation_model_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "dialogflow_v2_generated_ConversationModels_DeployConversationModel_async", - "segments": [ - { - "end": 55, - "start": 27, - "type": "FULL" - }, - { - "end": 55, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 52, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 56, - "start": 53, - "type": "RESPONSE_HANDLING" - } - ], - "title": "dialogflow_v2_generated_conversation_models_deploy_conversation_model_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.dialogflow_v2.ConversationModelsClient", - "shortName": "ConversationModelsClient" - }, - "fullName": "google.cloud.dialogflow_v2.ConversationModelsClient.deploy_conversation_model", - "method": { - "fullName": "google.cloud.dialogflow.v2.ConversationModels.DeployConversationModel", - "service": { - "fullName": "google.cloud.dialogflow.v2.ConversationModels", - "shortName": "ConversationModels" - }, - "shortName": "DeployConversationModel" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.dialogflow_v2.types.DeployConversationModelRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.api_core.operation.Operation", - "shortName": "deploy_conversation_model" - }, - "description": "Sample for DeployConversationModel", - "file": "dialogflow_v2_generated_conversation_models_deploy_conversation_model_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "dialogflow_v2_generated_ConversationModels_DeployConversationModel_sync", - "segments": [ - { - "end": 55, - "start": 27, - "type": "FULL" - }, - { - "end": 55, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 52, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 56, - "start": 53, - "type": "RESPONSE_HANDLING" - } - ], - "title": "dialogflow_v2_generated_conversation_models_deploy_conversation_model_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.dialogflow_v2.ConversationModelsAsyncClient", - "shortName": "ConversationModelsAsyncClient" - }, - "fullName": "google.cloud.dialogflow_v2.ConversationModelsAsyncClient.get_conversation_model_evaluation", - "method": { - "fullName": "google.cloud.dialogflow.v2.ConversationModels.GetConversationModelEvaluation", - "service": { - "fullName": "google.cloud.dialogflow.v2.ConversationModels", - "shortName": "ConversationModels" - }, - "shortName": "GetConversationModelEvaluation" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.dialogflow_v2.types.GetConversationModelEvaluationRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.dialogflow_v2.types.ConversationModelEvaluation", - "shortName": "get_conversation_model_evaluation" - }, - "description": "Sample for GetConversationModelEvaluation", - "file": "dialogflow_v2_generated_conversation_models_get_conversation_model_evaluation_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "dialogflow_v2_generated_ConversationModels_GetConversationModelEvaluation_async", - "segments": [ - { - "end": 51, - "start": 27, - "type": "FULL" - }, - { - "end": 51, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 48, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 52, - "start": 49, - "type": "RESPONSE_HANDLING" - } - ], - "title": "dialogflow_v2_generated_conversation_models_get_conversation_model_evaluation_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.dialogflow_v2.ConversationModelsClient", - "shortName": "ConversationModelsClient" - }, - "fullName": "google.cloud.dialogflow_v2.ConversationModelsClient.get_conversation_model_evaluation", - "method": { - "fullName": "google.cloud.dialogflow.v2.ConversationModels.GetConversationModelEvaluation", - "service": { - "fullName": "google.cloud.dialogflow.v2.ConversationModels", - "shortName": "ConversationModels" - }, - "shortName": "GetConversationModelEvaluation" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.dialogflow_v2.types.GetConversationModelEvaluationRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.dialogflow_v2.types.ConversationModelEvaluation", - "shortName": "get_conversation_model_evaluation" - }, - "description": "Sample for GetConversationModelEvaluation", - "file": "dialogflow_v2_generated_conversation_models_get_conversation_model_evaluation_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "dialogflow_v2_generated_ConversationModels_GetConversationModelEvaluation_sync", - "segments": [ - { - "end": 51, - "start": 27, - "type": "FULL" - }, - { - "end": 51, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 48, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 52, - "start": 49, - "type": "RESPONSE_HANDLING" - } - ], - "title": "dialogflow_v2_generated_conversation_models_get_conversation_model_evaluation_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.dialogflow_v2.ConversationModelsAsyncClient", - "shortName": "ConversationModelsAsyncClient" - }, - "fullName": "google.cloud.dialogflow_v2.ConversationModelsAsyncClient.get_conversation_model", - "method": { - "fullName": "google.cloud.dialogflow.v2.ConversationModels.GetConversationModel", - "service": { - "fullName": "google.cloud.dialogflow.v2.ConversationModels", - "shortName": "ConversationModels" - }, - "shortName": "GetConversationModel" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.dialogflow_v2.types.GetConversationModelRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.dialogflow_v2.types.ConversationModel", - "shortName": "get_conversation_model" - }, - "description": "Sample for GetConversationModel", - "file": "dialogflow_v2_generated_conversation_models_get_conversation_model_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "dialogflow_v2_generated_ConversationModels_GetConversationModel_async", - "segments": [ - { - "end": 51, - "start": 27, - "type": "FULL" - }, - { - "end": 51, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 48, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 52, - "start": 49, - "type": "RESPONSE_HANDLING" - } - ], - "title": "dialogflow_v2_generated_conversation_models_get_conversation_model_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.dialogflow_v2.ConversationModelsClient", - "shortName": "ConversationModelsClient" - }, - "fullName": "google.cloud.dialogflow_v2.ConversationModelsClient.get_conversation_model", - "method": { - "fullName": "google.cloud.dialogflow.v2.ConversationModels.GetConversationModel", - "service": { - "fullName": "google.cloud.dialogflow.v2.ConversationModels", - "shortName": "ConversationModels" - }, - "shortName": "GetConversationModel" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.dialogflow_v2.types.GetConversationModelRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.dialogflow_v2.types.ConversationModel", - "shortName": "get_conversation_model" - }, - "description": "Sample for GetConversationModel", - "file": "dialogflow_v2_generated_conversation_models_get_conversation_model_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "dialogflow_v2_generated_ConversationModels_GetConversationModel_sync", - "segments": [ - { - "end": 51, - "start": 27, - "type": "FULL" - }, - { - "end": 51, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 48, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 52, - "start": 49, - "type": "RESPONSE_HANDLING" - } - ], - "title": "dialogflow_v2_generated_conversation_models_get_conversation_model_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.dialogflow_v2.ConversationModelsAsyncClient", - "shortName": "ConversationModelsAsyncClient" - }, - "fullName": "google.cloud.dialogflow_v2.ConversationModelsAsyncClient.list_conversation_model_evaluations", - "method": { - "fullName": "google.cloud.dialogflow.v2.ConversationModels.ListConversationModelEvaluations", - "service": { - "fullName": "google.cloud.dialogflow.v2.ConversationModels", - "shortName": "ConversationModels" - }, - "shortName": "ListConversationModelEvaluations" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.dialogflow_v2.types.ListConversationModelEvaluationsRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.dialogflow_v2.services.conversation_models.pagers.ListConversationModelEvaluationsAsyncPager", - "shortName": "list_conversation_model_evaluations" - }, - "description": "Sample for ListConversationModelEvaluations", - "file": "dialogflow_v2_generated_conversation_models_list_conversation_model_evaluations_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "dialogflow_v2_generated_ConversationModels_ListConversationModelEvaluations_async", - "segments": [ - { - "end": 52, - "start": 27, - "type": "FULL" - }, - { - "end": 52, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 48, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 53, - "start": 49, - "type": "RESPONSE_HANDLING" - } - ], - "title": "dialogflow_v2_generated_conversation_models_list_conversation_model_evaluations_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.dialogflow_v2.ConversationModelsClient", - "shortName": "ConversationModelsClient" - }, - "fullName": "google.cloud.dialogflow_v2.ConversationModelsClient.list_conversation_model_evaluations", - "method": { - "fullName": "google.cloud.dialogflow.v2.ConversationModels.ListConversationModelEvaluations", - "service": { - "fullName": "google.cloud.dialogflow.v2.ConversationModels", - "shortName": "ConversationModels" - }, - "shortName": "ListConversationModelEvaluations" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.dialogflow_v2.types.ListConversationModelEvaluationsRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.dialogflow_v2.services.conversation_models.pagers.ListConversationModelEvaluationsPager", - "shortName": "list_conversation_model_evaluations" - }, - "description": "Sample for ListConversationModelEvaluations", - "file": "dialogflow_v2_generated_conversation_models_list_conversation_model_evaluations_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "dialogflow_v2_generated_ConversationModels_ListConversationModelEvaluations_sync", - "segments": [ - { - "end": 52, - "start": 27, - "type": "FULL" - }, - { - "end": 52, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 48, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 53, - "start": 49, - "type": "RESPONSE_HANDLING" - } - ], - "title": "dialogflow_v2_generated_conversation_models_list_conversation_model_evaluations_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.dialogflow_v2.ConversationModelsAsyncClient", - "shortName": "ConversationModelsAsyncClient" - }, - "fullName": "google.cloud.dialogflow_v2.ConversationModelsAsyncClient.list_conversation_models", - "method": { - "fullName": "google.cloud.dialogflow.v2.ConversationModels.ListConversationModels", - "service": { - "fullName": "google.cloud.dialogflow.v2.ConversationModels", - "shortName": "ConversationModels" - }, - "shortName": "ListConversationModels" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.dialogflow_v2.types.ListConversationModelsRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.dialogflow_v2.services.conversation_models.pagers.ListConversationModelsAsyncPager", - "shortName": "list_conversation_models" - }, - "description": "Sample for ListConversationModels", - "file": "dialogflow_v2_generated_conversation_models_list_conversation_models_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "dialogflow_v2_generated_ConversationModels_ListConversationModels_async", - "segments": [ - { - "end": 52, - "start": 27, - "type": "FULL" - }, - { - "end": 52, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 48, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 53, - "start": 49, - "type": "RESPONSE_HANDLING" - } - ], - "title": "dialogflow_v2_generated_conversation_models_list_conversation_models_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.dialogflow_v2.ConversationModelsClient", - "shortName": "ConversationModelsClient" - }, - "fullName": "google.cloud.dialogflow_v2.ConversationModelsClient.list_conversation_models", - "method": { - "fullName": "google.cloud.dialogflow.v2.ConversationModels.ListConversationModels", - "service": { - "fullName": "google.cloud.dialogflow.v2.ConversationModels", - "shortName": "ConversationModels" - }, - "shortName": "ListConversationModels" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.dialogflow_v2.types.ListConversationModelsRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.dialogflow_v2.services.conversation_models.pagers.ListConversationModelsPager", - "shortName": "list_conversation_models" - }, - "description": "Sample for ListConversationModels", - "file": "dialogflow_v2_generated_conversation_models_list_conversation_models_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "dialogflow_v2_generated_ConversationModels_ListConversationModels_sync", - "segments": [ - { - "end": 52, - "start": 27, - "type": "FULL" - }, - { - "end": 52, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 48, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 53, - "start": 49, - "type": "RESPONSE_HANDLING" - } - ], - "title": "dialogflow_v2_generated_conversation_models_list_conversation_models_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.dialogflow_v2.ConversationModelsAsyncClient", - "shortName": "ConversationModelsAsyncClient" - }, - "fullName": "google.cloud.dialogflow_v2.ConversationModelsAsyncClient.undeploy_conversation_model", - "method": { - "fullName": "google.cloud.dialogflow.v2.ConversationModels.UndeployConversationModel", - "service": { - "fullName": "google.cloud.dialogflow.v2.ConversationModels", - "shortName": "ConversationModels" - }, - "shortName": "UndeployConversationModel" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.dialogflow_v2.types.UndeployConversationModelRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.api_core.operation_async.AsyncOperation", - "shortName": "undeploy_conversation_model" - }, - "description": "Sample for UndeployConversationModel", - "file": "dialogflow_v2_generated_conversation_models_undeploy_conversation_model_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "dialogflow_v2_generated_ConversationModels_UndeployConversationModel_async", - "segments": [ - { - "end": 55, - "start": 27, - "type": "FULL" - }, - { - "end": 55, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 52, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 56, - "start": 53, - "type": "RESPONSE_HANDLING" - } - ], - "title": "dialogflow_v2_generated_conversation_models_undeploy_conversation_model_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.dialogflow_v2.ConversationModelsClient", - "shortName": "ConversationModelsClient" - }, - "fullName": "google.cloud.dialogflow_v2.ConversationModelsClient.undeploy_conversation_model", - "method": { - "fullName": "google.cloud.dialogflow.v2.ConversationModels.UndeployConversationModel", - "service": { - "fullName": "google.cloud.dialogflow.v2.ConversationModels", - "shortName": "ConversationModels" - }, - "shortName": "UndeployConversationModel" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.dialogflow_v2.types.UndeployConversationModelRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.api_core.operation.Operation", - "shortName": "undeploy_conversation_model" - }, - "description": "Sample for UndeployConversationModel", - "file": "dialogflow_v2_generated_conversation_models_undeploy_conversation_model_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "dialogflow_v2_generated_ConversationModels_UndeployConversationModel_sync", - "segments": [ - { - "end": 55, - "start": 27, - "type": "FULL" - }, - { - "end": 55, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 52, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 56, - "start": 53, - "type": "RESPONSE_HANDLING" - } - ], - "title": "dialogflow_v2_generated_conversation_models_undeploy_conversation_model_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.dialogflow_v2.ConversationProfilesAsyncClient", - "shortName": "ConversationProfilesAsyncClient" - }, - "fullName": "google.cloud.dialogflow_v2.ConversationProfilesAsyncClient.clear_suggestion_feature_config", - "method": { - "fullName": "google.cloud.dialogflow.v2.ConversationProfiles.ClearSuggestionFeatureConfig", - "service": { - "fullName": "google.cloud.dialogflow.v2.ConversationProfiles", - "shortName": "ConversationProfiles" - }, - "shortName": "ClearSuggestionFeatureConfig" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.dialogflow_v2.types.ClearSuggestionFeatureConfigRequest" - }, - { - "name": "conversation_profile", - "type": "str" - }, - { - "name": "participant_role", - "type": "google.cloud.dialogflow_v2.types.Participant.Role" - }, - { - "name": "suggestion_feature_type", - "type": "google.cloud.dialogflow_v2.types.SuggestionFeature.Type" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.api_core.operation_async.AsyncOperation", - "shortName": "clear_suggestion_feature_config" - }, - "description": "Sample for ClearSuggestionFeatureConfig", - "file": "dialogflow_v2_generated_conversation_profiles_clear_suggestion_feature_config_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "dialogflow_v2_generated_ConversationProfiles_ClearSuggestionFeatureConfig_async", - "segments": [ - { - "end": 57, - "start": 27, - "type": "FULL" - }, - { - "end": 57, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 47, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 54, - "start": 48, - "type": "REQUEST_EXECUTION" - }, - { - "end": 58, - "start": 55, - "type": "RESPONSE_HANDLING" - } - ], - "title": "dialogflow_v2_generated_conversation_profiles_clear_suggestion_feature_config_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.dialogflow_v2.ConversationProfilesClient", - "shortName": "ConversationProfilesClient" - }, - "fullName": "google.cloud.dialogflow_v2.ConversationProfilesClient.clear_suggestion_feature_config", - "method": { - "fullName": "google.cloud.dialogflow.v2.ConversationProfiles.ClearSuggestionFeatureConfig", - "service": { - "fullName": "google.cloud.dialogflow.v2.ConversationProfiles", - "shortName": "ConversationProfiles" - }, - "shortName": "ClearSuggestionFeatureConfig" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.dialogflow_v2.types.ClearSuggestionFeatureConfigRequest" - }, - { - "name": "conversation_profile", - "type": "str" - }, - { - "name": "participant_role", - "type": "google.cloud.dialogflow_v2.types.Participant.Role" - }, - { - "name": "suggestion_feature_type", - "type": "google.cloud.dialogflow_v2.types.SuggestionFeature.Type" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.api_core.operation.Operation", - "shortName": "clear_suggestion_feature_config" - }, - "description": "Sample for ClearSuggestionFeatureConfig", - "file": "dialogflow_v2_generated_conversation_profiles_clear_suggestion_feature_config_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "dialogflow_v2_generated_ConversationProfiles_ClearSuggestionFeatureConfig_sync", - "segments": [ - { - "end": 57, - "start": 27, - "type": "FULL" - }, - { - "end": 57, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 47, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 54, - "start": 48, - "type": "REQUEST_EXECUTION" - }, - { - "end": 58, - "start": 55, - "type": "RESPONSE_HANDLING" - } - ], - "title": "dialogflow_v2_generated_conversation_profiles_clear_suggestion_feature_config_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.dialogflow_v2.ConversationProfilesAsyncClient", - "shortName": "ConversationProfilesAsyncClient" - }, - "fullName": "google.cloud.dialogflow_v2.ConversationProfilesAsyncClient.create_conversation_profile", - "method": { - "fullName": "google.cloud.dialogflow.v2.ConversationProfiles.CreateConversationProfile", - "service": { - "fullName": "google.cloud.dialogflow.v2.ConversationProfiles", - "shortName": "ConversationProfiles" - }, - "shortName": "CreateConversationProfile" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.dialogflow_v2.types.CreateConversationProfileRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "conversation_profile", - "type": "google.cloud.dialogflow_v2.types.ConversationProfile" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.dialogflow_v2.types.ConversationProfile", - "shortName": "create_conversation_profile" - }, - "description": "Sample for CreateConversationProfile", - "file": "dialogflow_v2_generated_conversation_profiles_create_conversation_profile_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "dialogflow_v2_generated_ConversationProfiles_CreateConversationProfile_async", - "segments": [ - { - "end": 55, - "start": 27, - "type": "FULL" - }, - { - "end": 55, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 49, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 52, - "start": 50, - "type": "REQUEST_EXECUTION" - }, - { - "end": 56, - "start": 53, - "type": "RESPONSE_HANDLING" - } - ], - "title": "dialogflow_v2_generated_conversation_profiles_create_conversation_profile_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.dialogflow_v2.ConversationProfilesClient", - "shortName": "ConversationProfilesClient" - }, - "fullName": "google.cloud.dialogflow_v2.ConversationProfilesClient.create_conversation_profile", - "method": { - "fullName": "google.cloud.dialogflow.v2.ConversationProfiles.CreateConversationProfile", - "service": { - "fullName": "google.cloud.dialogflow.v2.ConversationProfiles", - "shortName": "ConversationProfiles" - }, - "shortName": "CreateConversationProfile" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.dialogflow_v2.types.CreateConversationProfileRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "conversation_profile", - "type": "google.cloud.dialogflow_v2.types.ConversationProfile" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.dialogflow_v2.types.ConversationProfile", - "shortName": "create_conversation_profile" - }, - "description": "Sample for CreateConversationProfile", - "file": "dialogflow_v2_generated_conversation_profiles_create_conversation_profile_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "dialogflow_v2_generated_ConversationProfiles_CreateConversationProfile_sync", - "segments": [ - { - "end": 55, - "start": 27, - "type": "FULL" - }, - { - "end": 55, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 49, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 52, - "start": 50, - "type": "REQUEST_EXECUTION" - }, - { - "end": 56, - "start": 53, - "type": "RESPONSE_HANDLING" - } - ], - "title": "dialogflow_v2_generated_conversation_profiles_create_conversation_profile_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.dialogflow_v2.ConversationProfilesAsyncClient", - "shortName": "ConversationProfilesAsyncClient" - }, - "fullName": "google.cloud.dialogflow_v2.ConversationProfilesAsyncClient.delete_conversation_profile", - "method": { - "fullName": "google.cloud.dialogflow.v2.ConversationProfiles.DeleteConversationProfile", - "service": { - "fullName": "google.cloud.dialogflow.v2.ConversationProfiles", - "shortName": "ConversationProfiles" - }, - "shortName": "DeleteConversationProfile" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.dialogflow_v2.types.DeleteConversationProfileRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "shortName": "delete_conversation_profile" - }, - "description": "Sample for DeleteConversationProfile", - "file": "dialogflow_v2_generated_conversation_profiles_delete_conversation_profile_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "dialogflow_v2_generated_ConversationProfiles_DeleteConversationProfile_async", - "segments": [ - { - "end": 49, - "start": 27, - "type": "FULL" - }, - { - "end": 49, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 50, - "type": "RESPONSE_HANDLING" - } - ], - "title": "dialogflow_v2_generated_conversation_profiles_delete_conversation_profile_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.dialogflow_v2.ConversationProfilesClient", - "shortName": "ConversationProfilesClient" - }, - "fullName": "google.cloud.dialogflow_v2.ConversationProfilesClient.delete_conversation_profile", - "method": { - "fullName": "google.cloud.dialogflow.v2.ConversationProfiles.DeleteConversationProfile", - "service": { - "fullName": "google.cloud.dialogflow.v2.ConversationProfiles", - "shortName": "ConversationProfiles" - }, - "shortName": "DeleteConversationProfile" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.dialogflow_v2.types.DeleteConversationProfileRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "shortName": "delete_conversation_profile" - }, - "description": "Sample for DeleteConversationProfile", - "file": "dialogflow_v2_generated_conversation_profiles_delete_conversation_profile_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "dialogflow_v2_generated_ConversationProfiles_DeleteConversationProfile_sync", - "segments": [ - { - "end": 49, - "start": 27, - "type": "FULL" - }, - { - "end": 49, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 50, - "type": "RESPONSE_HANDLING" - } - ], - "title": "dialogflow_v2_generated_conversation_profiles_delete_conversation_profile_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.dialogflow_v2.ConversationProfilesAsyncClient", - "shortName": "ConversationProfilesAsyncClient" - }, - "fullName": "google.cloud.dialogflow_v2.ConversationProfilesAsyncClient.get_conversation_profile", - "method": { - "fullName": "google.cloud.dialogflow.v2.ConversationProfiles.GetConversationProfile", - "service": { - "fullName": "google.cloud.dialogflow.v2.ConversationProfiles", - "shortName": "ConversationProfiles" - }, - "shortName": "GetConversationProfile" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.dialogflow_v2.types.GetConversationProfileRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.dialogflow_v2.types.ConversationProfile", - "shortName": "get_conversation_profile" - }, - "description": "Sample for GetConversationProfile", - "file": "dialogflow_v2_generated_conversation_profiles_get_conversation_profile_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "dialogflow_v2_generated_ConversationProfiles_GetConversationProfile_async", - "segments": [ - { - "end": 51, - "start": 27, - "type": "FULL" - }, - { - "end": 51, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 48, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 52, - "start": 49, - "type": "RESPONSE_HANDLING" - } - ], - "title": "dialogflow_v2_generated_conversation_profiles_get_conversation_profile_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.dialogflow_v2.ConversationProfilesClient", - "shortName": "ConversationProfilesClient" - }, - "fullName": "google.cloud.dialogflow_v2.ConversationProfilesClient.get_conversation_profile", - "method": { - "fullName": "google.cloud.dialogflow.v2.ConversationProfiles.GetConversationProfile", - "service": { - "fullName": "google.cloud.dialogflow.v2.ConversationProfiles", - "shortName": "ConversationProfiles" - }, - "shortName": "GetConversationProfile" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.dialogflow_v2.types.GetConversationProfileRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.dialogflow_v2.types.ConversationProfile", - "shortName": "get_conversation_profile" - }, - "description": "Sample for GetConversationProfile", - "file": "dialogflow_v2_generated_conversation_profiles_get_conversation_profile_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "dialogflow_v2_generated_ConversationProfiles_GetConversationProfile_sync", - "segments": [ - { - "end": 51, - "start": 27, - "type": "FULL" - }, - { - "end": 51, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 48, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 52, - "start": 49, - "type": "RESPONSE_HANDLING" - } - ], - "title": "dialogflow_v2_generated_conversation_profiles_get_conversation_profile_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.dialogflow_v2.ConversationProfilesAsyncClient", - "shortName": "ConversationProfilesAsyncClient" - }, - "fullName": "google.cloud.dialogflow_v2.ConversationProfilesAsyncClient.list_conversation_profiles", - "method": { - "fullName": "google.cloud.dialogflow.v2.ConversationProfiles.ListConversationProfiles", - "service": { - "fullName": "google.cloud.dialogflow.v2.ConversationProfiles", - "shortName": "ConversationProfiles" - }, - "shortName": "ListConversationProfiles" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.dialogflow_v2.types.ListConversationProfilesRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.dialogflow_v2.services.conversation_profiles.pagers.ListConversationProfilesAsyncPager", - "shortName": "list_conversation_profiles" - }, - "description": "Sample for ListConversationProfiles", - "file": "dialogflow_v2_generated_conversation_profiles_list_conversation_profiles_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "dialogflow_v2_generated_ConversationProfiles_ListConversationProfiles_async", - "segments": [ - { - "end": 52, - "start": 27, - "type": "FULL" - }, - { - "end": 52, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 48, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 53, - "start": 49, - "type": "RESPONSE_HANDLING" - } - ], - "title": "dialogflow_v2_generated_conversation_profiles_list_conversation_profiles_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.dialogflow_v2.ConversationProfilesClient", - "shortName": "ConversationProfilesClient" - }, - "fullName": "google.cloud.dialogflow_v2.ConversationProfilesClient.list_conversation_profiles", - "method": { - "fullName": "google.cloud.dialogflow.v2.ConversationProfiles.ListConversationProfiles", - "service": { - "fullName": "google.cloud.dialogflow.v2.ConversationProfiles", - "shortName": "ConversationProfiles" - }, - "shortName": "ListConversationProfiles" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.dialogflow_v2.types.ListConversationProfilesRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.dialogflow_v2.services.conversation_profiles.pagers.ListConversationProfilesPager", - "shortName": "list_conversation_profiles" - }, - "description": "Sample for ListConversationProfiles", - "file": "dialogflow_v2_generated_conversation_profiles_list_conversation_profiles_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "dialogflow_v2_generated_ConversationProfiles_ListConversationProfiles_sync", - "segments": [ - { - "end": 52, - "start": 27, - "type": "FULL" - }, - { - "end": 52, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 48, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 53, - "start": 49, - "type": "RESPONSE_HANDLING" - } - ], - "title": "dialogflow_v2_generated_conversation_profiles_list_conversation_profiles_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.dialogflow_v2.ConversationProfilesAsyncClient", - "shortName": "ConversationProfilesAsyncClient" - }, - "fullName": "google.cloud.dialogflow_v2.ConversationProfilesAsyncClient.set_suggestion_feature_config", - "method": { - "fullName": "google.cloud.dialogflow.v2.ConversationProfiles.SetSuggestionFeatureConfig", - "service": { - "fullName": "google.cloud.dialogflow.v2.ConversationProfiles", - "shortName": "ConversationProfiles" - }, - "shortName": "SetSuggestionFeatureConfig" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.dialogflow_v2.types.SetSuggestionFeatureConfigRequest" - }, - { - "name": "conversation_profile", - "type": "str" - }, - { - "name": "participant_role", - "type": "google.cloud.dialogflow_v2.types.Participant.Role" - }, - { - "name": "suggestion_feature_config", - "type": "google.cloud.dialogflow_v2.types.HumanAgentAssistantConfig.SuggestionFeatureConfig" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.api_core.operation_async.AsyncOperation", - "shortName": "set_suggestion_feature_config" - }, - "description": "Sample for SetSuggestionFeatureConfig", - "file": "dialogflow_v2_generated_conversation_profiles_set_suggestion_feature_config_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "dialogflow_v2_generated_ConversationProfiles_SetSuggestionFeatureConfig_async", - "segments": [ - { - "end": 56, - "start": 27, - "type": "FULL" - }, - { - "end": 56, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 46, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 53, - "start": 47, - "type": "REQUEST_EXECUTION" - }, - { - "end": 57, - "start": 54, - "type": "RESPONSE_HANDLING" - } - ], - "title": "dialogflow_v2_generated_conversation_profiles_set_suggestion_feature_config_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.dialogflow_v2.ConversationProfilesClient", - "shortName": "ConversationProfilesClient" - }, - "fullName": "google.cloud.dialogflow_v2.ConversationProfilesClient.set_suggestion_feature_config", - "method": { - "fullName": "google.cloud.dialogflow.v2.ConversationProfiles.SetSuggestionFeatureConfig", - "service": { - "fullName": "google.cloud.dialogflow.v2.ConversationProfiles", - "shortName": "ConversationProfiles" - }, - "shortName": "SetSuggestionFeatureConfig" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.dialogflow_v2.types.SetSuggestionFeatureConfigRequest" - }, - { - "name": "conversation_profile", - "type": "str" - }, - { - "name": "participant_role", - "type": "google.cloud.dialogflow_v2.types.Participant.Role" - }, - { - "name": "suggestion_feature_config", - "type": "google.cloud.dialogflow_v2.types.HumanAgentAssistantConfig.SuggestionFeatureConfig" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.api_core.operation.Operation", - "shortName": "set_suggestion_feature_config" - }, - "description": "Sample for SetSuggestionFeatureConfig", - "file": "dialogflow_v2_generated_conversation_profiles_set_suggestion_feature_config_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "dialogflow_v2_generated_ConversationProfiles_SetSuggestionFeatureConfig_sync", - "segments": [ - { - "end": 56, - "start": 27, - "type": "FULL" - }, - { - "end": 56, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 46, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 53, - "start": 47, - "type": "REQUEST_EXECUTION" - }, - { - "end": 57, - "start": 54, - "type": "RESPONSE_HANDLING" - } - ], - "title": "dialogflow_v2_generated_conversation_profiles_set_suggestion_feature_config_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.dialogflow_v2.ConversationProfilesAsyncClient", - "shortName": "ConversationProfilesAsyncClient" - }, - "fullName": "google.cloud.dialogflow_v2.ConversationProfilesAsyncClient.update_conversation_profile", - "method": { - "fullName": "google.cloud.dialogflow.v2.ConversationProfiles.UpdateConversationProfile", - "service": { - "fullName": "google.cloud.dialogflow.v2.ConversationProfiles", - "shortName": "ConversationProfiles" - }, - "shortName": "UpdateConversationProfile" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.dialogflow_v2.types.UpdateConversationProfileRequest" - }, - { - "name": "conversation_profile", - "type": "google.cloud.dialogflow_v2.types.ConversationProfile" - }, - { - "name": "update_mask", - "type": "google.protobuf.field_mask_pb2.FieldMask" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.dialogflow_v2.types.ConversationProfile", - "shortName": "update_conversation_profile" - }, - "description": "Sample for UpdateConversationProfile", - "file": "dialogflow_v2_generated_conversation_profiles_update_conversation_profile_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "dialogflow_v2_generated_ConversationProfiles_UpdateConversationProfile_async", - "segments": [ - { - "end": 54, - "start": 27, - "type": "FULL" - }, - { - "end": 54, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 48, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 51, - "start": 49, - "type": "REQUEST_EXECUTION" - }, - { - "end": 55, - "start": 52, - "type": "RESPONSE_HANDLING" - } - ], - "title": "dialogflow_v2_generated_conversation_profiles_update_conversation_profile_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.dialogflow_v2.ConversationProfilesClient", - "shortName": "ConversationProfilesClient" - }, - "fullName": "google.cloud.dialogflow_v2.ConversationProfilesClient.update_conversation_profile", - "method": { - "fullName": "google.cloud.dialogflow.v2.ConversationProfiles.UpdateConversationProfile", - "service": { - "fullName": "google.cloud.dialogflow.v2.ConversationProfiles", - "shortName": "ConversationProfiles" - }, - "shortName": "UpdateConversationProfile" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.dialogflow_v2.types.UpdateConversationProfileRequest" - }, - { - "name": "conversation_profile", - "type": "google.cloud.dialogflow_v2.types.ConversationProfile" - }, - { - "name": "update_mask", - "type": "google.protobuf.field_mask_pb2.FieldMask" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.dialogflow_v2.types.ConversationProfile", - "shortName": "update_conversation_profile" - }, - "description": "Sample for UpdateConversationProfile", - "file": "dialogflow_v2_generated_conversation_profiles_update_conversation_profile_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "dialogflow_v2_generated_ConversationProfiles_UpdateConversationProfile_sync", - "segments": [ - { - "end": 54, - "start": 27, - "type": "FULL" - }, - { - "end": 54, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 48, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 51, - "start": 49, - "type": "REQUEST_EXECUTION" - }, - { - "end": 55, - "start": 52, - "type": "RESPONSE_HANDLING" - } - ], - "title": "dialogflow_v2_generated_conversation_profiles_update_conversation_profile_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.dialogflow_v2.ConversationsAsyncClient", - "shortName": "ConversationsAsyncClient" - }, - "fullName": "google.cloud.dialogflow_v2.ConversationsAsyncClient.complete_conversation", - "method": { - "fullName": "google.cloud.dialogflow.v2.Conversations.CompleteConversation", - "service": { - "fullName": "google.cloud.dialogflow.v2.Conversations", - "shortName": "Conversations" - }, - "shortName": "CompleteConversation" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.dialogflow_v2.types.CompleteConversationRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.dialogflow_v2.types.Conversation", - "shortName": "complete_conversation" - }, - "description": "Sample for CompleteConversation", - "file": "dialogflow_v2_generated_conversations_complete_conversation_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "dialogflow_v2_generated_Conversations_CompleteConversation_async", - "segments": [ - { - "end": 51, - "start": 27, - "type": "FULL" - }, - { - "end": 51, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 48, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 52, - "start": 49, - "type": "RESPONSE_HANDLING" - } - ], - "title": "dialogflow_v2_generated_conversations_complete_conversation_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.dialogflow_v2.ConversationsClient", - "shortName": "ConversationsClient" - }, - "fullName": "google.cloud.dialogflow_v2.ConversationsClient.complete_conversation", - "method": { - "fullName": "google.cloud.dialogflow.v2.Conversations.CompleteConversation", - "service": { - "fullName": "google.cloud.dialogflow.v2.Conversations", - "shortName": "Conversations" - }, - "shortName": "CompleteConversation" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.dialogflow_v2.types.CompleteConversationRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.dialogflow_v2.types.Conversation", - "shortName": "complete_conversation" - }, - "description": "Sample for CompleteConversation", - "file": "dialogflow_v2_generated_conversations_complete_conversation_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "dialogflow_v2_generated_Conversations_CompleteConversation_sync", - "segments": [ - { - "end": 51, - "start": 27, - "type": "FULL" - }, - { - "end": 51, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 48, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 52, - "start": 49, - "type": "RESPONSE_HANDLING" - } - ], - "title": "dialogflow_v2_generated_conversations_complete_conversation_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.dialogflow_v2.ConversationsAsyncClient", - "shortName": "ConversationsAsyncClient" - }, - "fullName": "google.cloud.dialogflow_v2.ConversationsAsyncClient.create_conversation", - "method": { - "fullName": "google.cloud.dialogflow.v2.Conversations.CreateConversation", - "service": { - "fullName": "google.cloud.dialogflow.v2.Conversations", - "shortName": "Conversations" - }, - "shortName": "CreateConversation" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.dialogflow_v2.types.CreateConversationRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "conversation", - "type": "google.cloud.dialogflow_v2.types.Conversation" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.dialogflow_v2.types.Conversation", - "shortName": "create_conversation" - }, - "description": "Sample for CreateConversation", - "file": "dialogflow_v2_generated_conversations_create_conversation_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "dialogflow_v2_generated_Conversations_CreateConversation_async", - "segments": [ - { - "end": 55, - "start": 27, - "type": "FULL" - }, - { - "end": 55, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 49, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 52, - "start": 50, - "type": "REQUEST_EXECUTION" - }, - { - "end": 56, - "start": 53, - "type": "RESPONSE_HANDLING" - } - ], - "title": "dialogflow_v2_generated_conversations_create_conversation_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.dialogflow_v2.ConversationsClient", - "shortName": "ConversationsClient" - }, - "fullName": "google.cloud.dialogflow_v2.ConversationsClient.create_conversation", - "method": { - "fullName": "google.cloud.dialogflow.v2.Conversations.CreateConversation", - "service": { - "fullName": "google.cloud.dialogflow.v2.Conversations", - "shortName": "Conversations" - }, - "shortName": "CreateConversation" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.dialogflow_v2.types.CreateConversationRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "conversation", - "type": "google.cloud.dialogflow_v2.types.Conversation" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.dialogflow_v2.types.Conversation", - "shortName": "create_conversation" - }, - "description": "Sample for CreateConversation", - "file": "dialogflow_v2_generated_conversations_create_conversation_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "dialogflow_v2_generated_Conversations_CreateConversation_sync", - "segments": [ - { - "end": 55, - "start": 27, - "type": "FULL" - }, - { - "end": 55, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 49, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 52, - "start": 50, - "type": "REQUEST_EXECUTION" - }, - { - "end": 56, - "start": 53, - "type": "RESPONSE_HANDLING" - } - ], - "title": "dialogflow_v2_generated_conversations_create_conversation_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.dialogflow_v2.ConversationsAsyncClient", - "shortName": "ConversationsAsyncClient" - }, - "fullName": "google.cloud.dialogflow_v2.ConversationsAsyncClient.get_conversation", - "method": { - "fullName": "google.cloud.dialogflow.v2.Conversations.GetConversation", - "service": { - "fullName": "google.cloud.dialogflow.v2.Conversations", - "shortName": "Conversations" - }, - "shortName": "GetConversation" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.dialogflow_v2.types.GetConversationRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.dialogflow_v2.types.Conversation", - "shortName": "get_conversation" - }, - "description": "Sample for GetConversation", - "file": "dialogflow_v2_generated_conversations_get_conversation_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "dialogflow_v2_generated_Conversations_GetConversation_async", - "segments": [ - { - "end": 51, - "start": 27, - "type": "FULL" - }, - { - "end": 51, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 48, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 52, - "start": 49, - "type": "RESPONSE_HANDLING" - } - ], - "title": "dialogflow_v2_generated_conversations_get_conversation_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.dialogflow_v2.ConversationsClient", - "shortName": "ConversationsClient" - }, - "fullName": "google.cloud.dialogflow_v2.ConversationsClient.get_conversation", - "method": { - "fullName": "google.cloud.dialogflow.v2.Conversations.GetConversation", - "service": { - "fullName": "google.cloud.dialogflow.v2.Conversations", - "shortName": "Conversations" - }, - "shortName": "GetConversation" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.dialogflow_v2.types.GetConversationRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.dialogflow_v2.types.Conversation", - "shortName": "get_conversation" - }, - "description": "Sample for GetConversation", - "file": "dialogflow_v2_generated_conversations_get_conversation_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "dialogflow_v2_generated_Conversations_GetConversation_sync", - "segments": [ - { - "end": 51, - "start": 27, - "type": "FULL" - }, - { - "end": 51, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 48, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 52, - "start": 49, - "type": "RESPONSE_HANDLING" - } - ], - "title": "dialogflow_v2_generated_conversations_get_conversation_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.dialogflow_v2.ConversationsAsyncClient", - "shortName": "ConversationsAsyncClient" - }, - "fullName": "google.cloud.dialogflow_v2.ConversationsAsyncClient.list_conversations", - "method": { - "fullName": "google.cloud.dialogflow.v2.Conversations.ListConversations", - "service": { - "fullName": "google.cloud.dialogflow.v2.Conversations", - "shortName": "Conversations" - }, - "shortName": "ListConversations" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.dialogflow_v2.types.ListConversationsRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.dialogflow_v2.services.conversations.pagers.ListConversationsAsyncPager", - "shortName": "list_conversations" - }, - "description": "Sample for ListConversations", - "file": "dialogflow_v2_generated_conversations_list_conversations_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "dialogflow_v2_generated_Conversations_ListConversations_async", - "segments": [ - { - "end": 52, - "start": 27, - "type": "FULL" - }, - { - "end": 52, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 48, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 53, - "start": 49, - "type": "RESPONSE_HANDLING" - } - ], - "title": "dialogflow_v2_generated_conversations_list_conversations_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.dialogflow_v2.ConversationsClient", - "shortName": "ConversationsClient" - }, - "fullName": "google.cloud.dialogflow_v2.ConversationsClient.list_conversations", - "method": { - "fullName": "google.cloud.dialogflow.v2.Conversations.ListConversations", - "service": { - "fullName": "google.cloud.dialogflow.v2.Conversations", - "shortName": "Conversations" - }, - "shortName": "ListConversations" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.dialogflow_v2.types.ListConversationsRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.dialogflow_v2.services.conversations.pagers.ListConversationsPager", - "shortName": "list_conversations" - }, - "description": "Sample for ListConversations", - "file": "dialogflow_v2_generated_conversations_list_conversations_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "dialogflow_v2_generated_Conversations_ListConversations_sync", - "segments": [ - { - "end": 52, - "start": 27, - "type": "FULL" - }, - { - "end": 52, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 48, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 53, - "start": 49, - "type": "RESPONSE_HANDLING" - } - ], - "title": "dialogflow_v2_generated_conversations_list_conversations_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.dialogflow_v2.ConversationsAsyncClient", - "shortName": "ConversationsAsyncClient" - }, - "fullName": "google.cloud.dialogflow_v2.ConversationsAsyncClient.list_messages", - "method": { - "fullName": "google.cloud.dialogflow.v2.Conversations.ListMessages", - "service": { - "fullName": "google.cloud.dialogflow.v2.Conversations", - "shortName": "Conversations" - }, - "shortName": "ListMessages" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.dialogflow_v2.types.ListMessagesRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.dialogflow_v2.services.conversations.pagers.ListMessagesAsyncPager", - "shortName": "list_messages" - }, - "description": "Sample for ListMessages", - "file": "dialogflow_v2_generated_conversations_list_messages_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "dialogflow_v2_generated_Conversations_ListMessages_async", - "segments": [ - { - "end": 52, - "start": 27, - "type": "FULL" - }, - { - "end": 52, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 48, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 53, - "start": 49, - "type": "RESPONSE_HANDLING" - } - ], - "title": "dialogflow_v2_generated_conversations_list_messages_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.dialogflow_v2.ConversationsClient", - "shortName": "ConversationsClient" - }, - "fullName": "google.cloud.dialogflow_v2.ConversationsClient.list_messages", - "method": { - "fullName": "google.cloud.dialogflow.v2.Conversations.ListMessages", - "service": { - "fullName": "google.cloud.dialogflow.v2.Conversations", - "shortName": "Conversations" - }, - "shortName": "ListMessages" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.dialogflow_v2.types.ListMessagesRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.dialogflow_v2.services.conversations.pagers.ListMessagesPager", - "shortName": "list_messages" - }, - "description": "Sample for ListMessages", - "file": "dialogflow_v2_generated_conversations_list_messages_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "dialogflow_v2_generated_Conversations_ListMessages_sync", - "segments": [ - { - "end": 52, - "start": 27, - "type": "FULL" - }, - { - "end": 52, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 48, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 53, - "start": 49, - "type": "RESPONSE_HANDLING" - } - ], - "title": "dialogflow_v2_generated_conversations_list_messages_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.dialogflow_v2.ConversationsAsyncClient", - "shortName": "ConversationsAsyncClient" - }, - "fullName": "google.cloud.dialogflow_v2.ConversationsAsyncClient.suggest_conversation_summary", - "method": { - "fullName": "google.cloud.dialogflow.v2.Conversations.SuggestConversationSummary", - "service": { - "fullName": "google.cloud.dialogflow.v2.Conversations", - "shortName": "Conversations" - }, - "shortName": "SuggestConversationSummary" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.dialogflow_v2.types.SuggestConversationSummaryRequest" - }, - { - "name": "conversation", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.dialogflow_v2.types.SuggestConversationSummaryResponse", - "shortName": "suggest_conversation_summary" - }, - "description": "Sample for SuggestConversationSummary", - "file": "dialogflow_v2_generated_conversations_suggest_conversation_summary_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "dialogflow_v2_generated_Conversations_SuggestConversationSummary_async", - "segments": [ - { - "end": 51, - "start": 27, - "type": "FULL" - }, - { - "end": 51, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 48, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 52, - "start": 49, - "type": "RESPONSE_HANDLING" - } - ], - "title": "dialogflow_v2_generated_conversations_suggest_conversation_summary_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.dialogflow_v2.ConversationsClient", - "shortName": "ConversationsClient" - }, - "fullName": "google.cloud.dialogflow_v2.ConversationsClient.suggest_conversation_summary", - "method": { - "fullName": "google.cloud.dialogflow.v2.Conversations.SuggestConversationSummary", - "service": { - "fullName": "google.cloud.dialogflow.v2.Conversations", - "shortName": "Conversations" - }, - "shortName": "SuggestConversationSummary" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.dialogflow_v2.types.SuggestConversationSummaryRequest" - }, - { - "name": "conversation", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.dialogflow_v2.types.SuggestConversationSummaryResponse", - "shortName": "suggest_conversation_summary" - }, - "description": "Sample for SuggestConversationSummary", - "file": "dialogflow_v2_generated_conversations_suggest_conversation_summary_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "dialogflow_v2_generated_Conversations_SuggestConversationSummary_sync", - "segments": [ - { - "end": 51, - "start": 27, - "type": "FULL" - }, - { - "end": 51, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 48, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 52, - "start": 49, - "type": "RESPONSE_HANDLING" - } - ], - "title": "dialogflow_v2_generated_conversations_suggest_conversation_summary_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.dialogflow_v2.DocumentsAsyncClient", - "shortName": "DocumentsAsyncClient" - }, - "fullName": "google.cloud.dialogflow_v2.DocumentsAsyncClient.create_document", - "method": { - "fullName": "google.cloud.dialogflow.v2.Documents.CreateDocument", - "service": { - "fullName": "google.cloud.dialogflow.v2.Documents", - "shortName": "Documents" - }, - "shortName": "CreateDocument" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.dialogflow_v2.types.CreateDocumentRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "document", - "type": "google.cloud.dialogflow_v2.types.Document" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.api_core.operation_async.AsyncOperation", - "shortName": "create_document" - }, - "description": "Sample for CreateDocument", - "file": "dialogflow_v2_generated_documents_create_document_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "dialogflow_v2_generated_Documents_CreateDocument_async", - "segments": [ - { - "end": 62, - "start": 27, - "type": "FULL" - }, - { - "end": 62, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 52, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 59, - "start": 53, - "type": "REQUEST_EXECUTION" - }, - { - "end": 63, - "start": 60, - "type": "RESPONSE_HANDLING" - } - ], - "title": "dialogflow_v2_generated_documents_create_document_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.dialogflow_v2.DocumentsClient", - "shortName": "DocumentsClient" - }, - "fullName": "google.cloud.dialogflow_v2.DocumentsClient.create_document", - "method": { - "fullName": "google.cloud.dialogflow.v2.Documents.CreateDocument", - "service": { - "fullName": "google.cloud.dialogflow.v2.Documents", - "shortName": "Documents" - }, - "shortName": "CreateDocument" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.dialogflow_v2.types.CreateDocumentRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "document", - "type": "google.cloud.dialogflow_v2.types.Document" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.api_core.operation.Operation", - "shortName": "create_document" - }, - "description": "Sample for CreateDocument", - "file": "dialogflow_v2_generated_documents_create_document_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "dialogflow_v2_generated_Documents_CreateDocument_sync", - "segments": [ - { - "end": 62, - "start": 27, - "type": "FULL" - }, - { - "end": 62, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 52, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 59, - "start": 53, - "type": "REQUEST_EXECUTION" - }, - { - "end": 63, - "start": 60, - "type": "RESPONSE_HANDLING" - } - ], - "title": "dialogflow_v2_generated_documents_create_document_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.dialogflow_v2.DocumentsAsyncClient", - "shortName": "DocumentsAsyncClient" - }, - "fullName": "google.cloud.dialogflow_v2.DocumentsAsyncClient.delete_document", - "method": { - "fullName": "google.cloud.dialogflow.v2.Documents.DeleteDocument", - "service": { - "fullName": "google.cloud.dialogflow.v2.Documents", - "shortName": "Documents" - }, - "shortName": "DeleteDocument" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.dialogflow_v2.types.DeleteDocumentRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.api_core.operation_async.AsyncOperation", - "shortName": "delete_document" - }, - "description": "Sample for DeleteDocument", - "file": "dialogflow_v2_generated_documents_delete_document_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "dialogflow_v2_generated_Documents_DeleteDocument_async", - "segments": [ - { - "end": 55, - "start": 27, - "type": "FULL" - }, - { - "end": 55, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 52, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 56, - "start": 53, - "type": "RESPONSE_HANDLING" - } - ], - "title": "dialogflow_v2_generated_documents_delete_document_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.dialogflow_v2.DocumentsClient", - "shortName": "DocumentsClient" - }, - "fullName": "google.cloud.dialogflow_v2.DocumentsClient.delete_document", - "method": { - "fullName": "google.cloud.dialogflow.v2.Documents.DeleteDocument", - "service": { - "fullName": "google.cloud.dialogflow.v2.Documents", - "shortName": "Documents" - }, - "shortName": "DeleteDocument" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.dialogflow_v2.types.DeleteDocumentRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.api_core.operation.Operation", - "shortName": "delete_document" - }, - "description": "Sample for DeleteDocument", - "file": "dialogflow_v2_generated_documents_delete_document_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "dialogflow_v2_generated_Documents_DeleteDocument_sync", - "segments": [ - { - "end": 55, - "start": 27, - "type": "FULL" - }, - { - "end": 55, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 52, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 56, - "start": 53, - "type": "RESPONSE_HANDLING" - } - ], - "title": "dialogflow_v2_generated_documents_delete_document_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.dialogflow_v2.DocumentsAsyncClient", - "shortName": "DocumentsAsyncClient" - }, - "fullName": "google.cloud.dialogflow_v2.DocumentsAsyncClient.export_document", - "method": { - "fullName": "google.cloud.dialogflow.v2.Documents.ExportDocument", - "service": { - "fullName": "google.cloud.dialogflow.v2.Documents", - "shortName": "Documents" - }, - "shortName": "ExportDocument" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.dialogflow_v2.types.ExportDocumentRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.api_core.operation_async.AsyncOperation", - "shortName": "export_document" - }, - "description": "Sample for ExportDocument", - "file": "dialogflow_v2_generated_documents_export_document_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "dialogflow_v2_generated_Documents_ExportDocument_async", - "segments": [ - { - "end": 55, - "start": 27, - "type": "FULL" - }, - { - "end": 55, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 52, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 56, - "start": 53, - "type": "RESPONSE_HANDLING" - } - ], - "title": "dialogflow_v2_generated_documents_export_document_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.dialogflow_v2.DocumentsClient", - "shortName": "DocumentsClient" - }, - "fullName": "google.cloud.dialogflow_v2.DocumentsClient.export_document", - "method": { - "fullName": "google.cloud.dialogflow.v2.Documents.ExportDocument", - "service": { - "fullName": "google.cloud.dialogflow.v2.Documents", - "shortName": "Documents" - }, - "shortName": "ExportDocument" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.dialogflow_v2.types.ExportDocumentRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.api_core.operation.Operation", - "shortName": "export_document" - }, - "description": "Sample for ExportDocument", - "file": "dialogflow_v2_generated_documents_export_document_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "dialogflow_v2_generated_Documents_ExportDocument_sync", - "segments": [ - { - "end": 55, - "start": 27, - "type": "FULL" - }, - { - "end": 55, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 52, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 56, - "start": 53, - "type": "RESPONSE_HANDLING" - } - ], - "title": "dialogflow_v2_generated_documents_export_document_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.dialogflow_v2.DocumentsAsyncClient", - "shortName": "DocumentsAsyncClient" - }, - "fullName": "google.cloud.dialogflow_v2.DocumentsAsyncClient.get_document", - "method": { - "fullName": "google.cloud.dialogflow.v2.Documents.GetDocument", - "service": { - "fullName": "google.cloud.dialogflow.v2.Documents", - "shortName": "Documents" - }, - "shortName": "GetDocument" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.dialogflow_v2.types.GetDocumentRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.dialogflow_v2.types.Document", - "shortName": "get_document" - }, - "description": "Sample for GetDocument", - "file": "dialogflow_v2_generated_documents_get_document_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "dialogflow_v2_generated_Documents_GetDocument_async", - "segments": [ - { - "end": 51, - "start": 27, - "type": "FULL" - }, - { - "end": 51, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 48, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 52, - "start": 49, - "type": "RESPONSE_HANDLING" - } - ], - "title": "dialogflow_v2_generated_documents_get_document_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.dialogflow_v2.DocumentsClient", - "shortName": "DocumentsClient" - }, - "fullName": "google.cloud.dialogflow_v2.DocumentsClient.get_document", - "method": { - "fullName": "google.cloud.dialogflow.v2.Documents.GetDocument", - "service": { - "fullName": "google.cloud.dialogflow.v2.Documents", - "shortName": "Documents" - }, - "shortName": "GetDocument" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.dialogflow_v2.types.GetDocumentRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.dialogflow_v2.types.Document", - "shortName": "get_document" - }, - "description": "Sample for GetDocument", - "file": "dialogflow_v2_generated_documents_get_document_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "dialogflow_v2_generated_Documents_GetDocument_sync", - "segments": [ - { - "end": 51, - "start": 27, - "type": "FULL" - }, - { - "end": 51, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 48, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 52, - "start": 49, - "type": "RESPONSE_HANDLING" - } - ], - "title": "dialogflow_v2_generated_documents_get_document_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.dialogflow_v2.DocumentsAsyncClient", - "shortName": "DocumentsAsyncClient" - }, - "fullName": "google.cloud.dialogflow_v2.DocumentsAsyncClient.import_documents", - "method": { - "fullName": "google.cloud.dialogflow.v2.Documents.ImportDocuments", - "service": { - "fullName": "google.cloud.dialogflow.v2.Documents", - "shortName": "Documents" - }, - "shortName": "ImportDocuments" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.dialogflow_v2.types.ImportDocumentsRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.api_core.operation_async.AsyncOperation", - "shortName": "import_documents" - }, - "description": "Sample for ImportDocuments", - "file": "dialogflow_v2_generated_documents_import_documents_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "dialogflow_v2_generated_Documents_ImportDocuments_async", - "segments": [ - { - "end": 64, - "start": 27, - "type": "FULL" - }, - { - "end": 64, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 54, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 61, - "start": 55, - "type": "REQUEST_EXECUTION" - }, - { - "end": 65, - "start": 62, - "type": "RESPONSE_HANDLING" - } - ], - "title": "dialogflow_v2_generated_documents_import_documents_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.dialogflow_v2.DocumentsClient", - "shortName": "DocumentsClient" - }, - "fullName": "google.cloud.dialogflow_v2.DocumentsClient.import_documents", - "method": { - "fullName": "google.cloud.dialogflow.v2.Documents.ImportDocuments", - "service": { - "fullName": "google.cloud.dialogflow.v2.Documents", - "shortName": "Documents" - }, - "shortName": "ImportDocuments" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.dialogflow_v2.types.ImportDocumentsRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.api_core.operation.Operation", - "shortName": "import_documents" - }, - "description": "Sample for ImportDocuments", - "file": "dialogflow_v2_generated_documents_import_documents_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "dialogflow_v2_generated_Documents_ImportDocuments_sync", - "segments": [ - { - "end": 64, - "start": 27, - "type": "FULL" - }, - { - "end": 64, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 54, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 61, - "start": 55, - "type": "REQUEST_EXECUTION" - }, - { - "end": 65, - "start": 62, - "type": "RESPONSE_HANDLING" - } - ], - "title": "dialogflow_v2_generated_documents_import_documents_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.dialogflow_v2.DocumentsAsyncClient", - "shortName": "DocumentsAsyncClient" - }, - "fullName": "google.cloud.dialogflow_v2.DocumentsAsyncClient.list_documents", - "method": { - "fullName": "google.cloud.dialogflow.v2.Documents.ListDocuments", - "service": { - "fullName": "google.cloud.dialogflow.v2.Documents", - "shortName": "Documents" - }, - "shortName": "ListDocuments" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.dialogflow_v2.types.ListDocumentsRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.dialogflow_v2.services.documents.pagers.ListDocumentsAsyncPager", - "shortName": "list_documents" - }, - "description": "Sample for ListDocuments", - "file": "dialogflow_v2_generated_documents_list_documents_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "dialogflow_v2_generated_Documents_ListDocuments_async", - "segments": [ - { - "end": 52, - "start": 27, - "type": "FULL" - }, - { - "end": 52, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 48, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 53, - "start": 49, - "type": "RESPONSE_HANDLING" - } - ], - "title": "dialogflow_v2_generated_documents_list_documents_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.dialogflow_v2.DocumentsClient", - "shortName": "DocumentsClient" - }, - "fullName": "google.cloud.dialogflow_v2.DocumentsClient.list_documents", - "method": { - "fullName": "google.cloud.dialogflow.v2.Documents.ListDocuments", - "service": { - "fullName": "google.cloud.dialogflow.v2.Documents", - "shortName": "Documents" - }, - "shortName": "ListDocuments" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.dialogflow_v2.types.ListDocumentsRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.dialogflow_v2.services.documents.pagers.ListDocumentsPager", - "shortName": "list_documents" - }, - "description": "Sample for ListDocuments", - "file": "dialogflow_v2_generated_documents_list_documents_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "dialogflow_v2_generated_Documents_ListDocuments_sync", - "segments": [ - { - "end": 52, - "start": 27, - "type": "FULL" - }, - { - "end": 52, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 48, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 53, - "start": 49, - "type": "RESPONSE_HANDLING" - } - ], - "title": "dialogflow_v2_generated_documents_list_documents_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.dialogflow_v2.DocumentsAsyncClient", - "shortName": "DocumentsAsyncClient" - }, - "fullName": "google.cloud.dialogflow_v2.DocumentsAsyncClient.reload_document", - "method": { - "fullName": "google.cloud.dialogflow.v2.Documents.ReloadDocument", - "service": { - "fullName": "google.cloud.dialogflow.v2.Documents", - "shortName": "Documents" - }, - "shortName": "ReloadDocument" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.dialogflow_v2.types.ReloadDocumentRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "content_uri", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.api_core.operation_async.AsyncOperation", - "shortName": "reload_document" - }, - "description": "Sample for ReloadDocument", - "file": "dialogflow_v2_generated_documents_reload_document_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "dialogflow_v2_generated_Documents_ReloadDocument_async", - "segments": [ - { - "end": 56, - "start": 27, - "type": "FULL" - }, - { - "end": 56, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 46, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 53, - "start": 47, - "type": "REQUEST_EXECUTION" - }, - { - "end": 57, - "start": 54, - "type": "RESPONSE_HANDLING" - } - ], - "title": "dialogflow_v2_generated_documents_reload_document_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.dialogflow_v2.DocumentsClient", - "shortName": "DocumentsClient" - }, - "fullName": "google.cloud.dialogflow_v2.DocumentsClient.reload_document", - "method": { - "fullName": "google.cloud.dialogflow.v2.Documents.ReloadDocument", - "service": { - "fullName": "google.cloud.dialogflow.v2.Documents", - "shortName": "Documents" - }, - "shortName": "ReloadDocument" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.dialogflow_v2.types.ReloadDocumentRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "content_uri", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.api_core.operation.Operation", - "shortName": "reload_document" - }, - "description": "Sample for ReloadDocument", - "file": "dialogflow_v2_generated_documents_reload_document_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "dialogflow_v2_generated_Documents_ReloadDocument_sync", - "segments": [ - { - "end": 56, - "start": 27, - "type": "FULL" - }, - { - "end": 56, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 46, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 53, - "start": 47, - "type": "REQUEST_EXECUTION" - }, - { - "end": 57, - "start": 54, - "type": "RESPONSE_HANDLING" - } - ], - "title": "dialogflow_v2_generated_documents_reload_document_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.dialogflow_v2.DocumentsAsyncClient", - "shortName": "DocumentsAsyncClient" - }, - "fullName": "google.cloud.dialogflow_v2.DocumentsAsyncClient.update_document", - "method": { - "fullName": "google.cloud.dialogflow.v2.Documents.UpdateDocument", - "service": { - "fullName": "google.cloud.dialogflow.v2.Documents", - "shortName": "Documents" - }, - "shortName": "UpdateDocument" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.dialogflow_v2.types.UpdateDocumentRequest" - }, - { - "name": "document", - "type": "google.cloud.dialogflow_v2.types.Document" - }, - { - "name": "update_mask", - "type": "google.protobuf.field_mask_pb2.FieldMask" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.api_core.operation_async.AsyncOperation", - "shortName": "update_document" - }, - "description": "Sample for UpdateDocument", - "file": "dialogflow_v2_generated_documents_update_document_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "dialogflow_v2_generated_Documents_UpdateDocument_async", - "segments": [ - { - "end": 61, - "start": 27, - "type": "FULL" - }, - { - "end": 61, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 51, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 58, - "start": 52, - "type": "REQUEST_EXECUTION" - }, - { - "end": 62, - "start": 59, - "type": "RESPONSE_HANDLING" - } - ], - "title": "dialogflow_v2_generated_documents_update_document_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.dialogflow_v2.DocumentsClient", - "shortName": "DocumentsClient" - }, - "fullName": "google.cloud.dialogflow_v2.DocumentsClient.update_document", - "method": { - "fullName": "google.cloud.dialogflow.v2.Documents.UpdateDocument", - "service": { - "fullName": "google.cloud.dialogflow.v2.Documents", - "shortName": "Documents" - }, - "shortName": "UpdateDocument" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.dialogflow_v2.types.UpdateDocumentRequest" - }, - { - "name": "document", - "type": "google.cloud.dialogflow_v2.types.Document" - }, - { - "name": "update_mask", - "type": "google.protobuf.field_mask_pb2.FieldMask" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.api_core.operation.Operation", - "shortName": "update_document" - }, - "description": "Sample for UpdateDocument", - "file": "dialogflow_v2_generated_documents_update_document_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "dialogflow_v2_generated_Documents_UpdateDocument_sync", - "segments": [ - { - "end": 61, - "start": 27, - "type": "FULL" - }, - { - "end": 61, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 51, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 58, - "start": 52, - "type": "REQUEST_EXECUTION" - }, - { - "end": 62, - "start": 59, - "type": "RESPONSE_HANDLING" - } - ], - "title": "dialogflow_v2_generated_documents_update_document_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.dialogflow_v2.EntityTypesAsyncClient", - "shortName": "EntityTypesAsyncClient" - }, - "fullName": "google.cloud.dialogflow_v2.EntityTypesAsyncClient.batch_create_entities", - "method": { - "fullName": "google.cloud.dialogflow.v2.EntityTypes.BatchCreateEntities", - "service": { - "fullName": "google.cloud.dialogflow.v2.EntityTypes", - "shortName": "EntityTypes" - }, - "shortName": "BatchCreateEntities" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.dialogflow_v2.types.BatchCreateEntitiesRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "entities", - "type": "MutableSequence[google.cloud.dialogflow_v2.types.EntityType.Entity]" - }, - { - "name": "language_code", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.api_core.operation_async.AsyncOperation", - "shortName": "batch_create_entities" - }, - "description": "Sample for BatchCreateEntities", - "file": "dialogflow_v2_generated_entity_types_batch_create_entities_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "dialogflow_v2_generated_EntityTypes_BatchCreateEntities_async", - "segments": [ - { - "end": 60, - "start": 27, - "type": "FULL" - }, - { - "end": 60, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 50, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 57, - "start": 51, - "type": "REQUEST_EXECUTION" - }, - { - "end": 61, - "start": 58, - "type": "RESPONSE_HANDLING" - } - ], - "title": "dialogflow_v2_generated_entity_types_batch_create_entities_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.dialogflow_v2.EntityTypesClient", - "shortName": "EntityTypesClient" - }, - "fullName": "google.cloud.dialogflow_v2.EntityTypesClient.batch_create_entities", - "method": { - "fullName": "google.cloud.dialogflow.v2.EntityTypes.BatchCreateEntities", - "service": { - "fullName": "google.cloud.dialogflow.v2.EntityTypes", - "shortName": "EntityTypes" - }, - "shortName": "BatchCreateEntities" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.dialogflow_v2.types.BatchCreateEntitiesRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "entities", - "type": "MutableSequence[google.cloud.dialogflow_v2.types.EntityType.Entity]" - }, - { - "name": "language_code", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.api_core.operation.Operation", - "shortName": "batch_create_entities" - }, - "description": "Sample for BatchCreateEntities", - "file": "dialogflow_v2_generated_entity_types_batch_create_entities_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "dialogflow_v2_generated_EntityTypes_BatchCreateEntities_sync", - "segments": [ - { - "end": 60, - "start": 27, - "type": "FULL" - }, - { - "end": 60, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 50, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 57, - "start": 51, - "type": "REQUEST_EXECUTION" - }, - { - "end": 61, - "start": 58, - "type": "RESPONSE_HANDLING" - } - ], - "title": "dialogflow_v2_generated_entity_types_batch_create_entities_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.dialogflow_v2.EntityTypesAsyncClient", - "shortName": "EntityTypesAsyncClient" - }, - "fullName": "google.cloud.dialogflow_v2.EntityTypesAsyncClient.batch_delete_entities", - "method": { - "fullName": "google.cloud.dialogflow.v2.EntityTypes.BatchDeleteEntities", - "service": { - "fullName": "google.cloud.dialogflow.v2.EntityTypes", - "shortName": "EntityTypes" - }, - "shortName": "BatchDeleteEntities" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.dialogflow_v2.types.BatchDeleteEntitiesRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "entity_values", - "type": "MutableSequence[str]" - }, - { - "name": "language_code", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.api_core.operation_async.AsyncOperation", - "shortName": "batch_delete_entities" - }, - "description": "Sample for BatchDeleteEntities", - "file": "dialogflow_v2_generated_entity_types_batch_delete_entities_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "dialogflow_v2_generated_EntityTypes_BatchDeleteEntities_async", - "segments": [ - { - "end": 56, - "start": 27, - "type": "FULL" - }, - { - "end": 56, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 46, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 53, - "start": 47, - "type": "REQUEST_EXECUTION" - }, - { - "end": 57, - "start": 54, - "type": "RESPONSE_HANDLING" - } - ], - "title": "dialogflow_v2_generated_entity_types_batch_delete_entities_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.dialogflow_v2.EntityTypesClient", - "shortName": "EntityTypesClient" - }, - "fullName": "google.cloud.dialogflow_v2.EntityTypesClient.batch_delete_entities", - "method": { - "fullName": "google.cloud.dialogflow.v2.EntityTypes.BatchDeleteEntities", - "service": { - "fullName": "google.cloud.dialogflow.v2.EntityTypes", - "shortName": "EntityTypes" - }, - "shortName": "BatchDeleteEntities" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.dialogflow_v2.types.BatchDeleteEntitiesRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "entity_values", - "type": "MutableSequence[str]" - }, - { - "name": "language_code", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.api_core.operation.Operation", - "shortName": "batch_delete_entities" - }, - "description": "Sample for BatchDeleteEntities", - "file": "dialogflow_v2_generated_entity_types_batch_delete_entities_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "dialogflow_v2_generated_EntityTypes_BatchDeleteEntities_sync", - "segments": [ - { - "end": 56, - "start": 27, - "type": "FULL" - }, - { - "end": 56, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 46, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 53, - "start": 47, - "type": "REQUEST_EXECUTION" - }, - { - "end": 57, - "start": 54, - "type": "RESPONSE_HANDLING" - } - ], - "title": "dialogflow_v2_generated_entity_types_batch_delete_entities_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.dialogflow_v2.EntityTypesAsyncClient", - "shortName": "EntityTypesAsyncClient" - }, - "fullName": "google.cloud.dialogflow_v2.EntityTypesAsyncClient.batch_delete_entity_types", - "method": { - "fullName": "google.cloud.dialogflow.v2.EntityTypes.BatchDeleteEntityTypes", - "service": { - "fullName": "google.cloud.dialogflow.v2.EntityTypes", - "shortName": "EntityTypes" - }, - "shortName": "BatchDeleteEntityTypes" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.dialogflow_v2.types.BatchDeleteEntityTypesRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "entity_type_names", - "type": "MutableSequence[str]" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.api_core.operation_async.AsyncOperation", - "shortName": "batch_delete_entity_types" - }, - "description": "Sample for BatchDeleteEntityTypes", - "file": "dialogflow_v2_generated_entity_types_batch_delete_entity_types_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "dialogflow_v2_generated_EntityTypes_BatchDeleteEntityTypes_async", - "segments": [ - { - "end": 56, - "start": 27, - "type": "FULL" - }, - { - "end": 56, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 46, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 53, - "start": 47, - "type": "REQUEST_EXECUTION" - }, - { - "end": 57, - "start": 54, - "type": "RESPONSE_HANDLING" - } - ], - "title": "dialogflow_v2_generated_entity_types_batch_delete_entity_types_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.dialogflow_v2.EntityTypesClient", - "shortName": "EntityTypesClient" - }, - "fullName": "google.cloud.dialogflow_v2.EntityTypesClient.batch_delete_entity_types", - "method": { - "fullName": "google.cloud.dialogflow.v2.EntityTypes.BatchDeleteEntityTypes", - "service": { - "fullName": "google.cloud.dialogflow.v2.EntityTypes", - "shortName": "EntityTypes" - }, - "shortName": "BatchDeleteEntityTypes" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.dialogflow_v2.types.BatchDeleteEntityTypesRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "entity_type_names", - "type": "MutableSequence[str]" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.api_core.operation.Operation", - "shortName": "batch_delete_entity_types" - }, - "description": "Sample for BatchDeleteEntityTypes", - "file": "dialogflow_v2_generated_entity_types_batch_delete_entity_types_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "dialogflow_v2_generated_EntityTypes_BatchDeleteEntityTypes_sync", - "segments": [ - { - "end": 56, - "start": 27, - "type": "FULL" - }, - { - "end": 56, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 46, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 53, - "start": 47, - "type": "REQUEST_EXECUTION" - }, - { - "end": 57, - "start": 54, - "type": "RESPONSE_HANDLING" - } - ], - "title": "dialogflow_v2_generated_entity_types_batch_delete_entity_types_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.dialogflow_v2.EntityTypesAsyncClient", - "shortName": "EntityTypesAsyncClient" - }, - "fullName": "google.cloud.dialogflow_v2.EntityTypesAsyncClient.batch_update_entities", - "method": { - "fullName": "google.cloud.dialogflow.v2.EntityTypes.BatchUpdateEntities", - "service": { - "fullName": "google.cloud.dialogflow.v2.EntityTypes", - "shortName": "EntityTypes" - }, - "shortName": "BatchUpdateEntities" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.dialogflow_v2.types.BatchUpdateEntitiesRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "entities", - "type": "MutableSequence[google.cloud.dialogflow_v2.types.EntityType.Entity]" - }, - { - "name": "language_code", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.api_core.operation_async.AsyncOperation", - "shortName": "batch_update_entities" - }, - "description": "Sample for BatchUpdateEntities", - "file": "dialogflow_v2_generated_entity_types_batch_update_entities_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "dialogflow_v2_generated_EntityTypes_BatchUpdateEntities_async", - "segments": [ - { - "end": 60, - "start": 27, - "type": "FULL" - }, - { - "end": 60, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 50, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 57, - "start": 51, - "type": "REQUEST_EXECUTION" - }, - { - "end": 61, - "start": 58, - "type": "RESPONSE_HANDLING" - } - ], - "title": "dialogflow_v2_generated_entity_types_batch_update_entities_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.dialogflow_v2.EntityTypesClient", - "shortName": "EntityTypesClient" - }, - "fullName": "google.cloud.dialogflow_v2.EntityTypesClient.batch_update_entities", - "method": { - "fullName": "google.cloud.dialogflow.v2.EntityTypes.BatchUpdateEntities", - "service": { - "fullName": "google.cloud.dialogflow.v2.EntityTypes", - "shortName": "EntityTypes" - }, - "shortName": "BatchUpdateEntities" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.dialogflow_v2.types.BatchUpdateEntitiesRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "entities", - "type": "MutableSequence[google.cloud.dialogflow_v2.types.EntityType.Entity]" - }, - { - "name": "language_code", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.api_core.operation.Operation", - "shortName": "batch_update_entities" - }, - "description": "Sample for BatchUpdateEntities", - "file": "dialogflow_v2_generated_entity_types_batch_update_entities_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "dialogflow_v2_generated_EntityTypes_BatchUpdateEntities_sync", - "segments": [ - { - "end": 60, - "start": 27, - "type": "FULL" - }, - { - "end": 60, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 50, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 57, - "start": 51, - "type": "REQUEST_EXECUTION" - }, - { - "end": 61, - "start": 58, - "type": "RESPONSE_HANDLING" - } - ], - "title": "dialogflow_v2_generated_entity_types_batch_update_entities_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.dialogflow_v2.EntityTypesAsyncClient", - "shortName": "EntityTypesAsyncClient" - }, - "fullName": "google.cloud.dialogflow_v2.EntityTypesAsyncClient.batch_update_entity_types", - "method": { - "fullName": "google.cloud.dialogflow.v2.EntityTypes.BatchUpdateEntityTypes", - "service": { - "fullName": "google.cloud.dialogflow.v2.EntityTypes", - "shortName": "EntityTypes" - }, - "shortName": "BatchUpdateEntityTypes" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.dialogflow_v2.types.BatchUpdateEntityTypesRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.api_core.operation_async.AsyncOperation", - "shortName": "batch_update_entity_types" - }, - "description": "Sample for BatchUpdateEntityTypes", - "file": "dialogflow_v2_generated_entity_types_batch_update_entity_types_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "dialogflow_v2_generated_EntityTypes_BatchUpdateEntityTypes_async", - "segments": [ - { - "end": 56, - "start": 27, - "type": "FULL" - }, - { - "end": 56, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 46, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 53, - "start": 47, - "type": "REQUEST_EXECUTION" - }, - { - "end": 57, - "start": 54, - "type": "RESPONSE_HANDLING" - } - ], - "title": "dialogflow_v2_generated_entity_types_batch_update_entity_types_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.dialogflow_v2.EntityTypesClient", - "shortName": "EntityTypesClient" - }, - "fullName": "google.cloud.dialogflow_v2.EntityTypesClient.batch_update_entity_types", - "method": { - "fullName": "google.cloud.dialogflow.v2.EntityTypes.BatchUpdateEntityTypes", - "service": { - "fullName": "google.cloud.dialogflow.v2.EntityTypes", - "shortName": "EntityTypes" - }, - "shortName": "BatchUpdateEntityTypes" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.dialogflow_v2.types.BatchUpdateEntityTypesRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.api_core.operation.Operation", - "shortName": "batch_update_entity_types" - }, - "description": "Sample for BatchUpdateEntityTypes", - "file": "dialogflow_v2_generated_entity_types_batch_update_entity_types_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "dialogflow_v2_generated_EntityTypes_BatchUpdateEntityTypes_sync", - "segments": [ - { - "end": 56, - "start": 27, - "type": "FULL" - }, - { - "end": 56, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 46, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 53, - "start": 47, - "type": "REQUEST_EXECUTION" - }, - { - "end": 57, - "start": 54, - "type": "RESPONSE_HANDLING" - } - ], - "title": "dialogflow_v2_generated_entity_types_batch_update_entity_types_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.dialogflow_v2.EntityTypesAsyncClient", - "shortName": "EntityTypesAsyncClient" - }, - "fullName": "google.cloud.dialogflow_v2.EntityTypesAsyncClient.create_entity_type", - "method": { - "fullName": "google.cloud.dialogflow.v2.EntityTypes.CreateEntityType", - "service": { - "fullName": "google.cloud.dialogflow.v2.EntityTypes", - "shortName": "EntityTypes" - }, - "shortName": "CreateEntityType" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.dialogflow_v2.types.CreateEntityTypeRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "entity_type", - "type": "google.cloud.dialogflow_v2.types.EntityType" - }, - { - "name": "language_code", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.dialogflow_v2.types.EntityType", - "shortName": "create_entity_type" - }, - "description": "Sample for CreateEntityType", - "file": "dialogflow_v2_generated_entity_types_create_entity_type_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "dialogflow_v2_generated_EntityTypes_CreateEntityType_async", - "segments": [ - { - "end": 56, - "start": 27, - "type": "FULL" - }, - { - "end": 56, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 50, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 53, - "start": 51, - "type": "REQUEST_EXECUTION" - }, - { - "end": 57, - "start": 54, - "type": "RESPONSE_HANDLING" - } - ], - "title": "dialogflow_v2_generated_entity_types_create_entity_type_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.dialogflow_v2.EntityTypesClient", - "shortName": "EntityTypesClient" - }, - "fullName": "google.cloud.dialogflow_v2.EntityTypesClient.create_entity_type", - "method": { - "fullName": "google.cloud.dialogflow.v2.EntityTypes.CreateEntityType", - "service": { - "fullName": "google.cloud.dialogflow.v2.EntityTypes", - "shortName": "EntityTypes" - }, - "shortName": "CreateEntityType" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.dialogflow_v2.types.CreateEntityTypeRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "entity_type", - "type": "google.cloud.dialogflow_v2.types.EntityType" - }, - { - "name": "language_code", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.dialogflow_v2.types.EntityType", - "shortName": "create_entity_type" - }, - "description": "Sample for CreateEntityType", - "file": "dialogflow_v2_generated_entity_types_create_entity_type_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "dialogflow_v2_generated_EntityTypes_CreateEntityType_sync", - "segments": [ - { - "end": 56, - "start": 27, - "type": "FULL" - }, - { - "end": 56, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 50, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 53, - "start": 51, - "type": "REQUEST_EXECUTION" - }, - { - "end": 57, - "start": 54, - "type": "RESPONSE_HANDLING" - } - ], - "title": "dialogflow_v2_generated_entity_types_create_entity_type_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.dialogflow_v2.EntityTypesAsyncClient", - "shortName": "EntityTypesAsyncClient" - }, - "fullName": "google.cloud.dialogflow_v2.EntityTypesAsyncClient.delete_entity_type", - "method": { - "fullName": "google.cloud.dialogflow.v2.EntityTypes.DeleteEntityType", - "service": { - "fullName": "google.cloud.dialogflow.v2.EntityTypes", - "shortName": "EntityTypes" - }, - "shortName": "DeleteEntityType" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.dialogflow_v2.types.DeleteEntityTypeRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "shortName": "delete_entity_type" - }, - "description": "Sample for DeleteEntityType", - "file": "dialogflow_v2_generated_entity_types_delete_entity_type_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "dialogflow_v2_generated_EntityTypes_DeleteEntityType_async", - "segments": [ - { - "end": 49, - "start": 27, - "type": "FULL" - }, - { - "end": 49, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 50, - "type": "RESPONSE_HANDLING" - } - ], - "title": "dialogflow_v2_generated_entity_types_delete_entity_type_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.dialogflow_v2.EntityTypesClient", - "shortName": "EntityTypesClient" - }, - "fullName": "google.cloud.dialogflow_v2.EntityTypesClient.delete_entity_type", - "method": { - "fullName": "google.cloud.dialogflow.v2.EntityTypes.DeleteEntityType", - "service": { - "fullName": "google.cloud.dialogflow.v2.EntityTypes", - "shortName": "EntityTypes" - }, - "shortName": "DeleteEntityType" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.dialogflow_v2.types.DeleteEntityTypeRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "shortName": "delete_entity_type" - }, - "description": "Sample for DeleteEntityType", - "file": "dialogflow_v2_generated_entity_types_delete_entity_type_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "dialogflow_v2_generated_EntityTypes_DeleteEntityType_sync", - "segments": [ - { - "end": 49, - "start": 27, - "type": "FULL" - }, - { - "end": 49, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 50, - "type": "RESPONSE_HANDLING" - } - ], - "title": "dialogflow_v2_generated_entity_types_delete_entity_type_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.dialogflow_v2.EntityTypesAsyncClient", - "shortName": "EntityTypesAsyncClient" - }, - "fullName": "google.cloud.dialogflow_v2.EntityTypesAsyncClient.get_entity_type", - "method": { - "fullName": "google.cloud.dialogflow.v2.EntityTypes.GetEntityType", - "service": { - "fullName": "google.cloud.dialogflow.v2.EntityTypes", - "shortName": "EntityTypes" - }, - "shortName": "GetEntityType" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.dialogflow_v2.types.GetEntityTypeRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "language_code", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.dialogflow_v2.types.EntityType", - "shortName": "get_entity_type" - }, - "description": "Sample for GetEntityType", - "file": "dialogflow_v2_generated_entity_types_get_entity_type_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "dialogflow_v2_generated_EntityTypes_GetEntityType_async", - "segments": [ - { - "end": 51, - "start": 27, - "type": "FULL" - }, - { - "end": 51, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 48, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 52, - "start": 49, - "type": "RESPONSE_HANDLING" - } - ], - "title": "dialogflow_v2_generated_entity_types_get_entity_type_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.dialogflow_v2.EntityTypesClient", - "shortName": "EntityTypesClient" - }, - "fullName": "google.cloud.dialogflow_v2.EntityTypesClient.get_entity_type", - "method": { - "fullName": "google.cloud.dialogflow.v2.EntityTypes.GetEntityType", - "service": { - "fullName": "google.cloud.dialogflow.v2.EntityTypes", - "shortName": "EntityTypes" - }, - "shortName": "GetEntityType" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.dialogflow_v2.types.GetEntityTypeRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "language_code", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.dialogflow_v2.types.EntityType", - "shortName": "get_entity_type" - }, - "description": "Sample for GetEntityType", - "file": "dialogflow_v2_generated_entity_types_get_entity_type_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "dialogflow_v2_generated_EntityTypes_GetEntityType_sync", - "segments": [ - { - "end": 51, - "start": 27, - "type": "FULL" - }, - { - "end": 51, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 48, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 52, - "start": 49, - "type": "RESPONSE_HANDLING" - } - ], - "title": "dialogflow_v2_generated_entity_types_get_entity_type_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.dialogflow_v2.EntityTypesAsyncClient", - "shortName": "EntityTypesAsyncClient" - }, - "fullName": "google.cloud.dialogflow_v2.EntityTypesAsyncClient.list_entity_types", - "method": { - "fullName": "google.cloud.dialogflow.v2.EntityTypes.ListEntityTypes", - "service": { - "fullName": "google.cloud.dialogflow.v2.EntityTypes", - "shortName": "EntityTypes" - }, - "shortName": "ListEntityTypes" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.dialogflow_v2.types.ListEntityTypesRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "language_code", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.dialogflow_v2.services.entity_types.pagers.ListEntityTypesAsyncPager", - "shortName": "list_entity_types" - }, - "description": "Sample for ListEntityTypes", - "file": "dialogflow_v2_generated_entity_types_list_entity_types_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "dialogflow_v2_generated_EntityTypes_ListEntityTypes_async", - "segments": [ - { - "end": 52, - "start": 27, - "type": "FULL" - }, - { - "end": 52, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 48, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 53, - "start": 49, - "type": "RESPONSE_HANDLING" - } - ], - "title": "dialogflow_v2_generated_entity_types_list_entity_types_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.dialogflow_v2.EntityTypesClient", - "shortName": "EntityTypesClient" - }, - "fullName": "google.cloud.dialogflow_v2.EntityTypesClient.list_entity_types", - "method": { - "fullName": "google.cloud.dialogflow.v2.EntityTypes.ListEntityTypes", - "service": { - "fullName": "google.cloud.dialogflow.v2.EntityTypes", - "shortName": "EntityTypes" - }, - "shortName": "ListEntityTypes" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.dialogflow_v2.types.ListEntityTypesRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "language_code", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.dialogflow_v2.services.entity_types.pagers.ListEntityTypesPager", - "shortName": "list_entity_types" - }, - "description": "Sample for ListEntityTypes", - "file": "dialogflow_v2_generated_entity_types_list_entity_types_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "dialogflow_v2_generated_EntityTypes_ListEntityTypes_sync", - "segments": [ - { - "end": 52, - "start": 27, - "type": "FULL" - }, - { - "end": 52, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 48, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 53, - "start": 49, - "type": "RESPONSE_HANDLING" - } - ], - "title": "dialogflow_v2_generated_entity_types_list_entity_types_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.dialogflow_v2.EntityTypesAsyncClient", - "shortName": "EntityTypesAsyncClient" - }, - "fullName": "google.cloud.dialogflow_v2.EntityTypesAsyncClient.update_entity_type", - "method": { - "fullName": "google.cloud.dialogflow.v2.EntityTypes.UpdateEntityType", - "service": { - "fullName": "google.cloud.dialogflow.v2.EntityTypes", - "shortName": "EntityTypes" - }, - "shortName": "UpdateEntityType" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.dialogflow_v2.types.UpdateEntityTypeRequest" - }, - { - "name": "entity_type", - "type": "google.cloud.dialogflow_v2.types.EntityType" - }, - { - "name": "language_code", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.dialogflow_v2.types.EntityType", - "shortName": "update_entity_type" - }, - "description": "Sample for UpdateEntityType", - "file": "dialogflow_v2_generated_entity_types_update_entity_type_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "dialogflow_v2_generated_EntityTypes_UpdateEntityType_async", - "segments": [ - { - "end": 55, - "start": 27, - "type": "FULL" - }, - { - "end": 55, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 49, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 52, - "start": 50, - "type": "REQUEST_EXECUTION" - }, - { - "end": 56, - "start": 53, - "type": "RESPONSE_HANDLING" - } - ], - "title": "dialogflow_v2_generated_entity_types_update_entity_type_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.dialogflow_v2.EntityTypesClient", - "shortName": "EntityTypesClient" - }, - "fullName": "google.cloud.dialogflow_v2.EntityTypesClient.update_entity_type", - "method": { - "fullName": "google.cloud.dialogflow.v2.EntityTypes.UpdateEntityType", - "service": { - "fullName": "google.cloud.dialogflow.v2.EntityTypes", - "shortName": "EntityTypes" - }, - "shortName": "UpdateEntityType" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.dialogflow_v2.types.UpdateEntityTypeRequest" - }, - { - "name": "entity_type", - "type": "google.cloud.dialogflow_v2.types.EntityType" - }, - { - "name": "language_code", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.dialogflow_v2.types.EntityType", - "shortName": "update_entity_type" - }, - "description": "Sample for UpdateEntityType", - "file": "dialogflow_v2_generated_entity_types_update_entity_type_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "dialogflow_v2_generated_EntityTypes_UpdateEntityType_sync", - "segments": [ - { - "end": 55, - "start": 27, - "type": "FULL" - }, - { - "end": 55, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 49, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 52, - "start": 50, - "type": "REQUEST_EXECUTION" - }, - { - "end": 56, - "start": 53, - "type": "RESPONSE_HANDLING" - } - ], - "title": "dialogflow_v2_generated_entity_types_update_entity_type_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.dialogflow_v2.EnvironmentsAsyncClient", - "shortName": "EnvironmentsAsyncClient" - }, - "fullName": "google.cloud.dialogflow_v2.EnvironmentsAsyncClient.create_environment", - "method": { - "fullName": "google.cloud.dialogflow.v2.Environments.CreateEnvironment", - "service": { - "fullName": "google.cloud.dialogflow.v2.Environments", - "shortName": "Environments" - }, - "shortName": "CreateEnvironment" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.dialogflow_v2.types.CreateEnvironmentRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.dialogflow_v2.types.Environment", - "shortName": "create_environment" - }, - "description": "Sample for CreateEnvironment", - "file": "dialogflow_v2_generated_environments_create_environment_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "dialogflow_v2_generated_Environments_CreateEnvironment_async", - "segments": [ - { - "end": 52, - "start": 27, - "type": "FULL" - }, - { - "end": 52, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 46, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 49, - "start": 47, - "type": "REQUEST_EXECUTION" - }, - { - "end": 53, - "start": 50, - "type": "RESPONSE_HANDLING" - } - ], - "title": "dialogflow_v2_generated_environments_create_environment_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.dialogflow_v2.EnvironmentsClient", - "shortName": "EnvironmentsClient" - }, - "fullName": "google.cloud.dialogflow_v2.EnvironmentsClient.create_environment", - "method": { - "fullName": "google.cloud.dialogflow.v2.Environments.CreateEnvironment", - "service": { - "fullName": "google.cloud.dialogflow.v2.Environments", - "shortName": "Environments" - }, - "shortName": "CreateEnvironment" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.dialogflow_v2.types.CreateEnvironmentRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.dialogflow_v2.types.Environment", - "shortName": "create_environment" - }, - "description": "Sample for CreateEnvironment", - "file": "dialogflow_v2_generated_environments_create_environment_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "dialogflow_v2_generated_Environments_CreateEnvironment_sync", - "segments": [ - { - "end": 52, - "start": 27, - "type": "FULL" - }, - { - "end": 52, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 46, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 49, - "start": 47, - "type": "REQUEST_EXECUTION" - }, - { - "end": 53, - "start": 50, - "type": "RESPONSE_HANDLING" - } - ], - "title": "dialogflow_v2_generated_environments_create_environment_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.dialogflow_v2.EnvironmentsAsyncClient", - "shortName": "EnvironmentsAsyncClient" - }, - "fullName": "google.cloud.dialogflow_v2.EnvironmentsAsyncClient.delete_environment", - "method": { - "fullName": "google.cloud.dialogflow.v2.Environments.DeleteEnvironment", - "service": { - "fullName": "google.cloud.dialogflow.v2.Environments", - "shortName": "Environments" - }, - "shortName": "DeleteEnvironment" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.dialogflow_v2.types.DeleteEnvironmentRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "shortName": "delete_environment" - }, - "description": "Sample for DeleteEnvironment", - "file": "dialogflow_v2_generated_environments_delete_environment_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "dialogflow_v2_generated_Environments_DeleteEnvironment_async", - "segments": [ - { - "end": 49, - "start": 27, - "type": "FULL" - }, - { - "end": 49, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 50, - "type": "RESPONSE_HANDLING" - } - ], - "title": "dialogflow_v2_generated_environments_delete_environment_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.dialogflow_v2.EnvironmentsClient", - "shortName": "EnvironmentsClient" - }, - "fullName": "google.cloud.dialogflow_v2.EnvironmentsClient.delete_environment", - "method": { - "fullName": "google.cloud.dialogflow.v2.Environments.DeleteEnvironment", - "service": { - "fullName": "google.cloud.dialogflow.v2.Environments", - "shortName": "Environments" - }, - "shortName": "DeleteEnvironment" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.dialogflow_v2.types.DeleteEnvironmentRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "shortName": "delete_environment" - }, - "description": "Sample for DeleteEnvironment", - "file": "dialogflow_v2_generated_environments_delete_environment_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "dialogflow_v2_generated_Environments_DeleteEnvironment_sync", - "segments": [ - { - "end": 49, - "start": 27, - "type": "FULL" - }, - { - "end": 49, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 50, - "type": "RESPONSE_HANDLING" - } - ], - "title": "dialogflow_v2_generated_environments_delete_environment_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.dialogflow_v2.EnvironmentsAsyncClient", - "shortName": "EnvironmentsAsyncClient" - }, - "fullName": "google.cloud.dialogflow_v2.EnvironmentsAsyncClient.get_environment_history", - "method": { - "fullName": "google.cloud.dialogflow.v2.Environments.GetEnvironmentHistory", - "service": { - "fullName": "google.cloud.dialogflow.v2.Environments", - "shortName": "Environments" - }, - "shortName": "GetEnvironmentHistory" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.dialogflow_v2.types.GetEnvironmentHistoryRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.dialogflow_v2.services.environments.pagers.GetEnvironmentHistoryAsyncPager", - "shortName": "get_environment_history" - }, - "description": "Sample for GetEnvironmentHistory", - "file": "dialogflow_v2_generated_environments_get_environment_history_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "dialogflow_v2_generated_Environments_GetEnvironmentHistory_async", - "segments": [ - { - "end": 52, - "start": 27, - "type": "FULL" - }, - { - "end": 52, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 48, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 53, - "start": 49, - "type": "RESPONSE_HANDLING" - } - ], - "title": "dialogflow_v2_generated_environments_get_environment_history_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.dialogflow_v2.EnvironmentsClient", - "shortName": "EnvironmentsClient" - }, - "fullName": "google.cloud.dialogflow_v2.EnvironmentsClient.get_environment_history", - "method": { - "fullName": "google.cloud.dialogflow.v2.Environments.GetEnvironmentHistory", - "service": { - "fullName": "google.cloud.dialogflow.v2.Environments", - "shortName": "Environments" - }, - "shortName": "GetEnvironmentHistory" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.dialogflow_v2.types.GetEnvironmentHistoryRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.dialogflow_v2.services.environments.pagers.GetEnvironmentHistoryPager", - "shortName": "get_environment_history" - }, - "description": "Sample for GetEnvironmentHistory", - "file": "dialogflow_v2_generated_environments_get_environment_history_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "dialogflow_v2_generated_Environments_GetEnvironmentHistory_sync", - "segments": [ - { - "end": 52, - "start": 27, - "type": "FULL" - }, - { - "end": 52, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 48, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 53, - "start": 49, - "type": "RESPONSE_HANDLING" - } - ], - "title": "dialogflow_v2_generated_environments_get_environment_history_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.dialogflow_v2.EnvironmentsAsyncClient", - "shortName": "EnvironmentsAsyncClient" - }, - "fullName": "google.cloud.dialogflow_v2.EnvironmentsAsyncClient.get_environment", - "method": { - "fullName": "google.cloud.dialogflow.v2.Environments.GetEnvironment", - "service": { - "fullName": "google.cloud.dialogflow.v2.Environments", - "shortName": "Environments" - }, - "shortName": "GetEnvironment" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.dialogflow_v2.types.GetEnvironmentRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.dialogflow_v2.types.Environment", - "shortName": "get_environment" - }, - "description": "Sample for GetEnvironment", - "file": "dialogflow_v2_generated_environments_get_environment_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "dialogflow_v2_generated_Environments_GetEnvironment_async", - "segments": [ - { - "end": 51, - "start": 27, - "type": "FULL" - }, - { - "end": 51, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 48, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 52, - "start": 49, - "type": "RESPONSE_HANDLING" - } - ], - "title": "dialogflow_v2_generated_environments_get_environment_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.dialogflow_v2.EnvironmentsClient", - "shortName": "EnvironmentsClient" - }, - "fullName": "google.cloud.dialogflow_v2.EnvironmentsClient.get_environment", - "method": { - "fullName": "google.cloud.dialogflow.v2.Environments.GetEnvironment", - "service": { - "fullName": "google.cloud.dialogflow.v2.Environments", - "shortName": "Environments" - }, - "shortName": "GetEnvironment" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.dialogflow_v2.types.GetEnvironmentRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.dialogflow_v2.types.Environment", - "shortName": "get_environment" - }, - "description": "Sample for GetEnvironment", - "file": "dialogflow_v2_generated_environments_get_environment_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "dialogflow_v2_generated_Environments_GetEnvironment_sync", - "segments": [ - { - "end": 51, - "start": 27, - "type": "FULL" - }, - { - "end": 51, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 48, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 52, - "start": 49, - "type": "RESPONSE_HANDLING" - } - ], - "title": "dialogflow_v2_generated_environments_get_environment_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.dialogflow_v2.EnvironmentsAsyncClient", - "shortName": "EnvironmentsAsyncClient" - }, - "fullName": "google.cloud.dialogflow_v2.EnvironmentsAsyncClient.list_environments", - "method": { - "fullName": "google.cloud.dialogflow.v2.Environments.ListEnvironments", - "service": { - "fullName": "google.cloud.dialogflow.v2.Environments", - "shortName": "Environments" - }, - "shortName": "ListEnvironments" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.dialogflow_v2.types.ListEnvironmentsRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.dialogflow_v2.services.environments.pagers.ListEnvironmentsAsyncPager", - "shortName": "list_environments" - }, - "description": "Sample for ListEnvironments", - "file": "dialogflow_v2_generated_environments_list_environments_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "dialogflow_v2_generated_Environments_ListEnvironments_async", - "segments": [ - { - "end": 52, - "start": 27, - "type": "FULL" - }, - { - "end": 52, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 48, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 53, - "start": 49, - "type": "RESPONSE_HANDLING" - } - ], - "title": "dialogflow_v2_generated_environments_list_environments_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.dialogflow_v2.EnvironmentsClient", - "shortName": "EnvironmentsClient" - }, - "fullName": "google.cloud.dialogflow_v2.EnvironmentsClient.list_environments", - "method": { - "fullName": "google.cloud.dialogflow.v2.Environments.ListEnvironments", - "service": { - "fullName": "google.cloud.dialogflow.v2.Environments", - "shortName": "Environments" - }, - "shortName": "ListEnvironments" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.dialogflow_v2.types.ListEnvironmentsRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.dialogflow_v2.services.environments.pagers.ListEnvironmentsPager", - "shortName": "list_environments" - }, - "description": "Sample for ListEnvironments", - "file": "dialogflow_v2_generated_environments_list_environments_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "dialogflow_v2_generated_Environments_ListEnvironments_sync", - "segments": [ - { - "end": 52, - "start": 27, - "type": "FULL" - }, - { - "end": 52, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 48, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 53, - "start": 49, - "type": "RESPONSE_HANDLING" - } - ], - "title": "dialogflow_v2_generated_environments_list_environments_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.dialogflow_v2.EnvironmentsAsyncClient", - "shortName": "EnvironmentsAsyncClient" - }, - "fullName": "google.cloud.dialogflow_v2.EnvironmentsAsyncClient.update_environment", - "method": { - "fullName": "google.cloud.dialogflow.v2.Environments.UpdateEnvironment", - "service": { - "fullName": "google.cloud.dialogflow.v2.Environments", - "shortName": "Environments" - }, - "shortName": "UpdateEnvironment" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.dialogflow_v2.types.UpdateEnvironmentRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.dialogflow_v2.types.Environment", - "shortName": "update_environment" - }, - "description": "Sample for UpdateEnvironment", - "file": "dialogflow_v2_generated_environments_update_environment_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "dialogflow_v2_generated_Environments_UpdateEnvironment_async", - "segments": [ - { - "end": 50, - "start": 27, - "type": "FULL" - }, - { - "end": 50, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 44, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 47, - "start": 45, - "type": "REQUEST_EXECUTION" - }, - { - "end": 51, - "start": 48, - "type": "RESPONSE_HANDLING" - } - ], - "title": "dialogflow_v2_generated_environments_update_environment_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.dialogflow_v2.EnvironmentsClient", - "shortName": "EnvironmentsClient" - }, - "fullName": "google.cloud.dialogflow_v2.EnvironmentsClient.update_environment", - "method": { - "fullName": "google.cloud.dialogflow.v2.Environments.UpdateEnvironment", - "service": { - "fullName": "google.cloud.dialogflow.v2.Environments", - "shortName": "Environments" - }, - "shortName": "UpdateEnvironment" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.dialogflow_v2.types.UpdateEnvironmentRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.dialogflow_v2.types.Environment", - "shortName": "update_environment" - }, - "description": "Sample for UpdateEnvironment", - "file": "dialogflow_v2_generated_environments_update_environment_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "dialogflow_v2_generated_Environments_UpdateEnvironment_sync", - "segments": [ - { - "end": 50, - "start": 27, - "type": "FULL" - }, - { - "end": 50, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 44, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 47, - "start": 45, - "type": "REQUEST_EXECUTION" - }, - { - "end": 51, - "start": 48, - "type": "RESPONSE_HANDLING" - } - ], - "title": "dialogflow_v2_generated_environments_update_environment_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.dialogflow_v2.FulfillmentsAsyncClient", - "shortName": "FulfillmentsAsyncClient" - }, - "fullName": "google.cloud.dialogflow_v2.FulfillmentsAsyncClient.get_fulfillment", - "method": { - "fullName": "google.cloud.dialogflow.v2.Fulfillments.GetFulfillment", - "service": { - "fullName": "google.cloud.dialogflow.v2.Fulfillments", - "shortName": "Fulfillments" - }, - "shortName": "GetFulfillment" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.dialogflow_v2.types.GetFulfillmentRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.dialogflow_v2.types.Fulfillment", - "shortName": "get_fulfillment" - }, - "description": "Sample for GetFulfillment", - "file": "dialogflow_v2_generated_fulfillments_get_fulfillment_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "dialogflow_v2_generated_Fulfillments_GetFulfillment_async", - "segments": [ - { - "end": 51, - "start": 27, - "type": "FULL" - }, - { - "end": 51, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 48, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 52, - "start": 49, - "type": "RESPONSE_HANDLING" - } - ], - "title": "dialogflow_v2_generated_fulfillments_get_fulfillment_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.dialogflow_v2.FulfillmentsClient", - "shortName": "FulfillmentsClient" - }, - "fullName": "google.cloud.dialogflow_v2.FulfillmentsClient.get_fulfillment", - "method": { - "fullName": "google.cloud.dialogflow.v2.Fulfillments.GetFulfillment", - "service": { - "fullName": "google.cloud.dialogflow.v2.Fulfillments", - "shortName": "Fulfillments" - }, - "shortName": "GetFulfillment" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.dialogflow_v2.types.GetFulfillmentRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.dialogflow_v2.types.Fulfillment", - "shortName": "get_fulfillment" - }, - "description": "Sample for GetFulfillment", - "file": "dialogflow_v2_generated_fulfillments_get_fulfillment_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "dialogflow_v2_generated_Fulfillments_GetFulfillment_sync", - "segments": [ - { - "end": 51, - "start": 27, - "type": "FULL" - }, - { - "end": 51, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 48, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 52, - "start": 49, - "type": "RESPONSE_HANDLING" - } - ], - "title": "dialogflow_v2_generated_fulfillments_get_fulfillment_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.dialogflow_v2.FulfillmentsAsyncClient", - "shortName": "FulfillmentsAsyncClient" - }, - "fullName": "google.cloud.dialogflow_v2.FulfillmentsAsyncClient.update_fulfillment", - "method": { - "fullName": "google.cloud.dialogflow.v2.Fulfillments.UpdateFulfillment", - "service": { - "fullName": "google.cloud.dialogflow.v2.Fulfillments", - "shortName": "Fulfillments" - }, - "shortName": "UpdateFulfillment" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.dialogflow_v2.types.UpdateFulfillmentRequest" - }, - { - "name": "fulfillment", - "type": "google.cloud.dialogflow_v2.types.Fulfillment" - }, - { - "name": "update_mask", - "type": "google.protobuf.field_mask_pb2.FieldMask" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.dialogflow_v2.types.Fulfillment", - "shortName": "update_fulfillment" - }, - "description": "Sample for UpdateFulfillment", - "file": "dialogflow_v2_generated_fulfillments_update_fulfillment_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "dialogflow_v2_generated_Fulfillments_UpdateFulfillment_async", - "segments": [ - { - "end": 55, - "start": 27, - "type": "FULL" - }, - { - "end": 55, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 49, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 52, - "start": 50, - "type": "REQUEST_EXECUTION" - }, - { - "end": 56, - "start": 53, - "type": "RESPONSE_HANDLING" - } - ], - "title": "dialogflow_v2_generated_fulfillments_update_fulfillment_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.dialogflow_v2.FulfillmentsClient", - "shortName": "FulfillmentsClient" - }, - "fullName": "google.cloud.dialogflow_v2.FulfillmentsClient.update_fulfillment", - "method": { - "fullName": "google.cloud.dialogflow.v2.Fulfillments.UpdateFulfillment", - "service": { - "fullName": "google.cloud.dialogflow.v2.Fulfillments", - "shortName": "Fulfillments" - }, - "shortName": "UpdateFulfillment" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.dialogflow_v2.types.UpdateFulfillmentRequest" - }, - { - "name": "fulfillment", - "type": "google.cloud.dialogflow_v2.types.Fulfillment" - }, - { - "name": "update_mask", - "type": "google.protobuf.field_mask_pb2.FieldMask" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.dialogflow_v2.types.Fulfillment", - "shortName": "update_fulfillment" - }, - "description": "Sample for UpdateFulfillment", - "file": "dialogflow_v2_generated_fulfillments_update_fulfillment_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "dialogflow_v2_generated_Fulfillments_UpdateFulfillment_sync", - "segments": [ - { - "end": 55, - "start": 27, - "type": "FULL" - }, - { - "end": 55, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 49, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 52, - "start": 50, - "type": "REQUEST_EXECUTION" - }, - { - "end": 56, - "start": 53, - "type": "RESPONSE_HANDLING" - } - ], - "title": "dialogflow_v2_generated_fulfillments_update_fulfillment_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.dialogflow_v2.IntentsAsyncClient", - "shortName": "IntentsAsyncClient" - }, - "fullName": "google.cloud.dialogflow_v2.IntentsAsyncClient.batch_delete_intents", - "method": { - "fullName": "google.cloud.dialogflow.v2.Intents.BatchDeleteIntents", - "service": { - "fullName": "google.cloud.dialogflow.v2.Intents", - "shortName": "Intents" - }, - "shortName": "BatchDeleteIntents" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.dialogflow_v2.types.BatchDeleteIntentsRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "intents", - "type": "MutableSequence[google.cloud.dialogflow_v2.types.Intent]" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.api_core.operation_async.AsyncOperation", - "shortName": "batch_delete_intents" - }, - "description": "Sample for BatchDeleteIntents", - "file": "dialogflow_v2_generated_intents_batch_delete_intents_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "dialogflow_v2_generated_Intents_BatchDeleteIntents_async", - "segments": [ - { - "end": 59, - "start": 27, - "type": "FULL" - }, - { - "end": 59, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 49, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 56, - "start": 50, - "type": "REQUEST_EXECUTION" - }, - { - "end": 60, - "start": 57, - "type": "RESPONSE_HANDLING" - } - ], - "title": "dialogflow_v2_generated_intents_batch_delete_intents_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.dialogflow_v2.IntentsClient", - "shortName": "IntentsClient" - }, - "fullName": "google.cloud.dialogflow_v2.IntentsClient.batch_delete_intents", - "method": { - "fullName": "google.cloud.dialogflow.v2.Intents.BatchDeleteIntents", - "service": { - "fullName": "google.cloud.dialogflow.v2.Intents", - "shortName": "Intents" - }, - "shortName": "BatchDeleteIntents" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.dialogflow_v2.types.BatchDeleteIntentsRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "intents", - "type": "MutableSequence[google.cloud.dialogflow_v2.types.Intent]" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.api_core.operation.Operation", - "shortName": "batch_delete_intents" - }, - "description": "Sample for BatchDeleteIntents", - "file": "dialogflow_v2_generated_intents_batch_delete_intents_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "dialogflow_v2_generated_Intents_BatchDeleteIntents_sync", - "segments": [ - { - "end": 59, - "start": 27, - "type": "FULL" - }, - { - "end": 59, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 49, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 56, - "start": 50, - "type": "REQUEST_EXECUTION" - }, - { - "end": 60, - "start": 57, - "type": "RESPONSE_HANDLING" - } - ], - "title": "dialogflow_v2_generated_intents_batch_delete_intents_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.dialogflow_v2.IntentsAsyncClient", - "shortName": "IntentsAsyncClient" - }, - "fullName": "google.cloud.dialogflow_v2.IntentsAsyncClient.batch_update_intents", - "method": { - "fullName": "google.cloud.dialogflow.v2.Intents.BatchUpdateIntents", - "service": { - "fullName": "google.cloud.dialogflow.v2.Intents", - "shortName": "Intents" - }, - "shortName": "BatchUpdateIntents" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.dialogflow_v2.types.BatchUpdateIntentsRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "intent_batch_uri", - "type": "str" - }, - { - "name": "intent_batch_inline", - "type": "google.cloud.dialogflow_v2.types.IntentBatch" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.api_core.operation_async.AsyncOperation", - "shortName": "batch_update_intents" - }, - "description": "Sample for BatchUpdateIntents", - "file": "dialogflow_v2_generated_intents_batch_update_intents_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "dialogflow_v2_generated_Intents_BatchUpdateIntents_async", - "segments": [ - { - "end": 56, - "start": 27, - "type": "FULL" - }, - { - "end": 56, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 46, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 53, - "start": 47, - "type": "REQUEST_EXECUTION" - }, - { - "end": 57, - "start": 54, - "type": "RESPONSE_HANDLING" - } - ], - "title": "dialogflow_v2_generated_intents_batch_update_intents_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.dialogflow_v2.IntentsClient", - "shortName": "IntentsClient" - }, - "fullName": "google.cloud.dialogflow_v2.IntentsClient.batch_update_intents", - "method": { - "fullName": "google.cloud.dialogflow.v2.Intents.BatchUpdateIntents", - "service": { - "fullName": "google.cloud.dialogflow.v2.Intents", - "shortName": "Intents" - }, - "shortName": "BatchUpdateIntents" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.dialogflow_v2.types.BatchUpdateIntentsRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "intent_batch_uri", - "type": "str" - }, - { - "name": "intent_batch_inline", - "type": "google.cloud.dialogflow_v2.types.IntentBatch" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.api_core.operation.Operation", - "shortName": "batch_update_intents" - }, - "description": "Sample for BatchUpdateIntents", - "file": "dialogflow_v2_generated_intents_batch_update_intents_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "dialogflow_v2_generated_Intents_BatchUpdateIntents_sync", - "segments": [ - { - "end": 56, - "start": 27, - "type": "FULL" - }, - { - "end": 56, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 46, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 53, - "start": 47, - "type": "REQUEST_EXECUTION" - }, - { - "end": 57, - "start": 54, - "type": "RESPONSE_HANDLING" - } - ], - "title": "dialogflow_v2_generated_intents_batch_update_intents_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.dialogflow_v2.IntentsAsyncClient", - "shortName": "IntentsAsyncClient" - }, - "fullName": "google.cloud.dialogflow_v2.IntentsAsyncClient.create_intent", - "method": { - "fullName": "google.cloud.dialogflow.v2.Intents.CreateIntent", - "service": { - "fullName": "google.cloud.dialogflow.v2.Intents", - "shortName": "Intents" - }, - "shortName": "CreateIntent" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.dialogflow_v2.types.CreateIntentRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "intent", - "type": "google.cloud.dialogflow_v2.types.Intent" - }, - { - "name": "language_code", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.dialogflow_v2.types.Intent", - "shortName": "create_intent" - }, - "description": "Sample for CreateIntent", - "file": "dialogflow_v2_generated_intents_create_intent_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "dialogflow_v2_generated_Intents_CreateIntent_async", - "segments": [ - { - "end": 55, - "start": 27, - "type": "FULL" - }, - { - "end": 55, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 49, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 52, - "start": 50, - "type": "REQUEST_EXECUTION" - }, - { - "end": 56, - "start": 53, - "type": "RESPONSE_HANDLING" - } - ], - "title": "dialogflow_v2_generated_intents_create_intent_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.dialogflow_v2.IntentsClient", - "shortName": "IntentsClient" - }, - "fullName": "google.cloud.dialogflow_v2.IntentsClient.create_intent", - "method": { - "fullName": "google.cloud.dialogflow.v2.Intents.CreateIntent", - "service": { - "fullName": "google.cloud.dialogflow.v2.Intents", - "shortName": "Intents" - }, - "shortName": "CreateIntent" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.dialogflow_v2.types.CreateIntentRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "intent", - "type": "google.cloud.dialogflow_v2.types.Intent" - }, - { - "name": "language_code", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.dialogflow_v2.types.Intent", - "shortName": "create_intent" - }, - "description": "Sample for CreateIntent", - "file": "dialogflow_v2_generated_intents_create_intent_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "dialogflow_v2_generated_Intents_CreateIntent_sync", - "segments": [ - { - "end": 55, - "start": 27, - "type": "FULL" - }, - { - "end": 55, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 49, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 52, - "start": 50, - "type": "REQUEST_EXECUTION" - }, - { - "end": 56, - "start": 53, - "type": "RESPONSE_HANDLING" - } - ], - "title": "dialogflow_v2_generated_intents_create_intent_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.dialogflow_v2.IntentsAsyncClient", - "shortName": "IntentsAsyncClient" - }, - "fullName": "google.cloud.dialogflow_v2.IntentsAsyncClient.delete_intent", - "method": { - "fullName": "google.cloud.dialogflow.v2.Intents.DeleteIntent", - "service": { - "fullName": "google.cloud.dialogflow.v2.Intents", - "shortName": "Intents" - }, - "shortName": "DeleteIntent" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.dialogflow_v2.types.DeleteIntentRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "shortName": "delete_intent" - }, - "description": "Sample for DeleteIntent", - "file": "dialogflow_v2_generated_intents_delete_intent_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "dialogflow_v2_generated_Intents_DeleteIntent_async", - "segments": [ - { - "end": 49, - "start": 27, - "type": "FULL" - }, - { - "end": 49, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 50, - "type": "RESPONSE_HANDLING" - } - ], - "title": "dialogflow_v2_generated_intents_delete_intent_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.dialogflow_v2.IntentsClient", - "shortName": "IntentsClient" - }, - "fullName": "google.cloud.dialogflow_v2.IntentsClient.delete_intent", - "method": { - "fullName": "google.cloud.dialogflow.v2.Intents.DeleteIntent", - "service": { - "fullName": "google.cloud.dialogflow.v2.Intents", - "shortName": "Intents" - }, - "shortName": "DeleteIntent" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.dialogflow_v2.types.DeleteIntentRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "shortName": "delete_intent" - }, - "description": "Sample for DeleteIntent", - "file": "dialogflow_v2_generated_intents_delete_intent_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "dialogflow_v2_generated_Intents_DeleteIntent_sync", - "segments": [ - { - "end": 49, - "start": 27, - "type": "FULL" - }, - { - "end": 49, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 50, - "type": "RESPONSE_HANDLING" - } - ], - "title": "dialogflow_v2_generated_intents_delete_intent_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.dialogflow_v2.IntentsAsyncClient", - "shortName": "IntentsAsyncClient" - }, - "fullName": "google.cloud.dialogflow_v2.IntentsAsyncClient.get_intent", - "method": { - "fullName": "google.cloud.dialogflow.v2.Intents.GetIntent", - "service": { - "fullName": "google.cloud.dialogflow.v2.Intents", - "shortName": "Intents" - }, - "shortName": "GetIntent" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.dialogflow_v2.types.GetIntentRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "language_code", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.dialogflow_v2.types.Intent", - "shortName": "get_intent" - }, - "description": "Sample for GetIntent", - "file": "dialogflow_v2_generated_intents_get_intent_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "dialogflow_v2_generated_Intents_GetIntent_async", - "segments": [ - { - "end": 51, - "start": 27, - "type": "FULL" - }, - { - "end": 51, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 48, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 52, - "start": 49, - "type": "RESPONSE_HANDLING" - } - ], - "title": "dialogflow_v2_generated_intents_get_intent_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.dialogflow_v2.IntentsClient", - "shortName": "IntentsClient" - }, - "fullName": "google.cloud.dialogflow_v2.IntentsClient.get_intent", - "method": { - "fullName": "google.cloud.dialogflow.v2.Intents.GetIntent", - "service": { - "fullName": "google.cloud.dialogflow.v2.Intents", - "shortName": "Intents" - }, - "shortName": "GetIntent" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.dialogflow_v2.types.GetIntentRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "language_code", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.dialogflow_v2.types.Intent", - "shortName": "get_intent" - }, - "description": "Sample for GetIntent", - "file": "dialogflow_v2_generated_intents_get_intent_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "dialogflow_v2_generated_Intents_GetIntent_sync", - "segments": [ - { - "end": 51, - "start": 27, - "type": "FULL" - }, - { - "end": 51, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 48, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 52, - "start": 49, - "type": "RESPONSE_HANDLING" - } - ], - "title": "dialogflow_v2_generated_intents_get_intent_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.dialogflow_v2.IntentsAsyncClient", - "shortName": "IntentsAsyncClient" - }, - "fullName": "google.cloud.dialogflow_v2.IntentsAsyncClient.list_intents", - "method": { - "fullName": "google.cloud.dialogflow.v2.Intents.ListIntents", - "service": { - "fullName": "google.cloud.dialogflow.v2.Intents", - "shortName": "Intents" - }, - "shortName": "ListIntents" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.dialogflow_v2.types.ListIntentsRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "language_code", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.dialogflow_v2.services.intents.pagers.ListIntentsAsyncPager", - "shortName": "list_intents" - }, - "description": "Sample for ListIntents", - "file": "dialogflow_v2_generated_intents_list_intents_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "dialogflow_v2_generated_Intents_ListIntents_async", - "segments": [ - { - "end": 52, - "start": 27, - "type": "FULL" - }, - { - "end": 52, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 48, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 53, - "start": 49, - "type": "RESPONSE_HANDLING" - } - ], - "title": "dialogflow_v2_generated_intents_list_intents_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.dialogflow_v2.IntentsClient", - "shortName": "IntentsClient" - }, - "fullName": "google.cloud.dialogflow_v2.IntentsClient.list_intents", - "method": { - "fullName": "google.cloud.dialogflow.v2.Intents.ListIntents", - "service": { - "fullName": "google.cloud.dialogflow.v2.Intents", - "shortName": "Intents" - }, - "shortName": "ListIntents" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.dialogflow_v2.types.ListIntentsRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "language_code", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.dialogflow_v2.services.intents.pagers.ListIntentsPager", - "shortName": "list_intents" - }, - "description": "Sample for ListIntents", - "file": "dialogflow_v2_generated_intents_list_intents_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "dialogflow_v2_generated_Intents_ListIntents_sync", - "segments": [ - { - "end": 52, - "start": 27, - "type": "FULL" - }, - { - "end": 52, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 48, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 53, - "start": 49, - "type": "RESPONSE_HANDLING" - } - ], - "title": "dialogflow_v2_generated_intents_list_intents_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.dialogflow_v2.IntentsAsyncClient", - "shortName": "IntentsAsyncClient" - }, - "fullName": "google.cloud.dialogflow_v2.IntentsAsyncClient.update_intent", - "method": { - "fullName": "google.cloud.dialogflow.v2.Intents.UpdateIntent", - "service": { - "fullName": "google.cloud.dialogflow.v2.Intents", - "shortName": "Intents" - }, - "shortName": "UpdateIntent" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.dialogflow_v2.types.UpdateIntentRequest" - }, - { - "name": "intent", - "type": "google.cloud.dialogflow_v2.types.Intent" - }, - { - "name": "language_code", - "type": "str" - }, - { - "name": "update_mask", - "type": "google.protobuf.field_mask_pb2.FieldMask" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.dialogflow_v2.types.Intent", - "shortName": "update_intent" - }, - "description": "Sample for UpdateIntent", - "file": "dialogflow_v2_generated_intents_update_intent_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "dialogflow_v2_generated_Intents_UpdateIntent_async", - "segments": [ - { - "end": 54, - "start": 27, - "type": "FULL" - }, - { - "end": 54, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 48, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 51, - "start": 49, - "type": "REQUEST_EXECUTION" - }, - { - "end": 55, - "start": 52, - "type": "RESPONSE_HANDLING" - } - ], - "title": "dialogflow_v2_generated_intents_update_intent_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.dialogflow_v2.IntentsClient", - "shortName": "IntentsClient" - }, - "fullName": "google.cloud.dialogflow_v2.IntentsClient.update_intent", - "method": { - "fullName": "google.cloud.dialogflow.v2.Intents.UpdateIntent", - "service": { - "fullName": "google.cloud.dialogflow.v2.Intents", - "shortName": "Intents" - }, - "shortName": "UpdateIntent" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.dialogflow_v2.types.UpdateIntentRequest" - }, - { - "name": "intent", - "type": "google.cloud.dialogflow_v2.types.Intent" - }, - { - "name": "language_code", - "type": "str" - }, - { - "name": "update_mask", - "type": "google.protobuf.field_mask_pb2.FieldMask" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.dialogflow_v2.types.Intent", - "shortName": "update_intent" - }, - "description": "Sample for UpdateIntent", - "file": "dialogflow_v2_generated_intents_update_intent_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "dialogflow_v2_generated_Intents_UpdateIntent_sync", - "segments": [ - { - "end": 54, - "start": 27, - "type": "FULL" - }, - { - "end": 54, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 48, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 51, - "start": 49, - "type": "REQUEST_EXECUTION" - }, - { - "end": 55, - "start": 52, - "type": "RESPONSE_HANDLING" - } - ], - "title": "dialogflow_v2_generated_intents_update_intent_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.dialogflow_v2.KnowledgeBasesAsyncClient", - "shortName": "KnowledgeBasesAsyncClient" - }, - "fullName": "google.cloud.dialogflow_v2.KnowledgeBasesAsyncClient.create_knowledge_base", - "method": { - "fullName": "google.cloud.dialogflow.v2.KnowledgeBases.CreateKnowledgeBase", - "service": { - "fullName": "google.cloud.dialogflow.v2.KnowledgeBases", - "shortName": "KnowledgeBases" - }, - "shortName": "CreateKnowledgeBase" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.dialogflow_v2.types.CreateKnowledgeBaseRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "knowledge_base", - "type": "google.cloud.dialogflow_v2.types.KnowledgeBase" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.dialogflow_v2.types.KnowledgeBase", - "shortName": "create_knowledge_base" - }, - "description": "Sample for CreateKnowledgeBase", - "file": "dialogflow_v2_generated_knowledge_bases_create_knowledge_base_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "dialogflow_v2_generated_KnowledgeBases_CreateKnowledgeBase_async", - "segments": [ - { - "end": 55, - "start": 27, - "type": "FULL" - }, - { - "end": 55, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 49, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 52, - "start": 50, - "type": "REQUEST_EXECUTION" - }, - { - "end": 56, - "start": 53, - "type": "RESPONSE_HANDLING" - } - ], - "title": "dialogflow_v2_generated_knowledge_bases_create_knowledge_base_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.dialogflow_v2.KnowledgeBasesClient", - "shortName": "KnowledgeBasesClient" - }, - "fullName": "google.cloud.dialogflow_v2.KnowledgeBasesClient.create_knowledge_base", - "method": { - "fullName": "google.cloud.dialogflow.v2.KnowledgeBases.CreateKnowledgeBase", - "service": { - "fullName": "google.cloud.dialogflow.v2.KnowledgeBases", - "shortName": "KnowledgeBases" - }, - "shortName": "CreateKnowledgeBase" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.dialogflow_v2.types.CreateKnowledgeBaseRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "knowledge_base", - "type": "google.cloud.dialogflow_v2.types.KnowledgeBase" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.dialogflow_v2.types.KnowledgeBase", - "shortName": "create_knowledge_base" - }, - "description": "Sample for CreateKnowledgeBase", - "file": "dialogflow_v2_generated_knowledge_bases_create_knowledge_base_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "dialogflow_v2_generated_KnowledgeBases_CreateKnowledgeBase_sync", - "segments": [ - { - "end": 55, - "start": 27, - "type": "FULL" - }, - { - "end": 55, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 49, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 52, - "start": 50, - "type": "REQUEST_EXECUTION" - }, - { - "end": 56, - "start": 53, - "type": "RESPONSE_HANDLING" - } - ], - "title": "dialogflow_v2_generated_knowledge_bases_create_knowledge_base_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.dialogflow_v2.KnowledgeBasesAsyncClient", - "shortName": "KnowledgeBasesAsyncClient" - }, - "fullName": "google.cloud.dialogflow_v2.KnowledgeBasesAsyncClient.delete_knowledge_base", - "method": { - "fullName": "google.cloud.dialogflow.v2.KnowledgeBases.DeleteKnowledgeBase", - "service": { - "fullName": "google.cloud.dialogflow.v2.KnowledgeBases", - "shortName": "KnowledgeBases" - }, - "shortName": "DeleteKnowledgeBase" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.dialogflow_v2.types.DeleteKnowledgeBaseRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "shortName": "delete_knowledge_base" - }, - "description": "Sample for DeleteKnowledgeBase", - "file": "dialogflow_v2_generated_knowledge_bases_delete_knowledge_base_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "dialogflow_v2_generated_KnowledgeBases_DeleteKnowledgeBase_async", - "segments": [ - { - "end": 49, - "start": 27, - "type": "FULL" - }, - { - "end": 49, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 50, - "type": "RESPONSE_HANDLING" - } - ], - "title": "dialogflow_v2_generated_knowledge_bases_delete_knowledge_base_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.dialogflow_v2.KnowledgeBasesClient", - "shortName": "KnowledgeBasesClient" - }, - "fullName": "google.cloud.dialogflow_v2.KnowledgeBasesClient.delete_knowledge_base", - "method": { - "fullName": "google.cloud.dialogflow.v2.KnowledgeBases.DeleteKnowledgeBase", - "service": { - "fullName": "google.cloud.dialogflow.v2.KnowledgeBases", - "shortName": "KnowledgeBases" - }, - "shortName": "DeleteKnowledgeBase" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.dialogflow_v2.types.DeleteKnowledgeBaseRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "shortName": "delete_knowledge_base" - }, - "description": "Sample for DeleteKnowledgeBase", - "file": "dialogflow_v2_generated_knowledge_bases_delete_knowledge_base_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "dialogflow_v2_generated_KnowledgeBases_DeleteKnowledgeBase_sync", - "segments": [ - { - "end": 49, - "start": 27, - "type": "FULL" - }, - { - "end": 49, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 50, - "type": "RESPONSE_HANDLING" - } - ], - "title": "dialogflow_v2_generated_knowledge_bases_delete_knowledge_base_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.dialogflow_v2.KnowledgeBasesAsyncClient", - "shortName": "KnowledgeBasesAsyncClient" - }, - "fullName": "google.cloud.dialogflow_v2.KnowledgeBasesAsyncClient.get_knowledge_base", - "method": { - "fullName": "google.cloud.dialogflow.v2.KnowledgeBases.GetKnowledgeBase", - "service": { - "fullName": "google.cloud.dialogflow.v2.KnowledgeBases", - "shortName": "KnowledgeBases" - }, - "shortName": "GetKnowledgeBase" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.dialogflow_v2.types.GetKnowledgeBaseRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.dialogflow_v2.types.KnowledgeBase", - "shortName": "get_knowledge_base" - }, - "description": "Sample for GetKnowledgeBase", - "file": "dialogflow_v2_generated_knowledge_bases_get_knowledge_base_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "dialogflow_v2_generated_KnowledgeBases_GetKnowledgeBase_async", - "segments": [ - { - "end": 51, - "start": 27, - "type": "FULL" - }, - { - "end": 51, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 48, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 52, - "start": 49, - "type": "RESPONSE_HANDLING" - } - ], - "title": "dialogflow_v2_generated_knowledge_bases_get_knowledge_base_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.dialogflow_v2.KnowledgeBasesClient", - "shortName": "KnowledgeBasesClient" - }, - "fullName": "google.cloud.dialogflow_v2.KnowledgeBasesClient.get_knowledge_base", - "method": { - "fullName": "google.cloud.dialogflow.v2.KnowledgeBases.GetKnowledgeBase", - "service": { - "fullName": "google.cloud.dialogflow.v2.KnowledgeBases", - "shortName": "KnowledgeBases" - }, - "shortName": "GetKnowledgeBase" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.dialogflow_v2.types.GetKnowledgeBaseRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.dialogflow_v2.types.KnowledgeBase", - "shortName": "get_knowledge_base" - }, - "description": "Sample for GetKnowledgeBase", - "file": "dialogflow_v2_generated_knowledge_bases_get_knowledge_base_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "dialogflow_v2_generated_KnowledgeBases_GetKnowledgeBase_sync", - "segments": [ - { - "end": 51, - "start": 27, - "type": "FULL" - }, - { - "end": 51, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 48, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 52, - "start": 49, - "type": "RESPONSE_HANDLING" - } - ], - "title": "dialogflow_v2_generated_knowledge_bases_get_knowledge_base_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.dialogflow_v2.KnowledgeBasesAsyncClient", - "shortName": "KnowledgeBasesAsyncClient" - }, - "fullName": "google.cloud.dialogflow_v2.KnowledgeBasesAsyncClient.list_knowledge_bases", - "method": { - "fullName": "google.cloud.dialogflow.v2.KnowledgeBases.ListKnowledgeBases", - "service": { - "fullName": "google.cloud.dialogflow.v2.KnowledgeBases", - "shortName": "KnowledgeBases" - }, - "shortName": "ListKnowledgeBases" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.dialogflow_v2.types.ListKnowledgeBasesRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.dialogflow_v2.services.knowledge_bases.pagers.ListKnowledgeBasesAsyncPager", - "shortName": "list_knowledge_bases" - }, - "description": "Sample for ListKnowledgeBases", - "file": "dialogflow_v2_generated_knowledge_bases_list_knowledge_bases_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "dialogflow_v2_generated_KnowledgeBases_ListKnowledgeBases_async", - "segments": [ - { - "end": 52, - "start": 27, - "type": "FULL" - }, - { - "end": 52, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 48, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 53, - "start": 49, - "type": "RESPONSE_HANDLING" - } - ], - "title": "dialogflow_v2_generated_knowledge_bases_list_knowledge_bases_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.dialogflow_v2.KnowledgeBasesClient", - "shortName": "KnowledgeBasesClient" - }, - "fullName": "google.cloud.dialogflow_v2.KnowledgeBasesClient.list_knowledge_bases", - "method": { - "fullName": "google.cloud.dialogflow.v2.KnowledgeBases.ListKnowledgeBases", - "service": { - "fullName": "google.cloud.dialogflow.v2.KnowledgeBases", - "shortName": "KnowledgeBases" - }, - "shortName": "ListKnowledgeBases" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.dialogflow_v2.types.ListKnowledgeBasesRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.dialogflow_v2.services.knowledge_bases.pagers.ListKnowledgeBasesPager", - "shortName": "list_knowledge_bases" - }, - "description": "Sample for ListKnowledgeBases", - "file": "dialogflow_v2_generated_knowledge_bases_list_knowledge_bases_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "dialogflow_v2_generated_KnowledgeBases_ListKnowledgeBases_sync", - "segments": [ - { - "end": 52, - "start": 27, - "type": "FULL" - }, - { - "end": 52, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 48, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 53, - "start": 49, - "type": "RESPONSE_HANDLING" - } - ], - "title": "dialogflow_v2_generated_knowledge_bases_list_knowledge_bases_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.dialogflow_v2.KnowledgeBasesAsyncClient", - "shortName": "KnowledgeBasesAsyncClient" - }, - "fullName": "google.cloud.dialogflow_v2.KnowledgeBasesAsyncClient.update_knowledge_base", - "method": { - "fullName": "google.cloud.dialogflow.v2.KnowledgeBases.UpdateKnowledgeBase", - "service": { - "fullName": "google.cloud.dialogflow.v2.KnowledgeBases", - "shortName": "KnowledgeBases" - }, - "shortName": "UpdateKnowledgeBase" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.dialogflow_v2.types.UpdateKnowledgeBaseRequest" - }, - { - "name": "knowledge_base", - "type": "google.cloud.dialogflow_v2.types.KnowledgeBase" - }, - { - "name": "update_mask", - "type": "google.protobuf.field_mask_pb2.FieldMask" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.dialogflow_v2.types.KnowledgeBase", - "shortName": "update_knowledge_base" - }, - "description": "Sample for UpdateKnowledgeBase", - "file": "dialogflow_v2_generated_knowledge_bases_update_knowledge_base_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "dialogflow_v2_generated_KnowledgeBases_UpdateKnowledgeBase_async", - "segments": [ - { - "end": 54, - "start": 27, - "type": "FULL" - }, - { - "end": 54, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 48, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 51, - "start": 49, - "type": "REQUEST_EXECUTION" - }, - { - "end": 55, - "start": 52, - "type": "RESPONSE_HANDLING" - } - ], - "title": "dialogflow_v2_generated_knowledge_bases_update_knowledge_base_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.dialogflow_v2.KnowledgeBasesClient", - "shortName": "KnowledgeBasesClient" - }, - "fullName": "google.cloud.dialogflow_v2.KnowledgeBasesClient.update_knowledge_base", - "method": { - "fullName": "google.cloud.dialogflow.v2.KnowledgeBases.UpdateKnowledgeBase", - "service": { - "fullName": "google.cloud.dialogflow.v2.KnowledgeBases", - "shortName": "KnowledgeBases" - }, - "shortName": "UpdateKnowledgeBase" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.dialogflow_v2.types.UpdateKnowledgeBaseRequest" - }, - { - "name": "knowledge_base", - "type": "google.cloud.dialogflow_v2.types.KnowledgeBase" - }, - { - "name": "update_mask", - "type": "google.protobuf.field_mask_pb2.FieldMask" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.dialogflow_v2.types.KnowledgeBase", - "shortName": "update_knowledge_base" - }, - "description": "Sample for UpdateKnowledgeBase", - "file": "dialogflow_v2_generated_knowledge_bases_update_knowledge_base_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "dialogflow_v2_generated_KnowledgeBases_UpdateKnowledgeBase_sync", - "segments": [ - { - "end": 54, - "start": 27, - "type": "FULL" - }, - { - "end": 54, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 48, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 51, - "start": 49, - "type": "REQUEST_EXECUTION" - }, - { - "end": 55, - "start": 52, - "type": "RESPONSE_HANDLING" - } - ], - "title": "dialogflow_v2_generated_knowledge_bases_update_knowledge_base_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.dialogflow_v2.ParticipantsAsyncClient", - "shortName": "ParticipantsAsyncClient" - }, - "fullName": "google.cloud.dialogflow_v2.ParticipantsAsyncClient.analyze_content", - "method": { - "fullName": "google.cloud.dialogflow.v2.Participants.AnalyzeContent", - "service": { - "fullName": "google.cloud.dialogflow.v2.Participants", - "shortName": "Participants" - }, - "shortName": "AnalyzeContent" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.dialogflow_v2.types.AnalyzeContentRequest" - }, - { - "name": "participant", - "type": "str" - }, - { - "name": "text_input", - "type": "google.cloud.dialogflow_v2.types.TextInput" - }, - { - "name": "event_input", - "type": "google.cloud.dialogflow_v2.types.EventInput" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.dialogflow_v2.types.AnalyzeContentResponse", - "shortName": "analyze_content" - }, - "description": "Sample for AnalyzeContent", - "file": "dialogflow_v2_generated_participants_analyze_content_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "dialogflow_v2_generated_Participants_AnalyzeContent_async", - "segments": [ - { - "end": 56, - "start": 27, - "type": "FULL" - }, - { - "end": 56, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 50, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 53, - "start": 51, - "type": "REQUEST_EXECUTION" - }, - { - "end": 57, - "start": 54, - "type": "RESPONSE_HANDLING" - } - ], - "title": "dialogflow_v2_generated_participants_analyze_content_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.dialogflow_v2.ParticipantsClient", - "shortName": "ParticipantsClient" - }, - "fullName": "google.cloud.dialogflow_v2.ParticipantsClient.analyze_content", - "method": { - "fullName": "google.cloud.dialogflow.v2.Participants.AnalyzeContent", - "service": { - "fullName": "google.cloud.dialogflow.v2.Participants", - "shortName": "Participants" - }, - "shortName": "AnalyzeContent" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.dialogflow_v2.types.AnalyzeContentRequest" - }, - { - "name": "participant", - "type": "str" - }, - { - "name": "text_input", - "type": "google.cloud.dialogflow_v2.types.TextInput" - }, - { - "name": "event_input", - "type": "google.cloud.dialogflow_v2.types.EventInput" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.dialogflow_v2.types.AnalyzeContentResponse", - "shortName": "analyze_content" - }, - "description": "Sample for AnalyzeContent", - "file": "dialogflow_v2_generated_participants_analyze_content_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "dialogflow_v2_generated_Participants_AnalyzeContent_sync", - "segments": [ - { - "end": 56, - "start": 27, - "type": "FULL" - }, - { - "end": 56, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 50, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 53, - "start": 51, - "type": "REQUEST_EXECUTION" - }, - { - "end": 57, - "start": 54, - "type": "RESPONSE_HANDLING" - } - ], - "title": "dialogflow_v2_generated_participants_analyze_content_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.dialogflow_v2.ParticipantsAsyncClient", - "shortName": "ParticipantsAsyncClient" - }, - "fullName": "google.cloud.dialogflow_v2.ParticipantsAsyncClient.create_participant", - "method": { - "fullName": "google.cloud.dialogflow.v2.Participants.CreateParticipant", - "service": { - "fullName": "google.cloud.dialogflow.v2.Participants", - "shortName": "Participants" - }, - "shortName": "CreateParticipant" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.dialogflow_v2.types.CreateParticipantRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "participant", - "type": "google.cloud.dialogflow_v2.types.Participant" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.dialogflow_v2.types.Participant", - "shortName": "create_participant" - }, - "description": "Sample for CreateParticipant", - "file": "dialogflow_v2_generated_participants_create_participant_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "dialogflow_v2_generated_Participants_CreateParticipant_async", - "segments": [ - { - "end": 51, - "start": 27, - "type": "FULL" - }, - { - "end": 51, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 48, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 52, - "start": 49, - "type": "RESPONSE_HANDLING" - } - ], - "title": "dialogflow_v2_generated_participants_create_participant_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.dialogflow_v2.ParticipantsClient", - "shortName": "ParticipantsClient" - }, - "fullName": "google.cloud.dialogflow_v2.ParticipantsClient.create_participant", - "method": { - "fullName": "google.cloud.dialogflow.v2.Participants.CreateParticipant", - "service": { - "fullName": "google.cloud.dialogflow.v2.Participants", - "shortName": "Participants" - }, - "shortName": "CreateParticipant" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.dialogflow_v2.types.CreateParticipantRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "participant", - "type": "google.cloud.dialogflow_v2.types.Participant" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.dialogflow_v2.types.Participant", - "shortName": "create_participant" - }, - "description": "Sample for CreateParticipant", - "file": "dialogflow_v2_generated_participants_create_participant_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "dialogflow_v2_generated_Participants_CreateParticipant_sync", - "segments": [ - { - "end": 51, - "start": 27, - "type": "FULL" - }, - { - "end": 51, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 48, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 52, - "start": 49, - "type": "RESPONSE_HANDLING" - } - ], - "title": "dialogflow_v2_generated_participants_create_participant_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.dialogflow_v2.ParticipantsAsyncClient", - "shortName": "ParticipantsAsyncClient" - }, - "fullName": "google.cloud.dialogflow_v2.ParticipantsAsyncClient.get_participant", - "method": { - "fullName": "google.cloud.dialogflow.v2.Participants.GetParticipant", - "service": { - "fullName": "google.cloud.dialogflow.v2.Participants", - "shortName": "Participants" - }, - "shortName": "GetParticipant" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.dialogflow_v2.types.GetParticipantRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.dialogflow_v2.types.Participant", - "shortName": "get_participant" - }, - "description": "Sample for GetParticipant", - "file": "dialogflow_v2_generated_participants_get_participant_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "dialogflow_v2_generated_Participants_GetParticipant_async", - "segments": [ - { - "end": 51, - "start": 27, - "type": "FULL" - }, - { - "end": 51, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 48, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 52, - "start": 49, - "type": "RESPONSE_HANDLING" - } - ], - "title": "dialogflow_v2_generated_participants_get_participant_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.dialogflow_v2.ParticipantsClient", - "shortName": "ParticipantsClient" - }, - "fullName": "google.cloud.dialogflow_v2.ParticipantsClient.get_participant", - "method": { - "fullName": "google.cloud.dialogflow.v2.Participants.GetParticipant", - "service": { - "fullName": "google.cloud.dialogflow.v2.Participants", - "shortName": "Participants" - }, - "shortName": "GetParticipant" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.dialogflow_v2.types.GetParticipantRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.dialogflow_v2.types.Participant", - "shortName": "get_participant" - }, - "description": "Sample for GetParticipant", - "file": "dialogflow_v2_generated_participants_get_participant_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "dialogflow_v2_generated_Participants_GetParticipant_sync", - "segments": [ - { - "end": 51, - "start": 27, - "type": "FULL" - }, - { - "end": 51, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 48, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 52, - "start": 49, - "type": "RESPONSE_HANDLING" - } - ], - "title": "dialogflow_v2_generated_participants_get_participant_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.dialogflow_v2.ParticipantsAsyncClient", - "shortName": "ParticipantsAsyncClient" - }, - "fullName": "google.cloud.dialogflow_v2.ParticipantsAsyncClient.list_participants", - "method": { - "fullName": "google.cloud.dialogflow.v2.Participants.ListParticipants", - "service": { - "fullName": "google.cloud.dialogflow.v2.Participants", - "shortName": "Participants" - }, - "shortName": "ListParticipants" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.dialogflow_v2.types.ListParticipantsRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.dialogflow_v2.services.participants.pagers.ListParticipantsAsyncPager", - "shortName": "list_participants" - }, - "description": "Sample for ListParticipants", - "file": "dialogflow_v2_generated_participants_list_participants_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "dialogflow_v2_generated_Participants_ListParticipants_async", - "segments": [ - { - "end": 52, - "start": 27, - "type": "FULL" - }, - { - "end": 52, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 48, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 53, - "start": 49, - "type": "RESPONSE_HANDLING" - } - ], - "title": "dialogflow_v2_generated_participants_list_participants_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.dialogflow_v2.ParticipantsClient", - "shortName": "ParticipantsClient" - }, - "fullName": "google.cloud.dialogflow_v2.ParticipantsClient.list_participants", - "method": { - "fullName": "google.cloud.dialogflow.v2.Participants.ListParticipants", - "service": { - "fullName": "google.cloud.dialogflow.v2.Participants", - "shortName": "Participants" - }, - "shortName": "ListParticipants" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.dialogflow_v2.types.ListParticipantsRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.dialogflow_v2.services.participants.pagers.ListParticipantsPager", - "shortName": "list_participants" - }, - "description": "Sample for ListParticipants", - "file": "dialogflow_v2_generated_participants_list_participants_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "dialogflow_v2_generated_Participants_ListParticipants_sync", - "segments": [ - { - "end": 52, - "start": 27, - "type": "FULL" - }, - { - "end": 52, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 48, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 53, - "start": 49, - "type": "RESPONSE_HANDLING" - } - ], - "title": "dialogflow_v2_generated_participants_list_participants_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.dialogflow_v2.ParticipantsAsyncClient", - "shortName": "ParticipantsAsyncClient" - }, - "fullName": "google.cloud.dialogflow_v2.ParticipantsAsyncClient.streaming_analyze_content", - "method": { - "fullName": "google.cloud.dialogflow.v2.Participants.StreamingAnalyzeContent", - "service": { - "fullName": "google.cloud.dialogflow.v2.Participants", - "shortName": "Participants" - }, - "shortName": "StreamingAnalyzeContent" - }, - "parameters": [ - { - "name": "requests", - "type": "Iterator[google.cloud.dialogflow_v2.types.StreamingAnalyzeContentRequest]" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "Iterable[google.cloud.dialogflow_v2.types.StreamingAnalyzeContentResponse]", - "shortName": "streaming_analyze_content" - }, - "description": "Sample for StreamingAnalyzeContent", - "file": "dialogflow_v2_generated_participants_streaming_analyze_content_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "dialogflow_v2_generated_Participants_StreamingAnalyzeContent_async", - "segments": [ - { - "end": 63, - "start": 27, - "type": "FULL" - }, - { - "end": 63, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 56, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 59, - "start": 57, - "type": "REQUEST_EXECUTION" - }, - { - "end": 64, - "start": 60, - "type": "RESPONSE_HANDLING" - } - ], - "title": "dialogflow_v2_generated_participants_streaming_analyze_content_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.dialogflow_v2.ParticipantsClient", - "shortName": "ParticipantsClient" - }, - "fullName": "google.cloud.dialogflow_v2.ParticipantsClient.streaming_analyze_content", - "method": { - "fullName": "google.cloud.dialogflow.v2.Participants.StreamingAnalyzeContent", - "service": { - "fullName": "google.cloud.dialogflow.v2.Participants", - "shortName": "Participants" - }, - "shortName": "StreamingAnalyzeContent" - }, - "parameters": [ - { - "name": "requests", - "type": "Iterator[google.cloud.dialogflow_v2.types.StreamingAnalyzeContentRequest]" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "Iterable[google.cloud.dialogflow_v2.types.StreamingAnalyzeContentResponse]", - "shortName": "streaming_analyze_content" - }, - "description": "Sample for StreamingAnalyzeContent", - "file": "dialogflow_v2_generated_participants_streaming_analyze_content_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "dialogflow_v2_generated_Participants_StreamingAnalyzeContent_sync", - "segments": [ - { - "end": 63, - "start": 27, - "type": "FULL" - }, - { - "end": 63, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 56, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 59, - "start": 57, - "type": "REQUEST_EXECUTION" - }, - { - "end": 64, - "start": 60, - "type": "RESPONSE_HANDLING" - } - ], - "title": "dialogflow_v2_generated_participants_streaming_analyze_content_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.dialogflow_v2.ParticipantsAsyncClient", - "shortName": "ParticipantsAsyncClient" - }, - "fullName": "google.cloud.dialogflow_v2.ParticipantsAsyncClient.suggest_articles", - "method": { - "fullName": "google.cloud.dialogflow.v2.Participants.SuggestArticles", - "service": { - "fullName": "google.cloud.dialogflow.v2.Participants", - "shortName": "Participants" - }, - "shortName": "SuggestArticles" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.dialogflow_v2.types.SuggestArticlesRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.dialogflow_v2.types.SuggestArticlesResponse", - "shortName": "suggest_articles" - }, - "description": "Sample for SuggestArticles", - "file": "dialogflow_v2_generated_participants_suggest_articles_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "dialogflow_v2_generated_Participants_SuggestArticles_async", - "segments": [ - { - "end": 51, - "start": 27, - "type": "FULL" - }, - { - "end": 51, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 48, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 52, - "start": 49, - "type": "RESPONSE_HANDLING" - } - ], - "title": "dialogflow_v2_generated_participants_suggest_articles_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.dialogflow_v2.ParticipantsClient", - "shortName": "ParticipantsClient" - }, - "fullName": "google.cloud.dialogflow_v2.ParticipantsClient.suggest_articles", - "method": { - "fullName": "google.cloud.dialogflow.v2.Participants.SuggestArticles", - "service": { - "fullName": "google.cloud.dialogflow.v2.Participants", - "shortName": "Participants" - }, - "shortName": "SuggestArticles" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.dialogflow_v2.types.SuggestArticlesRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.dialogflow_v2.types.SuggestArticlesResponse", - "shortName": "suggest_articles" - }, - "description": "Sample for SuggestArticles", - "file": "dialogflow_v2_generated_participants_suggest_articles_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "dialogflow_v2_generated_Participants_SuggestArticles_sync", - "segments": [ - { - "end": 51, - "start": 27, - "type": "FULL" - }, - { - "end": 51, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 48, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 52, - "start": 49, - "type": "RESPONSE_HANDLING" - } - ], - "title": "dialogflow_v2_generated_participants_suggest_articles_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.dialogflow_v2.ParticipantsAsyncClient", - "shortName": "ParticipantsAsyncClient" - }, - "fullName": "google.cloud.dialogflow_v2.ParticipantsAsyncClient.suggest_faq_answers", - "method": { - "fullName": "google.cloud.dialogflow.v2.Participants.SuggestFaqAnswers", - "service": { - "fullName": "google.cloud.dialogflow.v2.Participants", - "shortName": "Participants" - }, - "shortName": "SuggestFaqAnswers" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.dialogflow_v2.types.SuggestFaqAnswersRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.dialogflow_v2.types.SuggestFaqAnswersResponse", - "shortName": "suggest_faq_answers" - }, - "description": "Sample for SuggestFaqAnswers", - "file": "dialogflow_v2_generated_participants_suggest_faq_answers_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "dialogflow_v2_generated_Participants_SuggestFaqAnswers_async", - "segments": [ - { - "end": 51, - "start": 27, - "type": "FULL" - }, - { - "end": 51, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 48, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 52, - "start": 49, - "type": "RESPONSE_HANDLING" - } - ], - "title": "dialogflow_v2_generated_participants_suggest_faq_answers_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.dialogflow_v2.ParticipantsClient", - "shortName": "ParticipantsClient" - }, - "fullName": "google.cloud.dialogflow_v2.ParticipantsClient.suggest_faq_answers", - "method": { - "fullName": "google.cloud.dialogflow.v2.Participants.SuggestFaqAnswers", - "service": { - "fullName": "google.cloud.dialogflow.v2.Participants", - "shortName": "Participants" - }, - "shortName": "SuggestFaqAnswers" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.dialogflow_v2.types.SuggestFaqAnswersRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.dialogflow_v2.types.SuggestFaqAnswersResponse", - "shortName": "suggest_faq_answers" - }, - "description": "Sample for SuggestFaqAnswers", - "file": "dialogflow_v2_generated_participants_suggest_faq_answers_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "dialogflow_v2_generated_Participants_SuggestFaqAnswers_sync", - "segments": [ - { - "end": 51, - "start": 27, - "type": "FULL" - }, - { - "end": 51, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 48, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 52, - "start": 49, - "type": "RESPONSE_HANDLING" - } - ], - "title": "dialogflow_v2_generated_participants_suggest_faq_answers_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.dialogflow_v2.ParticipantsAsyncClient", - "shortName": "ParticipantsAsyncClient" - }, - "fullName": "google.cloud.dialogflow_v2.ParticipantsAsyncClient.suggest_smart_replies", - "method": { - "fullName": "google.cloud.dialogflow.v2.Participants.SuggestSmartReplies", - "service": { - "fullName": "google.cloud.dialogflow.v2.Participants", - "shortName": "Participants" - }, - "shortName": "SuggestSmartReplies" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.dialogflow_v2.types.SuggestSmartRepliesRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.dialogflow_v2.types.SuggestSmartRepliesResponse", - "shortName": "suggest_smart_replies" - }, - "description": "Sample for SuggestSmartReplies", - "file": "dialogflow_v2_generated_participants_suggest_smart_replies_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "dialogflow_v2_generated_Participants_SuggestSmartReplies_async", - "segments": [ - { - "end": 51, - "start": 27, - "type": "FULL" - }, - { - "end": 51, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 48, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 52, - "start": 49, - "type": "RESPONSE_HANDLING" - } - ], - "title": "dialogflow_v2_generated_participants_suggest_smart_replies_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.dialogflow_v2.ParticipantsClient", - "shortName": "ParticipantsClient" - }, - "fullName": "google.cloud.dialogflow_v2.ParticipantsClient.suggest_smart_replies", - "method": { - "fullName": "google.cloud.dialogflow.v2.Participants.SuggestSmartReplies", - "service": { - "fullName": "google.cloud.dialogflow.v2.Participants", - "shortName": "Participants" - }, - "shortName": "SuggestSmartReplies" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.dialogflow_v2.types.SuggestSmartRepliesRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.dialogflow_v2.types.SuggestSmartRepliesResponse", - "shortName": "suggest_smart_replies" - }, - "description": "Sample for SuggestSmartReplies", - "file": "dialogflow_v2_generated_participants_suggest_smart_replies_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "dialogflow_v2_generated_Participants_SuggestSmartReplies_sync", - "segments": [ - { - "end": 51, - "start": 27, - "type": "FULL" - }, - { - "end": 51, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 48, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 52, - "start": 49, - "type": "RESPONSE_HANDLING" - } - ], - "title": "dialogflow_v2_generated_participants_suggest_smart_replies_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.dialogflow_v2.ParticipantsAsyncClient", - "shortName": "ParticipantsAsyncClient" - }, - "fullName": "google.cloud.dialogflow_v2.ParticipantsAsyncClient.update_participant", - "method": { - "fullName": "google.cloud.dialogflow.v2.Participants.UpdateParticipant", - "service": { - "fullName": "google.cloud.dialogflow.v2.Participants", - "shortName": "Participants" - }, - "shortName": "UpdateParticipant" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.dialogflow_v2.types.UpdateParticipantRequest" - }, - { - "name": "participant", - "type": "google.cloud.dialogflow_v2.types.Participant" - }, - { - "name": "update_mask", - "type": "google.protobuf.field_mask_pb2.FieldMask" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.dialogflow_v2.types.Participant", - "shortName": "update_participant" - }, - "description": "Sample for UpdateParticipant", - "file": "dialogflow_v2_generated_participants_update_participant_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "dialogflow_v2_generated_Participants_UpdateParticipant_async", - "segments": [ - { - "end": 50, - "start": 27, - "type": "FULL" - }, - { - "end": 50, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 44, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 47, - "start": 45, - "type": "REQUEST_EXECUTION" - }, - { - "end": 51, - "start": 48, - "type": "RESPONSE_HANDLING" - } - ], - "title": "dialogflow_v2_generated_participants_update_participant_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.dialogflow_v2.ParticipantsClient", - "shortName": "ParticipantsClient" - }, - "fullName": "google.cloud.dialogflow_v2.ParticipantsClient.update_participant", - "method": { - "fullName": "google.cloud.dialogflow.v2.Participants.UpdateParticipant", - "service": { - "fullName": "google.cloud.dialogflow.v2.Participants", - "shortName": "Participants" - }, - "shortName": "UpdateParticipant" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.dialogflow_v2.types.UpdateParticipantRequest" - }, - { - "name": "participant", - "type": "google.cloud.dialogflow_v2.types.Participant" - }, - { - "name": "update_mask", - "type": "google.protobuf.field_mask_pb2.FieldMask" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.dialogflow_v2.types.Participant", - "shortName": "update_participant" - }, - "description": "Sample for UpdateParticipant", - "file": "dialogflow_v2_generated_participants_update_participant_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "dialogflow_v2_generated_Participants_UpdateParticipant_sync", - "segments": [ - { - "end": 50, - "start": 27, - "type": "FULL" - }, - { - "end": 50, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 44, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 47, - "start": 45, - "type": "REQUEST_EXECUTION" - }, - { - "end": 51, - "start": 48, - "type": "RESPONSE_HANDLING" - } - ], - "title": "dialogflow_v2_generated_participants_update_participant_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.dialogflow_v2.SessionEntityTypesAsyncClient", - "shortName": "SessionEntityTypesAsyncClient" - }, - "fullName": "google.cloud.dialogflow_v2.SessionEntityTypesAsyncClient.create_session_entity_type", - "method": { - "fullName": "google.cloud.dialogflow.v2.SessionEntityTypes.CreateSessionEntityType", - "service": { - "fullName": "google.cloud.dialogflow.v2.SessionEntityTypes", - "shortName": "SessionEntityTypes" - }, - "shortName": "CreateSessionEntityType" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.dialogflow_v2.types.CreateSessionEntityTypeRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "session_entity_type", - "type": "google.cloud.dialogflow_v2.types.SessionEntityType" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.dialogflow_v2.types.SessionEntityType", - "shortName": "create_session_entity_type" - }, - "description": "Sample for CreateSessionEntityType", - "file": "dialogflow_v2_generated_session_entity_types_create_session_entity_type_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "dialogflow_v2_generated_SessionEntityTypes_CreateSessionEntityType_async", - "segments": [ - { - "end": 58, - "start": 27, - "type": "FULL" - }, - { - "end": 58, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 52, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 55, - "start": 53, - "type": "REQUEST_EXECUTION" - }, - { - "end": 59, - "start": 56, - "type": "RESPONSE_HANDLING" - } - ], - "title": "dialogflow_v2_generated_session_entity_types_create_session_entity_type_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.dialogflow_v2.SessionEntityTypesClient", - "shortName": "SessionEntityTypesClient" - }, - "fullName": "google.cloud.dialogflow_v2.SessionEntityTypesClient.create_session_entity_type", - "method": { - "fullName": "google.cloud.dialogflow.v2.SessionEntityTypes.CreateSessionEntityType", - "service": { - "fullName": "google.cloud.dialogflow.v2.SessionEntityTypes", - "shortName": "SessionEntityTypes" - }, - "shortName": "CreateSessionEntityType" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.dialogflow_v2.types.CreateSessionEntityTypeRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "session_entity_type", - "type": "google.cloud.dialogflow_v2.types.SessionEntityType" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.dialogflow_v2.types.SessionEntityType", - "shortName": "create_session_entity_type" - }, - "description": "Sample for CreateSessionEntityType", - "file": "dialogflow_v2_generated_session_entity_types_create_session_entity_type_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "dialogflow_v2_generated_SessionEntityTypes_CreateSessionEntityType_sync", - "segments": [ - { - "end": 58, - "start": 27, - "type": "FULL" - }, - { - "end": 58, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 52, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 55, - "start": 53, - "type": "REQUEST_EXECUTION" - }, - { - "end": 59, - "start": 56, - "type": "RESPONSE_HANDLING" - } - ], - "title": "dialogflow_v2_generated_session_entity_types_create_session_entity_type_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.dialogflow_v2.SessionEntityTypesAsyncClient", - "shortName": "SessionEntityTypesAsyncClient" - }, - "fullName": "google.cloud.dialogflow_v2.SessionEntityTypesAsyncClient.delete_session_entity_type", - "method": { - "fullName": "google.cloud.dialogflow.v2.SessionEntityTypes.DeleteSessionEntityType", - "service": { - "fullName": "google.cloud.dialogflow.v2.SessionEntityTypes", - "shortName": "SessionEntityTypes" - }, - "shortName": "DeleteSessionEntityType" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.dialogflow_v2.types.DeleteSessionEntityTypeRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "shortName": "delete_session_entity_type" - }, - "description": "Sample for DeleteSessionEntityType", - "file": "dialogflow_v2_generated_session_entity_types_delete_session_entity_type_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "dialogflow_v2_generated_SessionEntityTypes_DeleteSessionEntityType_async", - "segments": [ - { - "end": 49, - "start": 27, - "type": "FULL" - }, - { - "end": 49, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 50, - "type": "RESPONSE_HANDLING" - } - ], - "title": "dialogflow_v2_generated_session_entity_types_delete_session_entity_type_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.dialogflow_v2.SessionEntityTypesClient", - "shortName": "SessionEntityTypesClient" - }, - "fullName": "google.cloud.dialogflow_v2.SessionEntityTypesClient.delete_session_entity_type", - "method": { - "fullName": "google.cloud.dialogflow.v2.SessionEntityTypes.DeleteSessionEntityType", - "service": { - "fullName": "google.cloud.dialogflow.v2.SessionEntityTypes", - "shortName": "SessionEntityTypes" - }, - "shortName": "DeleteSessionEntityType" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.dialogflow_v2.types.DeleteSessionEntityTypeRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "shortName": "delete_session_entity_type" - }, - "description": "Sample for DeleteSessionEntityType", - "file": "dialogflow_v2_generated_session_entity_types_delete_session_entity_type_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "dialogflow_v2_generated_SessionEntityTypes_DeleteSessionEntityType_sync", - "segments": [ - { - "end": 49, - "start": 27, - "type": "FULL" - }, - { - "end": 49, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 50, - "type": "RESPONSE_HANDLING" - } - ], - "title": "dialogflow_v2_generated_session_entity_types_delete_session_entity_type_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.dialogflow_v2.SessionEntityTypesAsyncClient", - "shortName": "SessionEntityTypesAsyncClient" - }, - "fullName": "google.cloud.dialogflow_v2.SessionEntityTypesAsyncClient.get_session_entity_type", - "method": { - "fullName": "google.cloud.dialogflow.v2.SessionEntityTypes.GetSessionEntityType", - "service": { - "fullName": "google.cloud.dialogflow.v2.SessionEntityTypes", - "shortName": "SessionEntityTypes" - }, - "shortName": "GetSessionEntityType" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.dialogflow_v2.types.GetSessionEntityTypeRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.dialogflow_v2.types.SessionEntityType", - "shortName": "get_session_entity_type" - }, - "description": "Sample for GetSessionEntityType", - "file": "dialogflow_v2_generated_session_entity_types_get_session_entity_type_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "dialogflow_v2_generated_SessionEntityTypes_GetSessionEntityType_async", - "segments": [ - { - "end": 51, - "start": 27, - "type": "FULL" - }, - { - "end": 51, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 48, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 52, - "start": 49, - "type": "RESPONSE_HANDLING" - } - ], - "title": "dialogflow_v2_generated_session_entity_types_get_session_entity_type_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.dialogflow_v2.SessionEntityTypesClient", - "shortName": "SessionEntityTypesClient" - }, - "fullName": "google.cloud.dialogflow_v2.SessionEntityTypesClient.get_session_entity_type", - "method": { - "fullName": "google.cloud.dialogflow.v2.SessionEntityTypes.GetSessionEntityType", - "service": { - "fullName": "google.cloud.dialogflow.v2.SessionEntityTypes", - "shortName": "SessionEntityTypes" - }, - "shortName": "GetSessionEntityType" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.dialogflow_v2.types.GetSessionEntityTypeRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.dialogflow_v2.types.SessionEntityType", - "shortName": "get_session_entity_type" - }, - "description": "Sample for GetSessionEntityType", - "file": "dialogflow_v2_generated_session_entity_types_get_session_entity_type_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "dialogflow_v2_generated_SessionEntityTypes_GetSessionEntityType_sync", - "segments": [ - { - "end": 51, - "start": 27, - "type": "FULL" - }, - { - "end": 51, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 48, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 52, - "start": 49, - "type": "RESPONSE_HANDLING" - } - ], - "title": "dialogflow_v2_generated_session_entity_types_get_session_entity_type_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.dialogflow_v2.SessionEntityTypesAsyncClient", - "shortName": "SessionEntityTypesAsyncClient" - }, - "fullName": "google.cloud.dialogflow_v2.SessionEntityTypesAsyncClient.list_session_entity_types", - "method": { - "fullName": "google.cloud.dialogflow.v2.SessionEntityTypes.ListSessionEntityTypes", - "service": { - "fullName": "google.cloud.dialogflow.v2.SessionEntityTypes", - "shortName": "SessionEntityTypes" - }, - "shortName": "ListSessionEntityTypes" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.dialogflow_v2.types.ListSessionEntityTypesRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.dialogflow_v2.services.session_entity_types.pagers.ListSessionEntityTypesAsyncPager", - "shortName": "list_session_entity_types" - }, - "description": "Sample for ListSessionEntityTypes", - "file": "dialogflow_v2_generated_session_entity_types_list_session_entity_types_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "dialogflow_v2_generated_SessionEntityTypes_ListSessionEntityTypes_async", - "segments": [ - { - "end": 52, - "start": 27, - "type": "FULL" - }, - { - "end": 52, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 48, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 53, - "start": 49, - "type": "RESPONSE_HANDLING" - } - ], - "title": "dialogflow_v2_generated_session_entity_types_list_session_entity_types_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.dialogflow_v2.SessionEntityTypesClient", - "shortName": "SessionEntityTypesClient" - }, - "fullName": "google.cloud.dialogflow_v2.SessionEntityTypesClient.list_session_entity_types", - "method": { - "fullName": "google.cloud.dialogflow.v2.SessionEntityTypes.ListSessionEntityTypes", - "service": { - "fullName": "google.cloud.dialogflow.v2.SessionEntityTypes", - "shortName": "SessionEntityTypes" - }, - "shortName": "ListSessionEntityTypes" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.dialogflow_v2.types.ListSessionEntityTypesRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.dialogflow_v2.services.session_entity_types.pagers.ListSessionEntityTypesPager", - "shortName": "list_session_entity_types" - }, - "description": "Sample for ListSessionEntityTypes", - "file": "dialogflow_v2_generated_session_entity_types_list_session_entity_types_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "dialogflow_v2_generated_SessionEntityTypes_ListSessionEntityTypes_sync", - "segments": [ - { - "end": 52, - "start": 27, - "type": "FULL" - }, - { - "end": 52, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 48, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 53, - "start": 49, - "type": "RESPONSE_HANDLING" - } - ], - "title": "dialogflow_v2_generated_session_entity_types_list_session_entity_types_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.dialogflow_v2.SessionEntityTypesAsyncClient", - "shortName": "SessionEntityTypesAsyncClient" - }, - "fullName": "google.cloud.dialogflow_v2.SessionEntityTypesAsyncClient.update_session_entity_type", - "method": { - "fullName": "google.cloud.dialogflow.v2.SessionEntityTypes.UpdateSessionEntityType", - "service": { - "fullName": "google.cloud.dialogflow.v2.SessionEntityTypes", - "shortName": "SessionEntityTypes" - }, - "shortName": "UpdateSessionEntityType" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.dialogflow_v2.types.UpdateSessionEntityTypeRequest" - }, - { - "name": "session_entity_type", - "type": "google.cloud.dialogflow_v2.types.SessionEntityType" - }, - { - "name": "update_mask", - "type": "google.protobuf.field_mask_pb2.FieldMask" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.dialogflow_v2.types.SessionEntityType", - "shortName": "update_session_entity_type" - }, - "description": "Sample for UpdateSessionEntityType", - "file": "dialogflow_v2_generated_session_entity_types_update_session_entity_type_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "dialogflow_v2_generated_SessionEntityTypes_UpdateSessionEntityType_async", - "segments": [ - { - "end": 57, - "start": 27, - "type": "FULL" - }, - { - "end": 57, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 51, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 54, - "start": 52, - "type": "REQUEST_EXECUTION" - }, - { - "end": 58, - "start": 55, - "type": "RESPONSE_HANDLING" - } - ], - "title": "dialogflow_v2_generated_session_entity_types_update_session_entity_type_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.dialogflow_v2.SessionEntityTypesClient", - "shortName": "SessionEntityTypesClient" - }, - "fullName": "google.cloud.dialogflow_v2.SessionEntityTypesClient.update_session_entity_type", - "method": { - "fullName": "google.cloud.dialogflow.v2.SessionEntityTypes.UpdateSessionEntityType", - "service": { - "fullName": "google.cloud.dialogflow.v2.SessionEntityTypes", - "shortName": "SessionEntityTypes" - }, - "shortName": "UpdateSessionEntityType" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.dialogflow_v2.types.UpdateSessionEntityTypeRequest" - }, - { - "name": "session_entity_type", - "type": "google.cloud.dialogflow_v2.types.SessionEntityType" - }, - { - "name": "update_mask", - "type": "google.protobuf.field_mask_pb2.FieldMask" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.dialogflow_v2.types.SessionEntityType", - "shortName": "update_session_entity_type" - }, - "description": "Sample for UpdateSessionEntityType", - "file": "dialogflow_v2_generated_session_entity_types_update_session_entity_type_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "dialogflow_v2_generated_SessionEntityTypes_UpdateSessionEntityType_sync", - "segments": [ - { - "end": 57, - "start": 27, - "type": "FULL" - }, - { - "end": 57, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 51, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 54, - "start": 52, - "type": "REQUEST_EXECUTION" - }, - { - "end": 58, - "start": 55, - "type": "RESPONSE_HANDLING" - } - ], - "title": "dialogflow_v2_generated_session_entity_types_update_session_entity_type_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.dialogflow_v2.SessionsAsyncClient", - "shortName": "SessionsAsyncClient" - }, - "fullName": "google.cloud.dialogflow_v2.SessionsAsyncClient.detect_intent", - "method": { - "fullName": "google.cloud.dialogflow.v2.Sessions.DetectIntent", - "service": { - "fullName": "google.cloud.dialogflow.v2.Sessions", - "shortName": "Sessions" - }, - "shortName": "DetectIntent" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.dialogflow_v2.types.DetectIntentRequest" - }, - { - "name": "session", - "type": "str" - }, - { - "name": "query_input", - "type": "google.cloud.dialogflow_v2.types.QueryInput" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.dialogflow_v2.types.DetectIntentResponse", - "shortName": "detect_intent" - }, - "description": "Sample for DetectIntent", - "file": "dialogflow_v2_generated_sessions_detect_intent_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "dialogflow_v2_generated_Sessions_DetectIntent_async", - "segments": [ - { - "end": 51, - "start": 27, - "type": "FULL" - }, - { - "end": 51, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 48, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 52, - "start": 49, - "type": "RESPONSE_HANDLING" - } - ], - "title": "dialogflow_v2_generated_sessions_detect_intent_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.dialogflow_v2.SessionsClient", - "shortName": "SessionsClient" - }, - "fullName": "google.cloud.dialogflow_v2.SessionsClient.detect_intent", - "method": { - "fullName": "google.cloud.dialogflow.v2.Sessions.DetectIntent", - "service": { - "fullName": "google.cloud.dialogflow.v2.Sessions", - "shortName": "Sessions" - }, - "shortName": "DetectIntent" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.dialogflow_v2.types.DetectIntentRequest" - }, - { - "name": "session", - "type": "str" - }, - { - "name": "query_input", - "type": "google.cloud.dialogflow_v2.types.QueryInput" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.dialogflow_v2.types.DetectIntentResponse", - "shortName": "detect_intent" - }, - "description": "Sample for DetectIntent", - "file": "dialogflow_v2_generated_sessions_detect_intent_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "dialogflow_v2_generated_Sessions_DetectIntent_sync", - "segments": [ - { - "end": 51, - "start": 27, - "type": "FULL" - }, - { - "end": 51, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 48, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 52, - "start": 49, - "type": "RESPONSE_HANDLING" - } - ], - "title": "dialogflow_v2_generated_sessions_detect_intent_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.dialogflow_v2.SessionsAsyncClient", - "shortName": "SessionsAsyncClient" - }, - "fullName": "google.cloud.dialogflow_v2.SessionsAsyncClient.streaming_detect_intent", - "method": { - "fullName": "google.cloud.dialogflow.v2.Sessions.StreamingDetectIntent", - "service": { - "fullName": "google.cloud.dialogflow.v2.Sessions", - "shortName": "Sessions" - }, - "shortName": "StreamingDetectIntent" - }, - "parameters": [ - { - "name": "requests", - "type": "Iterator[google.cloud.dialogflow_v2.types.StreamingDetectIntentRequest]" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "Iterable[google.cloud.dialogflow_v2.types.StreamingDetectIntentResponse]", - "shortName": "streaming_detect_intent" - }, - "description": "Sample for StreamingDetectIntent", - "file": "dialogflow_v2_generated_sessions_streaming_detect_intent_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "dialogflow_v2_generated_Sessions_StreamingDetectIntent_async", - "segments": [ - { - "end": 62, - "start": 27, - "type": "FULL" - }, - { - "end": 62, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 55, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 58, - "start": 56, - "type": "REQUEST_EXECUTION" - }, - { - "end": 63, - "start": 59, - "type": "RESPONSE_HANDLING" - } - ], - "title": "dialogflow_v2_generated_sessions_streaming_detect_intent_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.dialogflow_v2.SessionsClient", - "shortName": "SessionsClient" - }, - "fullName": "google.cloud.dialogflow_v2.SessionsClient.streaming_detect_intent", - "method": { - "fullName": "google.cloud.dialogflow.v2.Sessions.StreamingDetectIntent", - "service": { - "fullName": "google.cloud.dialogflow.v2.Sessions", - "shortName": "Sessions" - }, - "shortName": "StreamingDetectIntent" - }, - "parameters": [ - { - "name": "requests", - "type": "Iterator[google.cloud.dialogflow_v2.types.StreamingDetectIntentRequest]" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "Iterable[google.cloud.dialogflow_v2.types.StreamingDetectIntentResponse]", - "shortName": "streaming_detect_intent" - }, - "description": "Sample for StreamingDetectIntent", - "file": "dialogflow_v2_generated_sessions_streaming_detect_intent_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "dialogflow_v2_generated_Sessions_StreamingDetectIntent_sync", - "segments": [ - { - "end": 62, - "start": 27, - "type": "FULL" - }, - { - "end": 62, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 55, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 58, - "start": 56, - "type": "REQUEST_EXECUTION" - }, - { - "end": 63, - "start": 59, - "type": "RESPONSE_HANDLING" - } - ], - "title": "dialogflow_v2_generated_sessions_streaming_detect_intent_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.dialogflow_v2.VersionsAsyncClient", - "shortName": "VersionsAsyncClient" - }, - "fullName": "google.cloud.dialogflow_v2.VersionsAsyncClient.create_version", - "method": { - "fullName": "google.cloud.dialogflow.v2.Versions.CreateVersion", - "service": { - "fullName": "google.cloud.dialogflow.v2.Versions", - "shortName": "Versions" - }, - "shortName": "CreateVersion" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.dialogflow_v2.types.CreateVersionRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "version", - "type": "google.cloud.dialogflow_v2.types.Version" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.dialogflow_v2.types.Version", - "shortName": "create_version" - }, - "description": "Sample for CreateVersion", - "file": "dialogflow_v2_generated_versions_create_version_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "dialogflow_v2_generated_Versions_CreateVersion_async", - "segments": [ - { - "end": 51, - "start": 27, - "type": "FULL" - }, - { - "end": 51, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 48, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 52, - "start": 49, - "type": "RESPONSE_HANDLING" - } - ], - "title": "dialogflow_v2_generated_versions_create_version_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.dialogflow_v2.VersionsClient", - "shortName": "VersionsClient" - }, - "fullName": "google.cloud.dialogflow_v2.VersionsClient.create_version", - "method": { - "fullName": "google.cloud.dialogflow.v2.Versions.CreateVersion", - "service": { - "fullName": "google.cloud.dialogflow.v2.Versions", - "shortName": "Versions" - }, - "shortName": "CreateVersion" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.dialogflow_v2.types.CreateVersionRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "version", - "type": "google.cloud.dialogflow_v2.types.Version" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.dialogflow_v2.types.Version", - "shortName": "create_version" - }, - "description": "Sample for CreateVersion", - "file": "dialogflow_v2_generated_versions_create_version_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "dialogflow_v2_generated_Versions_CreateVersion_sync", - "segments": [ - { - "end": 51, - "start": 27, - "type": "FULL" - }, - { - "end": 51, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 48, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 52, - "start": 49, - "type": "RESPONSE_HANDLING" - } - ], - "title": "dialogflow_v2_generated_versions_create_version_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.dialogflow_v2.VersionsAsyncClient", - "shortName": "VersionsAsyncClient" - }, - "fullName": "google.cloud.dialogflow_v2.VersionsAsyncClient.delete_version", - "method": { - "fullName": "google.cloud.dialogflow.v2.Versions.DeleteVersion", - "service": { - "fullName": "google.cloud.dialogflow.v2.Versions", - "shortName": "Versions" - }, - "shortName": "DeleteVersion" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.dialogflow_v2.types.DeleteVersionRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "shortName": "delete_version" - }, - "description": "Sample for DeleteVersion", - "file": "dialogflow_v2_generated_versions_delete_version_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "dialogflow_v2_generated_Versions_DeleteVersion_async", - "segments": [ - { - "end": 49, - "start": 27, - "type": "FULL" - }, - { - "end": 49, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 50, - "type": "RESPONSE_HANDLING" - } - ], - "title": "dialogflow_v2_generated_versions_delete_version_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.dialogflow_v2.VersionsClient", - "shortName": "VersionsClient" - }, - "fullName": "google.cloud.dialogflow_v2.VersionsClient.delete_version", - "method": { - "fullName": "google.cloud.dialogflow.v2.Versions.DeleteVersion", - "service": { - "fullName": "google.cloud.dialogflow.v2.Versions", - "shortName": "Versions" - }, - "shortName": "DeleteVersion" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.dialogflow_v2.types.DeleteVersionRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "shortName": "delete_version" - }, - "description": "Sample for DeleteVersion", - "file": "dialogflow_v2_generated_versions_delete_version_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "dialogflow_v2_generated_Versions_DeleteVersion_sync", - "segments": [ - { - "end": 49, - "start": 27, - "type": "FULL" - }, - { - "end": 49, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 50, - "type": "RESPONSE_HANDLING" - } - ], - "title": "dialogflow_v2_generated_versions_delete_version_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.dialogflow_v2.VersionsAsyncClient", - "shortName": "VersionsAsyncClient" - }, - "fullName": "google.cloud.dialogflow_v2.VersionsAsyncClient.get_version", - "method": { - "fullName": "google.cloud.dialogflow.v2.Versions.GetVersion", - "service": { - "fullName": "google.cloud.dialogflow.v2.Versions", - "shortName": "Versions" - }, - "shortName": "GetVersion" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.dialogflow_v2.types.GetVersionRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.dialogflow_v2.types.Version", - "shortName": "get_version" - }, - "description": "Sample for GetVersion", - "file": "dialogflow_v2_generated_versions_get_version_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "dialogflow_v2_generated_Versions_GetVersion_async", - "segments": [ - { - "end": 51, - "start": 27, - "type": "FULL" - }, - { - "end": 51, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 48, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 52, - "start": 49, - "type": "RESPONSE_HANDLING" - } - ], - "title": "dialogflow_v2_generated_versions_get_version_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.dialogflow_v2.VersionsClient", - "shortName": "VersionsClient" - }, - "fullName": "google.cloud.dialogflow_v2.VersionsClient.get_version", - "method": { - "fullName": "google.cloud.dialogflow.v2.Versions.GetVersion", - "service": { - "fullName": "google.cloud.dialogflow.v2.Versions", - "shortName": "Versions" - }, - "shortName": "GetVersion" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.dialogflow_v2.types.GetVersionRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.dialogflow_v2.types.Version", - "shortName": "get_version" - }, - "description": "Sample for GetVersion", - "file": "dialogflow_v2_generated_versions_get_version_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "dialogflow_v2_generated_Versions_GetVersion_sync", - "segments": [ - { - "end": 51, - "start": 27, - "type": "FULL" - }, - { - "end": 51, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 48, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 52, - "start": 49, - "type": "RESPONSE_HANDLING" - } - ], - "title": "dialogflow_v2_generated_versions_get_version_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.dialogflow_v2.VersionsAsyncClient", - "shortName": "VersionsAsyncClient" - }, - "fullName": "google.cloud.dialogflow_v2.VersionsAsyncClient.list_versions", - "method": { - "fullName": "google.cloud.dialogflow.v2.Versions.ListVersions", - "service": { - "fullName": "google.cloud.dialogflow.v2.Versions", - "shortName": "Versions" - }, - "shortName": "ListVersions" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.dialogflow_v2.types.ListVersionsRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.dialogflow_v2.services.versions.pagers.ListVersionsAsyncPager", - "shortName": "list_versions" - }, - "description": "Sample for ListVersions", - "file": "dialogflow_v2_generated_versions_list_versions_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "dialogflow_v2_generated_Versions_ListVersions_async", - "segments": [ - { - "end": 52, - "start": 27, - "type": "FULL" - }, - { - "end": 52, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 48, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 53, - "start": 49, - "type": "RESPONSE_HANDLING" - } - ], - "title": "dialogflow_v2_generated_versions_list_versions_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.dialogflow_v2.VersionsClient", - "shortName": "VersionsClient" - }, - "fullName": "google.cloud.dialogflow_v2.VersionsClient.list_versions", - "method": { - "fullName": "google.cloud.dialogflow.v2.Versions.ListVersions", - "service": { - "fullName": "google.cloud.dialogflow.v2.Versions", - "shortName": "Versions" - }, - "shortName": "ListVersions" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.dialogflow_v2.types.ListVersionsRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.dialogflow_v2.services.versions.pagers.ListVersionsPager", - "shortName": "list_versions" - }, - "description": "Sample for ListVersions", - "file": "dialogflow_v2_generated_versions_list_versions_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "dialogflow_v2_generated_Versions_ListVersions_sync", - "segments": [ - { - "end": 52, - "start": 27, - "type": "FULL" - }, - { - "end": 52, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 48, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 53, - "start": 49, - "type": "RESPONSE_HANDLING" - } - ], - "title": "dialogflow_v2_generated_versions_list_versions_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.dialogflow_v2.VersionsAsyncClient", - "shortName": "VersionsAsyncClient" - }, - "fullName": "google.cloud.dialogflow_v2.VersionsAsyncClient.update_version", - "method": { - "fullName": "google.cloud.dialogflow.v2.Versions.UpdateVersion", - "service": { - "fullName": "google.cloud.dialogflow.v2.Versions", - "shortName": "Versions" - }, - "shortName": "UpdateVersion" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.dialogflow_v2.types.UpdateVersionRequest" - }, - { - "name": "version", - "type": "google.cloud.dialogflow_v2.types.Version" - }, - { - "name": "update_mask", - "type": "google.protobuf.field_mask_pb2.FieldMask" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.dialogflow_v2.types.Version", - "shortName": "update_version" - }, - "description": "Sample for UpdateVersion", - "file": "dialogflow_v2_generated_versions_update_version_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "dialogflow_v2_generated_Versions_UpdateVersion_async", - "segments": [ - { - "end": 50, - "start": 27, - "type": "FULL" - }, - { - "end": 50, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 44, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 47, - "start": 45, - "type": "REQUEST_EXECUTION" - }, - { - "end": 51, - "start": 48, - "type": "RESPONSE_HANDLING" - } - ], - "title": "dialogflow_v2_generated_versions_update_version_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.dialogflow_v2.VersionsClient", - "shortName": "VersionsClient" - }, - "fullName": "google.cloud.dialogflow_v2.VersionsClient.update_version", - "method": { - "fullName": "google.cloud.dialogflow.v2.Versions.UpdateVersion", - "service": { - "fullName": "google.cloud.dialogflow.v2.Versions", - "shortName": "Versions" - }, - "shortName": "UpdateVersion" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.dialogflow_v2.types.UpdateVersionRequest" - }, - { - "name": "version", - "type": "google.cloud.dialogflow_v2.types.Version" - }, - { - "name": "update_mask", - "type": "google.protobuf.field_mask_pb2.FieldMask" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.dialogflow_v2.types.Version", - "shortName": "update_version" - }, - "description": "Sample for UpdateVersion", - "file": "dialogflow_v2_generated_versions_update_version_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "dialogflow_v2_generated_Versions_UpdateVersion_sync", - "segments": [ - { - "end": 50, - "start": 27, - "type": "FULL" - }, - { - "end": 50, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 44, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 47, - "start": 45, - "type": "REQUEST_EXECUTION" - }, - { - "end": 51, - "start": 48, - "type": "RESPONSE_HANDLING" - } - ], - "title": "dialogflow_v2_generated_versions_update_version_sync.py" - } - ] -} diff --git a/owl-bot-staging/v2/scripts/fixup_dialogflow_v2_keywords.py b/owl-bot-staging/v2/scripts/fixup_dialogflow_v2_keywords.py deleted file mode 100644 index 0822b56f0..000000000 --- a/owl-bot-staging/v2/scripts/fixup_dialogflow_v2_keywords.py +++ /dev/null @@ -1,278 +0,0 @@ -#! /usr/bin/env python3 -# -*- coding: utf-8 -*- -# Copyright 2022 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 argparse -import os -import libcst as cst -import pathlib -import sys -from typing import (Any, Callable, Dict, List, Sequence, Tuple) - - -def partition( - predicate: Callable[[Any], bool], - iterator: Sequence[Any] -) -> Tuple[List[Any], List[Any]]: - """A stable, out-of-place partition.""" - results = ([], []) - - for i in iterator: - results[int(predicate(i))].append(i) - - # Returns trueList, falseList - return results[1], results[0] - - -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', 'assist_query_params', 'cx_parameters', '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', ), - 'clear_suggestion_feature_config': ('conversation_profile', 'participant_role', 'suggestion_feature_type', ), - 'complete_conversation': ('name', ), - 'create_context': ('parent', 'context', ), - 'create_conversation': ('parent', 'conversation', 'conversation_id', ), - 'create_conversation_dataset': ('parent', 'conversation_dataset', ), - 'create_conversation_model': ('conversation_model', 'parent', ), - 'create_conversation_model_evaluation': ('parent', 'conversation_model_evaluation', ), - '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_dataset': ('name', ), - 'delete_conversation_model': ('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', ), - 'deploy_conversation_model': ('name', ), - 'detect_intent': ('session', 'query_input', 'query_params', 'output_audio_config', 'output_audio_config_mask', 'input_audio', ), - 'export_agent': ('parent', 'agent_uri', ), - 'export_document': ('name', 'gcs_destination', 'export_full_content', 'smart_messaging_partial_update', ), - 'get_agent': ('parent', ), - 'get_context': ('name', ), - 'get_conversation': ('name', ), - 'get_conversation_dataset': ('name', ), - 'get_conversation_model': ('name', ), - 'get_conversation_model_evaluation': ('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_conversation_data': ('name', 'input_config', ), - 'import_documents': ('parent', 'document_template', 'gcs_source', 'import_gcs_custom_metadata', ), - 'list_answer_records': ('parent', 'filter', 'page_size', 'page_token', ), - 'list_contexts': ('parent', 'page_size', 'page_token', ), - 'list_conversation_datasets': ('parent', 'page_size', 'page_token', ), - 'list_conversation_model_evaluations': ('parent', 'page_size', 'page_token', ), - 'list_conversation_models': ('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_versions': ('parent', 'page_size', 'page_token', ), - 'reload_document': ('name', 'content_uri', 'import_gcs_custom_metadata', 'smart_messaging_partial_update', ), - 'restore_agent': ('parent', 'agent_uri', 'agent_content', ), - 'search_agents': ('parent', 'page_size', 'page_token', ), - 'set_agent': ('agent', 'update_mask', ), - 'set_suggestion_feature_config': ('conversation_profile', 'participant_role', 'suggestion_feature_config', ), - 'streaming_analyze_content': ('participant', 'audio_config', 'text_config', 'reply_audio_config', 'input_audio', 'input_text', 'input_dtmf', 'query_params', 'assist_query_params', 'cx_parameters', 'enable_partial_automated_agent_reply', ), - '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', 'assist_query_params', ), - 'suggest_conversation_summary': ('conversation', 'latest_message', 'context_size', 'assist_query_params', ), - 'suggest_faq_answers': ('parent', 'latest_message', 'context_size', 'assist_query_params', ), - 'suggest_smart_replies': ('parent', 'current_text_input', 'latest_message', 'context_size', ), - 'train_agent': ('parent', ), - 'undeploy_conversation_model': ('name', ), - '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: - try: - key = original.func.attr.value - kword_params = self.METHOD_TO_PARAMS[key] - except (AttributeError, KeyError): - # Either not a method from the API or too convoluted to be sure. - return updated - - # If the existing code is valid, keyword args come after positional args. - # Therefore, all positional args must map to the first parameters. - args, kwargs = partition(lambda a: not bool(a.keyword), updated.args) - if any(k.keyword.value == "request" for k in kwargs): - # We've already fixed this file, don't fix it again. - return updated - - kwargs, ctrl_kwargs = partition( - lambda a: a.keyword.value not in self.CTRL_PARAMS, - kwargs - ) - - args, ctrl_args = args[:len(kword_params)], args[len(kword_params):] - ctrl_kwargs.extend(cst.Arg(value=a.value, keyword=cst.Name(value=ctrl)) - for a, ctrl in zip(ctrl_args, self.CTRL_PARAMS)) - - request_arg = cst.Arg( - value=cst.Dict([ - cst.DictElement( - cst.SimpleString("'{}'".format(name)), -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 - # those could have been passed positionally or by keyword. - for name, arg in zip(kword_params, args + kwargs)]), - keyword=cst.Name("request") - ) - - return updated.with_changes( - args=[request_arg] + ctrl_kwargs - ) - - -def fix_files( - in_dir: pathlib.Path, - out_dir: pathlib.Path, - *, - transformer=dialogflowCallTransformer(), -): - """Duplicate the input dir to the output dir, fixing file method calls. - - Preconditions: - * in_dir is a real directory - * out_dir is a real, empty directory - """ - pyfile_gen = ( - pathlib.Path(os.path.join(root, f)) - for root, _, files in os.walk(in_dir) - for f in files if os.path.splitext(f)[1] == ".py" - ) - - for fpath in pyfile_gen: - with open(fpath, 'r') as f: - src = f.read() - - # Parse the code and insert method call fixes. - tree = cst.parse_module(src) - updated = tree.visit(transformer) - - # Create the path and directory structure for the new file. - updated_path = out_dir.joinpath(fpath.relative_to(in_dir)) - updated_path.parent.mkdir(parents=True, exist_ok=True) - - # Generate the updated source file at the corresponding path. - with open(updated_path, 'w') as f: - f.write(updated.code) - - -if __name__ == '__main__': - parser = argparse.ArgumentParser( - description="""Fix up source that uses the dialogflow client library. - -The existing sources are NOT overwritten but are copied to output_dir with changes made. - -Note: This tool operates at a best-effort level at converting positional - parameters in client method calls to keyword based parameters. - Cases where it WILL FAIL include - A) * or ** expansion in a method call. - B) Calls via function or method alias (includes free function calls) - C) Indirect or dispatched calls (e.g. the method is looked up dynamically) - - These all constitute false negatives. The tool will also detect false - positives when an API method shares a name with another method. -""") - parser.add_argument( - '-d', - '--input-directory', - required=True, - dest='input_dir', - help='the input directory to walk for python files to fix up', - ) - parser.add_argument( - '-o', - '--output-directory', - required=True, - dest='output_dir', - help='the directory to output files fixed via un-flattening', - ) - args = parser.parse_args() - input_dir = pathlib.Path(args.input_dir) - output_dir = pathlib.Path(args.output_dir) - if not input_dir.is_dir(): - print( - f"input directory '{input_dir}' does not exist or is not a directory", - file=sys.stderr, - ) - sys.exit(-1) - - if not output_dir.is_dir(): - print( - f"output directory '{output_dir}' does not exist or is not a directory", - file=sys.stderr, - ) - sys.exit(-1) - - if os.listdir(output_dir): - print( - f"output directory '{output_dir}' is not empty", - file=sys.stderr, - ) - sys.exit(-1) - - fix_files(input_dir, output_dir) diff --git a/owl-bot-staging/v2/setup.py b/owl-bot-staging/v2/setup.py deleted file mode 100644 index 7a69d39a7..000000000 --- a/owl-bot-staging/v2/setup.py +++ /dev/null @@ -1,90 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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 io -import os - -import setuptools # type: ignore - -package_root = os.path.abspath(os.path.dirname(__file__)) - -name = 'google-cloud-dialogflow' - - -description = "Google Cloud Dialogflow API client library" - -version = {} -with open(os.path.join(package_root, 'google/cloud/dialogflow/gapic_version.py')) as fp: - exec(fp.read(), version) -version = version["__version__"] - -if version[0] == "0": - release_status = "Development Status :: 4 - Beta" -else: - release_status = "Development Status :: 5 - Production/Stable" - -dependencies = [ - "google-api-core[grpc] >= 1.34.0, <3.0.0dev,!=2.0.*,!=2.1.*,!=2.2.*,!=2.3.*,!=2.4.*,!=2.5.*,!=2.6.*,!=2.7.*,!=2.8.*,!=2.9.*,!=2.10.*", - "proto-plus >= 1.22.0, <2.0.0dev", - "proto-plus >= 1.22.2, <2.0.0dev; python_version>='3.11'", - "protobuf>=3.19.5,<5.0.0dev,!=3.20.0,!=3.20.1,!=4.21.0,!=4.21.1,!=4.21.2,!=4.21.3,!=4.21.4,!=4.21.5", -] -url = "https://github.com/googleapis/python-dialogflow" - -package_root = os.path.abspath(os.path.dirname(__file__)) - -readme_filename = os.path.join(package_root, "README.rst") -with io.open(readme_filename, encoding="utf-8") as readme_file: - readme = readme_file.read() - -packages = [ - package - for package in setuptools.PEP420PackageFinder.find() - if package.startswith("google") -] - -namespaces = ["google", "google.cloud"] - -setuptools.setup( - name=name, - version=version, - description=description, - long_description=readme, - author="Google LLC", - author_email="googleapis-packages@google.com", - license="Apache 2.0", - url=url, - classifiers=[ - release_status, - "Intended Audience :: Developers", - "License :: OSI Approved :: Apache Software License", - "Programming Language :: Python", - "Programming Language :: Python :: 3", - "Programming Language :: Python :: 3.7", - "Programming Language :: Python :: 3.8", - "Programming Language :: Python :: 3.9", - "Programming Language :: Python :: 3.10", - "Programming Language :: Python :: 3.11", - "Operating System :: OS Independent", - "Topic :: Internet", - ], - platforms="Posix; MacOS X; Windows", - packages=packages, - python_requires=">=3.7", - namespace_packages=namespaces, - install_requires=dependencies, - include_package_data=True, - zip_safe=False, -) diff --git a/owl-bot-staging/v2/testing/constraints-3.10.txt b/owl-bot-staging/v2/testing/constraints-3.10.txt deleted file mode 100644 index ed7f9aed2..000000000 --- a/owl-bot-staging/v2/testing/constraints-3.10.txt +++ /dev/null @@ -1,6 +0,0 @@ -# -*- coding: utf-8 -*- -# This constraints file is required for unit tests. -# List all library dependencies and extras in this file. -google-api-core -proto-plus -protobuf diff --git a/owl-bot-staging/v2/testing/constraints-3.11.txt b/owl-bot-staging/v2/testing/constraints-3.11.txt deleted file mode 100644 index ed7f9aed2..000000000 --- a/owl-bot-staging/v2/testing/constraints-3.11.txt +++ /dev/null @@ -1,6 +0,0 @@ -# -*- coding: utf-8 -*- -# This constraints file is required for unit tests. -# List all library dependencies and extras in this file. -google-api-core -proto-plus -protobuf diff --git a/owl-bot-staging/v2/testing/constraints-3.12.txt b/owl-bot-staging/v2/testing/constraints-3.12.txt deleted file mode 100644 index ed7f9aed2..000000000 --- a/owl-bot-staging/v2/testing/constraints-3.12.txt +++ /dev/null @@ -1,6 +0,0 @@ -# -*- coding: utf-8 -*- -# This constraints file is required for unit tests. -# List all library dependencies and extras in this file. -google-api-core -proto-plus -protobuf diff --git a/owl-bot-staging/v2/testing/constraints-3.7.txt b/owl-bot-staging/v2/testing/constraints-3.7.txt deleted file mode 100644 index 6c44adfea..000000000 --- a/owl-bot-staging/v2/testing/constraints-3.7.txt +++ /dev/null @@ -1,9 +0,0 @@ -# This constraints file is used to check that lower bounds -# are correct in setup.py -# List all library dependencies and extras in this file. -# Pin the version to the lower bound. -# e.g., if setup.py has "google-cloud-foo >= 1.14.0, < 2.0.0dev", -# Then this file should have google-cloud-foo==1.14.0 -google-api-core==1.34.0 -proto-plus==1.22.0 -protobuf==3.19.5 diff --git a/owl-bot-staging/v2/testing/constraints-3.8.txt b/owl-bot-staging/v2/testing/constraints-3.8.txt deleted file mode 100644 index ed7f9aed2..000000000 --- a/owl-bot-staging/v2/testing/constraints-3.8.txt +++ /dev/null @@ -1,6 +0,0 @@ -# -*- coding: utf-8 -*- -# This constraints file is required for unit tests. -# List all library dependencies and extras in this file. -google-api-core -proto-plus -protobuf diff --git a/owl-bot-staging/v2/testing/constraints-3.9.txt b/owl-bot-staging/v2/testing/constraints-3.9.txt deleted file mode 100644 index ed7f9aed2..000000000 --- a/owl-bot-staging/v2/testing/constraints-3.9.txt +++ /dev/null @@ -1,6 +0,0 @@ -# -*- coding: utf-8 -*- -# This constraints file is required for unit tests. -# List all library dependencies and extras in this file. -google-api-core -proto-plus -protobuf diff --git a/owl-bot-staging/v2/tests/__init__.py b/owl-bot-staging/v2/tests/__init__.py deleted file mode 100644 index 231bc1250..000000000 --- a/owl-bot-staging/v2/tests/__init__.py +++ /dev/null @@ -1,16 +0,0 @@ - -# -*- coding: utf-8 -*- -# Copyright 2022 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/owl-bot-staging/v2/tests/unit/__init__.py b/owl-bot-staging/v2/tests/unit/__init__.py deleted file mode 100644 index 231bc1250..000000000 --- a/owl-bot-staging/v2/tests/unit/__init__.py +++ /dev/null @@ -1,16 +0,0 @@ - -# -*- coding: utf-8 -*- -# Copyright 2022 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/owl-bot-staging/v2/tests/unit/gapic/__init__.py b/owl-bot-staging/v2/tests/unit/gapic/__init__.py deleted file mode 100644 index 231bc1250..000000000 --- a/owl-bot-staging/v2/tests/unit/gapic/__init__.py +++ /dev/null @@ -1,16 +0,0 @@ - -# -*- coding: utf-8 -*- -# Copyright 2022 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/owl-bot-staging/v2/tests/unit/gapic/dialogflow_v2/__init__.py b/owl-bot-staging/v2/tests/unit/gapic/dialogflow_v2/__init__.py deleted file mode 100644 index 231bc1250..000000000 --- a/owl-bot-staging/v2/tests/unit/gapic/dialogflow_v2/__init__.py +++ /dev/null @@ -1,16 +0,0 @@ - -# -*- coding: utf-8 -*- -# Copyright 2022 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/owl-bot-staging/v2/tests/unit/gapic/dialogflow_v2/test_agents.py b/owl-bot-staging/v2/tests/unit/gapic/dialogflow_v2/test_agents.py deleted file mode 100644 index 6417d27a7..000000000 --- a/owl-bot-staging/v2/tests/unit/gapic/dialogflow_v2/test_agents.py +++ /dev/null @@ -1,6314 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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 -# try/except added for compatibility with python < 3.8 -try: - from unittest import mock - from unittest.mock import AsyncMock # pragma: NO COVER -except ImportError: # pragma: NO COVER - import mock - -import grpc -from grpc.experimental import aio -from collections.abc import Iterable -from google.protobuf import json_format -import json -import math -import pytest -from proto.marshal.rules.dates import DurationRule, TimestampRule -from proto.marshal.rules import wrappers -from requests import Response -from requests import Request, PreparedRequest -from requests.sessions import Session -from google.protobuf import json_format - -from google.api_core import client_options -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 -from google.api_core import operation_async # type: ignore -from google.api_core import operations_v1 -from google.api_core import path_template -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.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.cloud.location import locations_pb2 -from google.longrunning import operations_pb2 -from google.oauth2 import service_account -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 -import google.auth - - -def client_cert_source_callback(): - return b"cert bytes", b"key bytes" - - -# If default endpoint is localhost, then default mtls endpoint will be the same. -# This method modifies the default endpoint so the client can produce a different -# mtls endpoint for endpoint testing purposes. -def modify_default_endpoint(client): - return "foo.googleapis.com" if ("localhost" in client.DEFAULT_ENDPOINT) else client.DEFAULT_ENDPOINT - - -def test__get_default_mtls_endpoint(): - api_endpoint = "example.googleapis.com" - api_mtls_endpoint = "example.mtls.googleapis.com" - sandbox_endpoint = "example.sandbox.googleapis.com" - sandbox_mtls_endpoint = "example.mtls.sandbox.googleapis.com" - non_googleapi = "api.example.com" - - assert AgentsClient._get_default_mtls_endpoint(None) is None - assert AgentsClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint - assert AgentsClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint - assert AgentsClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint - assert AgentsClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint - assert AgentsClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi - - -@pytest.mark.parametrize("client_class,transport_name", [ - (AgentsClient, "grpc"), - (AgentsAsyncClient, "grpc_asyncio"), - (AgentsClient, "rest"), -]) -def test_agents_client_from_service_account_info(client_class, transport_name): - 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, transport=transport_name) - assert client.transport._credentials == creds - assert isinstance(client, client_class) - - assert client.transport._host == ( - 'dialogflow.googleapis.com:443' - if transport_name in ['grpc', 'grpc_asyncio'] - else - 'https://dialogflow.googleapis.com' - ) - - -@pytest.mark.parametrize("transport_class,transport_name", [ - (transports.AgentsGrpcTransport, "grpc"), - (transports.AgentsGrpcAsyncIOTransport, "grpc_asyncio"), - (transports.AgentsRestTransport, "rest"), -]) -def test_agents_client_service_account_always_use_jwt(transport_class, transport_name): - with mock.patch.object(service_account.Credentials, 'with_always_use_jwt_access', create=True) as use_jwt: - creds = service_account.Credentials(None, None, None) - transport = transport_class(credentials=creds, always_use_jwt_access=True) - use_jwt.assert_called_once_with(True) - - with mock.patch.object(service_account.Credentials, 'with_always_use_jwt_access', create=True) as use_jwt: - creds = service_account.Credentials(None, None, None) - transport = transport_class(credentials=creds, always_use_jwt_access=False) - use_jwt.assert_not_called() - - -@pytest.mark.parametrize("client_class,transport_name", [ - (AgentsClient, "grpc"), - (AgentsAsyncClient, "grpc_asyncio"), - (AgentsClient, "rest"), -]) -def test_agents_client_from_service_account_file(client_class, transport_name): - 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", transport=transport_name) - assert client.transport._credentials == creds - assert isinstance(client, client_class) - - client = client_class.from_service_account_json("dummy/file/path.json", transport=transport_name) - assert client.transport._credentials == creds - assert isinstance(client, client_class) - - assert client.transport._host == ( - 'dialogflow.googleapis.com:443' - if transport_name in ['grpc', 'grpc_asyncio'] - else - 'https://dialogflow.googleapis.com' - ) - - -def test_agents_client_get_transport_class(): - transport = AgentsClient.get_transport_class() - available_transports = [ - transports.AgentsGrpcTransport, - transports.AgentsRestTransport, - ] - assert transport in available_transports - - transport = AgentsClient.get_transport_class("grpc") - assert transport == transports.AgentsGrpcTransport - - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (AgentsClient, transports.AgentsGrpcTransport, "grpc"), - (AgentsAsyncClient, transports.AgentsGrpcAsyncIOTransport, "grpc_asyncio"), - (AgentsClient, transports.AgentsRestTransport, "rest"), -]) -@mock.patch.object(AgentsClient, "DEFAULT_ENDPOINT", modify_default_endpoint(AgentsClient)) -@mock.patch.object(AgentsAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(AgentsAsyncClient)) -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=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(AgentsClient, 'get_transport_class') as gtc: - client = client_class(transport=transport_name) - gtc.assert_called() - - # Check the case api_endpoint is provided. - options = client_options.ClientOptions(api_endpoint="squid.clam.whelk") - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(transport=transport_name, client_options=options) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host="squid.clam.whelk", - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is - # "never". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is - # "always". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_MTLS_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # 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(transport=transport_name) - - # 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(transport=transport_name) - - # 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, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id="octopus", - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - # Check the case api_endpoint is provided - options = client_options.ClientOptions(api_audience="https://language.googleapis.com") - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience="https://language.googleapis.com" - ) - -@pytest.mark.parametrize("client_class,transport_class,transport_name,use_client_cert_env", [ - (AgentsClient, transports.AgentsGrpcTransport, "grpc", "true"), - (AgentsAsyncClient, transports.AgentsGrpcAsyncIOTransport, "grpc_asyncio", "true"), - (AgentsClient, transports.AgentsGrpcTransport, "grpc", "false"), - (AgentsAsyncClient, transports.AgentsGrpcAsyncIOTransport, "grpc_asyncio", "false"), - (AgentsClient, transports.AgentsRestTransport, "rest", "true"), - (AgentsClient, transports.AgentsRestTransport, "rest", "false"), -]) -@mock.patch.object(AgentsClient, "DEFAULT_ENDPOINT", modify_default_endpoint(AgentsClient)) -@mock.patch.object(AgentsAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(AgentsAsyncClient)) -@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) -def test_agents_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, transport=transport_name) - - if use_client_cert_env == "false": - expected_client_cert_source = None - expected_host = client.DEFAULT_ENDPOINT - else: - expected_client_cert_source = client_cert_source_callback - expected_host = client.DEFAULT_MTLS_ENDPOINT - - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=expected_host, - scopes=None, - client_cert_source_for_mtls=expected_client_cert_source, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case ADC client cert is provided. Whether client cert is used depends on - # GOOGLE_API_USE_CLIENT_CERTIFICATE value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): - with mock.patch.object(transport_class, '__init__') as patched: - with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): - with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=client_cert_source_callback): - if use_client_cert_env == "false": - expected_host = client.DEFAULT_ENDPOINT - expected_client_cert_source = None - else: - expected_host = client.DEFAULT_MTLS_ENDPOINT - expected_client_cert_source = client_cert_source_callback - - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=expected_host, - scopes=None, - client_cert_source_for_mtls=expected_client_cert_source, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case client_cert_source and ADC client cert are not provided. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): - with mock.patch.object(transport_class, '__init__') as patched: - with mock.patch("google.auth.transport.mtls.has_default_client_cert_source", return_value=False): - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - -@pytest.mark.parametrize("client_class", [ - AgentsClient, AgentsAsyncClient -]) -@mock.patch.object(AgentsClient, "DEFAULT_ENDPOINT", modify_default_endpoint(AgentsClient)) -@mock.patch.object(AgentsAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(AgentsAsyncClient)) -def test_agents_client_get_mtls_endpoint_and_cert_source(client_class): - mock_client_cert_source = mock.Mock() - - # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "true". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - mock_api_endpoint = "foo" - options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) - assert api_endpoint == mock_api_endpoint - assert cert_source == mock_client_cert_source - - # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "false". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): - mock_client_cert_source = mock.Mock() - mock_api_endpoint = "foo" - options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) - assert api_endpoint == mock_api_endpoint - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "never". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_ENDPOINT - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "always". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert doesn't exist. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=False): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_ENDPOINT - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert exists. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - 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=mock_client_cert_source): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT - assert cert_source == mock_client_cert_source - - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (AgentsClient, transports.AgentsGrpcTransport, "grpc"), - (AgentsAsyncClient, transports.AgentsGrpcAsyncIOTransport, "grpc_asyncio"), - (AgentsClient, transports.AgentsRestTransport, "rest"), -]) -def test_agents_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, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=["1", "2"], - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - -@pytest.mark.parametrize("client_class,transport_class,transport_name,grpc_helpers", [ - (AgentsClient, transports.AgentsGrpcTransport, "grpc", grpc_helpers), - (AgentsAsyncClient, transports.AgentsGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), - (AgentsClient, transports.AgentsRestTransport, "rest", None), -]) -def test_agents_client_client_options_credentials_file(client_class, transport_class, transport_name, grpc_helpers): - # 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, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file="credentials.json", - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - -def test_agents_client_client_options_from_dict(): - with mock.patch('google.cloud.dialogflow_v2.services.agents.transports.AgentsGrpcTransport.__init__') as grpc_transport: - grpc_transport.return_value = None - client = AgentsClient( - client_options={'api_endpoint': 'squid.clam.whelk'} - ) - grpc_transport.assert_called_once_with( - credentials=None, - credentials_file=None, - host="squid.clam.whelk", - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - -@pytest.mark.parametrize("client_class,transport_class,transport_name,grpc_helpers", [ - (AgentsClient, transports.AgentsGrpcTransport, "grpc", grpc_helpers), - (AgentsAsyncClient, transports.AgentsGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), -]) -def test_agents_client_create_channel_credentials_file(client_class, transport_class, transport_name, grpc_helpers): - # 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, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file="credentials.json", - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # test that the credentials from file are saved and used as the credentials. - with mock.patch.object( - google.auth, "load_credentials_from_file", autospec=True - ) as load_creds, mock.patch.object( - google.auth, "default", autospec=True - ) as adc, mock.patch.object( - grpc_helpers, "create_channel" - ) as create_channel: - creds = ga_credentials.AnonymousCredentials() - file_creds = ga_credentials.AnonymousCredentials() - load_creds.return_value = (file_creds, None) - adc.return_value = (creds, None) - client = client_class(client_options=options, transport=transport_name) - create_channel.assert_called_with( - "dialogflow.googleapis.com:443", - credentials=file_creds, - credentials_file=None, - quota_project_id=None, - default_scopes=( - 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/dialogflow', -), - scopes=None, - default_host="dialogflow.googleapis.com", - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - -@pytest.mark.parametrize("request_type", [ - agent.GetAgentRequest, - dict, -]) -def test_get_agent(request_type, transport: str = 'grpc'): - client = AgentsClient( - 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_agent), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = agent.Agent( - parent='parent_value', - display_name='display_name_value', - default_language_code='default_language_code_value', - supported_language_codes=['supported_language_codes_value'], - time_zone='time_zone_value', - description='description_value', - avatar_uri='avatar_uri_value', - enable_logging=True, - match_mode=agent.Agent.MatchMode.MATCH_MODE_HYBRID, - classification_threshold=0.25520000000000004, - 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.25520000000000004, rel_tol=1e-6) - assert response.api_version == agent.Agent.ApiVersion.API_VERSION_V1 - assert response.tier == agent.Agent.Tier.TIER_STANDARD - - -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=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_agent), - '__call__') as call: - client.get_agent() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == agent.GetAgentRequest() - -@pytest.mark.asyncio -async def test_get_agent_async(transport: str = 'grpc_asyncio', request_type=agent.GetAgentRequest): - client = AgentsAsyncClient( - 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_agent), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(agent.Agent( - parent='parent_value', - display_name='display_name_value', - default_language_code='default_language_code_value', - supported_language_codes=['supported_language_codes_value'], - time_zone='time_zone_value', - description='description_value', - avatar_uri='avatar_uri_value', - enable_logging=True, - match_mode=agent.Agent.MatchMode.MATCH_MODE_HYBRID, - classification_threshold=0.25520000000000004, - api_version=agent.Agent.ApiVersion.API_VERSION_V1, - 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.25520000000000004, rel_tol=1e-6) - assert response.api_version == agent.Agent.ApiVersion.API_VERSION_V1 - assert response.tier == agent.Agent.Tier.TIER_STANDARD - - -@pytest.mark.asyncio -async def test_get_agent_async_from_dict(): - await test_get_agent_async(request_type=dict) - - -def test_get_agent_field_headers(): - 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. - 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_agent_field_headers_async(): - 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. - 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_agent_flattened(): - 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', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - arg = args[0].parent - mock_val = 'parent_value' - assert arg == mock_val - - -def test_get_agent_flattened_error(): - client = AgentsClient( - 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_agent( - agent.GetAgentRequest(), - parent='parent_value', - ) - -@pytest.mark.asyncio -async def test_get_agent_flattened_async(): - 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: - # Designate an appropriate return value for the call. - call.return_value = agent.Agent() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(agent.Agent()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.get_agent( - 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] - arg = args[0].parent - mock_val = 'parent_value' - assert arg == mock_val - -@pytest.mark.asyncio -async def test_get_agent_flattened_error_async(): - client = AgentsAsyncClient( - 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_agent( - agent.GetAgentRequest(), - parent='parent_value', - ) - - -@pytest.mark.parametrize("request_type", [ - gcd_agent.SetAgentRequest, - dict, -]) -def test_set_agent(request_type, transport: str = 'grpc'): - client = AgentsClient( - 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.set_agent), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcd_agent.Agent( - parent='parent_value', - display_name='display_name_value', - default_language_code='default_language_code_value', - supported_language_codes=['supported_language_codes_value'], - time_zone='time_zone_value', - description='description_value', - avatar_uri='avatar_uri_value', - enable_logging=True, - match_mode=gcd_agent.Agent.MatchMode.MATCH_MODE_HYBRID, - classification_threshold=0.25520000000000004, - 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.25520000000000004, rel_tol=1e-6) - assert response.api_version == gcd_agent.Agent.ApiVersion.API_VERSION_V1 - assert response.tier == gcd_agent.Agent.Tier.TIER_STANDARD - - -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=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.set_agent), - '__call__') as call: - client.set_agent() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == gcd_agent.SetAgentRequest() - -@pytest.mark.asyncio -async def test_set_agent_async(transport: str = 'grpc_asyncio', request_type=gcd_agent.SetAgentRequest): - client = AgentsAsyncClient( - 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.set_agent), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gcd_agent.Agent( - parent='parent_value', - display_name='display_name_value', - default_language_code='default_language_code_value', - supported_language_codes=['supported_language_codes_value'], - time_zone='time_zone_value', - description='description_value', - avatar_uri='avatar_uri_value', - enable_logging=True, - match_mode=gcd_agent.Agent.MatchMode.MATCH_MODE_HYBRID, - classification_threshold=0.25520000000000004, - api_version=gcd_agent.Agent.ApiVersion.API_VERSION_V1, - 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.25520000000000004, rel_tol=1e-6) - assert response.api_version == gcd_agent.Agent.ApiVersion.API_VERSION_V1 - assert response.tier == gcd_agent.Agent.Tier.TIER_STANDARD - - -@pytest.mark.asyncio -async def test_set_agent_async_from_dict(): - await test_set_agent_async(request_type=dict) - - -def test_set_agent_field_headers(): - 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 = '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. - 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', - 'agent.parent=parent_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_set_agent_field_headers_async(): - 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 = '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. - 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', - 'agent.parent=parent_value', - ) in kw['metadata'] - - -def test_set_agent_flattened(): - 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'), - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - arg = args[0].agent - mock_val = gcd_agent.Agent(parent='parent_value') - assert arg == mock_val - - -def test_set_agent_flattened_error(): - client = AgentsClient( - 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.set_agent( - gcd_agent.SetAgentRequest(), - agent=gcd_agent.Agent(parent='parent_value'), - ) - -@pytest.mark.asyncio -async def test_set_agent_flattened_async(): - 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: - # Designate an appropriate return value for the call. - call.return_value = gcd_agent.Agent() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcd_agent.Agent()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.set_agent( - agent=gcd_agent.Agent(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] - arg = args[0].agent - mock_val = gcd_agent.Agent(parent='parent_value') - assert arg == mock_val - -@pytest.mark.asyncio -async def test_set_agent_flattened_error_async(): - client = AgentsAsyncClient( - 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.set_agent( - gcd_agent.SetAgentRequest(), - agent=gcd_agent.Agent(parent='parent_value'), - ) - - -@pytest.mark.parametrize("request_type", [ - agent.DeleteAgentRequest, - dict, -]) -def test_delete_agent(request_type, transport: str = 'grpc'): - client = AgentsClient( - 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_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. - assert response is None - - -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=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_agent), - '__call__') as call: - client.delete_agent() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == agent.DeleteAgentRequest() - -@pytest.mark.asyncio -async def test_delete_agent_async(transport: str = 'grpc_asyncio', request_type=agent.DeleteAgentRequest): - client = AgentsAsyncClient( - 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_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. - assert response is None - - -@pytest.mark.asyncio -async def test_delete_agent_async_from_dict(): - await test_delete_agent_async(request_type=dict) - - -def test_delete_agent_field_headers(): - 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. - 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_delete_agent_field_headers_async(): - 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. - 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_delete_agent_flattened(): - 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', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - arg = args[0].parent - mock_val = 'parent_value' - assert arg == mock_val - - -def test_delete_agent_flattened_error(): - client = AgentsClient( - 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_agent( - agent.DeleteAgentRequest(), - parent='parent_value', - ) - -@pytest.mark.asyncio -async def test_delete_agent_flattened_async(): - 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: - # 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_agent( - 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] - arg = args[0].parent - mock_val = 'parent_value' - assert arg == mock_val - -@pytest.mark.asyncio -async def test_delete_agent_flattened_error_async(): - client = AgentsAsyncClient( - 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_agent( - agent.DeleteAgentRequest(), - parent='parent_value', - ) - - -@pytest.mark.parametrize("request_type", [ - agent.SearchAgentsRequest, - dict, -]) -def test_search_agents(request_type, transport: str = 'grpc'): - client = AgentsClient( - 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.search_agents), - '__call__') as call: - # Designate an appropriate return value for the call. - 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' - - -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=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.search_agents), - '__call__') as call: - client.search_agents() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == agent.SearchAgentsRequest() - -@pytest.mark.asyncio -async def test_search_agents_async(transport: str = 'grpc_asyncio', request_type=agent.SearchAgentsRequest): - client = AgentsAsyncClient( - 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.search_agents), - '__call__') as call: - # Designate an appropriate return value for the call. - 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' - - -@pytest.mark.asyncio -async def test_search_agents_async_from_dict(): - await test_search_agents_async(request_type=dict) - - -def test_search_agents_field_headers(): - 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. - 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_search_agents_field_headers_async(): - 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. - with mock.patch.object( - type(client.transport.search_agents), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(agent.SearchAgentsResponse()) - 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] == 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_search_agents_flattened(): - 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', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - arg = args[0].parent - mock_val = 'parent_value' - assert arg == mock_val - - -def test_search_agents_flattened_error(): - client = AgentsClient( - 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.search_agents( - agent.SearchAgentsRequest(), - parent='parent_value', - ) - -@pytest.mark.asyncio -async def test_search_agents_flattened_async(): - 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: - # Designate an appropriate return value for the call. - call.return_value = agent.SearchAgentsResponse() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(agent.SearchAgentsResponse()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.search_agents( - 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] - arg = args[0].parent - mock_val = 'parent_value' - assert arg == mock_val - -@pytest.mark.asyncio -async def test_search_agents_flattened_error_async(): - client = AgentsAsyncClient( - 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.search_agents( - agent.SearchAgentsRequest(), - parent='parent_value', - ) - - -def test_search_agents_pager(transport_name: str = "grpc"): - client = AgentsClient( - credentials=ga_credentials.AnonymousCredentials, - transport=transport_name, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.search_agents), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - agent.SearchAgentsResponse( - agents=[ - agent.Agent(), - agent.Agent(), - agent.Agent(), - ], - next_page_token='abc', - ), - agent.SearchAgentsResponse( - agents=[], - next_page_token='def', - ), - agent.SearchAgentsResponse( - agents=[ - agent.Agent(), - ], - next_page_token='ghi', - ), - agent.SearchAgentsResponse( - agents=[ - agent.Agent(), - agent.Agent(), - ], - ), - RuntimeError, - ) - - metadata = () - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ('parent', ''), - )), - ) - pager = client.search_agents(request={}) - - assert pager._metadata == metadata - - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, agent.Agent) - for i in results) -def test_search_agents_pages(transport_name: str = "grpc"): - client = AgentsClient( - credentials=ga_credentials.AnonymousCredentials, - transport=transport_name, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.search_agents), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - agent.SearchAgentsResponse( - agents=[ - agent.Agent(), - agent.Agent(), - agent.Agent(), - ], - next_page_token='abc', - ), - agent.SearchAgentsResponse( - agents=[], - next_page_token='def', - ), - agent.SearchAgentsResponse( - agents=[ - agent.Agent(), - ], - next_page_token='ghi', - ), - agent.SearchAgentsResponse( - agents=[ - agent.Agent(), - agent.Agent(), - ], - ), - RuntimeError, - ) - pages = list(client.search_agents(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_search_agents_async_pager(): - 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__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - agent.SearchAgentsResponse( - agents=[ - agent.Agent(), - agent.Agent(), - agent.Agent(), - ], - next_page_token='abc', - ), - agent.SearchAgentsResponse( - agents=[], - next_page_token='def', - ), - agent.SearchAgentsResponse( - agents=[ - agent.Agent(), - ], - next_page_token='ghi', - ), - agent.SearchAgentsResponse( - agents=[ - agent.Agent(), - agent.Agent(), - ], - ), - RuntimeError, - ) - async_pager = await client.search_agents(request={},) - assert async_pager.next_page_token == 'abc' - responses = [] - async for response in async_pager: # pragma: no branch - responses.append(response) - - assert len(responses) == 6 - assert all(isinstance(i, agent.Agent) - for i in responses) - - -@pytest.mark.asyncio -async def test_search_agents_async_pages(): - 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__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - agent.SearchAgentsResponse( - agents=[ - agent.Agent(), - agent.Agent(), - agent.Agent(), - ], - next_page_token='abc', - ), - agent.SearchAgentsResponse( - agents=[], - next_page_token='def', - ), - agent.SearchAgentsResponse( - agents=[ - agent.Agent(), - ], - next_page_token='ghi', - ), - agent.SearchAgentsResponse( - agents=[ - agent.Agent(), - agent.Agent(), - ], - ), - RuntimeError, - ) - pages = [] - async for page_ in (await client.search_agents(request={})).pages: # pragma: no branch - pages.append(page_) - for page_, token in zip(pages, ['abc','def','ghi', '']): - assert page_.raw_page.next_page_token == token - -@pytest.mark.parametrize("request_type", [ - agent.TrainAgentRequest, - dict, -]) -def test_train_agent(request_type, transport: str = 'grpc'): - client = AgentsClient( - 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.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. - assert isinstance(response, future.Future) - - -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=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.train_agent), - '__call__') as call: - client.train_agent() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == agent.TrainAgentRequest() - -@pytest.mark.asyncio -async def test_train_agent_async(transport: str = 'grpc_asyncio', request_type=agent.TrainAgentRequest): - client = AgentsAsyncClient( - 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.train_agent), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name='operations/spam') - ) - response = await client.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. - assert isinstance(response, future.Future) - - -@pytest.mark.asyncio -async def test_train_agent_async_from_dict(): - await test_train_agent_async(request_type=dict) - - -def test_train_agent_field_headers(): - 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. - 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_train_agent_field_headers_async(): - 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. - with mock.patch.object( - type(client.transport.train_agent), - '__call__') as call: - 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. - 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_train_agent_flattened(): - 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', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - arg = args[0].parent - mock_val = 'parent_value' - assert arg == mock_val - - -def test_train_agent_flattened_error(): - client = AgentsClient( - 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.train_agent( - agent.TrainAgentRequest(), - parent='parent_value', - ) - -@pytest.mark.asyncio -async def test_train_agent_flattened_async(): - 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: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/op') - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name='operations/spam') - ) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.train_agent( - 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] - arg = args[0].parent - mock_val = 'parent_value' - assert arg == mock_val - -@pytest.mark.asyncio -async def test_train_agent_flattened_error_async(): - client = AgentsAsyncClient( - 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.train_agent( - agent.TrainAgentRequest(), - parent='parent_value', - ) - - -@pytest.mark.parametrize("request_type", [ - agent.ExportAgentRequest, - dict, -]) -def test_export_agent(request_type, transport: str = 'grpc'): - client = AgentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.export_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. - assert isinstance(response, future.Future) - - -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=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.export_agent), - '__call__') as call: - client.export_agent() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == agent.ExportAgentRequest() - -@pytest.mark.asyncio -async def test_export_agent_async(transport: str = 'grpc_asyncio', request_type=agent.ExportAgentRequest): - client = AgentsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.export_agent), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name='operations/spam') - ) - response = await client.export_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. - assert isinstance(response, future.Future) - - -@pytest.mark.asyncio -async def test_export_agent_async_from_dict(): - await test_export_agent_async(request_type=dict) - - -def test_export_agent_field_headers(): - 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. - 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_export_agent_field_headers_async(): - 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. - with mock.patch.object( - type(client.transport.export_agent), - '__call__') as call: - 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. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'parent=parent_value', - ) in kw['metadata'] - - -def test_export_agent_flattened(): - 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', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - arg = args[0].parent - mock_val = 'parent_value' - assert arg == mock_val - - -def test_export_agent_flattened_error(): - client = AgentsClient( - 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.export_agent( - agent.ExportAgentRequest(), - parent='parent_value', - ) - -@pytest.mark.asyncio -async def test_export_agent_flattened_async(): - 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: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/op') - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name='operations/spam') - ) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.export_agent( - 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] - arg = args[0].parent - mock_val = 'parent_value' - assert arg == mock_val - -@pytest.mark.asyncio -async def test_export_agent_flattened_error_async(): - client = AgentsAsyncClient( - 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.export_agent( - agent.ExportAgentRequest(), - parent='parent_value', - ) - - -@pytest.mark.parametrize("request_type", [ - agent.ImportAgentRequest, - dict, -]) -def test_import_agent(request_type, transport: str = 'grpc'): - client = AgentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.import_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. - assert isinstance(response, future.Future) - - -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=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.import_agent), - '__call__') as call: - client.import_agent() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == agent.ImportAgentRequest() - -@pytest.mark.asyncio -async def test_import_agent_async(transport: str = 'grpc_asyncio', request_type=agent.ImportAgentRequest): - client = AgentsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.import_agent), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name='operations/spam') - ) - response = await client.import_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. - assert isinstance(response, future.Future) - - -@pytest.mark.asyncio -async def test_import_agent_async_from_dict(): - await test_import_agent_async(request_type=dict) - - -def test_import_agent_field_headers(): - 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. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'parent=parent_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_import_agent_field_headers_async(): - 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. - with mock.patch.object( - type(client.transport.import_agent), - '__call__') as call: - 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. - 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'] - - -@pytest.mark.parametrize("request_type", [ - agent.RestoreAgentRequest, - dict, -]) -def test_restore_agent(request_type, transport: str = 'grpc'): - client = AgentsClient( - 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.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. - assert isinstance(response, future.Future) - - -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=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.restore_agent), - '__call__') as call: - client.restore_agent() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == agent.RestoreAgentRequest() - -@pytest.mark.asyncio -async def test_restore_agent_async(transport: str = 'grpc_asyncio', request_type=agent.RestoreAgentRequest): - client = AgentsAsyncClient( - 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.restore_agent), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name='operations/spam') - ) - response = await client.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. - assert isinstance(response, future.Future) - - -@pytest.mark.asyncio -async def test_restore_agent_async_from_dict(): - await test_restore_agent_async(request_type=dict) - - -def test_restore_agent_field_headers(): - 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. - 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_restore_agent_field_headers_async(): - 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. - with mock.patch.object( - type(client.transport.restore_agent), - '__call__') as call: - 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. - 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'] - - -@pytest.mark.parametrize("request_type", [ - agent.GetValidationResultRequest, - dict, -]) -def test_get_validation_result(request_type, transport: str = 'grpc'): - client = AgentsClient( - 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_validation_result), - '__call__') 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) - - -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=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_validation_result), - '__call__') as call: - client.get_validation_result() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == agent.GetValidationResultRequest() - -@pytest.mark.asyncio -async def test_get_validation_result_async(transport: str = 'grpc_asyncio', request_type=agent.GetValidationResultRequest): - client = AgentsAsyncClient( - 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_validation_result), - '__call__') as call: - # Designate an appropriate return value for the call. - 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. - assert isinstance(response, validation_result.ValidationResult) - - -@pytest.mark.asyncio -async def test_get_validation_result_async_from_dict(): - await test_get_validation_result_async(request_type=dict) - - -def test_get_validation_result_field_headers(): - 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. - with mock.patch.object( - 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. - 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_validation_result_field_headers_async(): - 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. - with mock.patch.object( - type(client.transport.get_validation_result), - '__call__') as call: - 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. - 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'] - - -@pytest.mark.parametrize("request_type", [ - agent.GetAgentRequest, - dict, -]) -def test_get_agent_rest(request_type): - client = AgentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = agent.Agent( - parent='parent_value', - display_name='display_name_value', - default_language_code='default_language_code_value', - supported_language_codes=['supported_language_codes_value'], - time_zone='time_zone_value', - description='description_value', - avatar_uri='avatar_uri_value', - enable_logging=True, - match_mode=agent.Agent.MatchMode.MATCH_MODE_HYBRID, - classification_threshold=0.25520000000000004, - api_version=agent.Agent.ApiVersion.API_VERSION_V1, - tier=agent.Agent.Tier.TIER_STANDARD, - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - pb_return_value = agent.Agent.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.get_agent(request) - - # 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.25520000000000004, rel_tol=1e-6) - assert response.api_version == agent.Agent.ApiVersion.API_VERSION_V1 - assert response.tier == agent.Agent.Tier.TIER_STANDARD - - -def test_get_agent_rest_required_fields(request_type=agent.GetAgentRequest): - transport_class = transports.AgentsRestTransport - - request_init = {} - request_init["parent"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - including_default_value_fields=False, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_agent._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["parent"] = 'parent_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_agent._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "parent" in jsonified_request - assert jsonified_request["parent"] == 'parent_value' - - client = AgentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = agent.Agent() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "get", - 'query_params': pb_request, - } - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - - pb_return_value = agent.Agent.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.get_agent(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_get_agent_rest_unset_required_fields(): - transport = transports.AgentsRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.get_agent._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("parent", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_get_agent_rest_interceptors(null_interceptor): - transport = transports.AgentsRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.AgentsRestInterceptor(), - ) - client = AgentsClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.AgentsRestInterceptor, "post_get_agent") as post, \ - mock.patch.object(transports.AgentsRestInterceptor, "pre_get_agent") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = agent.GetAgentRequest.pb(agent.GetAgentRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = agent.Agent.to_json(agent.Agent()) - - request = agent.GetAgentRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = agent.Agent() - - client.get_agent(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_get_agent_rest_bad_request(transport: str = 'rest', request_type=agent.GetAgentRequest): - client = AgentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.get_agent(request) - - -def test_get_agent_rest_flattened(): - client = AgentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = agent.Agent() - - # get arguments that satisfy an http rule for this method - sample_request = {'parent': 'projects/sample1'} - - # get truthy value for each flattened field - mock_args = dict( - parent='parent_value', - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - pb_return_value = agent.Agent.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.get_agent(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v2/{parent=projects/*}/agent" % client.transport._host, args[1]) - - -def test_get_agent_rest_flattened_error(transport: str = 'rest'): - client = AgentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.get_agent( - agent.GetAgentRequest(), - parent='parent_value', - ) - - -def test_get_agent_rest_error(): - client = AgentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - gcd_agent.SetAgentRequest, - dict, -]) -def test_set_agent_rest(request_type): - client = AgentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'agent': {'parent': 'projects/sample1'}} - request_init["agent"] = {'parent': 'projects/sample1', 'display_name': 'display_name_value', 'default_language_code': 'default_language_code_value', 'supported_language_codes': ['supported_language_codes_value1', 'supported_language_codes_value2'], 'time_zone': 'time_zone_value', 'description': 'description_value', 'avatar_uri': 'avatar_uri_value', 'enable_logging': True, 'match_mode': 1, 'classification_threshold': 0.25520000000000004, 'api_version': 1, 'tier': 1} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = gcd_agent.Agent( - parent='parent_value', - display_name='display_name_value', - default_language_code='default_language_code_value', - supported_language_codes=['supported_language_codes_value'], - time_zone='time_zone_value', - description='description_value', - avatar_uri='avatar_uri_value', - enable_logging=True, - match_mode=gcd_agent.Agent.MatchMode.MATCH_MODE_HYBRID, - classification_threshold=0.25520000000000004, - api_version=gcd_agent.Agent.ApiVersion.API_VERSION_V1, - tier=gcd_agent.Agent.Tier.TIER_STANDARD, - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - pb_return_value = gcd_agent.Agent.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.set_agent(request) - - # 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.25520000000000004, rel_tol=1e-6) - assert response.api_version == gcd_agent.Agent.ApiVersion.API_VERSION_V1 - assert response.tier == gcd_agent.Agent.Tier.TIER_STANDARD - - -def test_set_agent_rest_required_fields(request_type=gcd_agent.SetAgentRequest): - transport_class = transports.AgentsRestTransport - - request_init = {} - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - including_default_value_fields=False, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).set_agent._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).set_agent._get_unset_required_fields(jsonified_request) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("update_mask", )) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - - client = AgentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = gcd_agent.Agent() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "post", - 'query_params': pb_request, - } - transcode_result['body'] = pb_request - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - - pb_return_value = gcd_agent.Agent.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.set_agent(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_set_agent_rest_unset_required_fields(): - transport = transports.AgentsRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.set_agent._get_unset_required_fields({}) - assert set(unset_fields) == (set(("updateMask", )) & set(("agent", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_set_agent_rest_interceptors(null_interceptor): - transport = transports.AgentsRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.AgentsRestInterceptor(), - ) - client = AgentsClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.AgentsRestInterceptor, "post_set_agent") as post, \ - mock.patch.object(transports.AgentsRestInterceptor, "pre_set_agent") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = gcd_agent.SetAgentRequest.pb(gcd_agent.SetAgentRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = gcd_agent.Agent.to_json(gcd_agent.Agent()) - - request = gcd_agent.SetAgentRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = gcd_agent.Agent() - - client.set_agent(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_set_agent_rest_bad_request(transport: str = 'rest', request_type=gcd_agent.SetAgentRequest): - client = AgentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'agent': {'parent': 'projects/sample1'}} - request_init["agent"] = {'parent': 'projects/sample1', 'display_name': 'display_name_value', 'default_language_code': 'default_language_code_value', 'supported_language_codes': ['supported_language_codes_value1', 'supported_language_codes_value2'], 'time_zone': 'time_zone_value', 'description': 'description_value', 'avatar_uri': 'avatar_uri_value', 'enable_logging': True, 'match_mode': 1, 'classification_threshold': 0.25520000000000004, 'api_version': 1, 'tier': 1} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.set_agent(request) - - -def test_set_agent_rest_flattened(): - client = AgentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = gcd_agent.Agent() - - # get arguments that satisfy an http rule for this method - sample_request = {'agent': {'parent': 'projects/sample1'}} - - # get truthy value for each flattened field - mock_args = dict( - agent=gcd_agent.Agent(parent='parent_value'), - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - pb_return_value = gcd_agent.Agent.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.set_agent(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v2/{agent.parent=projects/*}/agent" % client.transport._host, args[1]) - - -def test_set_agent_rest_flattened_error(transport: str = 'rest'): - client = AgentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.set_agent( - gcd_agent.SetAgentRequest(), - agent=gcd_agent.Agent(parent='parent_value'), - ) - - -def test_set_agent_rest_error(): - client = AgentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - agent.DeleteAgentRequest, - dict, -]) -def test_delete_agent_rest(request_type): - client = AgentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = None - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = '' - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.delete_agent(request) - - # Establish that the response is the type that we expect. - assert response is None - - -def test_delete_agent_rest_required_fields(request_type=agent.DeleteAgentRequest): - transport_class = transports.AgentsRestTransport - - request_init = {} - request_init["parent"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - including_default_value_fields=False, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).delete_agent._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["parent"] = 'parent_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).delete_agent._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "parent" in jsonified_request - assert jsonified_request["parent"] == 'parent_value' - - client = AgentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = None - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "delete", - 'query_params': pb_request, - } - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - json_return_value = '' - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.delete_agent(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_delete_agent_rest_unset_required_fields(): - transport = transports.AgentsRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.delete_agent._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("parent", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_delete_agent_rest_interceptors(null_interceptor): - transport = transports.AgentsRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.AgentsRestInterceptor(), - ) - client = AgentsClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.AgentsRestInterceptor, "pre_delete_agent") as pre: - pre.assert_not_called() - pb_message = agent.DeleteAgentRequest.pb(agent.DeleteAgentRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - - request = agent.DeleteAgentRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - - client.delete_agent(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - - -def test_delete_agent_rest_bad_request(transport: str = 'rest', request_type=agent.DeleteAgentRequest): - client = AgentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.delete_agent(request) - - -def test_delete_agent_rest_flattened(): - client = AgentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = None - - # get arguments that satisfy an http rule for this method - sample_request = {'parent': 'projects/sample1'} - - # get truthy value for each flattened field - mock_args = dict( - parent='parent_value', - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = '' - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.delete_agent(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v2/{parent=projects/*}/agent" % client.transport._host, args[1]) - - -def test_delete_agent_rest_flattened_error(transport: str = 'rest'): - client = AgentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.delete_agent( - agent.DeleteAgentRequest(), - parent='parent_value', - ) - - -def test_delete_agent_rest_error(): - client = AgentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - agent.SearchAgentsRequest, - dict, -]) -def test_search_agents_rest(request_type): - client = AgentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = agent.SearchAgentsResponse( - next_page_token='next_page_token_value', - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - pb_return_value = agent.SearchAgentsResponse.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.search_agents(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.SearchAgentsPager) - assert response.next_page_token == 'next_page_token_value' - - -def test_search_agents_rest_required_fields(request_type=agent.SearchAgentsRequest): - transport_class = transports.AgentsRestTransport - - request_init = {} - request_init["parent"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - including_default_value_fields=False, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).search_agents._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["parent"] = 'parent_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).search_agents._get_unset_required_fields(jsonified_request) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("page_size", "page_token", )) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "parent" in jsonified_request - assert jsonified_request["parent"] == 'parent_value' - - client = AgentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = agent.SearchAgentsResponse() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "get", - 'query_params': pb_request, - } - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - - pb_return_value = agent.SearchAgentsResponse.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.search_agents(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_search_agents_rest_unset_required_fields(): - transport = transports.AgentsRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.search_agents._get_unset_required_fields({}) - assert set(unset_fields) == (set(("pageSize", "pageToken", )) & set(("parent", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_search_agents_rest_interceptors(null_interceptor): - transport = transports.AgentsRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.AgentsRestInterceptor(), - ) - client = AgentsClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.AgentsRestInterceptor, "post_search_agents") as post, \ - mock.patch.object(transports.AgentsRestInterceptor, "pre_search_agents") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = agent.SearchAgentsRequest.pb(agent.SearchAgentsRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = agent.SearchAgentsResponse.to_json(agent.SearchAgentsResponse()) - - request = agent.SearchAgentsRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = agent.SearchAgentsResponse() - - client.search_agents(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_search_agents_rest_bad_request(transport: str = 'rest', request_type=agent.SearchAgentsRequest): - client = AgentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.search_agents(request) - - -def test_search_agents_rest_flattened(): - client = AgentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = agent.SearchAgentsResponse() - - # get arguments that satisfy an http rule for this method - sample_request = {'parent': 'projects/sample1'} - - # get truthy value for each flattened field - mock_args = dict( - parent='parent_value', - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - pb_return_value = agent.SearchAgentsResponse.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.search_agents(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v2/{parent=projects/*}/agent:search" % client.transport._host, args[1]) - - -def test_search_agents_rest_flattened_error(transport: str = 'rest'): - client = AgentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.search_agents( - agent.SearchAgentsRequest(), - parent='parent_value', - ) - - -def test_search_agents_rest_pager(transport: str = 'rest'): - client = AgentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # TODO(kbandes): remove this mock unless there's a good reason for it. - #with mock.patch.object(path_template, 'transcode') as transcode: - # Set the response as a series of pages - response = ( - agent.SearchAgentsResponse( - agents=[ - agent.Agent(), - agent.Agent(), - agent.Agent(), - ], - next_page_token='abc', - ), - agent.SearchAgentsResponse( - agents=[], - next_page_token='def', - ), - agent.SearchAgentsResponse( - agents=[ - agent.Agent(), - ], - next_page_token='ghi', - ), - agent.SearchAgentsResponse( - agents=[ - agent.Agent(), - agent.Agent(), - ], - ), - ) - # Two responses for two calls - response = response + response - - # Wrap the values into proper Response objs - response = tuple(agent.SearchAgentsResponse.to_json(x) for x in response) - return_values = tuple(Response() for i in response) - for return_val, response_val in zip(return_values, response): - return_val._content = response_val.encode('UTF-8') - return_val.status_code = 200 - req.side_effect = return_values - - sample_request = {'parent': 'projects/sample1'} - - pager = client.search_agents(request=sample_request) - - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, agent.Agent) - for i in results) - - pages = list(client.search_agents(request=sample_request).pages) - for page_, token in zip(pages, ['abc','def','ghi', '']): - assert page_.raw_page.next_page_token == token - - -@pytest.mark.parametrize("request_type", [ - agent.TrainAgentRequest, - dict, -]) -def test_train_agent_rest(request_type): - client = AgentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name='operations/spam') - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.train_agent(request) - - # Establish that the response is the type that we expect. - assert response.operation.name == "operations/spam" - - -def test_train_agent_rest_required_fields(request_type=agent.TrainAgentRequest): - transport_class = transports.AgentsRestTransport - - request_init = {} - request_init["parent"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - including_default_value_fields=False, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).train_agent._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["parent"] = 'parent_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).train_agent._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "parent" in jsonified_request - assert jsonified_request["parent"] == 'parent_value' - - client = AgentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name='operations/spam') - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "post", - 'query_params': pb_request, - } - transcode_result['body'] = pb_request - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.train_agent(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_train_agent_rest_unset_required_fields(): - transport = transports.AgentsRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.train_agent._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("parent", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_train_agent_rest_interceptors(null_interceptor): - transport = transports.AgentsRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.AgentsRestInterceptor(), - ) - client = AgentsClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(operation.Operation, "_set_result_from_operation"), \ - mock.patch.object(transports.AgentsRestInterceptor, "post_train_agent") as post, \ - mock.patch.object(transports.AgentsRestInterceptor, "pre_train_agent") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = agent.TrainAgentRequest.pb(agent.TrainAgentRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = json_format.MessageToJson(operations_pb2.Operation()) - - request = agent.TrainAgentRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = operations_pb2.Operation() - - client.train_agent(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_train_agent_rest_bad_request(transport: str = 'rest', request_type=agent.TrainAgentRequest): - client = AgentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.train_agent(request) - - -def test_train_agent_rest_flattened(): - client = AgentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name='operations/spam') - - # get arguments that satisfy an http rule for this method - sample_request = {'parent': 'projects/sample1'} - - # get truthy value for each flattened field - mock_args = dict( - parent='parent_value', - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.train_agent(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v2/{parent=projects/*}/agent:train" % client.transport._host, args[1]) - - -def test_train_agent_rest_flattened_error(transport: str = 'rest'): - client = AgentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.train_agent( - agent.TrainAgentRequest(), - parent='parent_value', - ) - - -def test_train_agent_rest_error(): - client = AgentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - agent.ExportAgentRequest, - dict, -]) -def test_export_agent_rest(request_type): - client = AgentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name='operations/spam') - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.export_agent(request) - - # Establish that the response is the type that we expect. - assert response.operation.name == "operations/spam" - - -def test_export_agent_rest_required_fields(request_type=agent.ExportAgentRequest): - transport_class = transports.AgentsRestTransport - - request_init = {} - request_init["parent"] = "" - request_init["agent_uri"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - including_default_value_fields=False, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).export_agent._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["parent"] = 'parent_value' - jsonified_request["agentUri"] = 'agent_uri_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).export_agent._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "parent" in jsonified_request - assert jsonified_request["parent"] == 'parent_value' - assert "agentUri" in jsonified_request - assert jsonified_request["agentUri"] == 'agent_uri_value' - - client = AgentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name='operations/spam') - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "post", - 'query_params': pb_request, - } - transcode_result['body'] = pb_request - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.export_agent(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_export_agent_rest_unset_required_fields(): - transport = transports.AgentsRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.export_agent._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("parent", "agentUri", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_export_agent_rest_interceptors(null_interceptor): - transport = transports.AgentsRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.AgentsRestInterceptor(), - ) - client = AgentsClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(operation.Operation, "_set_result_from_operation"), \ - mock.patch.object(transports.AgentsRestInterceptor, "post_export_agent") as post, \ - mock.patch.object(transports.AgentsRestInterceptor, "pre_export_agent") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = agent.ExportAgentRequest.pb(agent.ExportAgentRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = json_format.MessageToJson(operations_pb2.Operation()) - - request = agent.ExportAgentRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = operations_pb2.Operation() - - client.export_agent(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_export_agent_rest_bad_request(transport: str = 'rest', request_type=agent.ExportAgentRequest): - client = AgentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.export_agent(request) - - -def test_export_agent_rest_flattened(): - client = AgentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name='operations/spam') - - # get arguments that satisfy an http rule for this method - sample_request = {'parent': 'projects/sample1'} - - # get truthy value for each flattened field - mock_args = dict( - parent='parent_value', - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.export_agent(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v2/{parent=projects/*}/agent:export" % client.transport._host, args[1]) - - -def test_export_agent_rest_flattened_error(transport: str = 'rest'): - client = AgentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.export_agent( - agent.ExportAgentRequest(), - parent='parent_value', - ) - - -def test_export_agent_rest_error(): - client = AgentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - agent.ImportAgentRequest, - dict, -]) -def test_import_agent_rest(request_type): - client = AgentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name='operations/spam') - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.import_agent(request) - - # Establish that the response is the type that we expect. - assert response.operation.name == "operations/spam" - - -def test_import_agent_rest_required_fields(request_type=agent.ImportAgentRequest): - transport_class = transports.AgentsRestTransport - - request_init = {} - request_init["parent"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - including_default_value_fields=False, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).import_agent._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["parent"] = 'parent_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).import_agent._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "parent" in jsonified_request - assert jsonified_request["parent"] == 'parent_value' - - client = AgentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name='operations/spam') - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "post", - 'query_params': pb_request, - } - transcode_result['body'] = pb_request - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.import_agent(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_import_agent_rest_unset_required_fields(): - transport = transports.AgentsRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.import_agent._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("parent", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_import_agent_rest_interceptors(null_interceptor): - transport = transports.AgentsRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.AgentsRestInterceptor(), - ) - client = AgentsClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(operation.Operation, "_set_result_from_operation"), \ - mock.patch.object(transports.AgentsRestInterceptor, "post_import_agent") as post, \ - mock.patch.object(transports.AgentsRestInterceptor, "pre_import_agent") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = agent.ImportAgentRequest.pb(agent.ImportAgentRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = json_format.MessageToJson(operations_pb2.Operation()) - - request = agent.ImportAgentRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = operations_pb2.Operation() - - client.import_agent(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_import_agent_rest_bad_request(transport: str = 'rest', request_type=agent.ImportAgentRequest): - client = AgentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.import_agent(request) - - -def test_import_agent_rest_error(): - client = AgentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - agent.RestoreAgentRequest, - dict, -]) -def test_restore_agent_rest(request_type): - client = AgentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name='operations/spam') - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.restore_agent(request) - - # Establish that the response is the type that we expect. - assert response.operation.name == "operations/spam" - - -def test_restore_agent_rest_required_fields(request_type=agent.RestoreAgentRequest): - transport_class = transports.AgentsRestTransport - - request_init = {} - request_init["parent"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - including_default_value_fields=False, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).restore_agent._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["parent"] = 'parent_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).restore_agent._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "parent" in jsonified_request - assert jsonified_request["parent"] == 'parent_value' - - client = AgentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name='operations/spam') - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "post", - 'query_params': pb_request, - } - transcode_result['body'] = pb_request - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.restore_agent(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_restore_agent_rest_unset_required_fields(): - transport = transports.AgentsRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.restore_agent._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("parent", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_restore_agent_rest_interceptors(null_interceptor): - transport = transports.AgentsRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.AgentsRestInterceptor(), - ) - client = AgentsClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(operation.Operation, "_set_result_from_operation"), \ - mock.patch.object(transports.AgentsRestInterceptor, "post_restore_agent") as post, \ - mock.patch.object(transports.AgentsRestInterceptor, "pre_restore_agent") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = agent.RestoreAgentRequest.pb(agent.RestoreAgentRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = json_format.MessageToJson(operations_pb2.Operation()) - - request = agent.RestoreAgentRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = operations_pb2.Operation() - - client.restore_agent(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_restore_agent_rest_bad_request(transport: str = 'rest', request_type=agent.RestoreAgentRequest): - client = AgentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.restore_agent(request) - - -def test_restore_agent_rest_error(): - client = AgentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - agent.GetValidationResultRequest, - dict, -]) -def test_get_validation_result_rest(request_type): - client = AgentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = validation_result.ValidationResult( - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - pb_return_value = validation_result.ValidationResult.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.get_validation_result(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, validation_result.ValidationResult) - - -def test_get_validation_result_rest_required_fields(request_type=agent.GetValidationResultRequest): - transport_class = transports.AgentsRestTransport - - request_init = {} - request_init["parent"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - including_default_value_fields=False, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_validation_result._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["parent"] = 'parent_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_validation_result._get_unset_required_fields(jsonified_request) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("language_code", )) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "parent" in jsonified_request - assert jsonified_request["parent"] == 'parent_value' - - client = AgentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = validation_result.ValidationResult() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "get", - 'query_params': pb_request, - } - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - - pb_return_value = validation_result.ValidationResult.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.get_validation_result(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_get_validation_result_rest_unset_required_fields(): - transport = transports.AgentsRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.get_validation_result._get_unset_required_fields({}) - assert set(unset_fields) == (set(("languageCode", )) & set(("parent", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_get_validation_result_rest_interceptors(null_interceptor): - transport = transports.AgentsRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.AgentsRestInterceptor(), - ) - client = AgentsClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.AgentsRestInterceptor, "post_get_validation_result") as post, \ - mock.patch.object(transports.AgentsRestInterceptor, "pre_get_validation_result") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = agent.GetValidationResultRequest.pb(agent.GetValidationResultRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = validation_result.ValidationResult.to_json(validation_result.ValidationResult()) - - request = agent.GetValidationResultRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = validation_result.ValidationResult() - - client.get_validation_result(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_get_validation_result_rest_bad_request(transport: str = 'rest', request_type=agent.GetValidationResultRequest): - client = AgentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.get_validation_result(request) - - -def test_get_validation_result_rest_error(): - client = AgentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -def test_credentials_transport_error(): - # It is an error to provide credentials and a transport instance. - transport = transports.AgentsGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = AgentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # It is an error to provide a credentials file and a transport instance. - transport = transports.AgentsGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = AgentsClient( - client_options={"credentials_file": "credentials.json"}, - transport=transport, - ) - - # It is an error to provide an api_key and a transport instance. - transport = transports.AgentsGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - options = client_options.ClientOptions() - options.api_key = "api_key" - with pytest.raises(ValueError): - client = AgentsClient( - client_options=options, - transport=transport, - ) - - # It is an error to provide an api_key and a credential. - options = mock.Mock() - options.api_key = "api_key" - with pytest.raises(ValueError): - client = AgentsClient( - client_options=options, - credentials=ga_credentials.AnonymousCredentials() - ) - - # It is an error to provide scopes and a transport instance. - transport = transports.AgentsGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = AgentsClient( - client_options={"scopes": ["1", "2"]}, - transport=transport, - ) - - -def test_transport_instance(): - # A client may be instantiated with a custom transport instance. - transport = transports.AgentsGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - client = AgentsClient(transport=transport) - assert client.transport is transport - -def test_transport_get_channel(): - # A client may be instantiated with a custom transport instance. - transport = transports.AgentsGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - - transport = transports.AgentsGrpcAsyncIOTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - -@pytest.mark.parametrize("transport_class", [ - transports.AgentsGrpcTransport, - transports.AgentsGrpcAsyncIOTransport, - transports.AgentsRestTransport, -]) -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() - -@pytest.mark.parametrize("transport_name", [ - "grpc", - "rest", -]) -def test_transport_kind(transport_name): - transport = AgentsClient.get_transport_class(transport_name)( - credentials=ga_credentials.AnonymousCredentials(), - ) - assert transport.kind == transport_name - -def test_transport_grpc_default(): - # A client should use the gRPC transport by default. - 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(core_exceptions.DuplicateCredentialArgs): - transport = transports.AgentsTransport( - credentials=ga_credentials.AnonymousCredentials(), - credentials_file="credentials.json" - ) - - -def test_agents_base_transport(): - # Instantiate the base transport. - with mock.patch('google.cloud.dialogflow_v2.services.agents.transports.AgentsTransport.__init__') as Transport: - Transport.return_value = None - transport = transports.AgentsTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Every method on the transport should just blindly - # raise NotImplementedError. - methods = ( - 'get_agent', - 'set_agent', - 'delete_agent', - 'search_agents', - 'train_agent', - 'export_agent', - 'import_agent', - 'restore_agent', - 'get_validation_result', - 'get_location', - 'list_locations', - 'get_operation', - 'cancel_operation', - 'list_operations', - ) - for method in methods: - with pytest.raises(NotImplementedError): - getattr(transport, method)(request=object()) - - with pytest.raises(NotImplementedError): - transport.close() - - # Additionally, the LRO client (a property) should - # also raise NotImplementedError - with pytest.raises(NotImplementedError): - transport.operations_client - - # Catch all for all remaining methods and properties - remainder = [ - 'kind', - ] - for r in remainder: - with pytest.raises(NotImplementedError): - getattr(transport, r)() - - -def test_agents_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.agents.transports.AgentsTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.AgentsTransport( - credentials_file="credentials.json", - quota_project_id="octopus", - ) - load_creds.assert_called_once_with("credentials.json", - scopes=None, - default_scopes=( - 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/dialogflow', -), - quota_project_id="octopus", - ) - - -def test_agents_base_transport_with_adc(): - # Test the default credentials are used if credentials and credentials_file are None. - with mock.patch.object(google.auth, 'default', autospec=True) as adc, mock.patch('google.cloud.dialogflow_v2.services.agents.transports.AgentsTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.AgentsTransport() - adc.assert_called_once() - - -def test_agents_auth_adc(): - # If no credentials are provided, we should use ADC credentials. - with mock.patch.object(google.auth, 'default', autospec=True) as adc: - 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, - ) - - -@pytest.mark.parametrize( - "transport_class", - [ - transports.AgentsGrpcTransport, - transports.AgentsGrpcAsyncIOTransport, - ], -) -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(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, - transports.AgentsRestTransport, - ], -) -def test_agents_transport_auth_gdch_credentials(transport_class): - host = 'https://language.com' - api_audience_tests = [None, 'https://language2.com'] - api_audience_expect = [host, 'https://language2.com'] - for t, e in zip(api_audience_tests, api_audience_expect): - with mock.patch.object(google.auth, 'default', autospec=True) as adc: - gdch_mock = mock.MagicMock() - type(gdch_mock).with_gdch_audience = mock.PropertyMock(return_value=gdch_mock) - adc.return_value = (gdch_mock, None) - transport_class(host=host, api_audience=t) - gdch_mock.with_gdch_audience.assert_called_once_with( - e - ) - - -@pytest.mark.parametrize( - "transport_class,grpc_helpers", - [ - (transports.AgentsGrpcTransport, grpc_helpers), - (transports.AgentsGrpcAsyncIOTransport, grpc_helpers_async) - ], -) -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", [transports.AgentsGrpcTransport, transports.AgentsGrpcAsyncIOTransport]) -def test_agents_grpc_transport_client_cert_source_for_mtls( - transport_class -): - cred = ga_credentials.AnonymousCredentials() - - # Check ssl_channel_credentials is used if provided. - with mock.patch.object(transport_class, "create_channel") as mock_create_channel: - mock_ssl_channel_creds = mock.Mock() - transport_class( - host="squid.clam.whelk", - credentials=cred, - ssl_channel_credentials=mock_ssl_channel_creds - ) - mock_create_channel.assert_called_once_with( - "squid.clam.whelk:443", - credentials=cred, - credentials_file=None, - scopes=None, - ssl_credentials=mock_ssl_channel_creds, - quota_project_id=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - # Check if ssl_channel_credentials is not provided, then client_cert_source_for_mtls - # is used. - with mock.patch.object(transport_class, "create_channel", return_value=mock.Mock()): - with mock.patch("grpc.ssl_channel_credentials") as mock_ssl_cred: - transport_class( - credentials=cred, - client_cert_source_for_mtls=client_cert_source_callback - ) - expected_cert, expected_key = client_cert_source_callback() - mock_ssl_cred.assert_called_once_with( - certificate_chain=expected_cert, - private_key=expected_key - ) - -def test_agents_http_transport_client_cert_source_for_mtls(): - cred = ga_credentials.AnonymousCredentials() - with mock.patch("google.auth.transport.requests.AuthorizedSession.configure_mtls_channel") as mock_configure_mtls_channel: - transports.AgentsRestTransport ( - credentials=cred, - client_cert_source_for_mtls=client_cert_source_callback - ) - mock_configure_mtls_channel.assert_called_once_with(client_cert_source_callback) - - -def test_agents_rest_lro_client(): - client = AgentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - transport = client.transport - - # Ensure that we have a api-core operations client. - assert isinstance( - transport.operations_client, - operations_v1.AbstractOperationsClient, - ) - - # Ensure that subsequent calls to the property send the exact same object. - assert transport.operations_client is transport.operations_client - - -@pytest.mark.parametrize("transport_name", [ - "grpc", - "grpc_asyncio", - "rest", -]) -def test_agents_host_no_port(transport_name): - client = AgentsClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='dialogflow.googleapis.com'), - transport=transport_name, - ) - assert client.transport._host == ( - 'dialogflow.googleapis.com:443' - if transport_name in ['grpc', 'grpc_asyncio'] - else 'https://dialogflow.googleapis.com' - ) - -@pytest.mark.parametrize("transport_name", [ - "grpc", - "grpc_asyncio", - "rest", -]) -def test_agents_host_with_port(transport_name): - client = AgentsClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='dialogflow.googleapis.com:8000'), - transport=transport_name, - ) - assert client.transport._host == ( - 'dialogflow.googleapis.com:8000' - if transport_name in ['grpc', 'grpc_asyncio'] - else 'https://dialogflow.googleapis.com:8000' - ) - -@pytest.mark.parametrize("transport_name", [ - "rest", -]) -def test_agents_client_transport_session_collision(transport_name): - creds1 = ga_credentials.AnonymousCredentials() - creds2 = ga_credentials.AnonymousCredentials() - client1 = AgentsClient( - credentials=creds1, - transport=transport_name, - ) - client2 = AgentsClient( - credentials=creds2, - transport=transport_name, - ) - session1 = client1.transport.get_agent._session - session2 = client2.transport.get_agent._session - assert session1 != session2 - session1 = client1.transport.set_agent._session - session2 = client2.transport.set_agent._session - assert session1 != session2 - session1 = client1.transport.delete_agent._session - session2 = client2.transport.delete_agent._session - assert session1 != session2 - session1 = client1.transport.search_agents._session - session2 = client2.transport.search_agents._session - assert session1 != session2 - session1 = client1.transport.train_agent._session - session2 = client2.transport.train_agent._session - assert session1 != session2 - session1 = client1.transport.export_agent._session - session2 = client2.transport.export_agent._session - assert session1 != session2 - session1 = client1.transport.import_agent._session - session2 = client2.transport.import_agent._session - assert session1 != session2 - session1 = client1.transport.restore_agent._session - session2 = client2.transport.restore_agent._session - assert session1 != session2 - session1 = client1.transport.get_validation_result._session - session2 = client2.transport.get_validation_result._session - assert session1 != session2 -def test_agents_grpc_transport_channel(): - channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.AgentsGrpcTransport( - 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_agents_grpc_asyncio_transport_channel(): - channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.AgentsGrpcAsyncIOTransport( - 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.AgentsGrpcTransport, transports.AgentsGrpcAsyncIOTransport]) -def test_agents_transport_channel_mtls_with_client_cert_source( - transport_class -): - with mock.patch("grpc.ssl_channel_credentials", autospec=True) as grpc_ssl_channel_cred: - with mock.patch.object(transport_class, "create_channel") as grpc_create_channel: - mock_ssl_cred = mock.Mock() - grpc_ssl_channel_cred.return_value = mock_ssl_cred - - mock_grpc_channel = mock.Mock() - grpc_create_channel.return_value = mock_grpc_channel - - cred = ga_credentials.AnonymousCredentials() - with pytest.warns(DeprecationWarning): - with mock.patch.object(google.auth, 'default') as adc: - adc.return_value = (cred, None) - transport = transport_class( - host="squid.clam.whelk", - api_mtls_endpoint="mtls.squid.clam.whelk", - client_cert_source=client_cert_source_callback, - ) - adc.assert_called_once() - - grpc_ssl_channel_cred.assert_called_once_with( - certificate_chain=b"cert bytes", private_key=b"key bytes" - ) - grpc_create_channel.assert_called_once_with( - "mtls.squid.clam.whelk:443", - credentials=cred, - credentials_file=None, - scopes=None, - ssl_credentials=mock_ssl_cred, - quota_project_id=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - assert transport.grpc_channel == mock_grpc_channel - assert transport._ssl_channel_credentials == mock_ssl_cred - - -# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are -# removed from grpc/grpc_asyncio transport constructor. -@pytest.mark.parametrize("transport_class", [transports.AgentsGrpcTransport, transports.AgentsGrpcAsyncIOTransport]) -def test_agents_transport_channel_mtls_with_adc( - transport_class -): - mock_ssl_cred = mock.Mock() - with mock.patch.multiple( - "google.auth.transport.grpc.SslCredentials", - __init__=mock.Mock(return_value=None), - ssl_credentials=mock.PropertyMock(return_value=mock_ssl_cred), - ): - with mock.patch.object(transport_class, "create_channel") as grpc_create_channel: - mock_grpc_channel = mock.Mock() - grpc_create_channel.return_value = mock_grpc_channel - mock_cred = mock.Mock() - - with pytest.warns(DeprecationWarning): - transport = transport_class( - host="squid.clam.whelk", - credentials=mock_cred, - api_mtls_endpoint="mtls.squid.clam.whelk", - client_cert_source=None, - ) - - grpc_create_channel.assert_called_once_with( - "mtls.squid.clam.whelk:443", - credentials=mock_cred, - credentials_file=None, - scopes=None, - ssl_credentials=mock_ssl_cred, - quota_project_id=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - assert transport.grpc_channel == mock_grpc_channel - - -def test_agents_grpc_lro_client(): - client = AgentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - transport = client.transport - - # Ensure that we have a api-core operations client. - assert isinstance( - transport.operations_client, - operations_v1.OperationsClient, - ) - - # Ensure that subsequent calls to the property send the exact same object. - assert transport.operations_client is transport.operations_client - - -def test_agents_grpc_lro_async_client(): - client = AgentsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc_asyncio', - ) - transport = client.transport - - # Ensure that we have a api-core operations client. - assert isinstance( - transport.operations_client, - operations_v1.OperationsAsyncClient, - ) - - # Ensure that subsequent calls to the property send the exact same object. - assert transport.operations_client is transport.operations_client - - -def test_agent_path(): - project = "squid" - expected = "projects/{project}/agent".format(project=project, ) - actual = AgentsClient.agent_path(project) - assert expected == actual - - -def test_parse_agent_path(): - expected = { - "project": "clam", - } - path = AgentsClient.agent_path(**expected) - - # Check that the path construction is reversible. - actual = AgentsClient.parse_agent_path(path) - assert expected == actual - -def test_common_billing_account_path(): - billing_account = "whelk" - expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) - actual = AgentsClient.common_billing_account_path(billing_account) - assert expected == actual - - -def test_parse_common_billing_account_path(): - expected = { - "billing_account": "octopus", - } - path = AgentsClient.common_billing_account_path(**expected) - - # Check that the path construction is reversible. - actual = AgentsClient.parse_common_billing_account_path(path) - assert expected == actual - -def test_common_folder_path(): - folder = "oyster" - expected = "folders/{folder}".format(folder=folder, ) - actual = AgentsClient.common_folder_path(folder) - assert expected == actual - - -def test_parse_common_folder_path(): - expected = { - "folder": "nudibranch", - } - path = AgentsClient.common_folder_path(**expected) - - # Check that the path construction is reversible. - actual = AgentsClient.parse_common_folder_path(path) - assert expected == actual - -def test_common_organization_path(): - organization = "cuttlefish" - expected = "organizations/{organization}".format(organization=organization, ) - actual = AgentsClient.common_organization_path(organization) - assert expected == actual - - -def test_parse_common_organization_path(): - expected = { - "organization": "mussel", - } - path = AgentsClient.common_organization_path(**expected) - - # Check that the path construction is reversible. - actual = AgentsClient.parse_common_organization_path(path) - assert expected == actual - -def test_common_project_path(): - project = "winkle" - expected = "projects/{project}".format(project=project, ) - actual = AgentsClient.common_project_path(project) - assert expected == actual - - -def test_parse_common_project_path(): - expected = { - "project": "nautilus", - } - path = AgentsClient.common_project_path(**expected) - - # Check that the path construction is reversible. - actual = AgentsClient.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 = AgentsClient.common_location_path(project, location) - assert expected == actual - - -def test_parse_common_location_path(): - expected = { - "project": "squid", - "location": "clam", - } - path = AgentsClient.common_location_path(**expected) - - # Check that the path construction is reversible. - actual = AgentsClient.parse_common_location_path(path) - assert expected == actual - - -def test_client_with_default_client_info(): - client_info = gapic_v1.client_info.ClientInfo() - - with mock.patch.object(transports.AgentsTransport, '_prep_wrapped_messages') as prep: - client = AgentsClient( - credentials=ga_credentials.AnonymousCredentials(), - client_info=client_info, - ) - prep.assert_called_once_with(client_info) - - with mock.patch.object(transports.AgentsTransport, '_prep_wrapped_messages') as prep: - transport_class = AgentsClient.get_transport_class() - transport = transport_class( - credentials=ga_credentials.AnonymousCredentials(), - client_info=client_info, - ) - prep.assert_called_once_with(client_info) - -@pytest.mark.asyncio -async def test_transport_close_async(): - client = AgentsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - with mock.patch.object(type(getattr(client.transport, "grpc_channel")), "close") as close: - async with client: - close.assert_not_called() - close.assert_called_once() - - -def test_get_location_rest_bad_request(transport: str = 'rest', request_type=locations_pb2.GetLocationRequest): - client = AgentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - request = request_type() - request = json_format.ParseDict({'name': 'projects/sample1/locations/sample2'}, request) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.get_location(request) - -@pytest.mark.parametrize("request_type", [ - locations_pb2.GetLocationRequest, - dict, -]) -def test_get_location_rest(request_type): - client = AgentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request_init = {'name': 'projects/sample1/locations/sample2'} - request = request_type(**request_init) - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = locations_pb2.Location() - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.get_location(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, locations_pb2.Location) - -def test_list_locations_rest_bad_request(transport: str = 'rest', request_type=locations_pb2.ListLocationsRequest): - client = AgentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - request = request_type() - request = json_format.ParseDict({'name': 'projects/sample1'}, request) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.list_locations(request) - -@pytest.mark.parametrize("request_type", [ - locations_pb2.ListLocationsRequest, - dict, -]) -def test_list_locations_rest(request_type): - client = AgentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request_init = {'name': 'projects/sample1'} - request = request_type(**request_init) - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = locations_pb2.ListLocationsResponse() - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.list_locations(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, locations_pb2.ListLocationsResponse) - -def test_cancel_operation_rest_bad_request(transport: str = 'rest', request_type=operations_pb2.CancelOperationRequest): - client = AgentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - request = request_type() - request = json_format.ParseDict({'name': 'projects/sample1/operations/sample2'}, request) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.cancel_operation(request) - -@pytest.mark.parametrize("request_type", [ - operations_pb2.CancelOperationRequest, - dict, -]) -def test_cancel_operation_rest(request_type): - client = AgentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request_init = {'name': 'projects/sample1/operations/sample2'} - request = request_type(**request_init) - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = None - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = '{}' - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.cancel_operation(request) - - # Establish that the response is the type that we expect. - assert response is None - -def test_get_operation_rest_bad_request(transport: str = 'rest', request_type=operations_pb2.GetOperationRequest): - client = AgentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - request = request_type() - request = json_format.ParseDict({'name': 'projects/sample1/operations/sample2'}, request) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.get_operation(request) - -@pytest.mark.parametrize("request_type", [ - operations_pb2.GetOperationRequest, - dict, -]) -def test_get_operation_rest(request_type): - client = AgentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request_init = {'name': 'projects/sample1/operations/sample2'} - request = request_type(**request_init) - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation() - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.get_operation(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, operations_pb2.Operation) - -def test_list_operations_rest_bad_request(transport: str = 'rest', request_type=operations_pb2.ListOperationsRequest): - client = AgentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - request = request_type() - request = json_format.ParseDict({'name': 'projects/sample1'}, request) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.list_operations(request) - -@pytest.mark.parametrize("request_type", [ - operations_pb2.ListOperationsRequest, - dict, -]) -def test_list_operations_rest(request_type): - client = AgentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request_init = {'name': 'projects/sample1'} - request = request_type(**request_init) - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = operations_pb2.ListOperationsResponse() - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.list_operations(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, operations_pb2.ListOperationsResponse) - - -def test_cancel_operation(transport: str = "grpc"): - client = AgentsClient( - 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 = operations_pb2.CancelOperationRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = None - response = client.cancel_operation(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 response is the type that we expect. - assert response is None -@pytest.mark.asyncio -async def test_cancel_operation_async(transport: str = "grpc"): - client = AgentsAsyncClient( - 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 = operations_pb2.CancelOperationRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - None - ) - response = await client.cancel_operation(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 response is the type that we expect. - assert response is None - -def test_cancel_operation_field_headers(): - 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 = operations_pb2.CancelOperationRequest() - request.name = "locations" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call: - call.return_value = None - - client.cancel_operation(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=locations",) in kw["metadata"] -@pytest.mark.asyncio -async def test_cancel_operation_field_headers_async(): - 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 = operations_pb2.CancelOperationRequest() - request.name = "locations" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - None - ) - await client.cancel_operation(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=locations",) in kw["metadata"] - -def test_cancel_operation_from_dict(): - 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.cancel_operation), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = None - - response = client.cancel_operation( - request={ - "name": "locations", - } - ) - call.assert_called() -@pytest.mark.asyncio -async def test_cancel_operation_from_dict_async(): - 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.cancel_operation), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - None - ) - response = await client.cancel_operation( - request={ - "name": "locations", - } - ) - call.assert_called() - - -def test_get_operation(transport: str = "grpc"): - client = AgentsClient( - 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 = operations_pb2.GetOperationRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_operation), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation() - response = client.get_operation(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 response is the type that we expect. - assert isinstance(response, operations_pb2.Operation) -@pytest.mark.asyncio -async def test_get_operation_async(transport: str = "grpc"): - client = AgentsAsyncClient( - 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 = operations_pb2.GetOperationRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_operation), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation() - ) - response = await client.get_operation(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 response is the type that we expect. - assert isinstance(response, operations_pb2.Operation) - -def test_get_operation_field_headers(): - 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 = operations_pb2.GetOperationRequest() - request.name = "locations" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_operation), "__call__") as call: - call.return_value = operations_pb2.Operation() - - client.get_operation(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=locations",) in kw["metadata"] -@pytest.mark.asyncio -async def test_get_operation_field_headers_async(): - 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 = operations_pb2.GetOperationRequest() - request.name = "locations" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_operation), "__call__") as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation() - ) - await client.get_operation(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=locations",) in kw["metadata"] - -def test_get_operation_from_dict(): - 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_operation), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation() - - response = client.get_operation( - request={ - "name": "locations", - } - ) - call.assert_called() -@pytest.mark.asyncio -async def test_get_operation_from_dict_async(): - 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_operation), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation() - ) - response = await client.get_operation( - request={ - "name": "locations", - } - ) - call.assert_called() - - -def test_list_operations(transport: str = "grpc"): - client = AgentsClient( - 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 = operations_pb2.ListOperationsRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_operations), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.ListOperationsResponse() - response = client.list_operations(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 response is the type that we expect. - assert isinstance(response, operations_pb2.ListOperationsResponse) -@pytest.mark.asyncio -async def test_list_operations_async(transport: str = "grpc"): - client = AgentsAsyncClient( - 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 = operations_pb2.ListOperationsRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_operations), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.ListOperationsResponse() - ) - response = await client.list_operations(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 response is the type that we expect. - assert isinstance(response, operations_pb2.ListOperationsResponse) - -def test_list_operations_field_headers(): - 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 = operations_pb2.ListOperationsRequest() - request.name = "locations" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_operations), "__call__") as call: - call.return_value = operations_pb2.ListOperationsResponse() - - client.list_operations(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=locations",) in kw["metadata"] -@pytest.mark.asyncio -async def test_list_operations_field_headers_async(): - 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 = operations_pb2.ListOperationsRequest() - request.name = "locations" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_operations), "__call__") as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.ListOperationsResponse() - ) - await client.list_operations(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=locations",) in kw["metadata"] - -def test_list_operations_from_dict(): - client = AgentsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_operations), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.ListOperationsResponse() - - response = client.list_operations( - request={ - "name": "locations", - } - ) - call.assert_called() -@pytest.mark.asyncio -async def test_list_operations_from_dict_async(): - client = AgentsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_operations), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.ListOperationsResponse() - ) - response = await client.list_operations( - request={ - "name": "locations", - } - ) - call.assert_called() - - -def test_list_locations(transport: str = "grpc"): - client = AgentsClient( - 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 = locations_pb2.ListLocationsRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_locations), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = locations_pb2.ListLocationsResponse() - response = client.list_locations(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 response is the type that we expect. - assert isinstance(response, locations_pb2.ListLocationsResponse) -@pytest.mark.asyncio -async def test_list_locations_async(transport: str = "grpc"): - client = AgentsAsyncClient( - 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 = locations_pb2.ListLocationsRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_locations), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - locations_pb2.ListLocationsResponse() - ) - response = await client.list_locations(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 response is the type that we expect. - assert isinstance(response, locations_pb2.ListLocationsResponse) - -def test_list_locations_field_headers(): - 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 = locations_pb2.ListLocationsRequest() - request.name = "locations" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_locations), "__call__") as call: - call.return_value = locations_pb2.ListLocationsResponse() - - client.list_locations(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=locations",) in kw["metadata"] -@pytest.mark.asyncio -async def test_list_locations_field_headers_async(): - 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 = locations_pb2.ListLocationsRequest() - request.name = "locations" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_locations), "__call__") as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - locations_pb2.ListLocationsResponse() - ) - await client.list_locations(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=locations",) in kw["metadata"] - -def test_list_locations_from_dict(): - client = AgentsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_locations), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = locations_pb2.ListLocationsResponse() - - response = client.list_locations( - request={ - "name": "locations", - } - ) - call.assert_called() -@pytest.mark.asyncio -async def test_list_locations_from_dict_async(): - client = AgentsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_locations), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - locations_pb2.ListLocationsResponse() - ) - response = await client.list_locations( - request={ - "name": "locations", - } - ) - call.assert_called() - - -def test_get_location(transport: str = "grpc"): - client = AgentsClient( - 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 = locations_pb2.GetLocationRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_location), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = locations_pb2.Location() - response = client.get_location(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 response is the type that we expect. - assert isinstance(response, locations_pb2.Location) -@pytest.mark.asyncio -async def test_get_location_async(transport: str = "grpc_asyncio"): - client = AgentsAsyncClient( - 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 = locations_pb2.GetLocationRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_location), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - locations_pb2.Location() - ) - response = await client.get_location(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 response is the type that we expect. - assert isinstance(response, locations_pb2.Location) - -def test_get_location_field_headers(): - 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 = locations_pb2.GetLocationRequest() - request.name = "locations/abc" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_location), "__call__") as call: - call.return_value = locations_pb2.Location() - - client.get_location(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=locations/abc",) in kw["metadata"] -@pytest.mark.asyncio -async def test_get_location_field_headers_async(): - 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 = locations_pb2.GetLocationRequest() - request.name = "locations/abc" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_location), "__call__") as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - locations_pb2.Location() - ) - await client.get_location(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=locations/abc",) in kw["metadata"] - -def test_get_location_from_dict(): - client = AgentsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_locations), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = locations_pb2.Location() - - response = client.get_location( - request={ - "name": "locations/abc", - } - ) - call.assert_called() -@pytest.mark.asyncio -async def test_get_location_from_dict_async(): - client = AgentsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_locations), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - locations_pb2.Location() - ) - response = await client.get_location( - request={ - "name": "locations", - } - ) - call.assert_called() - - -def test_transport_close(): - transports = { - "rest": "_session", - "grpc": "_grpc_channel", - } - - for transport, close_name in transports.items(): - client = AgentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport - ) - with mock.patch.object(type(getattr(client.transport, close_name)), "close") as close: - with client: - close.assert_not_called() - close.assert_called_once() - -def test_client_ctx(): - transports = [ - 'rest', - 'grpc', - ] - for transport in transports: - client = AgentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport - ) - # Test client calls underlying transport. - with mock.patch.object(type(client.transport), "close") as close: - close.assert_not_called() - with client: - pass - close.assert_called() - -@pytest.mark.parametrize("client_class,transport_class", [ - (AgentsClient, transports.AgentsGrpcTransport), - (AgentsAsyncClient, transports.AgentsGrpcAsyncIOTransport), -]) -def test_api_key_credentials(client_class, transport_class): - with mock.patch.object( - google.auth._default, "get_api_key_credentials", create=True - ) as get_api_key_credentials: - mock_cred = mock.Mock() - get_api_key_credentials.return_value = mock_cred - options = client_options.ClientOptions() - options.api_key = "api_key" - 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=mock_cred, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) diff --git a/owl-bot-staging/v2/tests/unit/gapic/dialogflow_v2/test_answer_records.py b/owl-bot-staging/v2/tests/unit/gapic/dialogflow_v2/test_answer_records.py deleted file mode 100644 index d5ced9ece..000000000 --- a/owl-bot-staging/v2/tests/unit/gapic/dialogflow_v2/test_answer_records.py +++ /dev/null @@ -1,3304 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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 -# try/except added for compatibility with python < 3.8 -try: - from unittest import mock - from unittest.mock import AsyncMock # pragma: NO COVER -except ImportError: # pragma: NO COVER - import mock - -import grpc -from grpc.experimental import aio -from collections.abc import Iterable -from google.protobuf import json_format -import json -import math -import pytest -from proto.marshal.rules.dates import DurationRule, TimestampRule -from proto.marshal.rules import wrappers -from requests import Response -from requests import Request, PreparedRequest -from requests.sessions import Session -from google.protobuf import json_format - -from google.api_core import client_options -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import grpc_helpers -from google.api_core import grpc_helpers_async -from google.api_core import path_template -from google.auth import credentials as ga_credentials -from google.auth.exceptions import MutualTLSChannelError -from google.cloud.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.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.cloud.location import locations_pb2 -from google.longrunning import operations_pb2 -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 - - -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 AnswerRecordsClient._get_default_mtls_endpoint(None) is None - assert AnswerRecordsClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint - assert AnswerRecordsClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint - assert AnswerRecordsClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint - assert AnswerRecordsClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint - assert AnswerRecordsClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi - - -@pytest.mark.parametrize("client_class,transport_name", [ - (AnswerRecordsClient, "grpc"), - (AnswerRecordsAsyncClient, "grpc_asyncio"), - (AnswerRecordsClient, "rest"), -]) -def test_answer_records_client_from_service_account_info(client_class, transport_name): - 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, transport=transport_name) - assert client.transport._credentials == creds - assert isinstance(client, client_class) - - assert client.transport._host == ( - 'dialogflow.googleapis.com:443' - if transport_name in ['grpc', 'grpc_asyncio'] - else - 'https://dialogflow.googleapis.com' - ) - - -@pytest.mark.parametrize("transport_class,transport_name", [ - (transports.AnswerRecordsGrpcTransport, "grpc"), - (transports.AnswerRecordsGrpcAsyncIOTransport, "grpc_asyncio"), - (transports.AnswerRecordsRestTransport, "rest"), -]) -def test_answer_records_client_service_account_always_use_jwt(transport_class, transport_name): - with mock.patch.object(service_account.Credentials, 'with_always_use_jwt_access', create=True) as use_jwt: - creds = service_account.Credentials(None, None, None) - transport = transport_class(credentials=creds, always_use_jwt_access=True) - use_jwt.assert_called_once_with(True) - - with mock.patch.object(service_account.Credentials, 'with_always_use_jwt_access', create=True) as use_jwt: - creds = service_account.Credentials(None, None, None) - transport = transport_class(credentials=creds, always_use_jwt_access=False) - use_jwt.assert_not_called() - - -@pytest.mark.parametrize("client_class,transport_name", [ - (AnswerRecordsClient, "grpc"), - (AnswerRecordsAsyncClient, "grpc_asyncio"), - (AnswerRecordsClient, "rest"), -]) -def test_answer_records_client_from_service_account_file(client_class, transport_name): - 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", transport=transport_name) - assert client.transport._credentials == creds - assert isinstance(client, client_class) - - client = client_class.from_service_account_json("dummy/file/path.json", transport=transport_name) - assert client.transport._credentials == creds - assert isinstance(client, client_class) - - assert client.transport._host == ( - 'dialogflow.googleapis.com:443' - if transport_name in ['grpc', 'grpc_asyncio'] - else - 'https://dialogflow.googleapis.com' - ) - - -def test_answer_records_client_get_transport_class(): - transport = AnswerRecordsClient.get_transport_class() - available_transports = [ - transports.AnswerRecordsGrpcTransport, - transports.AnswerRecordsRestTransport, - ] - assert transport in available_transports - - transport = AnswerRecordsClient.get_transport_class("grpc") - assert transport == transports.AnswerRecordsGrpcTransport - - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (AnswerRecordsClient, transports.AnswerRecordsGrpcTransport, "grpc"), - (AnswerRecordsAsyncClient, transports.AnswerRecordsGrpcAsyncIOTransport, "grpc_asyncio"), - (AnswerRecordsClient, transports.AnswerRecordsRestTransport, "rest"), -]) -@mock.patch.object(AnswerRecordsClient, "DEFAULT_ENDPOINT", modify_default_endpoint(AnswerRecordsClient)) -@mock.patch.object(AnswerRecordsAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(AnswerRecordsAsyncClient)) -def test_answer_records_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(AnswerRecordsClient, '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(AnswerRecordsClient, 'get_transport_class') as gtc: - client = client_class(transport=transport_name) - gtc.assert_called() - - # Check the case api_endpoint is provided. - options = client_options.ClientOptions(api_endpoint="squid.clam.whelk") - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(transport=transport_name, client_options=options) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host="squid.clam.whelk", - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is - # "never". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is - # "always". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_MTLS_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # 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(transport=transport_name) - - # 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(transport=transport_name) - - # 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, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id="octopus", - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - # Check the case api_endpoint is provided - options = client_options.ClientOptions(api_audience="https://language.googleapis.com") - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience="https://language.googleapis.com" - ) - -@pytest.mark.parametrize("client_class,transport_class,transport_name,use_client_cert_env", [ - (AnswerRecordsClient, transports.AnswerRecordsGrpcTransport, "grpc", "true"), - (AnswerRecordsAsyncClient, transports.AnswerRecordsGrpcAsyncIOTransport, "grpc_asyncio", "true"), - (AnswerRecordsClient, transports.AnswerRecordsGrpcTransport, "grpc", "false"), - (AnswerRecordsAsyncClient, transports.AnswerRecordsGrpcAsyncIOTransport, "grpc_asyncio", "false"), - (AnswerRecordsClient, transports.AnswerRecordsRestTransport, "rest", "true"), - (AnswerRecordsClient, transports.AnswerRecordsRestTransport, "rest", "false"), -]) -@mock.patch.object(AnswerRecordsClient, "DEFAULT_ENDPOINT", modify_default_endpoint(AnswerRecordsClient)) -@mock.patch.object(AnswerRecordsAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(AnswerRecordsAsyncClient)) -@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) -def test_answer_records_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, transport=transport_name) - - if use_client_cert_env == "false": - expected_client_cert_source = None - expected_host = client.DEFAULT_ENDPOINT - else: - expected_client_cert_source = client_cert_source_callback - expected_host = client.DEFAULT_MTLS_ENDPOINT - - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=expected_host, - scopes=None, - client_cert_source_for_mtls=expected_client_cert_source, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case ADC client cert is provided. Whether client cert is used depends on - # GOOGLE_API_USE_CLIENT_CERTIFICATE value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): - with mock.patch.object(transport_class, '__init__') as patched: - with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): - with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=client_cert_source_callback): - if use_client_cert_env == "false": - expected_host = client.DEFAULT_ENDPOINT - expected_client_cert_source = None - else: - expected_host = client.DEFAULT_MTLS_ENDPOINT - expected_client_cert_source = client_cert_source_callback - - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=expected_host, - scopes=None, - client_cert_source_for_mtls=expected_client_cert_source, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case client_cert_source and ADC client cert are not provided. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): - with mock.patch.object(transport_class, '__init__') as patched: - with mock.patch("google.auth.transport.mtls.has_default_client_cert_source", return_value=False): - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - -@pytest.mark.parametrize("client_class", [ - AnswerRecordsClient, AnswerRecordsAsyncClient -]) -@mock.patch.object(AnswerRecordsClient, "DEFAULT_ENDPOINT", modify_default_endpoint(AnswerRecordsClient)) -@mock.patch.object(AnswerRecordsAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(AnswerRecordsAsyncClient)) -def test_answer_records_client_get_mtls_endpoint_and_cert_source(client_class): - mock_client_cert_source = mock.Mock() - - # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "true". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - mock_api_endpoint = "foo" - options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) - assert api_endpoint == mock_api_endpoint - assert cert_source == mock_client_cert_source - - # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "false". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): - mock_client_cert_source = mock.Mock() - mock_api_endpoint = "foo" - options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) - assert api_endpoint == mock_api_endpoint - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "never". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_ENDPOINT - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "always". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert doesn't exist. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=False): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_ENDPOINT - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert exists. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - 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=mock_client_cert_source): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT - assert cert_source == mock_client_cert_source - - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (AnswerRecordsClient, transports.AnswerRecordsGrpcTransport, "grpc"), - (AnswerRecordsAsyncClient, transports.AnswerRecordsGrpcAsyncIOTransport, "grpc_asyncio"), - (AnswerRecordsClient, transports.AnswerRecordsRestTransport, "rest"), -]) -def test_answer_records_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, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=["1", "2"], - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - -@pytest.mark.parametrize("client_class,transport_class,transport_name,grpc_helpers", [ - (AnswerRecordsClient, transports.AnswerRecordsGrpcTransport, "grpc", grpc_helpers), - (AnswerRecordsAsyncClient, transports.AnswerRecordsGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), - (AnswerRecordsClient, transports.AnswerRecordsRestTransport, "rest", None), -]) -def test_answer_records_client_client_options_credentials_file(client_class, transport_class, transport_name, grpc_helpers): - # 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, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file="credentials.json", - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - -def test_answer_records_client_client_options_from_dict(): - with mock.patch('google.cloud.dialogflow_v2.services.answer_records.transports.AnswerRecordsGrpcTransport.__init__') as grpc_transport: - grpc_transport.return_value = None - client = AnswerRecordsClient( - client_options={'api_endpoint': 'squid.clam.whelk'} - ) - grpc_transport.assert_called_once_with( - credentials=None, - credentials_file=None, - host="squid.clam.whelk", - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - -@pytest.mark.parametrize("client_class,transport_class,transport_name,grpc_helpers", [ - (AnswerRecordsClient, transports.AnswerRecordsGrpcTransport, "grpc", grpc_helpers), - (AnswerRecordsAsyncClient, transports.AnswerRecordsGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), -]) -def test_answer_records_client_create_channel_credentials_file(client_class, transport_class, transport_name, grpc_helpers): - # 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, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file="credentials.json", - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # test that the credentials from file are saved and used as the credentials. - with mock.patch.object( - google.auth, "load_credentials_from_file", autospec=True - ) as load_creds, mock.patch.object( - google.auth, "default", autospec=True - ) as adc, mock.patch.object( - grpc_helpers, "create_channel" - ) as create_channel: - creds = ga_credentials.AnonymousCredentials() - file_creds = ga_credentials.AnonymousCredentials() - load_creds.return_value = (file_creds, None) - adc.return_value = (creds, None) - client = client_class(client_options=options, transport=transport_name) - create_channel.assert_called_with( - "dialogflow.googleapis.com:443", - credentials=file_creds, - credentials_file=None, - quota_project_id=None, - default_scopes=( - 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/dialogflow', -), - scopes=None, - default_host="dialogflow.googleapis.com", - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - -@pytest.mark.parametrize("request_type", [ - answer_record.ListAnswerRecordsRequest, - dict, -]) -def test_list_answer_records(request_type, transport: str = 'grpc'): - client = AnswerRecordsClient( - 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_answer_records), - '__call__') as call: - # Designate an appropriate return value for the call. - 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' - - -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=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_answer_records), - '__call__') as call: - client.list_answer_records() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == answer_record.ListAnswerRecordsRequest() - -@pytest.mark.asyncio -async def test_list_answer_records_async(transport: str = 'grpc_asyncio', request_type=answer_record.ListAnswerRecordsRequest): - client = AnswerRecordsAsyncClient( - 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_answer_records), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(answer_record.ListAnswerRecordsResponse( - 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' - - -@pytest.mark.asyncio -async def test_list_answer_records_async_from_dict(): - await test_list_answer_records_async(request_type=dict) - - -def test_list_answer_records_field_headers(): - 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. - with mock.patch.object( - 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. - 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_answer_records_field_headers_async(): - 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. - with mock.patch.object( - type(client.transport.list_answer_records), - '__call__') as call: - 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. - 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_answer_records_flattened(): - client = AnswerRecordsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_answer_records), - '__call__') 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', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - arg = args[0].parent - mock_val = 'parent_value' - assert arg == mock_val - - -def test_list_answer_records_flattened_error(): - client = AnswerRecordsClient( - 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_answer_records( - answer_record.ListAnswerRecordsRequest(), - parent='parent_value', - ) - -@pytest.mark.asyncio -async def test_list_answer_records_flattened_async(): - client = AnswerRecordsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_answer_records), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = answer_record.ListAnswerRecordsResponse() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(answer_record.ListAnswerRecordsResponse()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.list_answer_records( - 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] - arg = args[0].parent - mock_val = 'parent_value' - assert arg == mock_val - -@pytest.mark.asyncio -async def test_list_answer_records_flattened_error_async(): - client = AnswerRecordsAsyncClient( - 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_answer_records( - answer_record.ListAnswerRecordsRequest(), - parent='parent_value', - ) - - -def test_list_answer_records_pager(transport_name: str = "grpc"): - client = AnswerRecordsClient( - credentials=ga_credentials.AnonymousCredentials, - transport=transport_name, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_answer_records), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - answer_record.ListAnswerRecordsResponse( - answer_records=[ - answer_record.AnswerRecord(), - answer_record.AnswerRecord(), - answer_record.AnswerRecord(), - ], - next_page_token='abc', - ), - answer_record.ListAnswerRecordsResponse( - answer_records=[], - next_page_token='def', - ), - answer_record.ListAnswerRecordsResponse( - answer_records=[ - answer_record.AnswerRecord(), - ], - next_page_token='ghi', - ), - answer_record.ListAnswerRecordsResponse( - answer_records=[ - answer_record.AnswerRecord(), - answer_record.AnswerRecord(), - ], - ), - RuntimeError, - ) - - metadata = () - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ('parent', ''), - )), - ) - pager = client.list_answer_records(request={}) - - assert pager._metadata == metadata - - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, answer_record.AnswerRecord) - for i in results) -def test_list_answer_records_pages(transport_name: str = "grpc"): - client = AnswerRecordsClient( - credentials=ga_credentials.AnonymousCredentials, - transport=transport_name, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_answer_records), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - answer_record.ListAnswerRecordsResponse( - answer_records=[ - answer_record.AnswerRecord(), - answer_record.AnswerRecord(), - answer_record.AnswerRecord(), - ], - next_page_token='abc', - ), - answer_record.ListAnswerRecordsResponse( - answer_records=[], - next_page_token='def', - ), - answer_record.ListAnswerRecordsResponse( - answer_records=[ - answer_record.AnswerRecord(), - ], - next_page_token='ghi', - ), - answer_record.ListAnswerRecordsResponse( - answer_records=[ - answer_record.AnswerRecord(), - answer_record.AnswerRecord(), - ], - ), - RuntimeError, - ) - pages = list(client.list_answer_records(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_answer_records_async_pager(): - client = AnswerRecordsAsyncClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_answer_records), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - answer_record.ListAnswerRecordsResponse( - answer_records=[ - answer_record.AnswerRecord(), - answer_record.AnswerRecord(), - answer_record.AnswerRecord(), - ], - next_page_token='abc', - ), - answer_record.ListAnswerRecordsResponse( - answer_records=[], - next_page_token='def', - ), - answer_record.ListAnswerRecordsResponse( - answer_records=[ - answer_record.AnswerRecord(), - ], - next_page_token='ghi', - ), - answer_record.ListAnswerRecordsResponse( - answer_records=[ - answer_record.AnswerRecord(), - answer_record.AnswerRecord(), - ], - ), - RuntimeError, - ) - async_pager = await client.list_answer_records(request={},) - assert async_pager.next_page_token == 'abc' - responses = [] - async for response in async_pager: # pragma: no branch - responses.append(response) - - assert len(responses) == 6 - assert all(isinstance(i, answer_record.AnswerRecord) - for i in responses) - - -@pytest.mark.asyncio -async def test_list_answer_records_async_pages(): - client = AnswerRecordsAsyncClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_answer_records), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - answer_record.ListAnswerRecordsResponse( - answer_records=[ - answer_record.AnswerRecord(), - answer_record.AnswerRecord(), - answer_record.AnswerRecord(), - ], - next_page_token='abc', - ), - answer_record.ListAnswerRecordsResponse( - answer_records=[], - next_page_token='def', - ), - answer_record.ListAnswerRecordsResponse( - answer_records=[ - answer_record.AnswerRecord(), - ], - next_page_token='ghi', - ), - answer_record.ListAnswerRecordsResponse( - answer_records=[ - answer_record.AnswerRecord(), - answer_record.AnswerRecord(), - ], - ), - RuntimeError, - ) - pages = [] - async for page_ in (await client.list_answer_records(request={})).pages: # pragma: no branch - pages.append(page_) - for page_, token in zip(pages, ['abc','def','ghi', '']): - assert page_.raw_page.next_page_token == token - -@pytest.mark.parametrize("request_type", [ - gcd_answer_record.UpdateAnswerRecordRequest, - dict, -]) -def test_update_answer_record(request_type, transport: str = 'grpc'): - client = AnswerRecordsClient( - 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_answer_record), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcd_answer_record.AnswerRecord( - name='name_value', - agent_assistant_record=gcd_answer_record.AgentAssistantRecord(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' - - -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=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_answer_record), - '__call__') as call: - client.update_answer_record() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == gcd_answer_record.UpdateAnswerRecordRequest() - -@pytest.mark.asyncio -async def test_update_answer_record_async(transport: str = 'grpc_asyncio', request_type=gcd_answer_record.UpdateAnswerRecordRequest): - client = AnswerRecordsAsyncClient( - 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_answer_record), - '__call__') as call: - # Designate an appropriate return value for the call. - 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' - - -@pytest.mark.asyncio -async def test_update_answer_record_async_from_dict(): - await test_update_answer_record_async(request_type=dict) - - -def test_update_answer_record_field_headers(): - 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 = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - 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. - 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', - 'answer_record.name=name_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_update_answer_record_field_headers_async(): - 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 = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_answer_record), - '__call__') as call: - 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. - 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', - 'answer_record.name=name_value', - ) in kw['metadata'] - - -def test_update_answer_record_flattened(): - client = AnswerRecordsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_answer_record), - '__call__') 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_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] - arg = args[0].answer_record - mock_val = gcd_answer_record.AnswerRecord(name='name_value') - assert arg == mock_val - arg = args[0].update_mask - mock_val = field_mask_pb2.FieldMask(paths=['paths_value']) - assert arg == mock_val - - -def test_update_answer_record_flattened_error(): - client = AnswerRecordsClient( - 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_answer_record( - gcd_answer_record.UpdateAnswerRecordRequest(), - answer_record=gcd_answer_record.AnswerRecord(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - -@pytest.mark.asyncio -async def test_update_answer_record_flattened_async(): - client = AnswerRecordsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_answer_record), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcd_answer_record.AnswerRecord() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcd_answer_record.AnswerRecord()) - # Call the method with a truthy value for each flattened field, - # 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_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] - arg = args[0].answer_record - mock_val = gcd_answer_record.AnswerRecord(name='name_value') - assert arg == mock_val - arg = args[0].update_mask - mock_val = field_mask_pb2.FieldMask(paths=['paths_value']) - assert arg == mock_val - -@pytest.mark.asyncio -async def test_update_answer_record_flattened_error_async(): - client = AnswerRecordsAsyncClient( - 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_answer_record( - gcd_answer_record.UpdateAnswerRecordRequest(), - answer_record=gcd_answer_record.AnswerRecord(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - - -@pytest.mark.parametrize("request_type", [ - answer_record.ListAnswerRecordsRequest, - dict, -]) -def test_list_answer_records_rest(request_type): - client = AnswerRecordsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = answer_record.ListAnswerRecordsResponse( - next_page_token='next_page_token_value', - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - pb_return_value = answer_record.ListAnswerRecordsResponse.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.list_answer_records(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListAnswerRecordsPager) - assert response.next_page_token == 'next_page_token_value' - - -def test_list_answer_records_rest_required_fields(request_type=answer_record.ListAnswerRecordsRequest): - transport_class = transports.AnswerRecordsRestTransport - - request_init = {} - request_init["parent"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - including_default_value_fields=False, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).list_answer_records._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["parent"] = 'parent_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).list_answer_records._get_unset_required_fields(jsonified_request) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("filter", "page_size", "page_token", )) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "parent" in jsonified_request - assert jsonified_request["parent"] == 'parent_value' - - client = AnswerRecordsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = answer_record.ListAnswerRecordsResponse() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "get", - 'query_params': pb_request, - } - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - - pb_return_value = answer_record.ListAnswerRecordsResponse.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.list_answer_records(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_list_answer_records_rest_unset_required_fields(): - transport = transports.AnswerRecordsRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.list_answer_records._get_unset_required_fields({}) - assert set(unset_fields) == (set(("filter", "pageSize", "pageToken", )) & set(("parent", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_list_answer_records_rest_interceptors(null_interceptor): - transport = transports.AnswerRecordsRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.AnswerRecordsRestInterceptor(), - ) - client = AnswerRecordsClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.AnswerRecordsRestInterceptor, "post_list_answer_records") as post, \ - mock.patch.object(transports.AnswerRecordsRestInterceptor, "pre_list_answer_records") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = answer_record.ListAnswerRecordsRequest.pb(answer_record.ListAnswerRecordsRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = answer_record.ListAnswerRecordsResponse.to_json(answer_record.ListAnswerRecordsResponse()) - - request = answer_record.ListAnswerRecordsRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = answer_record.ListAnswerRecordsResponse() - - client.list_answer_records(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_list_answer_records_rest_bad_request(transport: str = 'rest', request_type=answer_record.ListAnswerRecordsRequest): - client = AnswerRecordsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.list_answer_records(request) - - -def test_list_answer_records_rest_flattened(): - client = AnswerRecordsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = answer_record.ListAnswerRecordsResponse() - - # get arguments that satisfy an http rule for this method - sample_request = {'parent': 'projects/sample1'} - - # get truthy value for each flattened field - mock_args = dict( - parent='parent_value', - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - pb_return_value = answer_record.ListAnswerRecordsResponse.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.list_answer_records(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v2/{parent=projects/*}/answerRecords" % client.transport._host, args[1]) - - -def test_list_answer_records_rest_flattened_error(transport: str = 'rest'): - client = AnswerRecordsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.list_answer_records( - answer_record.ListAnswerRecordsRequest(), - parent='parent_value', - ) - - -def test_list_answer_records_rest_pager(transport: str = 'rest'): - client = AnswerRecordsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # TODO(kbandes): remove this mock unless there's a good reason for it. - #with mock.patch.object(path_template, 'transcode') as transcode: - # Set the response as a series of pages - response = ( - answer_record.ListAnswerRecordsResponse( - answer_records=[ - answer_record.AnswerRecord(), - answer_record.AnswerRecord(), - answer_record.AnswerRecord(), - ], - next_page_token='abc', - ), - answer_record.ListAnswerRecordsResponse( - answer_records=[], - next_page_token='def', - ), - answer_record.ListAnswerRecordsResponse( - answer_records=[ - answer_record.AnswerRecord(), - ], - next_page_token='ghi', - ), - answer_record.ListAnswerRecordsResponse( - answer_records=[ - answer_record.AnswerRecord(), - answer_record.AnswerRecord(), - ], - ), - ) - # Two responses for two calls - response = response + response - - # Wrap the values into proper Response objs - response = tuple(answer_record.ListAnswerRecordsResponse.to_json(x) for x in response) - return_values = tuple(Response() for i in response) - for return_val, response_val in zip(return_values, response): - return_val._content = response_val.encode('UTF-8') - return_val.status_code = 200 - req.side_effect = return_values - - sample_request = {'parent': 'projects/sample1'} - - pager = client.list_answer_records(request=sample_request) - - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, answer_record.AnswerRecord) - for i in results) - - pages = list(client.list_answer_records(request=sample_request).pages) - for page_, token in zip(pages, ['abc','def','ghi', '']): - assert page_.raw_page.next_page_token == token - - -@pytest.mark.parametrize("request_type", [ - gcd_answer_record.UpdateAnswerRecordRequest, - dict, -]) -def test_update_answer_record_rest(request_type): - client = AnswerRecordsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'answer_record': {'name': 'projects/sample1/answerRecords/sample2'}} - request_init["answer_record"] = {'name': 'projects/sample1/answerRecords/sample2', 'answer_feedback': {'correctness_level': 1, 'agent_assistant_detail_feedback': {'answer_relevance': 1, 'document_correctness': 1, 'document_efficiency': 1, 'summarization_feedback': {'start_time': {'seconds': 751, 'nanos': 543}, 'submit_time': {}, 'summary_text': 'summary_text_value'}}, 'clicked': True, 'click_time': {}, 'displayed': True, 'display_time': {}}, 'agent_assistant_record': {'article_suggestion_answer': {'title': 'title_value', 'uri': 'uri_value', 'snippets': ['snippets_value1', 'snippets_value2'], 'confidence': 0.1038, 'metadata': {}, 'answer_record': 'answer_record_value'}, 'faq_answer': {'answer': 'answer_value', 'confidence': 0.1038, 'question': 'question_value', 'source': 'source_value', 'metadata': {}, 'answer_record': 'answer_record_value'}}} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = gcd_answer_record.AnswerRecord( - name='name_value', - agent_assistant_record=gcd_answer_record.AgentAssistantRecord(article_suggestion_answer=participant.ArticleAnswer(title='title_value')), - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - pb_return_value = gcd_answer_record.AnswerRecord.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.update_answer_record(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, gcd_answer_record.AnswerRecord) - assert response.name == 'name_value' - - -def test_update_answer_record_rest_required_fields(request_type=gcd_answer_record.UpdateAnswerRecordRequest): - transport_class = transports.AnswerRecordsRestTransport - - request_init = {} - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - including_default_value_fields=False, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).update_answer_record._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).update_answer_record._get_unset_required_fields(jsonified_request) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("update_mask", )) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - - client = AnswerRecordsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = gcd_answer_record.AnswerRecord() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "patch", - 'query_params': pb_request, - } - transcode_result['body'] = pb_request - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - - pb_return_value = gcd_answer_record.AnswerRecord.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.update_answer_record(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_update_answer_record_rest_unset_required_fields(): - transport = transports.AnswerRecordsRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.update_answer_record._get_unset_required_fields({}) - assert set(unset_fields) == (set(("updateMask", )) & set(("answerRecord", "updateMask", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_update_answer_record_rest_interceptors(null_interceptor): - transport = transports.AnswerRecordsRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.AnswerRecordsRestInterceptor(), - ) - client = AnswerRecordsClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.AnswerRecordsRestInterceptor, "post_update_answer_record") as post, \ - mock.patch.object(transports.AnswerRecordsRestInterceptor, "pre_update_answer_record") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = gcd_answer_record.UpdateAnswerRecordRequest.pb(gcd_answer_record.UpdateAnswerRecordRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = gcd_answer_record.AnswerRecord.to_json(gcd_answer_record.AnswerRecord()) - - request = gcd_answer_record.UpdateAnswerRecordRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = gcd_answer_record.AnswerRecord() - - client.update_answer_record(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_update_answer_record_rest_bad_request(transport: str = 'rest', request_type=gcd_answer_record.UpdateAnswerRecordRequest): - client = AnswerRecordsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'answer_record': {'name': 'projects/sample1/answerRecords/sample2'}} - request_init["answer_record"] = {'name': 'projects/sample1/answerRecords/sample2', 'answer_feedback': {'correctness_level': 1, 'agent_assistant_detail_feedback': {'answer_relevance': 1, 'document_correctness': 1, 'document_efficiency': 1, 'summarization_feedback': {'start_time': {'seconds': 751, 'nanos': 543}, 'submit_time': {}, 'summary_text': 'summary_text_value'}}, 'clicked': True, 'click_time': {}, 'displayed': True, 'display_time': {}}, 'agent_assistant_record': {'article_suggestion_answer': {'title': 'title_value', 'uri': 'uri_value', 'snippets': ['snippets_value1', 'snippets_value2'], 'confidence': 0.1038, 'metadata': {}, 'answer_record': 'answer_record_value'}, 'faq_answer': {'answer': 'answer_value', 'confidence': 0.1038, 'question': 'question_value', 'source': 'source_value', 'metadata': {}, 'answer_record': 'answer_record_value'}}} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.update_answer_record(request) - - -def test_update_answer_record_rest_flattened(): - client = AnswerRecordsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = gcd_answer_record.AnswerRecord() - - # get arguments that satisfy an http rule for this method - sample_request = {'answer_record': {'name': 'projects/sample1/answerRecords/sample2'}} - - # get truthy value for each flattened field - mock_args = dict( - answer_record=gcd_answer_record.AnswerRecord(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - pb_return_value = gcd_answer_record.AnswerRecord.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.update_answer_record(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v2/{answer_record.name=projects/*/answerRecords/*}" % client.transport._host, args[1]) - - -def test_update_answer_record_rest_flattened_error(transport: str = 'rest'): - client = AnswerRecordsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.update_answer_record( - gcd_answer_record.UpdateAnswerRecordRequest(), - answer_record=gcd_answer_record.AnswerRecord(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - - -def test_update_answer_record_rest_error(): - client = AnswerRecordsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -def test_credentials_transport_error(): - # It is an error to provide credentials and a transport instance. - transport = transports.AnswerRecordsGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = AnswerRecordsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # It is an error to provide a credentials file and a transport instance. - transport = transports.AnswerRecordsGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = AnswerRecordsClient( - client_options={"credentials_file": "credentials.json"}, - transport=transport, - ) - - # It is an error to provide an api_key and a transport instance. - transport = transports.AnswerRecordsGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - options = client_options.ClientOptions() - options.api_key = "api_key" - with pytest.raises(ValueError): - client = AnswerRecordsClient( - client_options=options, - transport=transport, - ) - - # It is an error to provide an api_key and a credential. - options = mock.Mock() - options.api_key = "api_key" - with pytest.raises(ValueError): - client = AnswerRecordsClient( - client_options=options, - credentials=ga_credentials.AnonymousCredentials() - ) - - # It is an error to provide scopes and a transport instance. - transport = transports.AnswerRecordsGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = AnswerRecordsClient( - client_options={"scopes": ["1", "2"]}, - transport=transport, - ) - - -def test_transport_instance(): - # A client may be instantiated with a custom transport instance. - transport = transports.AnswerRecordsGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - client = AnswerRecordsClient(transport=transport) - assert client.transport is transport - -def test_transport_get_channel(): - # A client may be instantiated with a custom transport instance. - transport = transports.AnswerRecordsGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - - transport = transports.AnswerRecordsGrpcAsyncIOTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - -@pytest.mark.parametrize("transport_class", [ - transports.AnswerRecordsGrpcTransport, - transports.AnswerRecordsGrpcAsyncIOTransport, - transports.AnswerRecordsRestTransport, -]) -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() - -@pytest.mark.parametrize("transport_name", [ - "grpc", - "rest", -]) -def test_transport_kind(transport_name): - transport = AnswerRecordsClient.get_transport_class(transport_name)( - credentials=ga_credentials.AnonymousCredentials(), - ) - assert transport.kind == transport_name - -def test_transport_grpc_default(): - # A client should use the gRPC transport by default. - 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(core_exceptions.DuplicateCredentialArgs): - transport = transports.AnswerRecordsTransport( - credentials=ga_credentials.AnonymousCredentials(), - credentials_file="credentials.json" - ) - - -def test_answer_records_base_transport(): - # Instantiate the base transport. - with mock.patch('google.cloud.dialogflow_v2.services.answer_records.transports.AnswerRecordsTransport.__init__') as Transport: - Transport.return_value = None - transport = transports.AnswerRecordsTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Every method on the transport should just blindly - # raise NotImplementedError. - methods = ( - 'list_answer_records', - 'update_answer_record', - 'get_location', - 'list_locations', - 'get_operation', - 'cancel_operation', - 'list_operations', - ) - for method in methods: - with pytest.raises(NotImplementedError): - getattr(transport, method)(request=object()) - - with pytest.raises(NotImplementedError): - transport.close() - - # Catch all for all remaining methods and properties - remainder = [ - 'kind', - ] - for r in remainder: - with pytest.raises(NotImplementedError): - getattr(transport, r)() - - -def test_answer_records_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.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", - ) - - -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(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 = (ga_credentials.AnonymousCredentials(), None) - transport = transports.AnswerRecordsTransport() - adc.assert_called_once() - - -def test_answer_records_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) - 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, - ) - - -@pytest.mark.parametrize( - "transport_class", - [ - transports.AnswerRecordsGrpcTransport, - transports.AnswerRecordsGrpcAsyncIOTransport, - ], -) -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(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, - transports.AnswerRecordsRestTransport, - ], -) -def test_answer_records_transport_auth_gdch_credentials(transport_class): - host = 'https://language.com' - api_audience_tests = [None, 'https://language2.com'] - api_audience_expect = [host, 'https://language2.com'] - for t, e in zip(api_audience_tests, api_audience_expect): - with mock.patch.object(google.auth, 'default', autospec=True) as adc: - gdch_mock = mock.MagicMock() - type(gdch_mock).with_gdch_audience = mock.PropertyMock(return_value=gdch_mock) - adc.return_value = (gdch_mock, None) - transport_class(host=host, api_audience=t) - gdch_mock.with_gdch_audience.assert_called_once_with( - e - ) - - -@pytest.mark.parametrize( - "transport_class,grpc_helpers", - [ - (transports.AnswerRecordsGrpcTransport, grpc_helpers), - (transports.AnswerRecordsGrpcAsyncIOTransport, grpc_helpers_async) - ], -) -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", [transports.AnswerRecordsGrpcTransport, transports.AnswerRecordsGrpcAsyncIOTransport]) -def test_answer_records_grpc_transport_client_cert_source_for_mtls( - transport_class -): - cred = ga_credentials.AnonymousCredentials() - - # Check ssl_channel_credentials is used if provided. - with mock.patch.object(transport_class, "create_channel") as mock_create_channel: - mock_ssl_channel_creds = mock.Mock() - transport_class( - host="squid.clam.whelk", - credentials=cred, - ssl_channel_credentials=mock_ssl_channel_creds - ) - mock_create_channel.assert_called_once_with( - "squid.clam.whelk:443", - credentials=cred, - credentials_file=None, - scopes=None, - ssl_credentials=mock_ssl_channel_creds, - quota_project_id=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - # Check if ssl_channel_credentials is not provided, then client_cert_source_for_mtls - # is used. - with mock.patch.object(transport_class, "create_channel", return_value=mock.Mock()): - with mock.patch("grpc.ssl_channel_credentials") as mock_ssl_cred: - transport_class( - credentials=cred, - client_cert_source_for_mtls=client_cert_source_callback - ) - expected_cert, expected_key = client_cert_source_callback() - mock_ssl_cred.assert_called_once_with( - certificate_chain=expected_cert, - private_key=expected_key - ) - -def test_answer_records_http_transport_client_cert_source_for_mtls(): - cred = ga_credentials.AnonymousCredentials() - with mock.patch("google.auth.transport.requests.AuthorizedSession.configure_mtls_channel") as mock_configure_mtls_channel: - transports.AnswerRecordsRestTransport ( - credentials=cred, - client_cert_source_for_mtls=client_cert_source_callback - ) - mock_configure_mtls_channel.assert_called_once_with(client_cert_source_callback) - - -@pytest.mark.parametrize("transport_name", [ - "grpc", - "grpc_asyncio", - "rest", -]) -def test_answer_records_host_no_port(transport_name): - client = AnswerRecordsClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='dialogflow.googleapis.com'), - transport=transport_name, - ) - assert client.transport._host == ( - 'dialogflow.googleapis.com:443' - if transport_name in ['grpc', 'grpc_asyncio'] - else 'https://dialogflow.googleapis.com' - ) - -@pytest.mark.parametrize("transport_name", [ - "grpc", - "grpc_asyncio", - "rest", -]) -def test_answer_records_host_with_port(transport_name): - client = AnswerRecordsClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='dialogflow.googleapis.com:8000'), - transport=transport_name, - ) - assert client.transport._host == ( - 'dialogflow.googleapis.com:8000' - if transport_name in ['grpc', 'grpc_asyncio'] - else 'https://dialogflow.googleapis.com:8000' - ) - -@pytest.mark.parametrize("transport_name", [ - "rest", -]) -def test_answer_records_client_transport_session_collision(transport_name): - creds1 = ga_credentials.AnonymousCredentials() - creds2 = ga_credentials.AnonymousCredentials() - client1 = AnswerRecordsClient( - credentials=creds1, - transport=transport_name, - ) - client2 = AnswerRecordsClient( - credentials=creds2, - transport=transport_name, - ) - session1 = client1.transport.list_answer_records._session - session2 = client2.transport.list_answer_records._session - assert session1 != session2 - session1 = client1.transport.update_answer_record._session - session2 = client2.transport.update_answer_record._session - assert session1 != session2 -def test_answer_records_grpc_transport_channel(): - channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.AnswerRecordsGrpcTransport( - 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_answer_records_grpc_asyncio_transport_channel(): - channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.AnswerRecordsGrpcAsyncIOTransport( - 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.AnswerRecordsGrpcTransport, transports.AnswerRecordsGrpcAsyncIOTransport]) -def test_answer_records_transport_channel_mtls_with_client_cert_source( - transport_class -): - with mock.patch("grpc.ssl_channel_credentials", autospec=True) as grpc_ssl_channel_cred: - with mock.patch.object(transport_class, "create_channel") as grpc_create_channel: - mock_ssl_cred = mock.Mock() - grpc_ssl_channel_cred.return_value = mock_ssl_cred - - mock_grpc_channel = mock.Mock() - grpc_create_channel.return_value = mock_grpc_channel - - cred = ga_credentials.AnonymousCredentials() - with pytest.warns(DeprecationWarning): - with mock.patch.object(google.auth, 'default') as adc: - adc.return_value = (cred, None) - transport = transport_class( - host="squid.clam.whelk", - api_mtls_endpoint="mtls.squid.clam.whelk", - client_cert_source=client_cert_source_callback, - ) - adc.assert_called_once() - - grpc_ssl_channel_cred.assert_called_once_with( - certificate_chain=b"cert bytes", private_key=b"key bytes" - ) - grpc_create_channel.assert_called_once_with( - "mtls.squid.clam.whelk:443", - credentials=cred, - credentials_file=None, - scopes=None, - ssl_credentials=mock_ssl_cred, - quota_project_id=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - assert transport.grpc_channel == mock_grpc_channel - assert transport._ssl_channel_credentials == mock_ssl_cred - - -# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are -# removed from grpc/grpc_asyncio transport constructor. -@pytest.mark.parametrize("transport_class", [transports.AnswerRecordsGrpcTransport, transports.AnswerRecordsGrpcAsyncIOTransport]) -def test_answer_records_transport_channel_mtls_with_adc( - transport_class -): - mock_ssl_cred = mock.Mock() - with mock.patch.multiple( - "google.auth.transport.grpc.SslCredentials", - __init__=mock.Mock(return_value=None), - ssl_credentials=mock.PropertyMock(return_value=mock_ssl_cred), - ): - with mock.patch.object(transport_class, "create_channel") as grpc_create_channel: - mock_grpc_channel = mock.Mock() - grpc_create_channel.return_value = mock_grpc_channel - mock_cred = mock.Mock() - - with pytest.warns(DeprecationWarning): - transport = transport_class( - host="squid.clam.whelk", - credentials=mock_cred, - api_mtls_endpoint="mtls.squid.clam.whelk", - client_cert_source=None, - ) - - grpc_create_channel.assert_called_once_with( - "mtls.squid.clam.whelk:443", - credentials=mock_cred, - credentials_file=None, - scopes=None, - ssl_credentials=mock_ssl_cred, - quota_project_id=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - assert transport.grpc_channel == mock_grpc_channel - - -def test_answer_record_path(): - project = "squid" - answer_record = "clam" - expected = "projects/{project}/answerRecords/{answer_record}".format(project=project, answer_record=answer_record, ) - actual = AnswerRecordsClient.answer_record_path(project, answer_record) - assert expected == actual - - -def test_parse_answer_record_path(): - expected = { - "project": "whelk", - "answer_record": "octopus", - } - path = AnswerRecordsClient.answer_record_path(**expected) - - # Check that the path construction is reversible. - actual = AnswerRecordsClient.parse_answer_record_path(path) - assert expected == actual - -def test_common_billing_account_path(): - billing_account = "oyster" - expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) - actual = AnswerRecordsClient.common_billing_account_path(billing_account) - assert expected == actual - - -def test_parse_common_billing_account_path(): - expected = { - "billing_account": "nudibranch", - } - path = AnswerRecordsClient.common_billing_account_path(**expected) - - # Check that the path construction is reversible. - actual = AnswerRecordsClient.parse_common_billing_account_path(path) - assert expected == actual - -def test_common_folder_path(): - folder = "cuttlefish" - expected = "folders/{folder}".format(folder=folder, ) - actual = AnswerRecordsClient.common_folder_path(folder) - assert expected == actual - - -def test_parse_common_folder_path(): - expected = { - "folder": "mussel", - } - path = AnswerRecordsClient.common_folder_path(**expected) - - # Check that the path construction is reversible. - actual = AnswerRecordsClient.parse_common_folder_path(path) - assert expected == actual - -def test_common_organization_path(): - organization = "winkle" - expected = "organizations/{organization}".format(organization=organization, ) - actual = AnswerRecordsClient.common_organization_path(organization) - assert expected == actual - - -def test_parse_common_organization_path(): - expected = { - "organization": "nautilus", - } - path = AnswerRecordsClient.common_organization_path(**expected) - - # Check that the path construction is reversible. - actual = AnswerRecordsClient.parse_common_organization_path(path) - assert expected == actual - -def test_common_project_path(): - project = "scallop" - expected = "projects/{project}".format(project=project, ) - actual = AnswerRecordsClient.common_project_path(project) - assert expected == actual - - -def test_parse_common_project_path(): - expected = { - "project": "abalone", - } - path = AnswerRecordsClient.common_project_path(**expected) - - # Check that the path construction is reversible. - actual = AnswerRecordsClient.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 = AnswerRecordsClient.common_location_path(project, location) - assert expected == actual - - -def test_parse_common_location_path(): - expected = { - "project": "whelk", - "location": "octopus", - } - path = AnswerRecordsClient.common_location_path(**expected) - - # Check that the path construction is reversible. - actual = AnswerRecordsClient.parse_common_location_path(path) - assert expected == actual - - -def test_client_with_default_client_info(): - client_info = gapic_v1.client_info.ClientInfo() - - with mock.patch.object(transports.AnswerRecordsTransport, '_prep_wrapped_messages') as prep: - client = AnswerRecordsClient( - credentials=ga_credentials.AnonymousCredentials(), - client_info=client_info, - ) - prep.assert_called_once_with(client_info) - - with mock.patch.object(transports.AnswerRecordsTransport, '_prep_wrapped_messages') as prep: - transport_class = AnswerRecordsClient.get_transport_class() - transport = transport_class( - credentials=ga_credentials.AnonymousCredentials(), - client_info=client_info, - ) - prep.assert_called_once_with(client_info) - -@pytest.mark.asyncio -async def test_transport_close_async(): - client = AnswerRecordsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - with mock.patch.object(type(getattr(client.transport, "grpc_channel")), "close") as close: - async with client: - close.assert_not_called() - close.assert_called_once() - - -def test_get_location_rest_bad_request(transport: str = 'rest', request_type=locations_pb2.GetLocationRequest): - client = AnswerRecordsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - request = request_type() - request = json_format.ParseDict({'name': 'projects/sample1/locations/sample2'}, request) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.get_location(request) - -@pytest.mark.parametrize("request_type", [ - locations_pb2.GetLocationRequest, - dict, -]) -def test_get_location_rest(request_type): - client = AnswerRecordsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request_init = {'name': 'projects/sample1/locations/sample2'} - request = request_type(**request_init) - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = locations_pb2.Location() - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.get_location(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, locations_pb2.Location) - -def test_list_locations_rest_bad_request(transport: str = 'rest', request_type=locations_pb2.ListLocationsRequest): - client = AnswerRecordsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - request = request_type() - request = json_format.ParseDict({'name': 'projects/sample1'}, request) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.list_locations(request) - -@pytest.mark.parametrize("request_type", [ - locations_pb2.ListLocationsRequest, - dict, -]) -def test_list_locations_rest(request_type): - client = AnswerRecordsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request_init = {'name': 'projects/sample1'} - request = request_type(**request_init) - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = locations_pb2.ListLocationsResponse() - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.list_locations(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, locations_pb2.ListLocationsResponse) - -def test_cancel_operation_rest_bad_request(transport: str = 'rest', request_type=operations_pb2.CancelOperationRequest): - client = AnswerRecordsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - request = request_type() - request = json_format.ParseDict({'name': 'projects/sample1/operations/sample2'}, request) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.cancel_operation(request) - -@pytest.mark.parametrize("request_type", [ - operations_pb2.CancelOperationRequest, - dict, -]) -def test_cancel_operation_rest(request_type): - client = AnswerRecordsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request_init = {'name': 'projects/sample1/operations/sample2'} - request = request_type(**request_init) - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = None - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = '{}' - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.cancel_operation(request) - - # Establish that the response is the type that we expect. - assert response is None - -def test_get_operation_rest_bad_request(transport: str = 'rest', request_type=operations_pb2.GetOperationRequest): - client = AnswerRecordsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - request = request_type() - request = json_format.ParseDict({'name': 'projects/sample1/operations/sample2'}, request) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.get_operation(request) - -@pytest.mark.parametrize("request_type", [ - operations_pb2.GetOperationRequest, - dict, -]) -def test_get_operation_rest(request_type): - client = AnswerRecordsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request_init = {'name': 'projects/sample1/operations/sample2'} - request = request_type(**request_init) - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation() - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.get_operation(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, operations_pb2.Operation) - -def test_list_operations_rest_bad_request(transport: str = 'rest', request_type=operations_pb2.ListOperationsRequest): - client = AnswerRecordsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - request = request_type() - request = json_format.ParseDict({'name': 'projects/sample1'}, request) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.list_operations(request) - -@pytest.mark.parametrize("request_type", [ - operations_pb2.ListOperationsRequest, - dict, -]) -def test_list_operations_rest(request_type): - client = AnswerRecordsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request_init = {'name': 'projects/sample1'} - request = request_type(**request_init) - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = operations_pb2.ListOperationsResponse() - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.list_operations(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, operations_pb2.ListOperationsResponse) - - -def test_cancel_operation(transport: str = "grpc"): - client = AnswerRecordsClient( - 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 = operations_pb2.CancelOperationRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = None - response = client.cancel_operation(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 response is the type that we expect. - assert response is None -@pytest.mark.asyncio -async def test_cancel_operation_async(transport: str = "grpc"): - client = AnswerRecordsAsyncClient( - 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 = operations_pb2.CancelOperationRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - None - ) - response = await client.cancel_operation(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 response is the type that we expect. - assert response is None - -def test_cancel_operation_field_headers(): - 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 = operations_pb2.CancelOperationRequest() - request.name = "locations" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call: - call.return_value = None - - client.cancel_operation(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=locations",) in kw["metadata"] -@pytest.mark.asyncio -async def test_cancel_operation_field_headers_async(): - 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 = operations_pb2.CancelOperationRequest() - request.name = "locations" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - None - ) - await client.cancel_operation(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=locations",) in kw["metadata"] - -def test_cancel_operation_from_dict(): - client = AnswerRecordsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = None - - response = client.cancel_operation( - request={ - "name": "locations", - } - ) - call.assert_called() -@pytest.mark.asyncio -async def test_cancel_operation_from_dict_async(): - client = AnswerRecordsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - None - ) - response = await client.cancel_operation( - request={ - "name": "locations", - } - ) - call.assert_called() - - -def test_get_operation(transport: str = "grpc"): - client = AnswerRecordsClient( - 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 = operations_pb2.GetOperationRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_operation), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation() - response = client.get_operation(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 response is the type that we expect. - assert isinstance(response, operations_pb2.Operation) -@pytest.mark.asyncio -async def test_get_operation_async(transport: str = "grpc"): - client = AnswerRecordsAsyncClient( - 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 = operations_pb2.GetOperationRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_operation), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation() - ) - response = await client.get_operation(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 response is the type that we expect. - assert isinstance(response, operations_pb2.Operation) - -def test_get_operation_field_headers(): - 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 = operations_pb2.GetOperationRequest() - request.name = "locations" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_operation), "__call__") as call: - call.return_value = operations_pb2.Operation() - - client.get_operation(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=locations",) in kw["metadata"] -@pytest.mark.asyncio -async def test_get_operation_field_headers_async(): - 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 = operations_pb2.GetOperationRequest() - request.name = "locations" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_operation), "__call__") as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation() - ) - await client.get_operation(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=locations",) in kw["metadata"] - -def test_get_operation_from_dict(): - client = AnswerRecordsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_operation), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation() - - response = client.get_operation( - request={ - "name": "locations", - } - ) - call.assert_called() -@pytest.mark.asyncio -async def test_get_operation_from_dict_async(): - client = AnswerRecordsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_operation), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation() - ) - response = await client.get_operation( - request={ - "name": "locations", - } - ) - call.assert_called() - - -def test_list_operations(transport: str = "grpc"): - client = AnswerRecordsClient( - 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 = operations_pb2.ListOperationsRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_operations), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.ListOperationsResponse() - response = client.list_operations(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 response is the type that we expect. - assert isinstance(response, operations_pb2.ListOperationsResponse) -@pytest.mark.asyncio -async def test_list_operations_async(transport: str = "grpc"): - client = AnswerRecordsAsyncClient( - 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 = operations_pb2.ListOperationsRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_operations), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.ListOperationsResponse() - ) - response = await client.list_operations(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 response is the type that we expect. - assert isinstance(response, operations_pb2.ListOperationsResponse) - -def test_list_operations_field_headers(): - 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 = operations_pb2.ListOperationsRequest() - request.name = "locations" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_operations), "__call__") as call: - call.return_value = operations_pb2.ListOperationsResponse() - - client.list_operations(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=locations",) in kw["metadata"] -@pytest.mark.asyncio -async def test_list_operations_field_headers_async(): - 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 = operations_pb2.ListOperationsRequest() - request.name = "locations" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_operations), "__call__") as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.ListOperationsResponse() - ) - await client.list_operations(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=locations",) in kw["metadata"] - -def test_list_operations_from_dict(): - client = AnswerRecordsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_operations), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.ListOperationsResponse() - - response = client.list_operations( - request={ - "name": "locations", - } - ) - call.assert_called() -@pytest.mark.asyncio -async def test_list_operations_from_dict_async(): - client = AnswerRecordsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_operations), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.ListOperationsResponse() - ) - response = await client.list_operations( - request={ - "name": "locations", - } - ) - call.assert_called() - - -def test_list_locations(transport: str = "grpc"): - client = AnswerRecordsClient( - 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 = locations_pb2.ListLocationsRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_locations), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = locations_pb2.ListLocationsResponse() - response = client.list_locations(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 response is the type that we expect. - assert isinstance(response, locations_pb2.ListLocationsResponse) -@pytest.mark.asyncio -async def test_list_locations_async(transport: str = "grpc"): - client = AnswerRecordsAsyncClient( - 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 = locations_pb2.ListLocationsRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_locations), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - locations_pb2.ListLocationsResponse() - ) - response = await client.list_locations(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 response is the type that we expect. - assert isinstance(response, locations_pb2.ListLocationsResponse) - -def test_list_locations_field_headers(): - 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 = locations_pb2.ListLocationsRequest() - request.name = "locations" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_locations), "__call__") as call: - call.return_value = locations_pb2.ListLocationsResponse() - - client.list_locations(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=locations",) in kw["metadata"] -@pytest.mark.asyncio -async def test_list_locations_field_headers_async(): - 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 = locations_pb2.ListLocationsRequest() - request.name = "locations" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_locations), "__call__") as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - locations_pb2.ListLocationsResponse() - ) - await client.list_locations(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=locations",) in kw["metadata"] - -def test_list_locations_from_dict(): - client = AnswerRecordsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_locations), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = locations_pb2.ListLocationsResponse() - - response = client.list_locations( - request={ - "name": "locations", - } - ) - call.assert_called() -@pytest.mark.asyncio -async def test_list_locations_from_dict_async(): - client = AnswerRecordsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_locations), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - locations_pb2.ListLocationsResponse() - ) - response = await client.list_locations( - request={ - "name": "locations", - } - ) - call.assert_called() - - -def test_get_location(transport: str = "grpc"): - client = AnswerRecordsClient( - 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 = locations_pb2.GetLocationRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_location), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = locations_pb2.Location() - response = client.get_location(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 response is the type that we expect. - assert isinstance(response, locations_pb2.Location) -@pytest.mark.asyncio -async def test_get_location_async(transport: str = "grpc_asyncio"): - client = AnswerRecordsAsyncClient( - 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 = locations_pb2.GetLocationRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_location), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - locations_pb2.Location() - ) - response = await client.get_location(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 response is the type that we expect. - assert isinstance(response, locations_pb2.Location) - -def test_get_location_field_headers(): - 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 = locations_pb2.GetLocationRequest() - request.name = "locations/abc" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_location), "__call__") as call: - call.return_value = locations_pb2.Location() - - client.get_location(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=locations/abc",) in kw["metadata"] -@pytest.mark.asyncio -async def test_get_location_field_headers_async(): - 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 = locations_pb2.GetLocationRequest() - request.name = "locations/abc" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_location), "__call__") as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - locations_pb2.Location() - ) - await client.get_location(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=locations/abc",) in kw["metadata"] - -def test_get_location_from_dict(): - client = AnswerRecordsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_locations), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = locations_pb2.Location() - - response = client.get_location( - request={ - "name": "locations/abc", - } - ) - call.assert_called() -@pytest.mark.asyncio -async def test_get_location_from_dict_async(): - client = AnswerRecordsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_locations), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - locations_pb2.Location() - ) - response = await client.get_location( - request={ - "name": "locations", - } - ) - call.assert_called() - - -def test_transport_close(): - transports = { - "rest": "_session", - "grpc": "_grpc_channel", - } - - for transport, close_name in transports.items(): - client = AnswerRecordsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport - ) - with mock.patch.object(type(getattr(client.transport, close_name)), "close") as close: - with client: - close.assert_not_called() - close.assert_called_once() - -def test_client_ctx(): - transports = [ - 'rest', - 'grpc', - ] - for transport in transports: - client = AnswerRecordsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport - ) - # Test client calls underlying transport. - with mock.patch.object(type(client.transport), "close") as close: - close.assert_not_called() - with client: - pass - close.assert_called() - -@pytest.mark.parametrize("client_class,transport_class", [ - (AnswerRecordsClient, transports.AnswerRecordsGrpcTransport), - (AnswerRecordsAsyncClient, transports.AnswerRecordsGrpcAsyncIOTransport), -]) -def test_api_key_credentials(client_class, transport_class): - with mock.patch.object( - google.auth._default, "get_api_key_credentials", create=True - ) as get_api_key_credentials: - mock_cred = mock.Mock() - get_api_key_credentials.return_value = mock_cred - options = client_options.ClientOptions() - options.api_key = "api_key" - 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=mock_cred, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) diff --git a/owl-bot-staging/v2/tests/unit/gapic/dialogflow_v2/test_contexts.py b/owl-bot-staging/v2/tests/unit/gapic/dialogflow_v2/test_contexts.py deleted file mode 100644 index d0a87372b..000000000 --- a/owl-bot-staging/v2/tests/unit/gapic/dialogflow_v2/test_contexts.py +++ /dev/null @@ -1,5176 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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 -# try/except added for compatibility with python < 3.8 -try: - from unittest import mock - from unittest.mock import AsyncMock # pragma: NO COVER -except ImportError: # pragma: NO COVER - import mock - -import grpc -from grpc.experimental import aio -from collections.abc import Iterable -from google.protobuf import json_format -import json -import math -import pytest -from proto.marshal.rules.dates import DurationRule, TimestampRule -from proto.marshal.rules import wrappers -from requests import Response -from requests import Request, PreparedRequest -from requests.sessions import Session -from google.protobuf import json_format - -from google.api_core import client_options -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import grpc_helpers -from google.api_core import grpc_helpers_async -from google.api_core import path_template -from google.auth import credentials as ga_credentials -from google.auth.exceptions import MutualTLSChannelError -from google.cloud.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.types import context -from google.cloud.dialogflow_v2.types import context as gcd_context -from google.cloud.location import locations_pb2 -from google.longrunning import operations_pb2 -from google.oauth2 import service_account -from google.protobuf import field_mask_pb2 # type: ignore -from google.protobuf import struct_pb2 # type: ignore -import google.auth - - -def client_cert_source_callback(): - return b"cert bytes", b"key bytes" - - -# If default endpoint is localhost, then default mtls endpoint will be the same. -# This method modifies the default endpoint so the client can produce a different -# mtls endpoint for endpoint testing purposes. -def modify_default_endpoint(client): - return "foo.googleapis.com" if ("localhost" in client.DEFAULT_ENDPOINT) else client.DEFAULT_ENDPOINT - - -def test__get_default_mtls_endpoint(): - api_endpoint = "example.googleapis.com" - api_mtls_endpoint = "example.mtls.googleapis.com" - sandbox_endpoint = "example.sandbox.googleapis.com" - sandbox_mtls_endpoint = "example.mtls.sandbox.googleapis.com" - non_googleapi = "api.example.com" - - assert ContextsClient._get_default_mtls_endpoint(None) is None - assert ContextsClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint - assert ContextsClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint - assert ContextsClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint - assert ContextsClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint - assert ContextsClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi - - -@pytest.mark.parametrize("client_class,transport_name", [ - (ContextsClient, "grpc"), - (ContextsAsyncClient, "grpc_asyncio"), - (ContextsClient, "rest"), -]) -def test_contexts_client_from_service_account_info(client_class, transport_name): - 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, transport=transport_name) - assert client.transport._credentials == creds - assert isinstance(client, client_class) - - assert client.transport._host == ( - 'dialogflow.googleapis.com:443' - if transport_name in ['grpc', 'grpc_asyncio'] - else - 'https://dialogflow.googleapis.com' - ) - - -@pytest.mark.parametrize("transport_class,transport_name", [ - (transports.ContextsGrpcTransport, "grpc"), - (transports.ContextsGrpcAsyncIOTransport, "grpc_asyncio"), - (transports.ContextsRestTransport, "rest"), -]) -def test_contexts_client_service_account_always_use_jwt(transport_class, transport_name): - with mock.patch.object(service_account.Credentials, 'with_always_use_jwt_access', create=True) as use_jwt: - creds = service_account.Credentials(None, None, None) - transport = transport_class(credentials=creds, always_use_jwt_access=True) - use_jwt.assert_called_once_with(True) - - with mock.patch.object(service_account.Credentials, 'with_always_use_jwt_access', create=True) as use_jwt: - creds = service_account.Credentials(None, None, None) - transport = transport_class(credentials=creds, always_use_jwt_access=False) - use_jwt.assert_not_called() - - -@pytest.mark.parametrize("client_class,transport_name", [ - (ContextsClient, "grpc"), - (ContextsAsyncClient, "grpc_asyncio"), - (ContextsClient, "rest"), -]) -def test_contexts_client_from_service_account_file(client_class, transport_name): - 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", transport=transport_name) - assert client.transport._credentials == creds - assert isinstance(client, client_class) - - client = client_class.from_service_account_json("dummy/file/path.json", transport=transport_name) - assert client.transport._credentials == creds - assert isinstance(client, client_class) - - assert client.transport._host == ( - 'dialogflow.googleapis.com:443' - if transport_name in ['grpc', 'grpc_asyncio'] - else - 'https://dialogflow.googleapis.com' - ) - - -def test_contexts_client_get_transport_class(): - transport = ContextsClient.get_transport_class() - available_transports = [ - transports.ContextsGrpcTransport, - transports.ContextsRestTransport, - ] - assert transport in available_transports - - transport = ContextsClient.get_transport_class("grpc") - assert transport == transports.ContextsGrpcTransport - - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (ContextsClient, transports.ContextsGrpcTransport, "grpc"), - (ContextsAsyncClient, transports.ContextsGrpcAsyncIOTransport, "grpc_asyncio"), - (ContextsClient, transports.ContextsRestTransport, "rest"), -]) -@mock.patch.object(ContextsClient, "DEFAULT_ENDPOINT", modify_default_endpoint(ContextsClient)) -@mock.patch.object(ContextsAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(ContextsAsyncClient)) -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=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(ContextsClient, 'get_transport_class') as gtc: - client = client_class(transport=transport_name) - gtc.assert_called() - - # Check the case api_endpoint is provided. - options = client_options.ClientOptions(api_endpoint="squid.clam.whelk") - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(transport=transport_name, client_options=options) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host="squid.clam.whelk", - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is - # "never". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is - # "always". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_MTLS_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # 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(transport=transport_name) - - # 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(transport=transport_name) - - # 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, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id="octopus", - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - # Check the case api_endpoint is provided - options = client_options.ClientOptions(api_audience="https://language.googleapis.com") - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience="https://language.googleapis.com" - ) - -@pytest.mark.parametrize("client_class,transport_class,transport_name,use_client_cert_env", [ - (ContextsClient, transports.ContextsGrpcTransport, "grpc", "true"), - (ContextsAsyncClient, transports.ContextsGrpcAsyncIOTransport, "grpc_asyncio", "true"), - (ContextsClient, transports.ContextsGrpcTransport, "grpc", "false"), - (ContextsAsyncClient, transports.ContextsGrpcAsyncIOTransport, "grpc_asyncio", "false"), - (ContextsClient, transports.ContextsRestTransport, "rest", "true"), - (ContextsClient, transports.ContextsRestTransport, "rest", "false"), -]) -@mock.patch.object(ContextsClient, "DEFAULT_ENDPOINT", modify_default_endpoint(ContextsClient)) -@mock.patch.object(ContextsAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(ContextsAsyncClient)) -@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) -def test_contexts_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, transport=transport_name) - - if use_client_cert_env == "false": - expected_client_cert_source = None - expected_host = client.DEFAULT_ENDPOINT - else: - expected_client_cert_source = client_cert_source_callback - expected_host = client.DEFAULT_MTLS_ENDPOINT - - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=expected_host, - scopes=None, - client_cert_source_for_mtls=expected_client_cert_source, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case ADC client cert is provided. Whether client cert is used depends on - # GOOGLE_API_USE_CLIENT_CERTIFICATE value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): - with mock.patch.object(transport_class, '__init__') as patched: - with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): - with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=client_cert_source_callback): - if use_client_cert_env == "false": - expected_host = client.DEFAULT_ENDPOINT - expected_client_cert_source = None - else: - expected_host = client.DEFAULT_MTLS_ENDPOINT - expected_client_cert_source = client_cert_source_callback - - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=expected_host, - scopes=None, - client_cert_source_for_mtls=expected_client_cert_source, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case client_cert_source and ADC client cert are not provided. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): - with mock.patch.object(transport_class, '__init__') as patched: - with mock.patch("google.auth.transport.mtls.has_default_client_cert_source", return_value=False): - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - -@pytest.mark.parametrize("client_class", [ - ContextsClient, ContextsAsyncClient -]) -@mock.patch.object(ContextsClient, "DEFAULT_ENDPOINT", modify_default_endpoint(ContextsClient)) -@mock.patch.object(ContextsAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(ContextsAsyncClient)) -def test_contexts_client_get_mtls_endpoint_and_cert_source(client_class): - mock_client_cert_source = mock.Mock() - - # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "true". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - mock_api_endpoint = "foo" - options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) - assert api_endpoint == mock_api_endpoint - assert cert_source == mock_client_cert_source - - # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "false". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): - mock_client_cert_source = mock.Mock() - mock_api_endpoint = "foo" - options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) - assert api_endpoint == mock_api_endpoint - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "never". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_ENDPOINT - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "always". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert doesn't exist. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=False): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_ENDPOINT - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert exists. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - 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=mock_client_cert_source): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT - assert cert_source == mock_client_cert_source - - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (ContextsClient, transports.ContextsGrpcTransport, "grpc"), - (ContextsAsyncClient, transports.ContextsGrpcAsyncIOTransport, "grpc_asyncio"), - (ContextsClient, transports.ContextsRestTransport, "rest"), -]) -def test_contexts_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, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=["1", "2"], - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - -@pytest.mark.parametrize("client_class,transport_class,transport_name,grpc_helpers", [ - (ContextsClient, transports.ContextsGrpcTransport, "grpc", grpc_helpers), - (ContextsAsyncClient, transports.ContextsGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), - (ContextsClient, transports.ContextsRestTransport, "rest", None), -]) -def test_contexts_client_client_options_credentials_file(client_class, transport_class, transport_name, grpc_helpers): - # 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, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file="credentials.json", - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - -def test_contexts_client_client_options_from_dict(): - with mock.patch('google.cloud.dialogflow_v2.services.contexts.transports.ContextsGrpcTransport.__init__') as grpc_transport: - grpc_transport.return_value = None - client = ContextsClient( - client_options={'api_endpoint': 'squid.clam.whelk'} - ) - grpc_transport.assert_called_once_with( - credentials=None, - credentials_file=None, - host="squid.clam.whelk", - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - -@pytest.mark.parametrize("client_class,transport_class,transport_name,grpc_helpers", [ - (ContextsClient, transports.ContextsGrpcTransport, "grpc", grpc_helpers), - (ContextsAsyncClient, transports.ContextsGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), -]) -def test_contexts_client_create_channel_credentials_file(client_class, transport_class, transport_name, grpc_helpers): - # 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, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file="credentials.json", - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # test that the credentials from file are saved and used as the credentials. - with mock.patch.object( - google.auth, "load_credentials_from_file", autospec=True - ) as load_creds, mock.patch.object( - google.auth, "default", autospec=True - ) as adc, mock.patch.object( - grpc_helpers, "create_channel" - ) as create_channel: - creds = ga_credentials.AnonymousCredentials() - file_creds = ga_credentials.AnonymousCredentials() - load_creds.return_value = (file_creds, None) - adc.return_value = (creds, None) - client = client_class(client_options=options, transport=transport_name) - create_channel.assert_called_with( - "dialogflow.googleapis.com:443", - credentials=file_creds, - credentials_file=None, - quota_project_id=None, - default_scopes=( - 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/dialogflow', -), - scopes=None, - default_host="dialogflow.googleapis.com", - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - -@pytest.mark.parametrize("request_type", [ - context.ListContextsRequest, - dict, -]) -def test_list_contexts(request_type, transport: str = 'grpc'): - client = ContextsClient( - 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_contexts), - '__call__') as call: - # Designate an appropriate return value for the call. - 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' - - -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=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_contexts), - '__call__') as call: - client.list_contexts() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == context.ListContextsRequest() - -@pytest.mark.asyncio -async def test_list_contexts_async(transport: str = 'grpc_asyncio', request_type=context.ListContextsRequest): - client = ContextsAsyncClient( - 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_contexts), - '__call__') as call: - # Designate an appropriate return value for the call. - 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' - - -@pytest.mark.asyncio -async def test_list_contexts_async_from_dict(): - await test_list_contexts_async(request_type=dict) - - -def test_list_contexts_field_headers(): - 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. - 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_contexts_field_headers_async(): - 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. - with mock.patch.object( - type(client.transport.list_contexts), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(context.ListContextsResponse()) - 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] == 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_contexts_flattened(): - 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', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - arg = args[0].parent - mock_val = 'parent_value' - assert arg == mock_val - - -def test_list_contexts_flattened_error(): - client = ContextsClient( - 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_contexts( - context.ListContextsRequest(), - parent='parent_value', - ) - -@pytest.mark.asyncio -async def test_list_contexts_flattened_async(): - 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: - # Designate an appropriate return value for the call. - call.return_value = context.ListContextsResponse() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(context.ListContextsResponse()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.list_contexts( - 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] - arg = args[0].parent - mock_val = 'parent_value' - assert arg == mock_val - -@pytest.mark.asyncio -async def test_list_contexts_flattened_error_async(): - client = ContextsAsyncClient( - 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_contexts( - context.ListContextsRequest(), - parent='parent_value', - ) - - -def test_list_contexts_pager(transport_name: str = "grpc"): - client = ContextsClient( - credentials=ga_credentials.AnonymousCredentials, - transport=transport_name, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_contexts), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - context.ListContextsResponse( - contexts=[ - context.Context(), - context.Context(), - context.Context(), - ], - next_page_token='abc', - ), - context.ListContextsResponse( - contexts=[], - next_page_token='def', - ), - context.ListContextsResponse( - contexts=[ - context.Context(), - ], - next_page_token='ghi', - ), - context.ListContextsResponse( - contexts=[ - context.Context(), - context.Context(), - ], - ), - RuntimeError, - ) - - metadata = () - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ('parent', ''), - )), - ) - pager = client.list_contexts(request={}) - - assert pager._metadata == metadata - - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, context.Context) - for i in results) -def test_list_contexts_pages(transport_name: str = "grpc"): - client = ContextsClient( - credentials=ga_credentials.AnonymousCredentials, - transport=transport_name, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_contexts), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - context.ListContextsResponse( - contexts=[ - context.Context(), - context.Context(), - context.Context(), - ], - next_page_token='abc', - ), - context.ListContextsResponse( - contexts=[], - next_page_token='def', - ), - context.ListContextsResponse( - contexts=[ - context.Context(), - ], - next_page_token='ghi', - ), - context.ListContextsResponse( - contexts=[ - context.Context(), - context.Context(), - ], - ), - RuntimeError, - ) - pages = list(client.list_contexts(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_contexts_async_pager(): - 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__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - context.ListContextsResponse( - contexts=[ - context.Context(), - context.Context(), - context.Context(), - ], - next_page_token='abc', - ), - context.ListContextsResponse( - contexts=[], - next_page_token='def', - ), - context.ListContextsResponse( - contexts=[ - context.Context(), - ], - next_page_token='ghi', - ), - context.ListContextsResponse( - contexts=[ - context.Context(), - context.Context(), - ], - ), - RuntimeError, - ) - async_pager = await client.list_contexts(request={},) - assert async_pager.next_page_token == 'abc' - responses = [] - async for response in async_pager: # pragma: no branch - responses.append(response) - - assert len(responses) == 6 - assert all(isinstance(i, context.Context) - for i in responses) - - -@pytest.mark.asyncio -async def test_list_contexts_async_pages(): - 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__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - context.ListContextsResponse( - contexts=[ - context.Context(), - context.Context(), - context.Context(), - ], - next_page_token='abc', - ), - context.ListContextsResponse( - contexts=[], - next_page_token='def', - ), - context.ListContextsResponse( - contexts=[ - context.Context(), - ], - next_page_token='ghi', - ), - context.ListContextsResponse( - contexts=[ - context.Context(), - context.Context(), - ], - ), - RuntimeError, - ) - pages = [] - async for page_ in (await client.list_contexts(request={})).pages: # pragma: no branch - pages.append(page_) - for page_, token in zip(pages, ['abc','def','ghi', '']): - assert page_.raw_page.next_page_token == token - -@pytest.mark.parametrize("request_type", [ - context.GetContextRequest, - dict, -]) -def test_get_context(request_type, transport: str = 'grpc'): - client = ContextsClient( - 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_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 - - -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=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_context), - '__call__') as call: - client.get_context() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == context.GetContextRequest() - -@pytest.mark.asyncio -async def test_get_context_async(transport: str = 'grpc_asyncio', request_type=context.GetContextRequest): - client = ContextsAsyncClient( - 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_context), - '__call__') as call: - # Designate an appropriate return value for the call. - 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 - - -@pytest.mark.asyncio -async def test_get_context_async_from_dict(): - await test_get_context_async(request_type=dict) - - -def test_get_context_field_headers(): - 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. - 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_context_field_headers_async(): - 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. - 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_context_flattened(): - 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', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - arg = args[0].name - mock_val = 'name_value' - assert arg == mock_val - - -def test_get_context_flattened_error(): - client = ContextsClient( - 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_context( - context.GetContextRequest(), - name='name_value', - ) - -@pytest.mark.asyncio -async def test_get_context_flattened_async(): - 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: - # Designate an appropriate return value for the call. - call.return_value = context.Context() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(context.Context()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.get_context( - 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] - arg = args[0].name - mock_val = 'name_value' - assert arg == mock_val - -@pytest.mark.asyncio -async def test_get_context_flattened_error_async(): - client = ContextsAsyncClient( - 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_context( - context.GetContextRequest(), - name='name_value', - ) - - -@pytest.mark.parametrize("request_type", [ - gcd_context.CreateContextRequest, - dict, -]) -def test_create_context(request_type, transport: str = 'grpc'): - client = ContextsClient( - 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_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 - - -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=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_context), - '__call__') as call: - client.create_context() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == gcd_context.CreateContextRequest() - -@pytest.mark.asyncio -async def test_create_context_async(transport: str = 'grpc_asyncio', request_type=gcd_context.CreateContextRequest): - client = ContextsAsyncClient( - 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_context), - '__call__') as call: - # Designate an appropriate return value for the call. - 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 - - -@pytest.mark.asyncio -async def test_create_context_async_from_dict(): - await test_create_context_async(request_type=dict) - - -def test_create_context_field_headers(): - 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. - 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_context_field_headers_async(): - 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. - 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_context_flattened(): - 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( - parent='parent_value', - context=gcd_context.Context(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] - arg = args[0].parent - mock_val = 'parent_value' - assert arg == mock_val - arg = args[0].context - mock_val = gcd_context.Context(name='name_value') - assert arg == mock_val - - -def test_create_context_flattened_error(): - client = ContextsClient( - 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_context( - gcd_context.CreateContextRequest(), - parent='parent_value', - context=gcd_context.Context(name='name_value'), - ) - -@pytest.mark.asyncio -async def test_create_context_flattened_async(): - 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: - # Designate an appropriate return value for the call. - call.return_value = gcd_context.Context() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcd_context.Context()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.create_context( - parent='parent_value', - context=gcd_context.Context(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] - arg = args[0].parent - mock_val = 'parent_value' - assert arg == mock_val - arg = args[0].context - mock_val = gcd_context.Context(name='name_value') - assert arg == mock_val - -@pytest.mark.asyncio -async def test_create_context_flattened_error_async(): - client = ContextsAsyncClient( - 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_context( - gcd_context.CreateContextRequest(), - parent='parent_value', - context=gcd_context.Context(name='name_value'), - ) - - -@pytest.mark.parametrize("request_type", [ - gcd_context.UpdateContextRequest, - dict, -]) -def test_update_context(request_type, transport: str = 'grpc'): - client = ContextsClient( - 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_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 - - -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=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_context), - '__call__') as call: - client.update_context() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == gcd_context.UpdateContextRequest() - -@pytest.mark.asyncio -async def test_update_context_async(transport: str = 'grpc_asyncio', request_type=gcd_context.UpdateContextRequest): - client = ContextsAsyncClient( - 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_context), - '__call__') as call: - # Designate an appropriate return value for the call. - 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 - - -@pytest.mark.asyncio -async def test_update_context_async_from_dict(): - await test_update_context_async(request_type=dict) - - -def test_update_context_field_headers(): - 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 = '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. - 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', - 'context.name=name_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_update_context_field_headers_async(): - 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 = '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. - 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', - 'context.name=name_value', - ) in kw['metadata'] - - -def test_update_context_flattened(): - 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_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] - arg = args[0].context - mock_val = gcd_context.Context(name='name_value') - assert arg == mock_val - arg = args[0].update_mask - mock_val = field_mask_pb2.FieldMask(paths=['paths_value']) - assert arg == mock_val - - -def test_update_context_flattened_error(): - client = ContextsClient( - 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_context( - gcd_context.UpdateContextRequest(), - context=gcd_context.Context(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - -@pytest.mark.asyncio -async def test_update_context_flattened_async(): - 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: - # Designate an appropriate return value for the call. - call.return_value = gcd_context.Context() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcd_context.Context()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.update_context( - context=gcd_context.Context(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] - arg = args[0].context - mock_val = gcd_context.Context(name='name_value') - assert arg == mock_val - arg = args[0].update_mask - mock_val = field_mask_pb2.FieldMask(paths=['paths_value']) - assert arg == mock_val - -@pytest.mark.asyncio -async def test_update_context_flattened_error_async(): - client = ContextsAsyncClient( - 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_context( - gcd_context.UpdateContextRequest(), - context=gcd_context.Context(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - - -@pytest.mark.parametrize("request_type", [ - context.DeleteContextRequest, - dict, -]) -def test_delete_context(request_type, transport: str = 'grpc'): - client = ContextsClient( - 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_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. - assert response is None - - -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=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_context), - '__call__') as call: - client.delete_context() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == context.DeleteContextRequest() - -@pytest.mark.asyncio -async def test_delete_context_async(transport: str = 'grpc_asyncio', request_type=context.DeleteContextRequest): - client = ContextsAsyncClient( - 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_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. - assert response is None - - -@pytest.mark.asyncio -async def test_delete_context_async_from_dict(): - await test_delete_context_async(request_type=dict) - - -def test_delete_context_field_headers(): - 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. - 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_context_field_headers_async(): - 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. - 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_context_flattened(): - 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', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - arg = args[0].name - mock_val = 'name_value' - assert arg == mock_val - - -def test_delete_context_flattened_error(): - client = ContextsClient( - 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_context( - context.DeleteContextRequest(), - name='name_value', - ) - -@pytest.mark.asyncio -async def test_delete_context_flattened_async(): - 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: - # 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_context( - 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] - arg = args[0].name - mock_val = 'name_value' - assert arg == mock_val - -@pytest.mark.asyncio -async def test_delete_context_flattened_error_async(): - client = ContextsAsyncClient( - 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_context( - context.DeleteContextRequest(), - name='name_value', - ) - - -@pytest.mark.parametrize("request_type", [ - context.DeleteAllContextsRequest, - dict, -]) -def test_delete_all_contexts(request_type, transport: str = 'grpc'): - client = ContextsClient( - 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_all_contexts), - '__call__') 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. - assert response is None - - -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=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_all_contexts), - '__call__') as call: - client.delete_all_contexts() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == context.DeleteAllContextsRequest() - -@pytest.mark.asyncio -async def test_delete_all_contexts_async(transport: str = 'grpc_asyncio', request_type=context.DeleteAllContextsRequest): - client = ContextsAsyncClient( - 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_all_contexts), - '__call__') 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. - assert response is None - - -@pytest.mark.asyncio -async def test_delete_all_contexts_async_from_dict(): - await test_delete_all_contexts_async(request_type=dict) - - -def test_delete_all_contexts_field_headers(): - 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. - with mock.patch.object( - 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. - 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_delete_all_contexts_field_headers_async(): - 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. - with mock.patch.object( - 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. - 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_delete_all_contexts_flattened(): - 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_all_contexts), - '__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_all_contexts( - 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] - arg = args[0].parent - mock_val = 'parent_value' - assert arg == mock_val - - -def test_delete_all_contexts_flattened_error(): - client = ContextsClient( - 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_all_contexts( - context.DeleteAllContextsRequest(), - parent='parent_value', - ) - -@pytest.mark.asyncio -async def test_delete_all_contexts_flattened_async(): - 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_all_contexts), - '__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_all_contexts( - 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] - arg = args[0].parent - mock_val = 'parent_value' - assert arg == mock_val - -@pytest.mark.asyncio -async def test_delete_all_contexts_flattened_error_async(): - client = ContextsAsyncClient( - 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_all_contexts( - context.DeleteAllContextsRequest(), - parent='parent_value', - ) - - -@pytest.mark.parametrize("request_type", [ - context.ListContextsRequest, - dict, -]) -def test_list_contexts_rest(request_type): - client = ContextsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1/agent/sessions/sample2'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = context.ListContextsResponse( - next_page_token='next_page_token_value', - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - pb_return_value = context.ListContextsResponse.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.list_contexts(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListContextsPager) - assert response.next_page_token == 'next_page_token_value' - - -def test_list_contexts_rest_required_fields(request_type=context.ListContextsRequest): - transport_class = transports.ContextsRestTransport - - request_init = {} - request_init["parent"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - including_default_value_fields=False, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).list_contexts._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["parent"] = 'parent_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).list_contexts._get_unset_required_fields(jsonified_request) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("page_size", "page_token", )) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "parent" in jsonified_request - assert jsonified_request["parent"] == 'parent_value' - - client = ContextsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = context.ListContextsResponse() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "get", - 'query_params': pb_request, - } - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - - pb_return_value = context.ListContextsResponse.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.list_contexts(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_list_contexts_rest_unset_required_fields(): - transport = transports.ContextsRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.list_contexts._get_unset_required_fields({}) - assert set(unset_fields) == (set(("pageSize", "pageToken", )) & set(("parent", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_list_contexts_rest_interceptors(null_interceptor): - transport = transports.ContextsRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.ContextsRestInterceptor(), - ) - client = ContextsClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.ContextsRestInterceptor, "post_list_contexts") as post, \ - mock.patch.object(transports.ContextsRestInterceptor, "pre_list_contexts") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = context.ListContextsRequest.pb(context.ListContextsRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = context.ListContextsResponse.to_json(context.ListContextsResponse()) - - request = context.ListContextsRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = context.ListContextsResponse() - - client.list_contexts(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_list_contexts_rest_bad_request(transport: str = 'rest', request_type=context.ListContextsRequest): - client = ContextsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1/agent/sessions/sample2'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.list_contexts(request) - - -def test_list_contexts_rest_flattened(): - client = ContextsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = context.ListContextsResponse() - - # get arguments that satisfy an http rule for this method - sample_request = {'parent': 'projects/sample1/agent/sessions/sample2'} - - # get truthy value for each flattened field - mock_args = dict( - parent='parent_value', - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - pb_return_value = context.ListContextsResponse.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.list_contexts(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v2/{parent=projects/*/agent/sessions/*}/contexts" % client.transport._host, args[1]) - - -def test_list_contexts_rest_flattened_error(transport: str = 'rest'): - client = ContextsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.list_contexts( - context.ListContextsRequest(), - parent='parent_value', - ) - - -def test_list_contexts_rest_pager(transport: str = 'rest'): - client = ContextsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # TODO(kbandes): remove this mock unless there's a good reason for it. - #with mock.patch.object(path_template, 'transcode') as transcode: - # Set the response as a series of pages - response = ( - context.ListContextsResponse( - contexts=[ - context.Context(), - context.Context(), - context.Context(), - ], - next_page_token='abc', - ), - context.ListContextsResponse( - contexts=[], - next_page_token='def', - ), - context.ListContextsResponse( - contexts=[ - context.Context(), - ], - next_page_token='ghi', - ), - context.ListContextsResponse( - contexts=[ - context.Context(), - context.Context(), - ], - ), - ) - # Two responses for two calls - response = response + response - - # Wrap the values into proper Response objs - response = tuple(context.ListContextsResponse.to_json(x) for x in response) - return_values = tuple(Response() for i in response) - for return_val, response_val in zip(return_values, response): - return_val._content = response_val.encode('UTF-8') - return_val.status_code = 200 - req.side_effect = return_values - - sample_request = {'parent': 'projects/sample1/agent/sessions/sample2'} - - pager = client.list_contexts(request=sample_request) - - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, context.Context) - for i in results) - - pages = list(client.list_contexts(request=sample_request).pages) - for page_, token in zip(pages, ['abc','def','ghi', '']): - assert page_.raw_page.next_page_token == token - - -@pytest.mark.parametrize("request_type", [ - context.GetContextRequest, - dict, -]) -def test_get_context_rest(request_type): - client = ContextsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/agent/sessions/sample2/contexts/sample3'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = context.Context( - name='name_value', - lifespan_count=1498, - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - pb_return_value = context.Context.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.get_context(request) - - # 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 - - -def test_get_context_rest_required_fields(request_type=context.GetContextRequest): - transport_class = transports.ContextsRestTransport - - request_init = {} - request_init["name"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - including_default_value_fields=False, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_context._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["name"] = 'name_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_context._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "name" in jsonified_request - assert jsonified_request["name"] == 'name_value' - - client = ContextsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = context.Context() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "get", - 'query_params': pb_request, - } - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - - pb_return_value = context.Context.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.get_context(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_get_context_rest_unset_required_fields(): - transport = transports.ContextsRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.get_context._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_get_context_rest_interceptors(null_interceptor): - transport = transports.ContextsRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.ContextsRestInterceptor(), - ) - client = ContextsClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.ContextsRestInterceptor, "post_get_context") as post, \ - mock.patch.object(transports.ContextsRestInterceptor, "pre_get_context") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = context.GetContextRequest.pb(context.GetContextRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = context.Context.to_json(context.Context()) - - request = context.GetContextRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = context.Context() - - client.get_context(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_get_context_rest_bad_request(transport: str = 'rest', request_type=context.GetContextRequest): - client = ContextsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/agent/sessions/sample2/contexts/sample3'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.get_context(request) - - -def test_get_context_rest_flattened(): - client = ContextsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = context.Context() - - # get arguments that satisfy an http rule for this method - sample_request = {'name': 'projects/sample1/agent/sessions/sample2/contexts/sample3'} - - # get truthy value for each flattened field - mock_args = dict( - name='name_value', - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - pb_return_value = context.Context.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.get_context(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v2/{name=projects/*/agent/sessions/*/contexts/*}" % client.transport._host, args[1]) - - -def test_get_context_rest_flattened_error(transport: str = 'rest'): - client = ContextsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.get_context( - context.GetContextRequest(), - name='name_value', - ) - - -def test_get_context_rest_error(): - client = ContextsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - gcd_context.CreateContextRequest, - dict, -]) -def test_create_context_rest(request_type): - client = ContextsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1/agent/sessions/sample2'} - request_init["context"] = {'name': 'name_value', 'lifespan_count': 1498, 'parameters': {'fields': {}}} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = gcd_context.Context( - name='name_value', - lifespan_count=1498, - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - pb_return_value = gcd_context.Context.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.create_context(request) - - # 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 - - -def test_create_context_rest_required_fields(request_type=gcd_context.CreateContextRequest): - transport_class = transports.ContextsRestTransport - - request_init = {} - request_init["parent"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - including_default_value_fields=False, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_context._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["parent"] = 'parent_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_context._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "parent" in jsonified_request - assert jsonified_request["parent"] == 'parent_value' - - client = ContextsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = gcd_context.Context() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "post", - 'query_params': pb_request, - } - transcode_result['body'] = pb_request - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - - pb_return_value = gcd_context.Context.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.create_context(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_create_context_rest_unset_required_fields(): - transport = transports.ContextsRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.create_context._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("parent", "context", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_create_context_rest_interceptors(null_interceptor): - transport = transports.ContextsRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.ContextsRestInterceptor(), - ) - client = ContextsClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.ContextsRestInterceptor, "post_create_context") as post, \ - mock.patch.object(transports.ContextsRestInterceptor, "pre_create_context") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = gcd_context.CreateContextRequest.pb(gcd_context.CreateContextRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = gcd_context.Context.to_json(gcd_context.Context()) - - request = gcd_context.CreateContextRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = gcd_context.Context() - - client.create_context(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_create_context_rest_bad_request(transport: str = 'rest', request_type=gcd_context.CreateContextRequest): - client = ContextsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1/agent/sessions/sample2'} - request_init["context"] = {'name': 'name_value', 'lifespan_count': 1498, 'parameters': {'fields': {}}} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.create_context(request) - - -def test_create_context_rest_flattened(): - client = ContextsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = gcd_context.Context() - - # get arguments that satisfy an http rule for this method - sample_request = {'parent': 'projects/sample1/agent/sessions/sample2'} - - # get truthy value for each flattened field - mock_args = dict( - parent='parent_value', - context=gcd_context.Context(name='name_value'), - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - pb_return_value = gcd_context.Context.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.create_context(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v2/{parent=projects/*/agent/sessions/*}/contexts" % client.transport._host, args[1]) - - -def test_create_context_rest_flattened_error(transport: str = 'rest'): - client = ContextsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.create_context( - gcd_context.CreateContextRequest(), - parent='parent_value', - context=gcd_context.Context(name='name_value'), - ) - - -def test_create_context_rest_error(): - client = ContextsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - gcd_context.UpdateContextRequest, - dict, -]) -def test_update_context_rest(request_type): - client = ContextsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'context': {'name': 'projects/sample1/agent/sessions/sample2/contexts/sample3'}} - request_init["context"] = {'name': 'projects/sample1/agent/sessions/sample2/contexts/sample3', 'lifespan_count': 1498, 'parameters': {'fields': {}}} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = gcd_context.Context( - name='name_value', - lifespan_count=1498, - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - pb_return_value = gcd_context.Context.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.update_context(request) - - # 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 - - -def test_update_context_rest_required_fields(request_type=gcd_context.UpdateContextRequest): - transport_class = transports.ContextsRestTransport - - request_init = {} - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - including_default_value_fields=False, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).update_context._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).update_context._get_unset_required_fields(jsonified_request) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("update_mask", )) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - - client = ContextsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = gcd_context.Context() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "patch", - 'query_params': pb_request, - } - transcode_result['body'] = pb_request - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - - pb_return_value = gcd_context.Context.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.update_context(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_update_context_rest_unset_required_fields(): - transport = transports.ContextsRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.update_context._get_unset_required_fields({}) - assert set(unset_fields) == (set(("updateMask", )) & set(("context", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_update_context_rest_interceptors(null_interceptor): - transport = transports.ContextsRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.ContextsRestInterceptor(), - ) - client = ContextsClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.ContextsRestInterceptor, "post_update_context") as post, \ - mock.patch.object(transports.ContextsRestInterceptor, "pre_update_context") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = gcd_context.UpdateContextRequest.pb(gcd_context.UpdateContextRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = gcd_context.Context.to_json(gcd_context.Context()) - - request = gcd_context.UpdateContextRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = gcd_context.Context() - - client.update_context(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_update_context_rest_bad_request(transport: str = 'rest', request_type=gcd_context.UpdateContextRequest): - client = ContextsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'context': {'name': 'projects/sample1/agent/sessions/sample2/contexts/sample3'}} - request_init["context"] = {'name': 'projects/sample1/agent/sessions/sample2/contexts/sample3', 'lifespan_count': 1498, 'parameters': {'fields': {}}} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.update_context(request) - - -def test_update_context_rest_flattened(): - client = ContextsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = gcd_context.Context() - - # get arguments that satisfy an http rule for this method - sample_request = {'context': {'name': 'projects/sample1/agent/sessions/sample2/contexts/sample3'}} - - # get truthy value for each flattened field - mock_args = dict( - context=gcd_context.Context(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - pb_return_value = gcd_context.Context.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.update_context(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v2/{context.name=projects/*/agent/sessions/*/contexts/*}" % client.transport._host, args[1]) - - -def test_update_context_rest_flattened_error(transport: str = 'rest'): - client = ContextsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.update_context( - gcd_context.UpdateContextRequest(), - context=gcd_context.Context(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - - -def test_update_context_rest_error(): - client = ContextsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - context.DeleteContextRequest, - dict, -]) -def test_delete_context_rest(request_type): - client = ContextsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/agent/sessions/sample2/contexts/sample3'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = None - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = '' - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.delete_context(request) - - # Establish that the response is the type that we expect. - assert response is None - - -def test_delete_context_rest_required_fields(request_type=context.DeleteContextRequest): - transport_class = transports.ContextsRestTransport - - request_init = {} - request_init["name"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - including_default_value_fields=False, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).delete_context._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["name"] = 'name_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).delete_context._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "name" in jsonified_request - assert jsonified_request["name"] == 'name_value' - - client = ContextsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = None - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "delete", - 'query_params': pb_request, - } - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - json_return_value = '' - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.delete_context(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_delete_context_rest_unset_required_fields(): - transport = transports.ContextsRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.delete_context._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_delete_context_rest_interceptors(null_interceptor): - transport = transports.ContextsRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.ContextsRestInterceptor(), - ) - client = ContextsClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.ContextsRestInterceptor, "pre_delete_context") as pre: - pre.assert_not_called() - pb_message = context.DeleteContextRequest.pb(context.DeleteContextRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - - request = context.DeleteContextRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - - client.delete_context(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - - -def test_delete_context_rest_bad_request(transport: str = 'rest', request_type=context.DeleteContextRequest): - client = ContextsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/agent/sessions/sample2/contexts/sample3'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.delete_context(request) - - -def test_delete_context_rest_flattened(): - client = ContextsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = None - - # get arguments that satisfy an http rule for this method - sample_request = {'name': 'projects/sample1/agent/sessions/sample2/contexts/sample3'} - - # get truthy value for each flattened field - mock_args = dict( - name='name_value', - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = '' - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.delete_context(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v2/{name=projects/*/agent/sessions/*/contexts/*}" % client.transport._host, args[1]) - - -def test_delete_context_rest_flattened_error(transport: str = 'rest'): - client = ContextsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.delete_context( - context.DeleteContextRequest(), - name='name_value', - ) - - -def test_delete_context_rest_error(): - client = ContextsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - context.DeleteAllContextsRequest, - dict, -]) -def test_delete_all_contexts_rest(request_type): - client = ContextsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1/agent/sessions/sample2'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = None - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = '' - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.delete_all_contexts(request) - - # Establish that the response is the type that we expect. - assert response is None - - -def test_delete_all_contexts_rest_required_fields(request_type=context.DeleteAllContextsRequest): - transport_class = transports.ContextsRestTransport - - request_init = {} - request_init["parent"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - including_default_value_fields=False, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).delete_all_contexts._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["parent"] = 'parent_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).delete_all_contexts._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "parent" in jsonified_request - assert jsonified_request["parent"] == 'parent_value' - - client = ContextsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = None - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "delete", - 'query_params': pb_request, - } - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - json_return_value = '' - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.delete_all_contexts(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_delete_all_contexts_rest_unset_required_fields(): - transport = transports.ContextsRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.delete_all_contexts._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("parent", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_delete_all_contexts_rest_interceptors(null_interceptor): - transport = transports.ContextsRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.ContextsRestInterceptor(), - ) - client = ContextsClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.ContextsRestInterceptor, "pre_delete_all_contexts") as pre: - pre.assert_not_called() - pb_message = context.DeleteAllContextsRequest.pb(context.DeleteAllContextsRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - - request = context.DeleteAllContextsRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - - client.delete_all_contexts(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - - -def test_delete_all_contexts_rest_bad_request(transport: str = 'rest', request_type=context.DeleteAllContextsRequest): - client = ContextsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1/agent/sessions/sample2'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.delete_all_contexts(request) - - -def test_delete_all_contexts_rest_flattened(): - client = ContextsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = None - - # get arguments that satisfy an http rule for this method - sample_request = {'parent': 'projects/sample1/agent/sessions/sample2'} - - # get truthy value for each flattened field - mock_args = dict( - parent='parent_value', - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = '' - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.delete_all_contexts(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v2/{parent=projects/*/agent/sessions/*}/contexts" % client.transport._host, args[1]) - - -def test_delete_all_contexts_rest_flattened_error(transport: str = 'rest'): - client = ContextsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.delete_all_contexts( - context.DeleteAllContextsRequest(), - parent='parent_value', - ) - - -def test_delete_all_contexts_rest_error(): - client = ContextsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -def test_credentials_transport_error(): - # It is an error to provide credentials and a transport instance. - transport = transports.ContextsGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = ContextsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # It is an error to provide a credentials file and a transport instance. - transport = transports.ContextsGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = ContextsClient( - client_options={"credentials_file": "credentials.json"}, - transport=transport, - ) - - # It is an error to provide an api_key and a transport instance. - transport = transports.ContextsGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - options = client_options.ClientOptions() - options.api_key = "api_key" - with pytest.raises(ValueError): - client = ContextsClient( - client_options=options, - transport=transport, - ) - - # It is an error to provide an api_key and a credential. - options = mock.Mock() - options.api_key = "api_key" - with pytest.raises(ValueError): - client = ContextsClient( - client_options=options, - credentials=ga_credentials.AnonymousCredentials() - ) - - # It is an error to provide scopes and a transport instance. - transport = transports.ContextsGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = ContextsClient( - client_options={"scopes": ["1", "2"]}, - transport=transport, - ) - - -def test_transport_instance(): - # A client may be instantiated with a custom transport instance. - transport = transports.ContextsGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - client = ContextsClient(transport=transport) - assert client.transport is transport - -def test_transport_get_channel(): - # A client may be instantiated with a custom transport instance. - transport = transports.ContextsGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - - transport = transports.ContextsGrpcAsyncIOTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - -@pytest.mark.parametrize("transport_class", [ - transports.ContextsGrpcTransport, - transports.ContextsGrpcAsyncIOTransport, - transports.ContextsRestTransport, -]) -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() - -@pytest.mark.parametrize("transport_name", [ - "grpc", - "rest", -]) -def test_transport_kind(transport_name): - transport = ContextsClient.get_transport_class(transport_name)( - credentials=ga_credentials.AnonymousCredentials(), - ) - assert transport.kind == transport_name - -def test_transport_grpc_default(): - # A client should use the gRPC transport by default. - 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(core_exceptions.DuplicateCredentialArgs): - transport = transports.ContextsTransport( - credentials=ga_credentials.AnonymousCredentials(), - credentials_file="credentials.json" - ) - - -def test_contexts_base_transport(): - # Instantiate the base transport. - with mock.patch('google.cloud.dialogflow_v2.services.contexts.transports.ContextsTransport.__init__') as Transport: - Transport.return_value = None - transport = transports.ContextsTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Every method on the transport should just blindly - # raise NotImplementedError. - methods = ( - 'list_contexts', - 'get_context', - 'create_context', - 'update_context', - 'delete_context', - 'delete_all_contexts', - 'get_location', - 'list_locations', - 'get_operation', - 'cancel_operation', - 'list_operations', - ) - for method in methods: - with pytest.raises(NotImplementedError): - getattr(transport, method)(request=object()) - - with pytest.raises(NotImplementedError): - transport.close() - - # Catch all for all remaining methods and properties - remainder = [ - 'kind', - ] - for r in remainder: - with pytest.raises(NotImplementedError): - getattr(transport, r)() - - -def test_contexts_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.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", - ) - - -def test_contexts_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.contexts.transports.ContextsTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.ContextsTransport() - adc.assert_called_once() - - -def test_contexts_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) - 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, - ) - - -@pytest.mark.parametrize( - "transport_class", - [ - transports.ContextsGrpcTransport, - transports.ContextsGrpcAsyncIOTransport, - ], -) -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(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, - transports.ContextsRestTransport, - ], -) -def test_contexts_transport_auth_gdch_credentials(transport_class): - host = 'https://language.com' - api_audience_tests = [None, 'https://language2.com'] - api_audience_expect = [host, 'https://language2.com'] - for t, e in zip(api_audience_tests, api_audience_expect): - with mock.patch.object(google.auth, 'default', autospec=True) as adc: - gdch_mock = mock.MagicMock() - type(gdch_mock).with_gdch_audience = mock.PropertyMock(return_value=gdch_mock) - adc.return_value = (gdch_mock, None) - transport_class(host=host, api_audience=t) - gdch_mock.with_gdch_audience.assert_called_once_with( - e - ) - - -@pytest.mark.parametrize( - "transport_class,grpc_helpers", - [ - (transports.ContextsGrpcTransport, grpc_helpers), - (transports.ContextsGrpcAsyncIOTransport, grpc_helpers_async) - ], -) -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", [transports.ContextsGrpcTransport, transports.ContextsGrpcAsyncIOTransport]) -def test_contexts_grpc_transport_client_cert_source_for_mtls( - transport_class -): - cred = ga_credentials.AnonymousCredentials() - - # Check ssl_channel_credentials is used if provided. - with mock.patch.object(transport_class, "create_channel") as mock_create_channel: - mock_ssl_channel_creds = mock.Mock() - transport_class( - host="squid.clam.whelk", - credentials=cred, - ssl_channel_credentials=mock_ssl_channel_creds - ) - mock_create_channel.assert_called_once_with( - "squid.clam.whelk:443", - credentials=cred, - credentials_file=None, - scopes=None, - ssl_credentials=mock_ssl_channel_creds, - quota_project_id=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - # Check if ssl_channel_credentials is not provided, then client_cert_source_for_mtls - # is used. - with mock.patch.object(transport_class, "create_channel", return_value=mock.Mock()): - with mock.patch("grpc.ssl_channel_credentials") as mock_ssl_cred: - transport_class( - credentials=cred, - client_cert_source_for_mtls=client_cert_source_callback - ) - expected_cert, expected_key = client_cert_source_callback() - mock_ssl_cred.assert_called_once_with( - certificate_chain=expected_cert, - private_key=expected_key - ) - -def test_contexts_http_transport_client_cert_source_for_mtls(): - cred = ga_credentials.AnonymousCredentials() - with mock.patch("google.auth.transport.requests.AuthorizedSession.configure_mtls_channel") as mock_configure_mtls_channel: - transports.ContextsRestTransport ( - credentials=cred, - client_cert_source_for_mtls=client_cert_source_callback - ) - mock_configure_mtls_channel.assert_called_once_with(client_cert_source_callback) - - -@pytest.mark.parametrize("transport_name", [ - "grpc", - "grpc_asyncio", - "rest", -]) -def test_contexts_host_no_port(transport_name): - client = ContextsClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='dialogflow.googleapis.com'), - transport=transport_name, - ) - assert client.transport._host == ( - 'dialogflow.googleapis.com:443' - if transport_name in ['grpc', 'grpc_asyncio'] - else 'https://dialogflow.googleapis.com' - ) - -@pytest.mark.parametrize("transport_name", [ - "grpc", - "grpc_asyncio", - "rest", -]) -def test_contexts_host_with_port(transport_name): - client = ContextsClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='dialogflow.googleapis.com:8000'), - transport=transport_name, - ) - assert client.transport._host == ( - 'dialogflow.googleapis.com:8000' - if transport_name in ['grpc', 'grpc_asyncio'] - else 'https://dialogflow.googleapis.com:8000' - ) - -@pytest.mark.parametrize("transport_name", [ - "rest", -]) -def test_contexts_client_transport_session_collision(transport_name): - creds1 = ga_credentials.AnonymousCredentials() - creds2 = ga_credentials.AnonymousCredentials() - client1 = ContextsClient( - credentials=creds1, - transport=transport_name, - ) - client2 = ContextsClient( - credentials=creds2, - transport=transport_name, - ) - session1 = client1.transport.list_contexts._session - session2 = client2.transport.list_contexts._session - assert session1 != session2 - session1 = client1.transport.get_context._session - session2 = client2.transport.get_context._session - assert session1 != session2 - session1 = client1.transport.create_context._session - session2 = client2.transport.create_context._session - assert session1 != session2 - session1 = client1.transport.update_context._session - session2 = client2.transport.update_context._session - assert session1 != session2 - session1 = client1.transport.delete_context._session - session2 = client2.transport.delete_context._session - assert session1 != session2 - session1 = client1.transport.delete_all_contexts._session - session2 = client2.transport.delete_all_contexts._session - assert session1 != session2 -def test_contexts_grpc_transport_channel(): - channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.ContextsGrpcTransport( - 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_contexts_grpc_asyncio_transport_channel(): - channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.ContextsGrpcAsyncIOTransport( - 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.ContextsGrpcTransport, transports.ContextsGrpcAsyncIOTransport]) -def test_contexts_transport_channel_mtls_with_client_cert_source( - transport_class -): - with mock.patch("grpc.ssl_channel_credentials", autospec=True) as grpc_ssl_channel_cred: - with mock.patch.object(transport_class, "create_channel") as grpc_create_channel: - mock_ssl_cred = mock.Mock() - grpc_ssl_channel_cred.return_value = mock_ssl_cred - - mock_grpc_channel = mock.Mock() - grpc_create_channel.return_value = mock_grpc_channel - - cred = ga_credentials.AnonymousCredentials() - with pytest.warns(DeprecationWarning): - with mock.patch.object(google.auth, 'default') as adc: - adc.return_value = (cred, None) - transport = transport_class( - host="squid.clam.whelk", - api_mtls_endpoint="mtls.squid.clam.whelk", - client_cert_source=client_cert_source_callback, - ) - adc.assert_called_once() - - grpc_ssl_channel_cred.assert_called_once_with( - certificate_chain=b"cert bytes", private_key=b"key bytes" - ) - grpc_create_channel.assert_called_once_with( - "mtls.squid.clam.whelk:443", - credentials=cred, - credentials_file=None, - scopes=None, - ssl_credentials=mock_ssl_cred, - quota_project_id=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - assert transport.grpc_channel == mock_grpc_channel - assert transport._ssl_channel_credentials == mock_ssl_cred - - -# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are -# removed from grpc/grpc_asyncio transport constructor. -@pytest.mark.parametrize("transport_class", [transports.ContextsGrpcTransport, transports.ContextsGrpcAsyncIOTransport]) -def test_contexts_transport_channel_mtls_with_adc( - transport_class -): - mock_ssl_cred = mock.Mock() - with mock.patch.multiple( - "google.auth.transport.grpc.SslCredentials", - __init__=mock.Mock(return_value=None), - ssl_credentials=mock.PropertyMock(return_value=mock_ssl_cred), - ): - with mock.patch.object(transport_class, "create_channel") as grpc_create_channel: - mock_grpc_channel = mock.Mock() - grpc_create_channel.return_value = mock_grpc_channel - mock_cred = mock.Mock() - - with pytest.warns(DeprecationWarning): - transport = transport_class( - host="squid.clam.whelk", - credentials=mock_cred, - api_mtls_endpoint="mtls.squid.clam.whelk", - client_cert_source=None, - ) - - grpc_create_channel.assert_called_once_with( - "mtls.squid.clam.whelk:443", - credentials=mock_cred, - credentials_file=None, - scopes=None, - ssl_credentials=mock_ssl_cred, - quota_project_id=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - assert transport.grpc_channel == mock_grpc_channel - - -def test_context_path(): - project = "squid" - session = "clam" - context = "whelk" - expected = "projects/{project}/agent/sessions/{session}/contexts/{context}".format(project=project, session=session, context=context, ) - actual = ContextsClient.context_path(project, session, context) - assert expected == actual - - -def test_parse_context_path(): - expected = { - "project": "octopus", - "session": "oyster", - "context": "nudibranch", - } - path = ContextsClient.context_path(**expected) - - # Check that the path construction is reversible. - actual = ContextsClient.parse_context_path(path) - assert expected == actual - -def test_common_billing_account_path(): - billing_account = "cuttlefish" - expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) - actual = ContextsClient.common_billing_account_path(billing_account) - assert expected == actual - - -def test_parse_common_billing_account_path(): - expected = { - "billing_account": "mussel", - } - path = ContextsClient.common_billing_account_path(**expected) - - # Check that the path construction is reversible. - actual = ContextsClient.parse_common_billing_account_path(path) - assert expected == actual - -def test_common_folder_path(): - folder = "winkle" - expected = "folders/{folder}".format(folder=folder, ) - actual = ContextsClient.common_folder_path(folder) - assert expected == actual - - -def test_parse_common_folder_path(): - expected = { - "folder": "nautilus", - } - path = ContextsClient.common_folder_path(**expected) - - # Check that the path construction is reversible. - actual = ContextsClient.parse_common_folder_path(path) - assert expected == actual - -def test_common_organization_path(): - organization = "scallop" - expected = "organizations/{organization}".format(organization=organization, ) - actual = ContextsClient.common_organization_path(organization) - assert expected == actual - - -def test_parse_common_organization_path(): - expected = { - "organization": "abalone", - } - path = ContextsClient.common_organization_path(**expected) - - # Check that the path construction is reversible. - actual = ContextsClient.parse_common_organization_path(path) - assert expected == actual - -def test_common_project_path(): - project = "squid" - expected = "projects/{project}".format(project=project, ) - actual = ContextsClient.common_project_path(project) - assert expected == actual - - -def test_parse_common_project_path(): - expected = { - "project": "clam", - } - path = ContextsClient.common_project_path(**expected) - - # Check that the path construction is reversible. - actual = ContextsClient.parse_common_project_path(path) - assert expected == actual - -def test_common_location_path(): - project = "whelk" - location = "octopus" - expected = "projects/{project}/locations/{location}".format(project=project, location=location, ) - actual = ContextsClient.common_location_path(project, location) - assert expected == actual - - -def test_parse_common_location_path(): - expected = { - "project": "oyster", - "location": "nudibranch", - } - path = ContextsClient.common_location_path(**expected) - - # Check that the path construction is reversible. - actual = ContextsClient.parse_common_location_path(path) - assert expected == actual - - -def test_client_with_default_client_info(): - client_info = gapic_v1.client_info.ClientInfo() - - with mock.patch.object(transports.ContextsTransport, '_prep_wrapped_messages') as prep: - client = ContextsClient( - credentials=ga_credentials.AnonymousCredentials(), - client_info=client_info, - ) - prep.assert_called_once_with(client_info) - - with mock.patch.object(transports.ContextsTransport, '_prep_wrapped_messages') as prep: - transport_class = ContextsClient.get_transport_class() - transport = transport_class( - credentials=ga_credentials.AnonymousCredentials(), - client_info=client_info, - ) - prep.assert_called_once_with(client_info) - -@pytest.mark.asyncio -async def test_transport_close_async(): - client = ContextsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - with mock.patch.object(type(getattr(client.transport, "grpc_channel")), "close") as close: - async with client: - close.assert_not_called() - close.assert_called_once() - - -def test_get_location_rest_bad_request(transport: str = 'rest', request_type=locations_pb2.GetLocationRequest): - client = ContextsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - request = request_type() - request = json_format.ParseDict({'name': 'projects/sample1/locations/sample2'}, request) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.get_location(request) - -@pytest.mark.parametrize("request_type", [ - locations_pb2.GetLocationRequest, - dict, -]) -def test_get_location_rest(request_type): - client = ContextsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request_init = {'name': 'projects/sample1/locations/sample2'} - request = request_type(**request_init) - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = locations_pb2.Location() - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.get_location(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, locations_pb2.Location) - -def test_list_locations_rest_bad_request(transport: str = 'rest', request_type=locations_pb2.ListLocationsRequest): - client = ContextsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - request = request_type() - request = json_format.ParseDict({'name': 'projects/sample1'}, request) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.list_locations(request) - -@pytest.mark.parametrize("request_type", [ - locations_pb2.ListLocationsRequest, - dict, -]) -def test_list_locations_rest(request_type): - client = ContextsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request_init = {'name': 'projects/sample1'} - request = request_type(**request_init) - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = locations_pb2.ListLocationsResponse() - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.list_locations(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, locations_pb2.ListLocationsResponse) - -def test_cancel_operation_rest_bad_request(transport: str = 'rest', request_type=operations_pb2.CancelOperationRequest): - client = ContextsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - request = request_type() - request = json_format.ParseDict({'name': 'projects/sample1/operations/sample2'}, request) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.cancel_operation(request) - -@pytest.mark.parametrize("request_type", [ - operations_pb2.CancelOperationRequest, - dict, -]) -def test_cancel_operation_rest(request_type): - client = ContextsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request_init = {'name': 'projects/sample1/operations/sample2'} - request = request_type(**request_init) - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = None - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = '{}' - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.cancel_operation(request) - - # Establish that the response is the type that we expect. - assert response is None - -def test_get_operation_rest_bad_request(transport: str = 'rest', request_type=operations_pb2.GetOperationRequest): - client = ContextsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - request = request_type() - request = json_format.ParseDict({'name': 'projects/sample1/operations/sample2'}, request) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.get_operation(request) - -@pytest.mark.parametrize("request_type", [ - operations_pb2.GetOperationRequest, - dict, -]) -def test_get_operation_rest(request_type): - client = ContextsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request_init = {'name': 'projects/sample1/operations/sample2'} - request = request_type(**request_init) - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation() - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.get_operation(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, operations_pb2.Operation) - -def test_list_operations_rest_bad_request(transport: str = 'rest', request_type=operations_pb2.ListOperationsRequest): - client = ContextsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - request = request_type() - request = json_format.ParseDict({'name': 'projects/sample1'}, request) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.list_operations(request) - -@pytest.mark.parametrize("request_type", [ - operations_pb2.ListOperationsRequest, - dict, -]) -def test_list_operations_rest(request_type): - client = ContextsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request_init = {'name': 'projects/sample1'} - request = request_type(**request_init) - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = operations_pb2.ListOperationsResponse() - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.list_operations(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, operations_pb2.ListOperationsResponse) - - -def test_cancel_operation(transport: str = "grpc"): - client = ContextsClient( - 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 = operations_pb2.CancelOperationRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = None - response = client.cancel_operation(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 response is the type that we expect. - assert response is None -@pytest.mark.asyncio -async def test_cancel_operation_async(transport: str = "grpc"): - client = ContextsAsyncClient( - 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 = operations_pb2.CancelOperationRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - None - ) - response = await client.cancel_operation(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 response is the type that we expect. - assert response is None - -def test_cancel_operation_field_headers(): - 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 = operations_pb2.CancelOperationRequest() - request.name = "locations" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call: - call.return_value = None - - client.cancel_operation(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=locations",) in kw["metadata"] -@pytest.mark.asyncio -async def test_cancel_operation_field_headers_async(): - 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 = operations_pb2.CancelOperationRequest() - request.name = "locations" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - None - ) - await client.cancel_operation(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=locations",) in kw["metadata"] - -def test_cancel_operation_from_dict(): - 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.cancel_operation), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = None - - response = client.cancel_operation( - request={ - "name": "locations", - } - ) - call.assert_called() -@pytest.mark.asyncio -async def test_cancel_operation_from_dict_async(): - 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.cancel_operation), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - None - ) - response = await client.cancel_operation( - request={ - "name": "locations", - } - ) - call.assert_called() - - -def test_get_operation(transport: str = "grpc"): - client = ContextsClient( - 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 = operations_pb2.GetOperationRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_operation), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation() - response = client.get_operation(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 response is the type that we expect. - assert isinstance(response, operations_pb2.Operation) -@pytest.mark.asyncio -async def test_get_operation_async(transport: str = "grpc"): - client = ContextsAsyncClient( - 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 = operations_pb2.GetOperationRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_operation), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation() - ) - response = await client.get_operation(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 response is the type that we expect. - assert isinstance(response, operations_pb2.Operation) - -def test_get_operation_field_headers(): - 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 = operations_pb2.GetOperationRequest() - request.name = "locations" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_operation), "__call__") as call: - call.return_value = operations_pb2.Operation() - - client.get_operation(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=locations",) in kw["metadata"] -@pytest.mark.asyncio -async def test_get_operation_field_headers_async(): - 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 = operations_pb2.GetOperationRequest() - request.name = "locations" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_operation), "__call__") as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation() - ) - await client.get_operation(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=locations",) in kw["metadata"] - -def test_get_operation_from_dict(): - 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_operation), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation() - - response = client.get_operation( - request={ - "name": "locations", - } - ) - call.assert_called() -@pytest.mark.asyncio -async def test_get_operation_from_dict_async(): - 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_operation), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation() - ) - response = await client.get_operation( - request={ - "name": "locations", - } - ) - call.assert_called() - - -def test_list_operations(transport: str = "grpc"): - client = ContextsClient( - 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 = operations_pb2.ListOperationsRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_operations), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.ListOperationsResponse() - response = client.list_operations(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 response is the type that we expect. - assert isinstance(response, operations_pb2.ListOperationsResponse) -@pytest.mark.asyncio -async def test_list_operations_async(transport: str = "grpc"): - client = ContextsAsyncClient( - 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 = operations_pb2.ListOperationsRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_operations), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.ListOperationsResponse() - ) - response = await client.list_operations(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 response is the type that we expect. - assert isinstance(response, operations_pb2.ListOperationsResponse) - -def test_list_operations_field_headers(): - 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 = operations_pb2.ListOperationsRequest() - request.name = "locations" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_operations), "__call__") as call: - call.return_value = operations_pb2.ListOperationsResponse() - - client.list_operations(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=locations",) in kw["metadata"] -@pytest.mark.asyncio -async def test_list_operations_field_headers_async(): - 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 = operations_pb2.ListOperationsRequest() - request.name = "locations" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_operations), "__call__") as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.ListOperationsResponse() - ) - await client.list_operations(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=locations",) in kw["metadata"] - -def test_list_operations_from_dict(): - 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_operations), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.ListOperationsResponse() - - response = client.list_operations( - request={ - "name": "locations", - } - ) - call.assert_called() -@pytest.mark.asyncio -async def test_list_operations_from_dict_async(): - 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_operations), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.ListOperationsResponse() - ) - response = await client.list_operations( - request={ - "name": "locations", - } - ) - call.assert_called() - - -def test_list_locations(transport: str = "grpc"): - client = ContextsClient( - 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 = locations_pb2.ListLocationsRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_locations), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = locations_pb2.ListLocationsResponse() - response = client.list_locations(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 response is the type that we expect. - assert isinstance(response, locations_pb2.ListLocationsResponse) -@pytest.mark.asyncio -async def test_list_locations_async(transport: str = "grpc"): - client = ContextsAsyncClient( - 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 = locations_pb2.ListLocationsRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_locations), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - locations_pb2.ListLocationsResponse() - ) - response = await client.list_locations(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 response is the type that we expect. - assert isinstance(response, locations_pb2.ListLocationsResponse) - -def test_list_locations_field_headers(): - 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 = locations_pb2.ListLocationsRequest() - request.name = "locations" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_locations), "__call__") as call: - call.return_value = locations_pb2.ListLocationsResponse() - - client.list_locations(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=locations",) in kw["metadata"] -@pytest.mark.asyncio -async def test_list_locations_field_headers_async(): - 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 = locations_pb2.ListLocationsRequest() - request.name = "locations" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_locations), "__call__") as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - locations_pb2.ListLocationsResponse() - ) - await client.list_locations(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=locations",) in kw["metadata"] - -def test_list_locations_from_dict(): - 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_locations), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = locations_pb2.ListLocationsResponse() - - response = client.list_locations( - request={ - "name": "locations", - } - ) - call.assert_called() -@pytest.mark.asyncio -async def test_list_locations_from_dict_async(): - 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_locations), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - locations_pb2.ListLocationsResponse() - ) - response = await client.list_locations( - request={ - "name": "locations", - } - ) - call.assert_called() - - -def test_get_location(transport: str = "grpc"): - client = ContextsClient( - 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 = locations_pb2.GetLocationRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_location), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = locations_pb2.Location() - response = client.get_location(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 response is the type that we expect. - assert isinstance(response, locations_pb2.Location) -@pytest.mark.asyncio -async def test_get_location_async(transport: str = "grpc_asyncio"): - client = ContextsAsyncClient( - 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 = locations_pb2.GetLocationRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_location), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - locations_pb2.Location() - ) - response = await client.get_location(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 response is the type that we expect. - assert isinstance(response, locations_pb2.Location) - -def test_get_location_field_headers(): - 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 = locations_pb2.GetLocationRequest() - request.name = "locations/abc" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_location), "__call__") as call: - call.return_value = locations_pb2.Location() - - client.get_location(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=locations/abc",) in kw["metadata"] -@pytest.mark.asyncio -async def test_get_location_field_headers_async(): - 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 = locations_pb2.GetLocationRequest() - request.name = "locations/abc" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_location), "__call__") as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - locations_pb2.Location() - ) - await client.get_location(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=locations/abc",) in kw["metadata"] - -def test_get_location_from_dict(): - 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_locations), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = locations_pb2.Location() - - response = client.get_location( - request={ - "name": "locations/abc", - } - ) - call.assert_called() -@pytest.mark.asyncio -async def test_get_location_from_dict_async(): - 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_locations), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - locations_pb2.Location() - ) - response = await client.get_location( - request={ - "name": "locations", - } - ) - call.assert_called() - - -def test_transport_close(): - transports = { - "rest": "_session", - "grpc": "_grpc_channel", - } - - for transport, close_name in transports.items(): - client = ContextsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport - ) - with mock.patch.object(type(getattr(client.transport, close_name)), "close") as close: - with client: - close.assert_not_called() - close.assert_called_once() - -def test_client_ctx(): - transports = [ - 'rest', - 'grpc', - ] - for transport in transports: - client = ContextsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport - ) - # Test client calls underlying transport. - with mock.patch.object(type(client.transport), "close") as close: - close.assert_not_called() - with client: - pass - close.assert_called() - -@pytest.mark.parametrize("client_class,transport_class", [ - (ContextsClient, transports.ContextsGrpcTransport), - (ContextsAsyncClient, transports.ContextsGrpcAsyncIOTransport), -]) -def test_api_key_credentials(client_class, transport_class): - with mock.patch.object( - google.auth._default, "get_api_key_credentials", create=True - ) as get_api_key_credentials: - mock_cred = mock.Mock() - get_api_key_credentials.return_value = mock_cred - options = client_options.ClientOptions() - options.api_key = "api_key" - 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=mock_cred, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) diff --git a/owl-bot-staging/v2/tests/unit/gapic/dialogflow_v2/test_conversation_datasets.py b/owl-bot-staging/v2/tests/unit/gapic/dialogflow_v2/test_conversation_datasets.py deleted file mode 100644 index f454afe42..000000000 --- a/owl-bot-staging/v2/tests/unit/gapic/dialogflow_v2/test_conversation_datasets.py +++ /dev/null @@ -1,4634 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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 -# try/except added for compatibility with python < 3.8 -try: - from unittest import mock - from unittest.mock import AsyncMock # pragma: NO COVER -except ImportError: # pragma: NO COVER - import mock - -import grpc -from grpc.experimental import aio -from collections.abc import Iterable -from google.protobuf import json_format -import json -import math -import pytest -from proto.marshal.rules.dates import DurationRule, TimestampRule -from proto.marshal.rules import wrappers -from requests import Response -from requests import Request, PreparedRequest -from requests.sessions import Session -from google.protobuf import json_format - -from google.api_core import client_options -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 -from google.api_core import operation_async # type: ignore -from google.api_core import operations_v1 -from google.api_core import path_template -from google.auth import credentials as ga_credentials -from google.auth.exceptions import MutualTLSChannelError -from google.cloud.dialogflow_v2.services.conversation_datasets import ConversationDatasetsAsyncClient -from google.cloud.dialogflow_v2.services.conversation_datasets import ConversationDatasetsClient -from google.cloud.dialogflow_v2.services.conversation_datasets import pagers -from google.cloud.dialogflow_v2.services.conversation_datasets import transports -from google.cloud.dialogflow_v2.types import conversation_dataset -from google.cloud.dialogflow_v2.types import conversation_dataset as gcd_conversation_dataset -from google.cloud.dialogflow_v2.types import gcs -from google.cloud.location import locations_pb2 -from google.longrunning import operations_pb2 -from google.oauth2 import service_account -from google.protobuf import empty_pb2 # type: ignore -from google.protobuf import timestamp_pb2 # type: ignore -import google.auth - - -def client_cert_source_callback(): - return b"cert bytes", b"key bytes" - - -# If default endpoint is localhost, then default mtls endpoint will be the same. -# This method modifies the default endpoint so the client can produce a different -# mtls endpoint for endpoint testing purposes. -def modify_default_endpoint(client): - return "foo.googleapis.com" if ("localhost" in client.DEFAULT_ENDPOINT) else client.DEFAULT_ENDPOINT - - -def test__get_default_mtls_endpoint(): - api_endpoint = "example.googleapis.com" - api_mtls_endpoint = "example.mtls.googleapis.com" - sandbox_endpoint = "example.sandbox.googleapis.com" - sandbox_mtls_endpoint = "example.mtls.sandbox.googleapis.com" - non_googleapi = "api.example.com" - - assert ConversationDatasetsClient._get_default_mtls_endpoint(None) is None - assert ConversationDatasetsClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint - assert ConversationDatasetsClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint - assert ConversationDatasetsClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint - assert ConversationDatasetsClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint - assert ConversationDatasetsClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi - - -@pytest.mark.parametrize("client_class,transport_name", [ - (ConversationDatasetsClient, "grpc"), - (ConversationDatasetsAsyncClient, "grpc_asyncio"), - (ConversationDatasetsClient, "rest"), -]) -def test_conversation_datasets_client_from_service_account_info(client_class, transport_name): - 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, transport=transport_name) - assert client.transport._credentials == creds - assert isinstance(client, client_class) - - assert client.transport._host == ( - 'dialogflow.googleapis.com:443' - if transport_name in ['grpc', 'grpc_asyncio'] - else - 'https://dialogflow.googleapis.com' - ) - - -@pytest.mark.parametrize("transport_class,transport_name", [ - (transports.ConversationDatasetsGrpcTransport, "grpc"), - (transports.ConversationDatasetsGrpcAsyncIOTransport, "grpc_asyncio"), - (transports.ConversationDatasetsRestTransport, "rest"), -]) -def test_conversation_datasets_client_service_account_always_use_jwt(transport_class, transport_name): - with mock.patch.object(service_account.Credentials, 'with_always_use_jwt_access', create=True) as use_jwt: - creds = service_account.Credentials(None, None, None) - transport = transport_class(credentials=creds, always_use_jwt_access=True) - use_jwt.assert_called_once_with(True) - - with mock.patch.object(service_account.Credentials, 'with_always_use_jwt_access', create=True) as use_jwt: - creds = service_account.Credentials(None, None, None) - transport = transport_class(credentials=creds, always_use_jwt_access=False) - use_jwt.assert_not_called() - - -@pytest.mark.parametrize("client_class,transport_name", [ - (ConversationDatasetsClient, "grpc"), - (ConversationDatasetsAsyncClient, "grpc_asyncio"), - (ConversationDatasetsClient, "rest"), -]) -def test_conversation_datasets_client_from_service_account_file(client_class, transport_name): - 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", transport=transport_name) - assert client.transport._credentials == creds - assert isinstance(client, client_class) - - client = client_class.from_service_account_json("dummy/file/path.json", transport=transport_name) - assert client.transport._credentials == creds - assert isinstance(client, client_class) - - assert client.transport._host == ( - 'dialogflow.googleapis.com:443' - if transport_name in ['grpc', 'grpc_asyncio'] - else - 'https://dialogflow.googleapis.com' - ) - - -def test_conversation_datasets_client_get_transport_class(): - transport = ConversationDatasetsClient.get_transport_class() - available_transports = [ - transports.ConversationDatasetsGrpcTransport, - transports.ConversationDatasetsRestTransport, - ] - assert transport in available_transports - - transport = ConversationDatasetsClient.get_transport_class("grpc") - assert transport == transports.ConversationDatasetsGrpcTransport - - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (ConversationDatasetsClient, transports.ConversationDatasetsGrpcTransport, "grpc"), - (ConversationDatasetsAsyncClient, transports.ConversationDatasetsGrpcAsyncIOTransport, "grpc_asyncio"), - (ConversationDatasetsClient, transports.ConversationDatasetsRestTransport, "rest"), -]) -@mock.patch.object(ConversationDatasetsClient, "DEFAULT_ENDPOINT", modify_default_endpoint(ConversationDatasetsClient)) -@mock.patch.object(ConversationDatasetsAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(ConversationDatasetsAsyncClient)) -def test_conversation_datasets_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(ConversationDatasetsClient, '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(ConversationDatasetsClient, 'get_transport_class') as gtc: - client = client_class(transport=transport_name) - gtc.assert_called() - - # Check the case api_endpoint is provided. - options = client_options.ClientOptions(api_endpoint="squid.clam.whelk") - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(transport=transport_name, client_options=options) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host="squid.clam.whelk", - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is - # "never". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is - # "always". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_MTLS_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # 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(transport=transport_name) - - # 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(transport=transport_name) - - # 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, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id="octopus", - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - # Check the case api_endpoint is provided - options = client_options.ClientOptions(api_audience="https://language.googleapis.com") - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience="https://language.googleapis.com" - ) - -@pytest.mark.parametrize("client_class,transport_class,transport_name,use_client_cert_env", [ - (ConversationDatasetsClient, transports.ConversationDatasetsGrpcTransport, "grpc", "true"), - (ConversationDatasetsAsyncClient, transports.ConversationDatasetsGrpcAsyncIOTransport, "grpc_asyncio", "true"), - (ConversationDatasetsClient, transports.ConversationDatasetsGrpcTransport, "grpc", "false"), - (ConversationDatasetsAsyncClient, transports.ConversationDatasetsGrpcAsyncIOTransport, "grpc_asyncio", "false"), - (ConversationDatasetsClient, transports.ConversationDatasetsRestTransport, "rest", "true"), - (ConversationDatasetsClient, transports.ConversationDatasetsRestTransport, "rest", "false"), -]) -@mock.patch.object(ConversationDatasetsClient, "DEFAULT_ENDPOINT", modify_default_endpoint(ConversationDatasetsClient)) -@mock.patch.object(ConversationDatasetsAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(ConversationDatasetsAsyncClient)) -@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) -def test_conversation_datasets_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, transport=transport_name) - - if use_client_cert_env == "false": - expected_client_cert_source = None - expected_host = client.DEFAULT_ENDPOINT - else: - expected_client_cert_source = client_cert_source_callback - expected_host = client.DEFAULT_MTLS_ENDPOINT - - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=expected_host, - scopes=None, - client_cert_source_for_mtls=expected_client_cert_source, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case ADC client cert is provided. Whether client cert is used depends on - # GOOGLE_API_USE_CLIENT_CERTIFICATE value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): - with mock.patch.object(transport_class, '__init__') as patched: - with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): - with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=client_cert_source_callback): - if use_client_cert_env == "false": - expected_host = client.DEFAULT_ENDPOINT - expected_client_cert_source = None - else: - expected_host = client.DEFAULT_MTLS_ENDPOINT - expected_client_cert_source = client_cert_source_callback - - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=expected_host, - scopes=None, - client_cert_source_for_mtls=expected_client_cert_source, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case client_cert_source and ADC client cert are not provided. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): - with mock.patch.object(transport_class, '__init__') as patched: - with mock.patch("google.auth.transport.mtls.has_default_client_cert_source", return_value=False): - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - -@pytest.mark.parametrize("client_class", [ - ConversationDatasetsClient, ConversationDatasetsAsyncClient -]) -@mock.patch.object(ConversationDatasetsClient, "DEFAULT_ENDPOINT", modify_default_endpoint(ConversationDatasetsClient)) -@mock.patch.object(ConversationDatasetsAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(ConversationDatasetsAsyncClient)) -def test_conversation_datasets_client_get_mtls_endpoint_and_cert_source(client_class): - mock_client_cert_source = mock.Mock() - - # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "true". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - mock_api_endpoint = "foo" - options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) - assert api_endpoint == mock_api_endpoint - assert cert_source == mock_client_cert_source - - # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "false". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): - mock_client_cert_source = mock.Mock() - mock_api_endpoint = "foo" - options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) - assert api_endpoint == mock_api_endpoint - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "never". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_ENDPOINT - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "always". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert doesn't exist. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=False): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_ENDPOINT - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert exists. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - 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=mock_client_cert_source): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT - assert cert_source == mock_client_cert_source - - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (ConversationDatasetsClient, transports.ConversationDatasetsGrpcTransport, "grpc"), - (ConversationDatasetsAsyncClient, transports.ConversationDatasetsGrpcAsyncIOTransport, "grpc_asyncio"), - (ConversationDatasetsClient, transports.ConversationDatasetsRestTransport, "rest"), -]) -def test_conversation_datasets_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, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=["1", "2"], - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - -@pytest.mark.parametrize("client_class,transport_class,transport_name,grpc_helpers", [ - (ConversationDatasetsClient, transports.ConversationDatasetsGrpcTransport, "grpc", grpc_helpers), - (ConversationDatasetsAsyncClient, transports.ConversationDatasetsGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), - (ConversationDatasetsClient, transports.ConversationDatasetsRestTransport, "rest", None), -]) -def test_conversation_datasets_client_client_options_credentials_file(client_class, transport_class, transport_name, grpc_helpers): - # 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, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file="credentials.json", - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - -def test_conversation_datasets_client_client_options_from_dict(): - with mock.patch('google.cloud.dialogflow_v2.services.conversation_datasets.transports.ConversationDatasetsGrpcTransport.__init__') as grpc_transport: - grpc_transport.return_value = None - client = ConversationDatasetsClient( - client_options={'api_endpoint': 'squid.clam.whelk'} - ) - grpc_transport.assert_called_once_with( - credentials=None, - credentials_file=None, - host="squid.clam.whelk", - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - -@pytest.mark.parametrize("client_class,transport_class,transport_name,grpc_helpers", [ - (ConversationDatasetsClient, transports.ConversationDatasetsGrpcTransport, "grpc", grpc_helpers), - (ConversationDatasetsAsyncClient, transports.ConversationDatasetsGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), -]) -def test_conversation_datasets_client_create_channel_credentials_file(client_class, transport_class, transport_name, grpc_helpers): - # 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, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file="credentials.json", - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # test that the credentials from file are saved and used as the credentials. - with mock.patch.object( - google.auth, "load_credentials_from_file", autospec=True - ) as load_creds, mock.patch.object( - google.auth, "default", autospec=True - ) as adc, mock.patch.object( - grpc_helpers, "create_channel" - ) as create_channel: - creds = ga_credentials.AnonymousCredentials() - file_creds = ga_credentials.AnonymousCredentials() - load_creds.return_value = (file_creds, None) - adc.return_value = (creds, None) - client = client_class(client_options=options, transport=transport_name) - create_channel.assert_called_with( - "dialogflow.googleapis.com:443", - credentials=file_creds, - credentials_file=None, - quota_project_id=None, - default_scopes=( - 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/dialogflow', -), - scopes=None, - default_host="dialogflow.googleapis.com", - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - -@pytest.mark.parametrize("request_type", [ - gcd_conversation_dataset.CreateConversationDatasetRequest, - dict, -]) -def test_create_conversation_dataset(request_type, transport: str = 'grpc'): - client = ConversationDatasetsClient( - 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_conversation_dataset), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/spam') - response = client.create_conversation_dataset(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_dataset.CreateConversationDatasetRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -def test_create_conversation_dataset_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = ConversationDatasetsClient( - 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_conversation_dataset), - '__call__') as call: - client.create_conversation_dataset() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == gcd_conversation_dataset.CreateConversationDatasetRequest() - -@pytest.mark.asyncio -async def test_create_conversation_dataset_async(transport: str = 'grpc_asyncio', request_type=gcd_conversation_dataset.CreateConversationDatasetRequest): - client = ConversationDatasetsAsyncClient( - 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_conversation_dataset), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name='operations/spam') - ) - response = await client.create_conversation_dataset(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_dataset.CreateConversationDatasetRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -@pytest.mark.asyncio -async def test_create_conversation_dataset_async_from_dict(): - await test_create_conversation_dataset_async(request_type=dict) - - -def test_create_conversation_dataset_field_headers(): - client = ConversationDatasetsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value 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_dataset.CreateConversationDatasetRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_conversation_dataset), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') - client.create_conversation_dataset(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_conversation_dataset_field_headers_async(): - client = ConversationDatasetsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value 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_dataset.CreateConversationDatasetRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_conversation_dataset), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) - await client.create_conversation_dataset(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_conversation_dataset_flattened(): - client = ConversationDatasetsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_conversation_dataset), - '__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_conversation_dataset( - parent='parent_value', - conversation_dataset=gcd_conversation_dataset.ConversationDataset(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] - arg = args[0].parent - mock_val = 'parent_value' - assert arg == mock_val - arg = args[0].conversation_dataset - mock_val = gcd_conversation_dataset.ConversationDataset(name='name_value') - assert arg == mock_val - - -def test_create_conversation_dataset_flattened_error(): - client = ConversationDatasetsClient( - 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_conversation_dataset( - gcd_conversation_dataset.CreateConversationDatasetRequest(), - parent='parent_value', - conversation_dataset=gcd_conversation_dataset.ConversationDataset(name='name_value'), - ) - -@pytest.mark.asyncio -async def test_create_conversation_dataset_flattened_async(): - client = ConversationDatasetsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_conversation_dataset), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/op') - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name='operations/spam') - ) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.create_conversation_dataset( - parent='parent_value', - conversation_dataset=gcd_conversation_dataset.ConversationDataset(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] - arg = args[0].parent - mock_val = 'parent_value' - assert arg == mock_val - arg = args[0].conversation_dataset - mock_val = gcd_conversation_dataset.ConversationDataset(name='name_value') - assert arg == mock_val - -@pytest.mark.asyncio -async def test_create_conversation_dataset_flattened_error_async(): - client = ConversationDatasetsAsyncClient( - 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_conversation_dataset( - gcd_conversation_dataset.CreateConversationDatasetRequest(), - parent='parent_value', - conversation_dataset=gcd_conversation_dataset.ConversationDataset(name='name_value'), - ) - - -@pytest.mark.parametrize("request_type", [ - conversation_dataset.GetConversationDatasetRequest, - dict, -]) -def test_get_conversation_dataset(request_type, transport: str = 'grpc'): - client = ConversationDatasetsClient( - 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_conversation_dataset), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = conversation_dataset.ConversationDataset( - name='name_value', - display_name='display_name_value', - description='description_value', - conversation_count=1955, - ) - response = client.get_conversation_dataset(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_dataset.GetConversationDatasetRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, conversation_dataset.ConversationDataset) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.description == 'description_value' - assert response.conversation_count == 1955 - - -def test_get_conversation_dataset_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = ConversationDatasetsClient( - 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_conversation_dataset), - '__call__') as call: - client.get_conversation_dataset() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == conversation_dataset.GetConversationDatasetRequest() - -@pytest.mark.asyncio -async def test_get_conversation_dataset_async(transport: str = 'grpc_asyncio', request_type=conversation_dataset.GetConversationDatasetRequest): - client = ConversationDatasetsAsyncClient( - 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_conversation_dataset), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(conversation_dataset.ConversationDataset( - name='name_value', - display_name='display_name_value', - description='description_value', - conversation_count=1955, - )) - response = await client.get_conversation_dataset(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == conversation_dataset.GetConversationDatasetRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, conversation_dataset.ConversationDataset) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.description == 'description_value' - assert response.conversation_count == 1955 - - -@pytest.mark.asyncio -async def test_get_conversation_dataset_async_from_dict(): - await test_get_conversation_dataset_async(request_type=dict) - - -def test_get_conversation_dataset_field_headers(): - client = ConversationDatasetsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value 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_dataset.GetConversationDatasetRequest() - - 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_dataset), - '__call__') as call: - call.return_value = conversation_dataset.ConversationDataset() - client.get_conversation_dataset(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_conversation_dataset_field_headers_async(): - client = ConversationDatasetsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value 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_dataset.GetConversationDatasetRequest() - - 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_dataset), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(conversation_dataset.ConversationDataset()) - await client.get_conversation_dataset(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_conversation_dataset_flattened(): - client = ConversationDatasetsClient( - 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_dataset), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = conversation_dataset.ConversationDataset() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.get_conversation_dataset( - 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] - arg = args[0].name - mock_val = 'name_value' - assert arg == mock_val - - -def test_get_conversation_dataset_flattened_error(): - client = ConversationDatasetsClient( - 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_conversation_dataset( - conversation_dataset.GetConversationDatasetRequest(), - name='name_value', - ) - -@pytest.mark.asyncio -async def test_get_conversation_dataset_flattened_async(): - client = ConversationDatasetsAsyncClient( - 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_dataset), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = conversation_dataset.ConversationDataset() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(conversation_dataset.ConversationDataset()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.get_conversation_dataset( - 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] - arg = args[0].name - mock_val = 'name_value' - assert arg == mock_val - -@pytest.mark.asyncio -async def test_get_conversation_dataset_flattened_error_async(): - client = ConversationDatasetsAsyncClient( - 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_conversation_dataset( - conversation_dataset.GetConversationDatasetRequest(), - name='name_value', - ) - - -@pytest.mark.parametrize("request_type", [ - conversation_dataset.ListConversationDatasetsRequest, - dict, -]) -def test_list_conversation_datasets(request_type, transport: str = 'grpc'): - client = ConversationDatasetsClient( - 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_conversation_datasets), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = conversation_dataset.ListConversationDatasetsResponse( - next_page_token='next_page_token_value', - ) - response = client.list_conversation_datasets(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_dataset.ListConversationDatasetsRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListConversationDatasetsPager) - assert response.next_page_token == 'next_page_token_value' - - -def test_list_conversation_datasets_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = ConversationDatasetsClient( - 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_conversation_datasets), - '__call__') as call: - client.list_conversation_datasets() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == conversation_dataset.ListConversationDatasetsRequest() - -@pytest.mark.asyncio -async def test_list_conversation_datasets_async(transport: str = 'grpc_asyncio', request_type=conversation_dataset.ListConversationDatasetsRequest): - client = ConversationDatasetsAsyncClient( - 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_conversation_datasets), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(conversation_dataset.ListConversationDatasetsResponse( - next_page_token='next_page_token_value', - )) - response = await client.list_conversation_datasets(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == conversation_dataset.ListConversationDatasetsRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListConversationDatasetsAsyncPager) - assert response.next_page_token == 'next_page_token_value' - - -@pytest.mark.asyncio -async def test_list_conversation_datasets_async_from_dict(): - await test_list_conversation_datasets_async(request_type=dict) - - -def test_list_conversation_datasets_field_headers(): - client = ConversationDatasetsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value 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_dataset.ListConversationDatasetsRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_conversation_datasets), - '__call__') as call: - call.return_value = conversation_dataset.ListConversationDatasetsResponse() - client.list_conversation_datasets(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_conversation_datasets_field_headers_async(): - client = ConversationDatasetsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value 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_dataset.ListConversationDatasetsRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_conversation_datasets), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(conversation_dataset.ListConversationDatasetsResponse()) - await client.list_conversation_datasets(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_conversation_datasets_flattened(): - client = ConversationDatasetsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_conversation_datasets), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = conversation_dataset.ListConversationDatasetsResponse() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.list_conversation_datasets( - 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] - arg = args[0].parent - mock_val = 'parent_value' - assert arg == mock_val - - -def test_list_conversation_datasets_flattened_error(): - client = ConversationDatasetsClient( - 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_conversation_datasets( - conversation_dataset.ListConversationDatasetsRequest(), - parent='parent_value', - ) - -@pytest.mark.asyncio -async def test_list_conversation_datasets_flattened_async(): - client = ConversationDatasetsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_conversation_datasets), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = conversation_dataset.ListConversationDatasetsResponse() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(conversation_dataset.ListConversationDatasetsResponse()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.list_conversation_datasets( - 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] - arg = args[0].parent - mock_val = 'parent_value' - assert arg == mock_val - -@pytest.mark.asyncio -async def test_list_conversation_datasets_flattened_error_async(): - client = ConversationDatasetsAsyncClient( - 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_conversation_datasets( - conversation_dataset.ListConversationDatasetsRequest(), - parent='parent_value', - ) - - -def test_list_conversation_datasets_pager(transport_name: str = "grpc"): - client = ConversationDatasetsClient( - credentials=ga_credentials.AnonymousCredentials, - transport=transport_name, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_conversation_datasets), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - conversation_dataset.ListConversationDatasetsResponse( - conversation_datasets=[ - conversation_dataset.ConversationDataset(), - conversation_dataset.ConversationDataset(), - conversation_dataset.ConversationDataset(), - ], - next_page_token='abc', - ), - conversation_dataset.ListConversationDatasetsResponse( - conversation_datasets=[], - next_page_token='def', - ), - conversation_dataset.ListConversationDatasetsResponse( - conversation_datasets=[ - conversation_dataset.ConversationDataset(), - ], - next_page_token='ghi', - ), - conversation_dataset.ListConversationDatasetsResponse( - conversation_datasets=[ - conversation_dataset.ConversationDataset(), - conversation_dataset.ConversationDataset(), - ], - ), - RuntimeError, - ) - - metadata = () - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ('parent', ''), - )), - ) - pager = client.list_conversation_datasets(request={}) - - assert pager._metadata == metadata - - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, conversation_dataset.ConversationDataset) - for i in results) -def test_list_conversation_datasets_pages(transport_name: str = "grpc"): - client = ConversationDatasetsClient( - credentials=ga_credentials.AnonymousCredentials, - transport=transport_name, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_conversation_datasets), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - conversation_dataset.ListConversationDatasetsResponse( - conversation_datasets=[ - conversation_dataset.ConversationDataset(), - conversation_dataset.ConversationDataset(), - conversation_dataset.ConversationDataset(), - ], - next_page_token='abc', - ), - conversation_dataset.ListConversationDatasetsResponse( - conversation_datasets=[], - next_page_token='def', - ), - conversation_dataset.ListConversationDatasetsResponse( - conversation_datasets=[ - conversation_dataset.ConversationDataset(), - ], - next_page_token='ghi', - ), - conversation_dataset.ListConversationDatasetsResponse( - conversation_datasets=[ - conversation_dataset.ConversationDataset(), - conversation_dataset.ConversationDataset(), - ], - ), - RuntimeError, - ) - pages = list(client.list_conversation_datasets(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_conversation_datasets_async_pager(): - client = ConversationDatasetsAsyncClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_conversation_datasets), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - conversation_dataset.ListConversationDatasetsResponse( - conversation_datasets=[ - conversation_dataset.ConversationDataset(), - conversation_dataset.ConversationDataset(), - conversation_dataset.ConversationDataset(), - ], - next_page_token='abc', - ), - conversation_dataset.ListConversationDatasetsResponse( - conversation_datasets=[], - next_page_token='def', - ), - conversation_dataset.ListConversationDatasetsResponse( - conversation_datasets=[ - conversation_dataset.ConversationDataset(), - ], - next_page_token='ghi', - ), - conversation_dataset.ListConversationDatasetsResponse( - conversation_datasets=[ - conversation_dataset.ConversationDataset(), - conversation_dataset.ConversationDataset(), - ], - ), - RuntimeError, - ) - async_pager = await client.list_conversation_datasets(request={},) - assert async_pager.next_page_token == 'abc' - responses = [] - async for response in async_pager: # pragma: no branch - responses.append(response) - - assert len(responses) == 6 - assert all(isinstance(i, conversation_dataset.ConversationDataset) - for i in responses) - - -@pytest.mark.asyncio -async def test_list_conversation_datasets_async_pages(): - client = ConversationDatasetsAsyncClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_conversation_datasets), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - conversation_dataset.ListConversationDatasetsResponse( - conversation_datasets=[ - conversation_dataset.ConversationDataset(), - conversation_dataset.ConversationDataset(), - conversation_dataset.ConversationDataset(), - ], - next_page_token='abc', - ), - conversation_dataset.ListConversationDatasetsResponse( - conversation_datasets=[], - next_page_token='def', - ), - conversation_dataset.ListConversationDatasetsResponse( - conversation_datasets=[ - conversation_dataset.ConversationDataset(), - ], - next_page_token='ghi', - ), - conversation_dataset.ListConversationDatasetsResponse( - conversation_datasets=[ - conversation_dataset.ConversationDataset(), - conversation_dataset.ConversationDataset(), - ], - ), - RuntimeError, - ) - pages = [] - async for page_ in (await client.list_conversation_datasets(request={})).pages: # pragma: no branch - pages.append(page_) - for page_, token in zip(pages, ['abc','def','ghi', '']): - assert page_.raw_page.next_page_token == token - -@pytest.mark.parametrize("request_type", [ - conversation_dataset.DeleteConversationDatasetRequest, - dict, -]) -def test_delete_conversation_dataset(request_type, transport: str = 'grpc'): - client = ConversationDatasetsClient( - 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_conversation_dataset), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/spam') - response = client.delete_conversation_dataset(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_dataset.DeleteConversationDatasetRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -def test_delete_conversation_dataset_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = ConversationDatasetsClient( - 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_conversation_dataset), - '__call__') as call: - client.delete_conversation_dataset() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == conversation_dataset.DeleteConversationDatasetRequest() - -@pytest.mark.asyncio -async def test_delete_conversation_dataset_async(transport: str = 'grpc_asyncio', request_type=conversation_dataset.DeleteConversationDatasetRequest): - client = ConversationDatasetsAsyncClient( - 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_conversation_dataset), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name='operations/spam') - ) - response = await client.delete_conversation_dataset(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == conversation_dataset.DeleteConversationDatasetRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -@pytest.mark.asyncio -async def test_delete_conversation_dataset_async_from_dict(): - await test_delete_conversation_dataset_async(request_type=dict) - - -def test_delete_conversation_dataset_field_headers(): - client = ConversationDatasetsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value 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_dataset.DeleteConversationDatasetRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_conversation_dataset), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') - client.delete_conversation_dataset(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_conversation_dataset_field_headers_async(): - client = ConversationDatasetsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value 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_dataset.DeleteConversationDatasetRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_conversation_dataset), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) - await client.delete_conversation_dataset(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_conversation_dataset_flattened(): - client = ConversationDatasetsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_conversation_dataset), - '__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_conversation_dataset( - 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] - arg = args[0].name - mock_val = 'name_value' - assert arg == mock_val - - -def test_delete_conversation_dataset_flattened_error(): - client = ConversationDatasetsClient( - 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_conversation_dataset( - conversation_dataset.DeleteConversationDatasetRequest(), - name='name_value', - ) - -@pytest.mark.asyncio -async def test_delete_conversation_dataset_flattened_async(): - client = ConversationDatasetsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_conversation_dataset), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/op') - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name='operations/spam') - ) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.delete_conversation_dataset( - 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] - arg = args[0].name - mock_val = 'name_value' - assert arg == mock_val - -@pytest.mark.asyncio -async def test_delete_conversation_dataset_flattened_error_async(): - client = ConversationDatasetsAsyncClient( - 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_conversation_dataset( - conversation_dataset.DeleteConversationDatasetRequest(), - name='name_value', - ) - - -@pytest.mark.parametrize("request_type", [ - conversation_dataset.ImportConversationDataRequest, - dict, -]) -def test_import_conversation_data(request_type, transport: str = 'grpc'): - client = ConversationDatasetsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.import_conversation_data), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/spam') - response = client.import_conversation_data(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_dataset.ImportConversationDataRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -def test_import_conversation_data_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = ConversationDatasetsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.import_conversation_data), - '__call__') as call: - client.import_conversation_data() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == conversation_dataset.ImportConversationDataRequest() - -@pytest.mark.asyncio -async def test_import_conversation_data_async(transport: str = 'grpc_asyncio', request_type=conversation_dataset.ImportConversationDataRequest): - client = ConversationDatasetsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.import_conversation_data), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name='operations/spam') - ) - response = await client.import_conversation_data(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == conversation_dataset.ImportConversationDataRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -@pytest.mark.asyncio -async def test_import_conversation_data_async_from_dict(): - await test_import_conversation_data_async(request_type=dict) - - -def test_import_conversation_data_field_headers(): - client = ConversationDatasetsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value 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_dataset.ImportConversationDataRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.import_conversation_data), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') - client.import_conversation_data(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_import_conversation_data_field_headers_async(): - client = ConversationDatasetsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value 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_dataset.ImportConversationDataRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.import_conversation_data), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) - await client.import_conversation_data(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'] - - -@pytest.mark.parametrize("request_type", [ - gcd_conversation_dataset.CreateConversationDatasetRequest, - dict, -]) -def test_create_conversation_dataset_rest(request_type): - client = ConversationDatasetsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1/locations/sample2'} - request_init["conversation_dataset"] = {'name': 'name_value', 'display_name': 'display_name_value', 'description': 'description_value', 'create_time': {'seconds': 751, 'nanos': 543}, 'input_config': {'gcs_source': {'uris': ['uris_value1', 'uris_value2']}}, 'conversation_info': {'language_code': 'language_code_value'}, 'conversation_count': 1955} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name='operations/spam') - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.create_conversation_dataset(request) - - # Establish that the response is the type that we expect. - assert response.operation.name == "operations/spam" - - -def test_create_conversation_dataset_rest_required_fields(request_type=gcd_conversation_dataset.CreateConversationDatasetRequest): - transport_class = transports.ConversationDatasetsRestTransport - - request_init = {} - request_init["parent"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - including_default_value_fields=False, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_conversation_dataset._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["parent"] = 'parent_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_conversation_dataset._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "parent" in jsonified_request - assert jsonified_request["parent"] == 'parent_value' - - client = ConversationDatasetsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name='operations/spam') - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "post", - 'query_params': pb_request, - } - transcode_result['body'] = pb_request - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.create_conversation_dataset(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_create_conversation_dataset_rest_unset_required_fields(): - transport = transports.ConversationDatasetsRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.create_conversation_dataset._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("parent", "conversationDataset", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_create_conversation_dataset_rest_interceptors(null_interceptor): - transport = transports.ConversationDatasetsRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.ConversationDatasetsRestInterceptor(), - ) - client = ConversationDatasetsClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(operation.Operation, "_set_result_from_operation"), \ - mock.patch.object(transports.ConversationDatasetsRestInterceptor, "post_create_conversation_dataset") as post, \ - mock.patch.object(transports.ConversationDatasetsRestInterceptor, "pre_create_conversation_dataset") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = gcd_conversation_dataset.CreateConversationDatasetRequest.pb(gcd_conversation_dataset.CreateConversationDatasetRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = json_format.MessageToJson(operations_pb2.Operation()) - - request = gcd_conversation_dataset.CreateConversationDatasetRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = operations_pb2.Operation() - - client.create_conversation_dataset(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_create_conversation_dataset_rest_bad_request(transport: str = 'rest', request_type=gcd_conversation_dataset.CreateConversationDatasetRequest): - client = ConversationDatasetsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1/locations/sample2'} - request_init["conversation_dataset"] = {'name': 'name_value', 'display_name': 'display_name_value', 'description': 'description_value', 'create_time': {'seconds': 751, 'nanos': 543}, 'input_config': {'gcs_source': {'uris': ['uris_value1', 'uris_value2']}}, 'conversation_info': {'language_code': 'language_code_value'}, 'conversation_count': 1955} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.create_conversation_dataset(request) - - -def test_create_conversation_dataset_rest_flattened(): - client = ConversationDatasetsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name='operations/spam') - - # get arguments that satisfy an http rule for this method - sample_request = {'parent': 'projects/sample1/locations/sample2'} - - # get truthy value for each flattened field - mock_args = dict( - parent='parent_value', - conversation_dataset=gcd_conversation_dataset.ConversationDataset(name='name_value'), - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.create_conversation_dataset(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v2/{parent=projects/*/locations/*}/conversationDatasets" % client.transport._host, args[1]) - - -def test_create_conversation_dataset_rest_flattened_error(transport: str = 'rest'): - client = ConversationDatasetsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.create_conversation_dataset( - gcd_conversation_dataset.CreateConversationDatasetRequest(), - parent='parent_value', - conversation_dataset=gcd_conversation_dataset.ConversationDataset(name='name_value'), - ) - - -def test_create_conversation_dataset_rest_error(): - client = ConversationDatasetsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - conversation_dataset.GetConversationDatasetRequest, - dict, -]) -def test_get_conversation_dataset_rest(request_type): - client = ConversationDatasetsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/conversationDatasets/sample2'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = conversation_dataset.ConversationDataset( - name='name_value', - display_name='display_name_value', - description='description_value', - conversation_count=1955, - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - pb_return_value = conversation_dataset.ConversationDataset.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.get_conversation_dataset(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, conversation_dataset.ConversationDataset) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.description == 'description_value' - assert response.conversation_count == 1955 - - -def test_get_conversation_dataset_rest_required_fields(request_type=conversation_dataset.GetConversationDatasetRequest): - transport_class = transports.ConversationDatasetsRestTransport - - request_init = {} - request_init["name"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - including_default_value_fields=False, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_conversation_dataset._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["name"] = 'name_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_conversation_dataset._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "name" in jsonified_request - assert jsonified_request["name"] == 'name_value' - - client = ConversationDatasetsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = conversation_dataset.ConversationDataset() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "get", - 'query_params': pb_request, - } - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - - pb_return_value = conversation_dataset.ConversationDataset.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.get_conversation_dataset(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_get_conversation_dataset_rest_unset_required_fields(): - transport = transports.ConversationDatasetsRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.get_conversation_dataset._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_get_conversation_dataset_rest_interceptors(null_interceptor): - transport = transports.ConversationDatasetsRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.ConversationDatasetsRestInterceptor(), - ) - client = ConversationDatasetsClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.ConversationDatasetsRestInterceptor, "post_get_conversation_dataset") as post, \ - mock.patch.object(transports.ConversationDatasetsRestInterceptor, "pre_get_conversation_dataset") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = conversation_dataset.GetConversationDatasetRequest.pb(conversation_dataset.GetConversationDatasetRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = conversation_dataset.ConversationDataset.to_json(conversation_dataset.ConversationDataset()) - - request = conversation_dataset.GetConversationDatasetRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = conversation_dataset.ConversationDataset() - - client.get_conversation_dataset(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_get_conversation_dataset_rest_bad_request(transport: str = 'rest', request_type=conversation_dataset.GetConversationDatasetRequest): - client = ConversationDatasetsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/conversationDatasets/sample2'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.get_conversation_dataset(request) - - -def test_get_conversation_dataset_rest_flattened(): - client = ConversationDatasetsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = conversation_dataset.ConversationDataset() - - # get arguments that satisfy an http rule for this method - sample_request = {'name': 'projects/sample1/conversationDatasets/sample2'} - - # get truthy value for each flattened field - mock_args = dict( - name='name_value', - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - pb_return_value = conversation_dataset.ConversationDataset.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.get_conversation_dataset(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v2/{name=projects/*/conversationDatasets/*}" % client.transport._host, args[1]) - - -def test_get_conversation_dataset_rest_flattened_error(transport: str = 'rest'): - client = ConversationDatasetsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.get_conversation_dataset( - conversation_dataset.GetConversationDatasetRequest(), - name='name_value', - ) - - -def test_get_conversation_dataset_rest_error(): - client = ConversationDatasetsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - conversation_dataset.ListConversationDatasetsRequest, - dict, -]) -def test_list_conversation_datasets_rest(request_type): - client = ConversationDatasetsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = conversation_dataset.ListConversationDatasetsResponse( - next_page_token='next_page_token_value', - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - pb_return_value = conversation_dataset.ListConversationDatasetsResponse.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.list_conversation_datasets(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListConversationDatasetsPager) - assert response.next_page_token == 'next_page_token_value' - - -def test_list_conversation_datasets_rest_required_fields(request_type=conversation_dataset.ListConversationDatasetsRequest): - transport_class = transports.ConversationDatasetsRestTransport - - request_init = {} - request_init["parent"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - including_default_value_fields=False, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).list_conversation_datasets._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["parent"] = 'parent_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).list_conversation_datasets._get_unset_required_fields(jsonified_request) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("page_size", "page_token", )) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "parent" in jsonified_request - assert jsonified_request["parent"] == 'parent_value' - - client = ConversationDatasetsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = conversation_dataset.ListConversationDatasetsResponse() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "get", - 'query_params': pb_request, - } - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - - pb_return_value = conversation_dataset.ListConversationDatasetsResponse.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.list_conversation_datasets(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_list_conversation_datasets_rest_unset_required_fields(): - transport = transports.ConversationDatasetsRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.list_conversation_datasets._get_unset_required_fields({}) - assert set(unset_fields) == (set(("pageSize", "pageToken", )) & set(("parent", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_list_conversation_datasets_rest_interceptors(null_interceptor): - transport = transports.ConversationDatasetsRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.ConversationDatasetsRestInterceptor(), - ) - client = ConversationDatasetsClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.ConversationDatasetsRestInterceptor, "post_list_conversation_datasets") as post, \ - mock.patch.object(transports.ConversationDatasetsRestInterceptor, "pre_list_conversation_datasets") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = conversation_dataset.ListConversationDatasetsRequest.pb(conversation_dataset.ListConversationDatasetsRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = conversation_dataset.ListConversationDatasetsResponse.to_json(conversation_dataset.ListConversationDatasetsResponse()) - - request = conversation_dataset.ListConversationDatasetsRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = conversation_dataset.ListConversationDatasetsResponse() - - client.list_conversation_datasets(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_list_conversation_datasets_rest_bad_request(transport: str = 'rest', request_type=conversation_dataset.ListConversationDatasetsRequest): - client = ConversationDatasetsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.list_conversation_datasets(request) - - -def test_list_conversation_datasets_rest_flattened(): - client = ConversationDatasetsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = conversation_dataset.ListConversationDatasetsResponse() - - # get arguments that satisfy an http rule for this method - sample_request = {'parent': 'projects/sample1'} - - # get truthy value for each flattened field - mock_args = dict( - parent='parent_value', - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - pb_return_value = conversation_dataset.ListConversationDatasetsResponse.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.list_conversation_datasets(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v2/{parent=projects/*}/conversationDatasets" % client.transport._host, args[1]) - - -def test_list_conversation_datasets_rest_flattened_error(transport: str = 'rest'): - client = ConversationDatasetsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.list_conversation_datasets( - conversation_dataset.ListConversationDatasetsRequest(), - parent='parent_value', - ) - - -def test_list_conversation_datasets_rest_pager(transport: str = 'rest'): - client = ConversationDatasetsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # TODO(kbandes): remove this mock unless there's a good reason for it. - #with mock.patch.object(path_template, 'transcode') as transcode: - # Set the response as a series of pages - response = ( - conversation_dataset.ListConversationDatasetsResponse( - conversation_datasets=[ - conversation_dataset.ConversationDataset(), - conversation_dataset.ConversationDataset(), - conversation_dataset.ConversationDataset(), - ], - next_page_token='abc', - ), - conversation_dataset.ListConversationDatasetsResponse( - conversation_datasets=[], - next_page_token='def', - ), - conversation_dataset.ListConversationDatasetsResponse( - conversation_datasets=[ - conversation_dataset.ConversationDataset(), - ], - next_page_token='ghi', - ), - conversation_dataset.ListConversationDatasetsResponse( - conversation_datasets=[ - conversation_dataset.ConversationDataset(), - conversation_dataset.ConversationDataset(), - ], - ), - ) - # Two responses for two calls - response = response + response - - # Wrap the values into proper Response objs - response = tuple(conversation_dataset.ListConversationDatasetsResponse.to_json(x) for x in response) - return_values = tuple(Response() for i in response) - for return_val, response_val in zip(return_values, response): - return_val._content = response_val.encode('UTF-8') - return_val.status_code = 200 - req.side_effect = return_values - - sample_request = {'parent': 'projects/sample1'} - - pager = client.list_conversation_datasets(request=sample_request) - - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, conversation_dataset.ConversationDataset) - for i in results) - - pages = list(client.list_conversation_datasets(request=sample_request).pages) - for page_, token in zip(pages, ['abc','def','ghi', '']): - assert page_.raw_page.next_page_token == token - - -@pytest.mark.parametrize("request_type", [ - conversation_dataset.DeleteConversationDatasetRequest, - dict, -]) -def test_delete_conversation_dataset_rest(request_type): - client = ConversationDatasetsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/locations/sample2/conversationDatasets/sample3'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name='operations/spam') - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.delete_conversation_dataset(request) - - # Establish that the response is the type that we expect. - assert response.operation.name == "operations/spam" - - -def test_delete_conversation_dataset_rest_required_fields(request_type=conversation_dataset.DeleteConversationDatasetRequest): - transport_class = transports.ConversationDatasetsRestTransport - - request_init = {} - request_init["name"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - including_default_value_fields=False, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).delete_conversation_dataset._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["name"] = 'name_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).delete_conversation_dataset._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "name" in jsonified_request - assert jsonified_request["name"] == 'name_value' - - client = ConversationDatasetsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name='operations/spam') - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "delete", - 'query_params': pb_request, - } - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.delete_conversation_dataset(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_delete_conversation_dataset_rest_unset_required_fields(): - transport = transports.ConversationDatasetsRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.delete_conversation_dataset._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_delete_conversation_dataset_rest_interceptors(null_interceptor): - transport = transports.ConversationDatasetsRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.ConversationDatasetsRestInterceptor(), - ) - client = ConversationDatasetsClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(operation.Operation, "_set_result_from_operation"), \ - mock.patch.object(transports.ConversationDatasetsRestInterceptor, "post_delete_conversation_dataset") as post, \ - mock.patch.object(transports.ConversationDatasetsRestInterceptor, "pre_delete_conversation_dataset") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = conversation_dataset.DeleteConversationDatasetRequest.pb(conversation_dataset.DeleteConversationDatasetRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = json_format.MessageToJson(operations_pb2.Operation()) - - request = conversation_dataset.DeleteConversationDatasetRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = operations_pb2.Operation() - - client.delete_conversation_dataset(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_delete_conversation_dataset_rest_bad_request(transport: str = 'rest', request_type=conversation_dataset.DeleteConversationDatasetRequest): - client = ConversationDatasetsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/locations/sample2/conversationDatasets/sample3'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.delete_conversation_dataset(request) - - -def test_delete_conversation_dataset_rest_flattened(): - client = ConversationDatasetsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name='operations/spam') - - # get arguments that satisfy an http rule for this method - sample_request = {'name': 'projects/sample1/locations/sample2/conversationDatasets/sample3'} - - # get truthy value for each flattened field - mock_args = dict( - name='name_value', - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.delete_conversation_dataset(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v2/{name=projects/*/locations/*/conversationDatasets/*}" % client.transport._host, args[1]) - - -def test_delete_conversation_dataset_rest_flattened_error(transport: str = 'rest'): - client = ConversationDatasetsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.delete_conversation_dataset( - conversation_dataset.DeleteConversationDatasetRequest(), - name='name_value', - ) - - -def test_delete_conversation_dataset_rest_error(): - client = ConversationDatasetsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - conversation_dataset.ImportConversationDataRequest, - dict, -]) -def test_import_conversation_data_rest(request_type): - client = ConversationDatasetsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/conversationDatasets/sample2'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name='operations/spam') - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.import_conversation_data(request) - - # Establish that the response is the type that we expect. - assert response.operation.name == "operations/spam" - - -def test_import_conversation_data_rest_required_fields(request_type=conversation_dataset.ImportConversationDataRequest): - transport_class = transports.ConversationDatasetsRestTransport - - request_init = {} - request_init["name"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - including_default_value_fields=False, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).import_conversation_data._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["name"] = 'name_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).import_conversation_data._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "name" in jsonified_request - assert jsonified_request["name"] == 'name_value' - - client = ConversationDatasetsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name='operations/spam') - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "post", - 'query_params': pb_request, - } - transcode_result['body'] = pb_request - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.import_conversation_data(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_import_conversation_data_rest_unset_required_fields(): - transport = transports.ConversationDatasetsRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.import_conversation_data._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name", "inputConfig", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_import_conversation_data_rest_interceptors(null_interceptor): - transport = transports.ConversationDatasetsRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.ConversationDatasetsRestInterceptor(), - ) - client = ConversationDatasetsClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(operation.Operation, "_set_result_from_operation"), \ - mock.patch.object(transports.ConversationDatasetsRestInterceptor, "post_import_conversation_data") as post, \ - mock.patch.object(transports.ConversationDatasetsRestInterceptor, "pre_import_conversation_data") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = conversation_dataset.ImportConversationDataRequest.pb(conversation_dataset.ImportConversationDataRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = json_format.MessageToJson(operations_pb2.Operation()) - - request = conversation_dataset.ImportConversationDataRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = operations_pb2.Operation() - - client.import_conversation_data(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_import_conversation_data_rest_bad_request(transport: str = 'rest', request_type=conversation_dataset.ImportConversationDataRequest): - client = ConversationDatasetsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/conversationDatasets/sample2'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.import_conversation_data(request) - - -def test_import_conversation_data_rest_error(): - client = ConversationDatasetsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -def test_credentials_transport_error(): - # It is an error to provide credentials and a transport instance. - transport = transports.ConversationDatasetsGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = ConversationDatasetsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # It is an error to provide a credentials file and a transport instance. - transport = transports.ConversationDatasetsGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = ConversationDatasetsClient( - client_options={"credentials_file": "credentials.json"}, - transport=transport, - ) - - # It is an error to provide an api_key and a transport instance. - transport = transports.ConversationDatasetsGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - options = client_options.ClientOptions() - options.api_key = "api_key" - with pytest.raises(ValueError): - client = ConversationDatasetsClient( - client_options=options, - transport=transport, - ) - - # It is an error to provide an api_key and a credential. - options = mock.Mock() - options.api_key = "api_key" - with pytest.raises(ValueError): - client = ConversationDatasetsClient( - client_options=options, - credentials=ga_credentials.AnonymousCredentials() - ) - - # It is an error to provide scopes and a transport instance. - transport = transports.ConversationDatasetsGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = ConversationDatasetsClient( - client_options={"scopes": ["1", "2"]}, - transport=transport, - ) - - -def test_transport_instance(): - # A client may be instantiated with a custom transport instance. - transport = transports.ConversationDatasetsGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - client = ConversationDatasetsClient(transport=transport) - assert client.transport is transport - -def test_transport_get_channel(): - # A client may be instantiated with a custom transport instance. - transport = transports.ConversationDatasetsGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - - transport = transports.ConversationDatasetsGrpcAsyncIOTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - -@pytest.mark.parametrize("transport_class", [ - transports.ConversationDatasetsGrpcTransport, - transports.ConversationDatasetsGrpcAsyncIOTransport, - transports.ConversationDatasetsRestTransport, -]) -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() - -@pytest.mark.parametrize("transport_name", [ - "grpc", - "rest", -]) -def test_transport_kind(transport_name): - transport = ConversationDatasetsClient.get_transport_class(transport_name)( - credentials=ga_credentials.AnonymousCredentials(), - ) - assert transport.kind == transport_name - -def test_transport_grpc_default(): - # A client should use the gRPC transport by default. - client = ConversationDatasetsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - assert isinstance( - client.transport, - transports.ConversationDatasetsGrpcTransport, - ) - -def test_conversation_datasets_base_transport_error(): - # Passing both a credentials object and credentials_file should raise an error - with pytest.raises(core_exceptions.DuplicateCredentialArgs): - transport = transports.ConversationDatasetsTransport( - credentials=ga_credentials.AnonymousCredentials(), - credentials_file="credentials.json" - ) - - -def test_conversation_datasets_base_transport(): - # Instantiate the base transport. - with mock.patch('google.cloud.dialogflow_v2.services.conversation_datasets.transports.ConversationDatasetsTransport.__init__') as Transport: - Transport.return_value = None - transport = transports.ConversationDatasetsTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Every method on the transport should just blindly - # raise NotImplementedError. - methods = ( - 'create_conversation_dataset', - 'get_conversation_dataset', - 'list_conversation_datasets', - 'delete_conversation_dataset', - 'import_conversation_data', - 'get_location', - 'list_locations', - 'get_operation', - 'cancel_operation', - 'list_operations', - ) - for method in methods: - with pytest.raises(NotImplementedError): - getattr(transport, method)(request=object()) - - with pytest.raises(NotImplementedError): - transport.close() - - # Additionally, the LRO client (a property) should - # also raise NotImplementedError - with pytest.raises(NotImplementedError): - transport.operations_client - - # Catch all for all remaining methods and properties - remainder = [ - 'kind', - ] - for r in remainder: - with pytest.raises(NotImplementedError): - getattr(transport, r)() - - -def test_conversation_datasets_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.conversation_datasets.transports.ConversationDatasetsTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.ConversationDatasetsTransport( - credentials_file="credentials.json", - quota_project_id="octopus", - ) - load_creds.assert_called_once_with("credentials.json", - scopes=None, - default_scopes=( - 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/dialogflow', -), - quota_project_id="octopus", - ) - - -def test_conversation_datasets_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.conversation_datasets.transports.ConversationDatasetsTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.ConversationDatasetsTransport() - adc.assert_called_once() - - -def test_conversation_datasets_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) - ConversationDatasetsClient() - adc.assert_called_once_with( - scopes=None, - default_scopes=( - 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/dialogflow', -), - quota_project_id=None, - ) - - -@pytest.mark.parametrize( - "transport_class", - [ - transports.ConversationDatasetsGrpcTransport, - transports.ConversationDatasetsGrpcAsyncIOTransport, - ], -) -def test_conversation_datasets_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.ConversationDatasetsGrpcTransport, - transports.ConversationDatasetsGrpcAsyncIOTransport, - transports.ConversationDatasetsRestTransport, - ], -) -def test_conversation_datasets_transport_auth_gdch_credentials(transport_class): - host = 'https://language.com' - api_audience_tests = [None, 'https://language2.com'] - api_audience_expect = [host, 'https://language2.com'] - for t, e in zip(api_audience_tests, api_audience_expect): - with mock.patch.object(google.auth, 'default', autospec=True) as adc: - gdch_mock = mock.MagicMock() - type(gdch_mock).with_gdch_audience = mock.PropertyMock(return_value=gdch_mock) - adc.return_value = (gdch_mock, None) - transport_class(host=host, api_audience=t) - gdch_mock.with_gdch_audience.assert_called_once_with( - e - ) - - -@pytest.mark.parametrize( - "transport_class,grpc_helpers", - [ - (transports.ConversationDatasetsGrpcTransport, grpc_helpers), - (transports.ConversationDatasetsGrpcAsyncIOTransport, grpc_helpers_async) - ], -) -def test_conversation_datasets_transport_create_channel(transport_class, grpc_helpers): - # If credentials and host are not provided, the transport class should use - # ADC credentials. - with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch.object( - grpc_helpers, "create_channel", autospec=True - ) as create_channel: - creds = ga_credentials.AnonymousCredentials() - adc.return_value = (creds, None) - transport_class( - quota_project_id="octopus", - scopes=["1", "2"] - ) - - create_channel.assert_called_with( - "dialogflow.googleapis.com:443", - credentials=creds, - credentials_file=None, - quota_project_id="octopus", - default_scopes=( - 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/dialogflow', -), - scopes=["1", "2"], - default_host="dialogflow.googleapis.com", - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - -@pytest.mark.parametrize("transport_class", [transports.ConversationDatasetsGrpcTransport, transports.ConversationDatasetsGrpcAsyncIOTransport]) -def test_conversation_datasets_grpc_transport_client_cert_source_for_mtls( - transport_class -): - cred = ga_credentials.AnonymousCredentials() - - # Check ssl_channel_credentials is used if provided. - with mock.patch.object(transport_class, "create_channel") as mock_create_channel: - mock_ssl_channel_creds = mock.Mock() - transport_class( - host="squid.clam.whelk", - credentials=cred, - ssl_channel_credentials=mock_ssl_channel_creds - ) - mock_create_channel.assert_called_once_with( - "squid.clam.whelk:443", - credentials=cred, - credentials_file=None, - scopes=None, - ssl_credentials=mock_ssl_channel_creds, - quota_project_id=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - # Check if ssl_channel_credentials is not provided, then client_cert_source_for_mtls - # is used. - with mock.patch.object(transport_class, "create_channel", return_value=mock.Mock()): - with mock.patch("grpc.ssl_channel_credentials") as mock_ssl_cred: - transport_class( - credentials=cred, - client_cert_source_for_mtls=client_cert_source_callback - ) - expected_cert, expected_key = client_cert_source_callback() - mock_ssl_cred.assert_called_once_with( - certificate_chain=expected_cert, - private_key=expected_key - ) - -def test_conversation_datasets_http_transport_client_cert_source_for_mtls(): - cred = ga_credentials.AnonymousCredentials() - with mock.patch("google.auth.transport.requests.AuthorizedSession.configure_mtls_channel") as mock_configure_mtls_channel: - transports.ConversationDatasetsRestTransport ( - credentials=cred, - client_cert_source_for_mtls=client_cert_source_callback - ) - mock_configure_mtls_channel.assert_called_once_with(client_cert_source_callback) - - -def test_conversation_datasets_rest_lro_client(): - client = ConversationDatasetsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - transport = client.transport - - # Ensure that we have a api-core operations client. - assert isinstance( - transport.operations_client, - operations_v1.AbstractOperationsClient, - ) - - # Ensure that subsequent calls to the property send the exact same object. - assert transport.operations_client is transport.operations_client - - -@pytest.mark.parametrize("transport_name", [ - "grpc", - "grpc_asyncio", - "rest", -]) -def test_conversation_datasets_host_no_port(transport_name): - client = ConversationDatasetsClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='dialogflow.googleapis.com'), - transport=transport_name, - ) - assert client.transport._host == ( - 'dialogflow.googleapis.com:443' - if transport_name in ['grpc', 'grpc_asyncio'] - else 'https://dialogflow.googleapis.com' - ) - -@pytest.mark.parametrize("transport_name", [ - "grpc", - "grpc_asyncio", - "rest", -]) -def test_conversation_datasets_host_with_port(transport_name): - client = ConversationDatasetsClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='dialogflow.googleapis.com:8000'), - transport=transport_name, - ) - assert client.transport._host == ( - 'dialogflow.googleapis.com:8000' - if transport_name in ['grpc', 'grpc_asyncio'] - else 'https://dialogflow.googleapis.com:8000' - ) - -@pytest.mark.parametrize("transport_name", [ - "rest", -]) -def test_conversation_datasets_client_transport_session_collision(transport_name): - creds1 = ga_credentials.AnonymousCredentials() - creds2 = ga_credentials.AnonymousCredentials() - client1 = ConversationDatasetsClient( - credentials=creds1, - transport=transport_name, - ) - client2 = ConversationDatasetsClient( - credentials=creds2, - transport=transport_name, - ) - session1 = client1.transport.create_conversation_dataset._session - session2 = client2.transport.create_conversation_dataset._session - assert session1 != session2 - session1 = client1.transport.get_conversation_dataset._session - session2 = client2.transport.get_conversation_dataset._session - assert session1 != session2 - session1 = client1.transport.list_conversation_datasets._session - session2 = client2.transport.list_conversation_datasets._session - assert session1 != session2 - session1 = client1.transport.delete_conversation_dataset._session - session2 = client2.transport.delete_conversation_dataset._session - assert session1 != session2 - session1 = client1.transport.import_conversation_data._session - session2 = client2.transport.import_conversation_data._session - assert session1 != session2 -def test_conversation_datasets_grpc_transport_channel(): - channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.ConversationDatasetsGrpcTransport( - 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_conversation_datasets_grpc_asyncio_transport_channel(): - channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.ConversationDatasetsGrpcAsyncIOTransport( - 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.ConversationDatasetsGrpcTransport, transports.ConversationDatasetsGrpcAsyncIOTransport]) -def test_conversation_datasets_transport_channel_mtls_with_client_cert_source( - transport_class -): - with mock.patch("grpc.ssl_channel_credentials", autospec=True) as grpc_ssl_channel_cred: - with mock.patch.object(transport_class, "create_channel") as grpc_create_channel: - mock_ssl_cred = mock.Mock() - grpc_ssl_channel_cred.return_value = mock_ssl_cred - - mock_grpc_channel = mock.Mock() - grpc_create_channel.return_value = mock_grpc_channel - - cred = ga_credentials.AnonymousCredentials() - with pytest.warns(DeprecationWarning): - with mock.patch.object(google.auth, 'default') as adc: - adc.return_value = (cred, None) - transport = transport_class( - host="squid.clam.whelk", - api_mtls_endpoint="mtls.squid.clam.whelk", - client_cert_source=client_cert_source_callback, - ) - adc.assert_called_once() - - grpc_ssl_channel_cred.assert_called_once_with( - certificate_chain=b"cert bytes", private_key=b"key bytes" - ) - grpc_create_channel.assert_called_once_with( - "mtls.squid.clam.whelk:443", - credentials=cred, - credentials_file=None, - scopes=None, - ssl_credentials=mock_ssl_cred, - quota_project_id=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - assert transport.grpc_channel == mock_grpc_channel - assert transport._ssl_channel_credentials == mock_ssl_cred - - -# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are -# removed from grpc/grpc_asyncio transport constructor. -@pytest.mark.parametrize("transport_class", [transports.ConversationDatasetsGrpcTransport, transports.ConversationDatasetsGrpcAsyncIOTransport]) -def test_conversation_datasets_transport_channel_mtls_with_adc( - transport_class -): - mock_ssl_cred = mock.Mock() - with mock.patch.multiple( - "google.auth.transport.grpc.SslCredentials", - __init__=mock.Mock(return_value=None), - ssl_credentials=mock.PropertyMock(return_value=mock_ssl_cred), - ): - with mock.patch.object(transport_class, "create_channel") as grpc_create_channel: - mock_grpc_channel = mock.Mock() - grpc_create_channel.return_value = mock_grpc_channel - mock_cred = mock.Mock() - - with pytest.warns(DeprecationWarning): - transport = transport_class( - host="squid.clam.whelk", - credentials=mock_cred, - api_mtls_endpoint="mtls.squid.clam.whelk", - client_cert_source=None, - ) - - grpc_create_channel.assert_called_once_with( - "mtls.squid.clam.whelk:443", - credentials=mock_cred, - credentials_file=None, - scopes=None, - ssl_credentials=mock_ssl_cred, - quota_project_id=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - assert transport.grpc_channel == mock_grpc_channel - - -def test_conversation_datasets_grpc_lro_client(): - client = ConversationDatasetsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - transport = client.transport - - # Ensure that we have a api-core operations client. - assert isinstance( - transport.operations_client, - operations_v1.OperationsClient, - ) - - # Ensure that subsequent calls to the property send the exact same object. - assert transport.operations_client is transport.operations_client - - -def test_conversation_datasets_grpc_lro_async_client(): - client = ConversationDatasetsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc_asyncio', - ) - transport = client.transport - - # Ensure that we have a api-core operations client. - assert isinstance( - transport.operations_client, - operations_v1.OperationsAsyncClient, - ) - - # Ensure that subsequent calls to the property send the exact same object. - assert transport.operations_client is transport.operations_client - - -def test_conversation_dataset_path(): - project = "squid" - location = "clam" - conversation_dataset = "whelk" - expected = "projects/{project}/locations/{location}/conversationDatasets/{conversation_dataset}".format(project=project, location=location, conversation_dataset=conversation_dataset, ) - actual = ConversationDatasetsClient.conversation_dataset_path(project, location, conversation_dataset) - assert expected == actual - - -def test_parse_conversation_dataset_path(): - expected = { - "project": "octopus", - "location": "oyster", - "conversation_dataset": "nudibranch", - } - path = ConversationDatasetsClient.conversation_dataset_path(**expected) - - # Check that the path construction is reversible. - actual = ConversationDatasetsClient.parse_conversation_dataset_path(path) - assert expected == actual - -def test_common_billing_account_path(): - billing_account = "cuttlefish" - expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) - actual = ConversationDatasetsClient.common_billing_account_path(billing_account) - assert expected == actual - - -def test_parse_common_billing_account_path(): - expected = { - "billing_account": "mussel", - } - path = ConversationDatasetsClient.common_billing_account_path(**expected) - - # Check that the path construction is reversible. - actual = ConversationDatasetsClient.parse_common_billing_account_path(path) - assert expected == actual - -def test_common_folder_path(): - folder = "winkle" - expected = "folders/{folder}".format(folder=folder, ) - actual = ConversationDatasetsClient.common_folder_path(folder) - assert expected == actual - - -def test_parse_common_folder_path(): - expected = { - "folder": "nautilus", - } - path = ConversationDatasetsClient.common_folder_path(**expected) - - # Check that the path construction is reversible. - actual = ConversationDatasetsClient.parse_common_folder_path(path) - assert expected == actual - -def test_common_organization_path(): - organization = "scallop" - expected = "organizations/{organization}".format(organization=organization, ) - actual = ConversationDatasetsClient.common_organization_path(organization) - assert expected == actual - - -def test_parse_common_organization_path(): - expected = { - "organization": "abalone", - } - path = ConversationDatasetsClient.common_organization_path(**expected) - - # Check that the path construction is reversible. - actual = ConversationDatasetsClient.parse_common_organization_path(path) - assert expected == actual - -def test_common_project_path(): - project = "squid" - expected = "projects/{project}".format(project=project, ) - actual = ConversationDatasetsClient.common_project_path(project) - assert expected == actual - - -def test_parse_common_project_path(): - expected = { - "project": "clam", - } - path = ConversationDatasetsClient.common_project_path(**expected) - - # Check that the path construction is reversible. - actual = ConversationDatasetsClient.parse_common_project_path(path) - assert expected == actual - -def test_common_location_path(): - project = "whelk" - location = "octopus" - expected = "projects/{project}/locations/{location}".format(project=project, location=location, ) - actual = ConversationDatasetsClient.common_location_path(project, location) - assert expected == actual - - -def test_parse_common_location_path(): - expected = { - "project": "oyster", - "location": "nudibranch", - } - path = ConversationDatasetsClient.common_location_path(**expected) - - # Check that the path construction is reversible. - actual = ConversationDatasetsClient.parse_common_location_path(path) - assert expected == actual - - -def test_client_with_default_client_info(): - client_info = gapic_v1.client_info.ClientInfo() - - with mock.patch.object(transports.ConversationDatasetsTransport, '_prep_wrapped_messages') as prep: - client = ConversationDatasetsClient( - credentials=ga_credentials.AnonymousCredentials(), - client_info=client_info, - ) - prep.assert_called_once_with(client_info) - - with mock.patch.object(transports.ConversationDatasetsTransport, '_prep_wrapped_messages') as prep: - transport_class = ConversationDatasetsClient.get_transport_class() - transport = transport_class( - credentials=ga_credentials.AnonymousCredentials(), - client_info=client_info, - ) - prep.assert_called_once_with(client_info) - -@pytest.mark.asyncio -async def test_transport_close_async(): - client = ConversationDatasetsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - with mock.patch.object(type(getattr(client.transport, "grpc_channel")), "close") as close: - async with client: - close.assert_not_called() - close.assert_called_once() - - -def test_get_location_rest_bad_request(transport: str = 'rest', request_type=locations_pb2.GetLocationRequest): - client = ConversationDatasetsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - request = request_type() - request = json_format.ParseDict({'name': 'projects/sample1/locations/sample2'}, request) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.get_location(request) - -@pytest.mark.parametrize("request_type", [ - locations_pb2.GetLocationRequest, - dict, -]) -def test_get_location_rest(request_type): - client = ConversationDatasetsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request_init = {'name': 'projects/sample1/locations/sample2'} - request = request_type(**request_init) - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = locations_pb2.Location() - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.get_location(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, locations_pb2.Location) - -def test_list_locations_rest_bad_request(transport: str = 'rest', request_type=locations_pb2.ListLocationsRequest): - client = ConversationDatasetsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - request = request_type() - request = json_format.ParseDict({'name': 'projects/sample1'}, request) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.list_locations(request) - -@pytest.mark.parametrize("request_type", [ - locations_pb2.ListLocationsRequest, - dict, -]) -def test_list_locations_rest(request_type): - client = ConversationDatasetsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request_init = {'name': 'projects/sample1'} - request = request_type(**request_init) - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = locations_pb2.ListLocationsResponse() - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.list_locations(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, locations_pb2.ListLocationsResponse) - -def test_cancel_operation_rest_bad_request(transport: str = 'rest', request_type=operations_pb2.CancelOperationRequest): - client = ConversationDatasetsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - request = request_type() - request = json_format.ParseDict({'name': 'projects/sample1/operations/sample2'}, request) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.cancel_operation(request) - -@pytest.mark.parametrize("request_type", [ - operations_pb2.CancelOperationRequest, - dict, -]) -def test_cancel_operation_rest(request_type): - client = ConversationDatasetsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request_init = {'name': 'projects/sample1/operations/sample2'} - request = request_type(**request_init) - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = None - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = '{}' - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.cancel_operation(request) - - # Establish that the response is the type that we expect. - assert response is None - -def test_get_operation_rest_bad_request(transport: str = 'rest', request_type=operations_pb2.GetOperationRequest): - client = ConversationDatasetsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - request = request_type() - request = json_format.ParseDict({'name': 'projects/sample1/operations/sample2'}, request) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.get_operation(request) - -@pytest.mark.parametrize("request_type", [ - operations_pb2.GetOperationRequest, - dict, -]) -def test_get_operation_rest(request_type): - client = ConversationDatasetsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request_init = {'name': 'projects/sample1/operations/sample2'} - request = request_type(**request_init) - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation() - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.get_operation(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, operations_pb2.Operation) - -def test_list_operations_rest_bad_request(transport: str = 'rest', request_type=operations_pb2.ListOperationsRequest): - client = ConversationDatasetsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - request = request_type() - request = json_format.ParseDict({'name': 'projects/sample1'}, request) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.list_operations(request) - -@pytest.mark.parametrize("request_type", [ - operations_pb2.ListOperationsRequest, - dict, -]) -def test_list_operations_rest(request_type): - client = ConversationDatasetsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request_init = {'name': 'projects/sample1'} - request = request_type(**request_init) - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = operations_pb2.ListOperationsResponse() - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.list_operations(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, operations_pb2.ListOperationsResponse) - - -def test_cancel_operation(transport: str = "grpc"): - client = ConversationDatasetsClient( - 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 = operations_pb2.CancelOperationRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = None - response = client.cancel_operation(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 response is the type that we expect. - assert response is None -@pytest.mark.asyncio -async def test_cancel_operation_async(transport: str = "grpc"): - client = ConversationDatasetsAsyncClient( - 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 = operations_pb2.CancelOperationRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - None - ) - response = await client.cancel_operation(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 response is the type that we expect. - assert response is None - -def test_cancel_operation_field_headers(): - client = ConversationDatasetsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = operations_pb2.CancelOperationRequest() - request.name = "locations" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call: - call.return_value = None - - client.cancel_operation(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=locations",) in kw["metadata"] -@pytest.mark.asyncio -async def test_cancel_operation_field_headers_async(): - client = ConversationDatasetsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = operations_pb2.CancelOperationRequest() - request.name = "locations" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - None - ) - await client.cancel_operation(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=locations",) in kw["metadata"] - -def test_cancel_operation_from_dict(): - client = ConversationDatasetsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = None - - response = client.cancel_operation( - request={ - "name": "locations", - } - ) - call.assert_called() -@pytest.mark.asyncio -async def test_cancel_operation_from_dict_async(): - client = ConversationDatasetsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - None - ) - response = await client.cancel_operation( - request={ - "name": "locations", - } - ) - call.assert_called() - - -def test_get_operation(transport: str = "grpc"): - client = ConversationDatasetsClient( - 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 = operations_pb2.GetOperationRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_operation), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation() - response = client.get_operation(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 response is the type that we expect. - assert isinstance(response, operations_pb2.Operation) -@pytest.mark.asyncio -async def test_get_operation_async(transport: str = "grpc"): - client = ConversationDatasetsAsyncClient( - 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 = operations_pb2.GetOperationRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_operation), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation() - ) - response = await client.get_operation(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 response is the type that we expect. - assert isinstance(response, operations_pb2.Operation) - -def test_get_operation_field_headers(): - client = ConversationDatasetsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = operations_pb2.GetOperationRequest() - request.name = "locations" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_operation), "__call__") as call: - call.return_value = operations_pb2.Operation() - - client.get_operation(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=locations",) in kw["metadata"] -@pytest.mark.asyncio -async def test_get_operation_field_headers_async(): - client = ConversationDatasetsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = operations_pb2.GetOperationRequest() - request.name = "locations" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_operation), "__call__") as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation() - ) - await client.get_operation(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=locations",) in kw["metadata"] - -def test_get_operation_from_dict(): - client = ConversationDatasetsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_operation), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation() - - response = client.get_operation( - request={ - "name": "locations", - } - ) - call.assert_called() -@pytest.mark.asyncio -async def test_get_operation_from_dict_async(): - client = ConversationDatasetsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_operation), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation() - ) - response = await client.get_operation( - request={ - "name": "locations", - } - ) - call.assert_called() - - -def test_list_operations(transport: str = "grpc"): - client = ConversationDatasetsClient( - 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 = operations_pb2.ListOperationsRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_operations), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.ListOperationsResponse() - response = client.list_operations(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 response is the type that we expect. - assert isinstance(response, operations_pb2.ListOperationsResponse) -@pytest.mark.asyncio -async def test_list_operations_async(transport: str = "grpc"): - client = ConversationDatasetsAsyncClient( - 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 = operations_pb2.ListOperationsRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_operations), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.ListOperationsResponse() - ) - response = await client.list_operations(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 response is the type that we expect. - assert isinstance(response, operations_pb2.ListOperationsResponse) - -def test_list_operations_field_headers(): - client = ConversationDatasetsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = operations_pb2.ListOperationsRequest() - request.name = "locations" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_operations), "__call__") as call: - call.return_value = operations_pb2.ListOperationsResponse() - - client.list_operations(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=locations",) in kw["metadata"] -@pytest.mark.asyncio -async def test_list_operations_field_headers_async(): - client = ConversationDatasetsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = operations_pb2.ListOperationsRequest() - request.name = "locations" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_operations), "__call__") as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.ListOperationsResponse() - ) - await client.list_operations(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=locations",) in kw["metadata"] - -def test_list_operations_from_dict(): - client = ConversationDatasetsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_operations), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.ListOperationsResponse() - - response = client.list_operations( - request={ - "name": "locations", - } - ) - call.assert_called() -@pytest.mark.asyncio -async def test_list_operations_from_dict_async(): - client = ConversationDatasetsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_operations), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.ListOperationsResponse() - ) - response = await client.list_operations( - request={ - "name": "locations", - } - ) - call.assert_called() - - -def test_list_locations(transport: str = "grpc"): - client = ConversationDatasetsClient( - 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 = locations_pb2.ListLocationsRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_locations), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = locations_pb2.ListLocationsResponse() - response = client.list_locations(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 response is the type that we expect. - assert isinstance(response, locations_pb2.ListLocationsResponse) -@pytest.mark.asyncio -async def test_list_locations_async(transport: str = "grpc"): - client = ConversationDatasetsAsyncClient( - 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 = locations_pb2.ListLocationsRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_locations), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - locations_pb2.ListLocationsResponse() - ) - response = await client.list_locations(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 response is the type that we expect. - assert isinstance(response, locations_pb2.ListLocationsResponse) - -def test_list_locations_field_headers(): - client = ConversationDatasetsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = locations_pb2.ListLocationsRequest() - request.name = "locations" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_locations), "__call__") as call: - call.return_value = locations_pb2.ListLocationsResponse() - - client.list_locations(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=locations",) in kw["metadata"] -@pytest.mark.asyncio -async def test_list_locations_field_headers_async(): - client = ConversationDatasetsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = locations_pb2.ListLocationsRequest() - request.name = "locations" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_locations), "__call__") as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - locations_pb2.ListLocationsResponse() - ) - await client.list_locations(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=locations",) in kw["metadata"] - -def test_list_locations_from_dict(): - client = ConversationDatasetsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_locations), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = locations_pb2.ListLocationsResponse() - - response = client.list_locations( - request={ - "name": "locations", - } - ) - call.assert_called() -@pytest.mark.asyncio -async def test_list_locations_from_dict_async(): - client = ConversationDatasetsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_locations), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - locations_pb2.ListLocationsResponse() - ) - response = await client.list_locations( - request={ - "name": "locations", - } - ) - call.assert_called() - - -def test_get_location(transport: str = "grpc"): - client = ConversationDatasetsClient( - 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 = locations_pb2.GetLocationRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_location), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = locations_pb2.Location() - response = client.get_location(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 response is the type that we expect. - assert isinstance(response, locations_pb2.Location) -@pytest.mark.asyncio -async def test_get_location_async(transport: str = "grpc_asyncio"): - client = ConversationDatasetsAsyncClient( - 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 = locations_pb2.GetLocationRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_location), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - locations_pb2.Location() - ) - response = await client.get_location(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 response is the type that we expect. - assert isinstance(response, locations_pb2.Location) - -def test_get_location_field_headers(): - client = ConversationDatasetsClient( - credentials=ga_credentials.AnonymousCredentials()) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = locations_pb2.GetLocationRequest() - request.name = "locations/abc" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_location), "__call__") as call: - call.return_value = locations_pb2.Location() - - client.get_location(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=locations/abc",) in kw["metadata"] -@pytest.mark.asyncio -async def test_get_location_field_headers_async(): - client = ConversationDatasetsAsyncClient( - credentials=ga_credentials.AnonymousCredentials() - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = locations_pb2.GetLocationRequest() - request.name = "locations/abc" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_location), "__call__") as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - locations_pb2.Location() - ) - await client.get_location(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=locations/abc",) in kw["metadata"] - -def test_get_location_from_dict(): - client = ConversationDatasetsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_locations), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = locations_pb2.Location() - - response = client.get_location( - request={ - "name": "locations/abc", - } - ) - call.assert_called() -@pytest.mark.asyncio -async def test_get_location_from_dict_async(): - client = ConversationDatasetsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_locations), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - locations_pb2.Location() - ) - response = await client.get_location( - request={ - "name": "locations", - } - ) - call.assert_called() - - -def test_transport_close(): - transports = { - "rest": "_session", - "grpc": "_grpc_channel", - } - - for transport, close_name in transports.items(): - client = ConversationDatasetsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport - ) - with mock.patch.object(type(getattr(client.transport, close_name)), "close") as close: - with client: - close.assert_not_called() - close.assert_called_once() - -def test_client_ctx(): - transports = [ - 'rest', - 'grpc', - ] - for transport in transports: - client = ConversationDatasetsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport - ) - # Test client calls underlying transport. - with mock.patch.object(type(client.transport), "close") as close: - close.assert_not_called() - with client: - pass - close.assert_called() - -@pytest.mark.parametrize("client_class,transport_class", [ - (ConversationDatasetsClient, transports.ConversationDatasetsGrpcTransport), - (ConversationDatasetsAsyncClient, transports.ConversationDatasetsGrpcAsyncIOTransport), -]) -def test_api_key_credentials(client_class, transport_class): - with mock.patch.object( - google.auth._default, "get_api_key_credentials", create=True - ) as get_api_key_credentials: - mock_cred = mock.Mock() - get_api_key_credentials.return_value = mock_cred - options = client_options.ClientOptions() - options.api_key = "api_key" - 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=mock_cred, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) diff --git a/owl-bot-staging/v2/tests/unit/gapic/dialogflow_v2/test_conversation_models.py b/owl-bot-staging/v2/tests/unit/gapic/dialogflow_v2/test_conversation_models.py deleted file mode 100644 index 553dacec6..000000000 --- a/owl-bot-staging/v2/tests/unit/gapic/dialogflow_v2/test_conversation_models.py +++ /dev/null @@ -1,6691 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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 -# try/except added for compatibility with python < 3.8 -try: - from unittest import mock - from unittest.mock import AsyncMock # pragma: NO COVER -except ImportError: # pragma: NO COVER - import mock - -import grpc -from grpc.experimental import aio -from collections.abc import Iterable -from google.protobuf import json_format -import json -import math -import pytest -from proto.marshal.rules.dates import DurationRule, TimestampRule -from proto.marshal.rules import wrappers -from requests import Response -from requests import Request, PreparedRequest -from requests.sessions import Session -from google.protobuf import json_format - -from google.api_core import client_options -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 -from google.api_core import operation_async # type: ignore -from google.api_core import operations_v1 -from google.api_core import path_template -from google.auth import credentials as ga_credentials -from google.auth.exceptions import MutualTLSChannelError -from google.cloud.dialogflow_v2.services.conversation_models import ConversationModelsAsyncClient -from google.cloud.dialogflow_v2.services.conversation_models import ConversationModelsClient -from google.cloud.dialogflow_v2.services.conversation_models import pagers -from google.cloud.dialogflow_v2.services.conversation_models import transports -from google.cloud.dialogflow_v2.types import conversation_model -from google.cloud.dialogflow_v2.types import conversation_model as gcd_conversation_model -from google.cloud.location import locations_pb2 -from google.longrunning import operations_pb2 -from google.oauth2 import service_account -from google.protobuf import empty_pb2 # type: ignore -from google.protobuf import timestamp_pb2 # type: ignore -import google.auth - - -def client_cert_source_callback(): - return b"cert bytes", b"key bytes" - - -# If default endpoint is localhost, then default mtls endpoint will be the same. -# This method modifies the default endpoint so the client can produce a different -# mtls endpoint for endpoint testing purposes. -def modify_default_endpoint(client): - return "foo.googleapis.com" if ("localhost" in client.DEFAULT_ENDPOINT) else client.DEFAULT_ENDPOINT - - -def test__get_default_mtls_endpoint(): - api_endpoint = "example.googleapis.com" - api_mtls_endpoint = "example.mtls.googleapis.com" - sandbox_endpoint = "example.sandbox.googleapis.com" - sandbox_mtls_endpoint = "example.mtls.sandbox.googleapis.com" - non_googleapi = "api.example.com" - - assert ConversationModelsClient._get_default_mtls_endpoint(None) is None - assert ConversationModelsClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint - assert ConversationModelsClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint - assert ConversationModelsClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint - assert ConversationModelsClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint - assert ConversationModelsClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi - - -@pytest.mark.parametrize("client_class,transport_name", [ - (ConversationModelsClient, "grpc"), - (ConversationModelsAsyncClient, "grpc_asyncio"), - (ConversationModelsClient, "rest"), -]) -def test_conversation_models_client_from_service_account_info(client_class, transport_name): - 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, transport=transport_name) - assert client.transport._credentials == creds - assert isinstance(client, client_class) - - assert client.transport._host == ( - 'dialogflow.googleapis.com:443' - if transport_name in ['grpc', 'grpc_asyncio'] - else - 'https://dialogflow.googleapis.com' - ) - - -@pytest.mark.parametrize("transport_class,transport_name", [ - (transports.ConversationModelsGrpcTransport, "grpc"), - (transports.ConversationModelsGrpcAsyncIOTransport, "grpc_asyncio"), - (transports.ConversationModelsRestTransport, "rest"), -]) -def test_conversation_models_client_service_account_always_use_jwt(transport_class, transport_name): - with mock.patch.object(service_account.Credentials, 'with_always_use_jwt_access', create=True) as use_jwt: - creds = service_account.Credentials(None, None, None) - transport = transport_class(credentials=creds, always_use_jwt_access=True) - use_jwt.assert_called_once_with(True) - - with mock.patch.object(service_account.Credentials, 'with_always_use_jwt_access', create=True) as use_jwt: - creds = service_account.Credentials(None, None, None) - transport = transport_class(credentials=creds, always_use_jwt_access=False) - use_jwt.assert_not_called() - - -@pytest.mark.parametrize("client_class,transport_name", [ - (ConversationModelsClient, "grpc"), - (ConversationModelsAsyncClient, "grpc_asyncio"), - (ConversationModelsClient, "rest"), -]) -def test_conversation_models_client_from_service_account_file(client_class, transport_name): - 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", transport=transport_name) - assert client.transport._credentials == creds - assert isinstance(client, client_class) - - client = client_class.from_service_account_json("dummy/file/path.json", transport=transport_name) - assert client.transport._credentials == creds - assert isinstance(client, client_class) - - assert client.transport._host == ( - 'dialogflow.googleapis.com:443' - if transport_name in ['grpc', 'grpc_asyncio'] - else - 'https://dialogflow.googleapis.com' - ) - - -def test_conversation_models_client_get_transport_class(): - transport = ConversationModelsClient.get_transport_class() - available_transports = [ - transports.ConversationModelsGrpcTransport, - transports.ConversationModelsRestTransport, - ] - assert transport in available_transports - - transport = ConversationModelsClient.get_transport_class("grpc") - assert transport == transports.ConversationModelsGrpcTransport - - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (ConversationModelsClient, transports.ConversationModelsGrpcTransport, "grpc"), - (ConversationModelsAsyncClient, transports.ConversationModelsGrpcAsyncIOTransport, "grpc_asyncio"), - (ConversationModelsClient, transports.ConversationModelsRestTransport, "rest"), -]) -@mock.patch.object(ConversationModelsClient, "DEFAULT_ENDPOINT", modify_default_endpoint(ConversationModelsClient)) -@mock.patch.object(ConversationModelsAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(ConversationModelsAsyncClient)) -def test_conversation_models_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(ConversationModelsClient, '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(ConversationModelsClient, 'get_transport_class') as gtc: - client = client_class(transport=transport_name) - gtc.assert_called() - - # Check the case api_endpoint is provided. - options = client_options.ClientOptions(api_endpoint="squid.clam.whelk") - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(transport=transport_name, client_options=options) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host="squid.clam.whelk", - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is - # "never". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is - # "always". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_MTLS_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # 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(transport=transport_name) - - # 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(transport=transport_name) - - # 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, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id="octopus", - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - # Check the case api_endpoint is provided - options = client_options.ClientOptions(api_audience="https://language.googleapis.com") - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience="https://language.googleapis.com" - ) - -@pytest.mark.parametrize("client_class,transport_class,transport_name,use_client_cert_env", [ - (ConversationModelsClient, transports.ConversationModelsGrpcTransport, "grpc", "true"), - (ConversationModelsAsyncClient, transports.ConversationModelsGrpcAsyncIOTransport, "grpc_asyncio", "true"), - (ConversationModelsClient, transports.ConversationModelsGrpcTransport, "grpc", "false"), - (ConversationModelsAsyncClient, transports.ConversationModelsGrpcAsyncIOTransport, "grpc_asyncio", "false"), - (ConversationModelsClient, transports.ConversationModelsRestTransport, "rest", "true"), - (ConversationModelsClient, transports.ConversationModelsRestTransport, "rest", "false"), -]) -@mock.patch.object(ConversationModelsClient, "DEFAULT_ENDPOINT", modify_default_endpoint(ConversationModelsClient)) -@mock.patch.object(ConversationModelsAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(ConversationModelsAsyncClient)) -@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) -def test_conversation_models_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, transport=transport_name) - - if use_client_cert_env == "false": - expected_client_cert_source = None - expected_host = client.DEFAULT_ENDPOINT - else: - expected_client_cert_source = client_cert_source_callback - expected_host = client.DEFAULT_MTLS_ENDPOINT - - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=expected_host, - scopes=None, - client_cert_source_for_mtls=expected_client_cert_source, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case ADC client cert is provided. Whether client cert is used depends on - # GOOGLE_API_USE_CLIENT_CERTIFICATE value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): - with mock.patch.object(transport_class, '__init__') as patched: - with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): - with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=client_cert_source_callback): - if use_client_cert_env == "false": - expected_host = client.DEFAULT_ENDPOINT - expected_client_cert_source = None - else: - expected_host = client.DEFAULT_MTLS_ENDPOINT - expected_client_cert_source = client_cert_source_callback - - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=expected_host, - scopes=None, - client_cert_source_for_mtls=expected_client_cert_source, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case client_cert_source and ADC client cert are not provided. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): - with mock.patch.object(transport_class, '__init__') as patched: - with mock.patch("google.auth.transport.mtls.has_default_client_cert_source", return_value=False): - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - -@pytest.mark.parametrize("client_class", [ - ConversationModelsClient, ConversationModelsAsyncClient -]) -@mock.patch.object(ConversationModelsClient, "DEFAULT_ENDPOINT", modify_default_endpoint(ConversationModelsClient)) -@mock.patch.object(ConversationModelsAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(ConversationModelsAsyncClient)) -def test_conversation_models_client_get_mtls_endpoint_and_cert_source(client_class): - mock_client_cert_source = mock.Mock() - - # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "true". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - mock_api_endpoint = "foo" - options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) - assert api_endpoint == mock_api_endpoint - assert cert_source == mock_client_cert_source - - # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "false". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): - mock_client_cert_source = mock.Mock() - mock_api_endpoint = "foo" - options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) - assert api_endpoint == mock_api_endpoint - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "never". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_ENDPOINT - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "always". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert doesn't exist. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=False): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_ENDPOINT - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert exists. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - 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=mock_client_cert_source): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT - assert cert_source == mock_client_cert_source - - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (ConversationModelsClient, transports.ConversationModelsGrpcTransport, "grpc"), - (ConversationModelsAsyncClient, transports.ConversationModelsGrpcAsyncIOTransport, "grpc_asyncio"), - (ConversationModelsClient, transports.ConversationModelsRestTransport, "rest"), -]) -def test_conversation_models_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, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=["1", "2"], - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - -@pytest.mark.parametrize("client_class,transport_class,transport_name,grpc_helpers", [ - (ConversationModelsClient, transports.ConversationModelsGrpcTransport, "grpc", grpc_helpers), - (ConversationModelsAsyncClient, transports.ConversationModelsGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), - (ConversationModelsClient, transports.ConversationModelsRestTransport, "rest", None), -]) -def test_conversation_models_client_client_options_credentials_file(client_class, transport_class, transport_name, grpc_helpers): - # 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, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file="credentials.json", - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - -def test_conversation_models_client_client_options_from_dict(): - with mock.patch('google.cloud.dialogflow_v2.services.conversation_models.transports.ConversationModelsGrpcTransport.__init__') as grpc_transport: - grpc_transport.return_value = None - client = ConversationModelsClient( - client_options={'api_endpoint': 'squid.clam.whelk'} - ) - grpc_transport.assert_called_once_with( - credentials=None, - credentials_file=None, - host="squid.clam.whelk", - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - -@pytest.mark.parametrize("client_class,transport_class,transport_name,grpc_helpers", [ - (ConversationModelsClient, transports.ConversationModelsGrpcTransport, "grpc", grpc_helpers), - (ConversationModelsAsyncClient, transports.ConversationModelsGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), -]) -def test_conversation_models_client_create_channel_credentials_file(client_class, transport_class, transport_name, grpc_helpers): - # 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, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file="credentials.json", - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # test that the credentials from file are saved and used as the credentials. - with mock.patch.object( - google.auth, "load_credentials_from_file", autospec=True - ) as load_creds, mock.patch.object( - google.auth, "default", autospec=True - ) as adc, mock.patch.object( - grpc_helpers, "create_channel" - ) as create_channel: - creds = ga_credentials.AnonymousCredentials() - file_creds = ga_credentials.AnonymousCredentials() - load_creds.return_value = (file_creds, None) - adc.return_value = (creds, None) - client = client_class(client_options=options, transport=transport_name) - create_channel.assert_called_with( - "dialogflow.googleapis.com:443", - credentials=file_creds, - credentials_file=None, - quota_project_id=None, - default_scopes=( - 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/dialogflow', -), - scopes=None, - default_host="dialogflow.googleapis.com", - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - -@pytest.mark.parametrize("request_type", [ - gcd_conversation_model.CreateConversationModelRequest, - dict, -]) -def test_create_conversation_model(request_type, transport: str = 'grpc'): - client = ConversationModelsClient( - 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_conversation_model), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/spam') - response = client.create_conversation_model(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_model.CreateConversationModelRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -def test_create_conversation_model_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = ConversationModelsClient( - 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_conversation_model), - '__call__') as call: - client.create_conversation_model() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == gcd_conversation_model.CreateConversationModelRequest() - -@pytest.mark.asyncio -async def test_create_conversation_model_async(transport: str = 'grpc_asyncio', request_type=gcd_conversation_model.CreateConversationModelRequest): - client = ConversationModelsAsyncClient( - 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_conversation_model), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name='operations/spam') - ) - response = await client.create_conversation_model(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_model.CreateConversationModelRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -@pytest.mark.asyncio -async def test_create_conversation_model_async_from_dict(): - await test_create_conversation_model_async(request_type=dict) - - -def test_create_conversation_model_field_headers(): - client = ConversationModelsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value 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_model.CreateConversationModelRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_conversation_model), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') - client.create_conversation_model(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_conversation_model_field_headers_async(): - client = ConversationModelsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value 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_model.CreateConversationModelRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_conversation_model), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) - await client.create_conversation_model(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_conversation_model_flattened(): - client = ConversationModelsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_conversation_model), - '__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_conversation_model( - parent='parent_value', - conversation_model=gcd_conversation_model.ConversationModel(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] - arg = args[0].parent - mock_val = 'parent_value' - assert arg == mock_val - arg = args[0].conversation_model - mock_val = gcd_conversation_model.ConversationModel(name='name_value') - assert arg == mock_val - - -def test_create_conversation_model_flattened_error(): - client = ConversationModelsClient( - 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_conversation_model( - gcd_conversation_model.CreateConversationModelRequest(), - parent='parent_value', - conversation_model=gcd_conversation_model.ConversationModel(name='name_value'), - ) - -@pytest.mark.asyncio -async def test_create_conversation_model_flattened_async(): - client = ConversationModelsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_conversation_model), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/op') - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name='operations/spam') - ) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.create_conversation_model( - parent='parent_value', - conversation_model=gcd_conversation_model.ConversationModel(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] - arg = args[0].parent - mock_val = 'parent_value' - assert arg == mock_val - arg = args[0].conversation_model - mock_val = gcd_conversation_model.ConversationModel(name='name_value') - assert arg == mock_val - -@pytest.mark.asyncio -async def test_create_conversation_model_flattened_error_async(): - client = ConversationModelsAsyncClient( - 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_conversation_model( - gcd_conversation_model.CreateConversationModelRequest(), - parent='parent_value', - conversation_model=gcd_conversation_model.ConversationModel(name='name_value'), - ) - - -@pytest.mark.parametrize("request_type", [ - conversation_model.GetConversationModelRequest, - dict, -]) -def test_get_conversation_model(request_type, transport: str = 'grpc'): - client = ConversationModelsClient( - 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_conversation_model), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = conversation_model.ConversationModel( - name='name_value', - display_name='display_name_value', - state=conversation_model.ConversationModel.State.CREATING, - language_code='language_code_value', - article_suggestion_model_metadata=conversation_model.ArticleSuggestionModelMetadata(training_model_type=conversation_model.ConversationModel.ModelType.SMART_REPLY_DUAL_ENCODER_MODEL), - ) - response = client.get_conversation_model(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_model.GetConversationModelRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, conversation_model.ConversationModel) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.state == conversation_model.ConversationModel.State.CREATING - assert response.language_code == 'language_code_value' - - -def test_get_conversation_model_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = ConversationModelsClient( - 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_conversation_model), - '__call__') as call: - client.get_conversation_model() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == conversation_model.GetConversationModelRequest() - -@pytest.mark.asyncio -async def test_get_conversation_model_async(transport: str = 'grpc_asyncio', request_type=conversation_model.GetConversationModelRequest): - client = ConversationModelsAsyncClient( - 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_conversation_model), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(conversation_model.ConversationModel( - name='name_value', - display_name='display_name_value', - state=conversation_model.ConversationModel.State.CREATING, - language_code='language_code_value', - )) - response = await client.get_conversation_model(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == conversation_model.GetConversationModelRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, conversation_model.ConversationModel) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.state == conversation_model.ConversationModel.State.CREATING - assert response.language_code == 'language_code_value' - - -@pytest.mark.asyncio -async def test_get_conversation_model_async_from_dict(): - await test_get_conversation_model_async(request_type=dict) - - -def test_get_conversation_model_field_headers(): - client = ConversationModelsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value 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_model.GetConversationModelRequest() - - 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_model), - '__call__') as call: - call.return_value = conversation_model.ConversationModel() - client.get_conversation_model(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_conversation_model_field_headers_async(): - client = ConversationModelsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value 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_model.GetConversationModelRequest() - - 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_model), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(conversation_model.ConversationModel()) - await client.get_conversation_model(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_conversation_model_flattened(): - client = ConversationModelsClient( - 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_model), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = conversation_model.ConversationModel() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.get_conversation_model( - 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] - arg = args[0].name - mock_val = 'name_value' - assert arg == mock_val - - -def test_get_conversation_model_flattened_error(): - client = ConversationModelsClient( - 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_conversation_model( - conversation_model.GetConversationModelRequest(), - name='name_value', - ) - -@pytest.mark.asyncio -async def test_get_conversation_model_flattened_async(): - client = ConversationModelsAsyncClient( - 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_model), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = conversation_model.ConversationModel() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(conversation_model.ConversationModel()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.get_conversation_model( - 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] - arg = args[0].name - mock_val = 'name_value' - assert arg == mock_val - -@pytest.mark.asyncio -async def test_get_conversation_model_flattened_error_async(): - client = ConversationModelsAsyncClient( - 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_conversation_model( - conversation_model.GetConversationModelRequest(), - name='name_value', - ) - - -@pytest.mark.parametrize("request_type", [ - conversation_model.ListConversationModelsRequest, - dict, -]) -def test_list_conversation_models(request_type, transport: str = 'grpc'): - client = ConversationModelsClient( - 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_conversation_models), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = conversation_model.ListConversationModelsResponse( - next_page_token='next_page_token_value', - ) - response = client.list_conversation_models(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_model.ListConversationModelsRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListConversationModelsPager) - assert response.next_page_token == 'next_page_token_value' - - -def test_list_conversation_models_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = ConversationModelsClient( - 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_conversation_models), - '__call__') as call: - client.list_conversation_models() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == conversation_model.ListConversationModelsRequest() - -@pytest.mark.asyncio -async def test_list_conversation_models_async(transport: str = 'grpc_asyncio', request_type=conversation_model.ListConversationModelsRequest): - client = ConversationModelsAsyncClient( - 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_conversation_models), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(conversation_model.ListConversationModelsResponse( - next_page_token='next_page_token_value', - )) - response = await client.list_conversation_models(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == conversation_model.ListConversationModelsRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListConversationModelsAsyncPager) - assert response.next_page_token == 'next_page_token_value' - - -@pytest.mark.asyncio -async def test_list_conversation_models_async_from_dict(): - await test_list_conversation_models_async(request_type=dict) - - -def test_list_conversation_models_field_headers(): - client = ConversationModelsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value 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_model.ListConversationModelsRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_conversation_models), - '__call__') as call: - call.return_value = conversation_model.ListConversationModelsResponse() - client.list_conversation_models(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_conversation_models_field_headers_async(): - client = ConversationModelsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value 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_model.ListConversationModelsRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_conversation_models), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(conversation_model.ListConversationModelsResponse()) - await client.list_conversation_models(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_conversation_models_flattened(): - client = ConversationModelsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_conversation_models), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = conversation_model.ListConversationModelsResponse() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.list_conversation_models( - 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] - arg = args[0].parent - mock_val = 'parent_value' - assert arg == mock_val - - -def test_list_conversation_models_flattened_error(): - client = ConversationModelsClient( - 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_conversation_models( - conversation_model.ListConversationModelsRequest(), - parent='parent_value', - ) - -@pytest.mark.asyncio -async def test_list_conversation_models_flattened_async(): - client = ConversationModelsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_conversation_models), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = conversation_model.ListConversationModelsResponse() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(conversation_model.ListConversationModelsResponse()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.list_conversation_models( - 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] - arg = args[0].parent - mock_val = 'parent_value' - assert arg == mock_val - -@pytest.mark.asyncio -async def test_list_conversation_models_flattened_error_async(): - client = ConversationModelsAsyncClient( - 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_conversation_models( - conversation_model.ListConversationModelsRequest(), - parent='parent_value', - ) - - -def test_list_conversation_models_pager(transport_name: str = "grpc"): - client = ConversationModelsClient( - credentials=ga_credentials.AnonymousCredentials, - transport=transport_name, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_conversation_models), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - conversation_model.ListConversationModelsResponse( - conversation_models=[ - conversation_model.ConversationModel(), - conversation_model.ConversationModel(), - conversation_model.ConversationModel(), - ], - next_page_token='abc', - ), - conversation_model.ListConversationModelsResponse( - conversation_models=[], - next_page_token='def', - ), - conversation_model.ListConversationModelsResponse( - conversation_models=[ - conversation_model.ConversationModel(), - ], - next_page_token='ghi', - ), - conversation_model.ListConversationModelsResponse( - conversation_models=[ - conversation_model.ConversationModel(), - conversation_model.ConversationModel(), - ], - ), - RuntimeError, - ) - - metadata = () - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ('parent', ''), - )), - ) - pager = client.list_conversation_models(request={}) - - assert pager._metadata == metadata - - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, conversation_model.ConversationModel) - for i in results) -def test_list_conversation_models_pages(transport_name: str = "grpc"): - client = ConversationModelsClient( - credentials=ga_credentials.AnonymousCredentials, - transport=transport_name, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_conversation_models), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - conversation_model.ListConversationModelsResponse( - conversation_models=[ - conversation_model.ConversationModel(), - conversation_model.ConversationModel(), - conversation_model.ConversationModel(), - ], - next_page_token='abc', - ), - conversation_model.ListConversationModelsResponse( - conversation_models=[], - next_page_token='def', - ), - conversation_model.ListConversationModelsResponse( - conversation_models=[ - conversation_model.ConversationModel(), - ], - next_page_token='ghi', - ), - conversation_model.ListConversationModelsResponse( - conversation_models=[ - conversation_model.ConversationModel(), - conversation_model.ConversationModel(), - ], - ), - RuntimeError, - ) - pages = list(client.list_conversation_models(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_conversation_models_async_pager(): - client = ConversationModelsAsyncClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_conversation_models), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - conversation_model.ListConversationModelsResponse( - conversation_models=[ - conversation_model.ConversationModel(), - conversation_model.ConversationModel(), - conversation_model.ConversationModel(), - ], - next_page_token='abc', - ), - conversation_model.ListConversationModelsResponse( - conversation_models=[], - next_page_token='def', - ), - conversation_model.ListConversationModelsResponse( - conversation_models=[ - conversation_model.ConversationModel(), - ], - next_page_token='ghi', - ), - conversation_model.ListConversationModelsResponse( - conversation_models=[ - conversation_model.ConversationModel(), - conversation_model.ConversationModel(), - ], - ), - RuntimeError, - ) - async_pager = await client.list_conversation_models(request={},) - assert async_pager.next_page_token == 'abc' - responses = [] - async for response in async_pager: # pragma: no branch - responses.append(response) - - assert len(responses) == 6 - assert all(isinstance(i, conversation_model.ConversationModel) - for i in responses) - - -@pytest.mark.asyncio -async def test_list_conversation_models_async_pages(): - client = ConversationModelsAsyncClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_conversation_models), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - conversation_model.ListConversationModelsResponse( - conversation_models=[ - conversation_model.ConversationModel(), - conversation_model.ConversationModel(), - conversation_model.ConversationModel(), - ], - next_page_token='abc', - ), - conversation_model.ListConversationModelsResponse( - conversation_models=[], - next_page_token='def', - ), - conversation_model.ListConversationModelsResponse( - conversation_models=[ - conversation_model.ConversationModel(), - ], - next_page_token='ghi', - ), - conversation_model.ListConversationModelsResponse( - conversation_models=[ - conversation_model.ConversationModel(), - conversation_model.ConversationModel(), - ], - ), - RuntimeError, - ) - pages = [] - async for page_ in (await client.list_conversation_models(request={})).pages: # pragma: no branch - pages.append(page_) - for page_, token in zip(pages, ['abc','def','ghi', '']): - assert page_.raw_page.next_page_token == token - -@pytest.mark.parametrize("request_type", [ - conversation_model.DeleteConversationModelRequest, - dict, -]) -def test_delete_conversation_model(request_type, transport: str = 'grpc'): - client = ConversationModelsClient( - 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_conversation_model), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/spam') - response = client.delete_conversation_model(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_model.DeleteConversationModelRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -def test_delete_conversation_model_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = ConversationModelsClient( - 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_conversation_model), - '__call__') as call: - client.delete_conversation_model() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == conversation_model.DeleteConversationModelRequest() - -@pytest.mark.asyncio -async def test_delete_conversation_model_async(transport: str = 'grpc_asyncio', request_type=conversation_model.DeleteConversationModelRequest): - client = ConversationModelsAsyncClient( - 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_conversation_model), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name='operations/spam') - ) - response = await client.delete_conversation_model(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == conversation_model.DeleteConversationModelRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -@pytest.mark.asyncio -async def test_delete_conversation_model_async_from_dict(): - await test_delete_conversation_model_async(request_type=dict) - - -def test_delete_conversation_model_field_headers(): - client = ConversationModelsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value 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_model.DeleteConversationModelRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_conversation_model), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') - client.delete_conversation_model(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_conversation_model_field_headers_async(): - client = ConversationModelsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value 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_model.DeleteConversationModelRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_conversation_model), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) - await client.delete_conversation_model(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_conversation_model_flattened(): - client = ConversationModelsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_conversation_model), - '__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_conversation_model( - 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] - arg = args[0].name - mock_val = 'name_value' - assert arg == mock_val - - -def test_delete_conversation_model_flattened_error(): - client = ConversationModelsClient( - 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_conversation_model( - conversation_model.DeleteConversationModelRequest(), - name='name_value', - ) - -@pytest.mark.asyncio -async def test_delete_conversation_model_flattened_async(): - client = ConversationModelsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_conversation_model), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/op') - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name='operations/spam') - ) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.delete_conversation_model( - 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] - arg = args[0].name - mock_val = 'name_value' - assert arg == mock_val - -@pytest.mark.asyncio -async def test_delete_conversation_model_flattened_error_async(): - client = ConversationModelsAsyncClient( - 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_conversation_model( - conversation_model.DeleteConversationModelRequest(), - name='name_value', - ) - - -@pytest.mark.parametrize("request_type", [ - conversation_model.DeployConversationModelRequest, - dict, -]) -def test_deploy_conversation_model(request_type, transport: str = 'grpc'): - client = ConversationModelsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.deploy_conversation_model), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/spam') - response = client.deploy_conversation_model(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_model.DeployConversationModelRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -def test_deploy_conversation_model_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = ConversationModelsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.deploy_conversation_model), - '__call__') as call: - client.deploy_conversation_model() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == conversation_model.DeployConversationModelRequest() - -@pytest.mark.asyncio -async def test_deploy_conversation_model_async(transport: str = 'grpc_asyncio', request_type=conversation_model.DeployConversationModelRequest): - client = ConversationModelsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.deploy_conversation_model), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name='operations/spam') - ) - response = await client.deploy_conversation_model(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == conversation_model.DeployConversationModelRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -@pytest.mark.asyncio -async def test_deploy_conversation_model_async_from_dict(): - await test_deploy_conversation_model_async(request_type=dict) - - -def test_deploy_conversation_model_field_headers(): - client = ConversationModelsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value 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_model.DeployConversationModelRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.deploy_conversation_model), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') - client.deploy_conversation_model(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_deploy_conversation_model_field_headers_async(): - client = ConversationModelsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value 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_model.DeployConversationModelRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.deploy_conversation_model), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) - await client.deploy_conversation_model(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'] - - -@pytest.mark.parametrize("request_type", [ - conversation_model.UndeployConversationModelRequest, - dict, -]) -def test_undeploy_conversation_model(request_type, transport: str = 'grpc'): - client = ConversationModelsClient( - 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.undeploy_conversation_model), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/spam') - response = client.undeploy_conversation_model(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_model.UndeployConversationModelRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -def test_undeploy_conversation_model_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = ConversationModelsClient( - 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.undeploy_conversation_model), - '__call__') as call: - client.undeploy_conversation_model() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == conversation_model.UndeployConversationModelRequest() - -@pytest.mark.asyncio -async def test_undeploy_conversation_model_async(transport: str = 'grpc_asyncio', request_type=conversation_model.UndeployConversationModelRequest): - client = ConversationModelsAsyncClient( - 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.undeploy_conversation_model), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name='operations/spam') - ) - response = await client.undeploy_conversation_model(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == conversation_model.UndeployConversationModelRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -@pytest.mark.asyncio -async def test_undeploy_conversation_model_async_from_dict(): - await test_undeploy_conversation_model_async(request_type=dict) - - -def test_undeploy_conversation_model_field_headers(): - client = ConversationModelsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value 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_model.UndeployConversationModelRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.undeploy_conversation_model), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') - client.undeploy_conversation_model(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_undeploy_conversation_model_field_headers_async(): - client = ConversationModelsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value 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_model.UndeployConversationModelRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.undeploy_conversation_model), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) - await client.undeploy_conversation_model(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'] - - -@pytest.mark.parametrize("request_type", [ - conversation_model.GetConversationModelEvaluationRequest, - dict, -]) -def test_get_conversation_model_evaluation(request_type, transport: str = 'grpc'): - client = ConversationModelsClient( - 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_conversation_model_evaluation), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = conversation_model.ConversationModelEvaluation( - name='name_value', - display_name='display_name_value', - raw_human_eval_template_csv='raw_human_eval_template_csv_value', - smart_reply_metrics=conversation_model.SmartReplyMetrics(allowlist_coverage=0.19260000000000002), - ) - response = client.get_conversation_model_evaluation(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_model.GetConversationModelEvaluationRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, conversation_model.ConversationModelEvaluation) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.raw_human_eval_template_csv == 'raw_human_eval_template_csv_value' - - -def test_get_conversation_model_evaluation_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = ConversationModelsClient( - 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_conversation_model_evaluation), - '__call__') as call: - client.get_conversation_model_evaluation() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == conversation_model.GetConversationModelEvaluationRequest() - -@pytest.mark.asyncio -async def test_get_conversation_model_evaluation_async(transport: str = 'grpc_asyncio', request_type=conversation_model.GetConversationModelEvaluationRequest): - client = ConversationModelsAsyncClient( - 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_conversation_model_evaluation), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(conversation_model.ConversationModelEvaluation( - name='name_value', - display_name='display_name_value', - raw_human_eval_template_csv='raw_human_eval_template_csv_value', - )) - response = await client.get_conversation_model_evaluation(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == conversation_model.GetConversationModelEvaluationRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, conversation_model.ConversationModelEvaluation) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.raw_human_eval_template_csv == 'raw_human_eval_template_csv_value' - - -@pytest.mark.asyncio -async def test_get_conversation_model_evaluation_async_from_dict(): - await test_get_conversation_model_evaluation_async(request_type=dict) - - -def test_get_conversation_model_evaluation_field_headers(): - client = ConversationModelsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value 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_model.GetConversationModelEvaluationRequest() - - 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_model_evaluation), - '__call__') as call: - call.return_value = conversation_model.ConversationModelEvaluation() - client.get_conversation_model_evaluation(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_conversation_model_evaluation_field_headers_async(): - client = ConversationModelsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value 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_model.GetConversationModelEvaluationRequest() - - 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_model_evaluation), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(conversation_model.ConversationModelEvaluation()) - await client.get_conversation_model_evaluation(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_conversation_model_evaluation_flattened(): - client = ConversationModelsClient( - 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_model_evaluation), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = conversation_model.ConversationModelEvaluation() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.get_conversation_model_evaluation( - 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] - arg = args[0].name - mock_val = 'name_value' - assert arg == mock_val - - -def test_get_conversation_model_evaluation_flattened_error(): - client = ConversationModelsClient( - 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_conversation_model_evaluation( - conversation_model.GetConversationModelEvaluationRequest(), - name='name_value', - ) - -@pytest.mark.asyncio -async def test_get_conversation_model_evaluation_flattened_async(): - client = ConversationModelsAsyncClient( - 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_model_evaluation), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = conversation_model.ConversationModelEvaluation() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(conversation_model.ConversationModelEvaluation()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.get_conversation_model_evaluation( - 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] - arg = args[0].name - mock_val = 'name_value' - assert arg == mock_val - -@pytest.mark.asyncio -async def test_get_conversation_model_evaluation_flattened_error_async(): - client = ConversationModelsAsyncClient( - 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_conversation_model_evaluation( - conversation_model.GetConversationModelEvaluationRequest(), - name='name_value', - ) - - -@pytest.mark.parametrize("request_type", [ - conversation_model.ListConversationModelEvaluationsRequest, - dict, -]) -def test_list_conversation_model_evaluations(request_type, transport: str = 'grpc'): - client = ConversationModelsClient( - 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_conversation_model_evaluations), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = conversation_model.ListConversationModelEvaluationsResponse( - next_page_token='next_page_token_value', - ) - response = client.list_conversation_model_evaluations(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_model.ListConversationModelEvaluationsRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListConversationModelEvaluationsPager) - assert response.next_page_token == 'next_page_token_value' - - -def test_list_conversation_model_evaluations_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = ConversationModelsClient( - 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_conversation_model_evaluations), - '__call__') as call: - client.list_conversation_model_evaluations() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == conversation_model.ListConversationModelEvaluationsRequest() - -@pytest.mark.asyncio -async def test_list_conversation_model_evaluations_async(transport: str = 'grpc_asyncio', request_type=conversation_model.ListConversationModelEvaluationsRequest): - client = ConversationModelsAsyncClient( - 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_conversation_model_evaluations), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(conversation_model.ListConversationModelEvaluationsResponse( - next_page_token='next_page_token_value', - )) - response = await client.list_conversation_model_evaluations(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == conversation_model.ListConversationModelEvaluationsRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListConversationModelEvaluationsAsyncPager) - assert response.next_page_token == 'next_page_token_value' - - -@pytest.mark.asyncio -async def test_list_conversation_model_evaluations_async_from_dict(): - await test_list_conversation_model_evaluations_async(request_type=dict) - - -def test_list_conversation_model_evaluations_field_headers(): - client = ConversationModelsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value 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_model.ListConversationModelEvaluationsRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_conversation_model_evaluations), - '__call__') as call: - call.return_value = conversation_model.ListConversationModelEvaluationsResponse() - client.list_conversation_model_evaluations(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_conversation_model_evaluations_field_headers_async(): - client = ConversationModelsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value 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_model.ListConversationModelEvaluationsRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_conversation_model_evaluations), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(conversation_model.ListConversationModelEvaluationsResponse()) - await client.list_conversation_model_evaluations(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_conversation_model_evaluations_flattened(): - client = ConversationModelsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_conversation_model_evaluations), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = conversation_model.ListConversationModelEvaluationsResponse() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.list_conversation_model_evaluations( - 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] - arg = args[0].parent - mock_val = 'parent_value' - assert arg == mock_val - - -def test_list_conversation_model_evaluations_flattened_error(): - client = ConversationModelsClient( - 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_conversation_model_evaluations( - conversation_model.ListConversationModelEvaluationsRequest(), - parent='parent_value', - ) - -@pytest.mark.asyncio -async def test_list_conversation_model_evaluations_flattened_async(): - client = ConversationModelsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_conversation_model_evaluations), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = conversation_model.ListConversationModelEvaluationsResponse() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(conversation_model.ListConversationModelEvaluationsResponse()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.list_conversation_model_evaluations( - 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] - arg = args[0].parent - mock_val = 'parent_value' - assert arg == mock_val - -@pytest.mark.asyncio -async def test_list_conversation_model_evaluations_flattened_error_async(): - client = ConversationModelsAsyncClient( - 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_conversation_model_evaluations( - conversation_model.ListConversationModelEvaluationsRequest(), - parent='parent_value', - ) - - -def test_list_conversation_model_evaluations_pager(transport_name: str = "grpc"): - client = ConversationModelsClient( - credentials=ga_credentials.AnonymousCredentials, - transport=transport_name, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_conversation_model_evaluations), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - conversation_model.ListConversationModelEvaluationsResponse( - conversation_model_evaluations=[ - conversation_model.ConversationModelEvaluation(), - conversation_model.ConversationModelEvaluation(), - conversation_model.ConversationModelEvaluation(), - ], - next_page_token='abc', - ), - conversation_model.ListConversationModelEvaluationsResponse( - conversation_model_evaluations=[], - next_page_token='def', - ), - conversation_model.ListConversationModelEvaluationsResponse( - conversation_model_evaluations=[ - conversation_model.ConversationModelEvaluation(), - ], - next_page_token='ghi', - ), - conversation_model.ListConversationModelEvaluationsResponse( - conversation_model_evaluations=[ - conversation_model.ConversationModelEvaluation(), - conversation_model.ConversationModelEvaluation(), - ], - ), - RuntimeError, - ) - - metadata = () - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ('parent', ''), - )), - ) - pager = client.list_conversation_model_evaluations(request={}) - - assert pager._metadata == metadata - - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, conversation_model.ConversationModelEvaluation) - for i in results) -def test_list_conversation_model_evaluations_pages(transport_name: str = "grpc"): - client = ConversationModelsClient( - credentials=ga_credentials.AnonymousCredentials, - transport=transport_name, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_conversation_model_evaluations), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - conversation_model.ListConversationModelEvaluationsResponse( - conversation_model_evaluations=[ - conversation_model.ConversationModelEvaluation(), - conversation_model.ConversationModelEvaluation(), - conversation_model.ConversationModelEvaluation(), - ], - next_page_token='abc', - ), - conversation_model.ListConversationModelEvaluationsResponse( - conversation_model_evaluations=[], - next_page_token='def', - ), - conversation_model.ListConversationModelEvaluationsResponse( - conversation_model_evaluations=[ - conversation_model.ConversationModelEvaluation(), - ], - next_page_token='ghi', - ), - conversation_model.ListConversationModelEvaluationsResponse( - conversation_model_evaluations=[ - conversation_model.ConversationModelEvaluation(), - conversation_model.ConversationModelEvaluation(), - ], - ), - RuntimeError, - ) - pages = list(client.list_conversation_model_evaluations(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_conversation_model_evaluations_async_pager(): - client = ConversationModelsAsyncClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_conversation_model_evaluations), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - conversation_model.ListConversationModelEvaluationsResponse( - conversation_model_evaluations=[ - conversation_model.ConversationModelEvaluation(), - conversation_model.ConversationModelEvaluation(), - conversation_model.ConversationModelEvaluation(), - ], - next_page_token='abc', - ), - conversation_model.ListConversationModelEvaluationsResponse( - conversation_model_evaluations=[], - next_page_token='def', - ), - conversation_model.ListConversationModelEvaluationsResponse( - conversation_model_evaluations=[ - conversation_model.ConversationModelEvaluation(), - ], - next_page_token='ghi', - ), - conversation_model.ListConversationModelEvaluationsResponse( - conversation_model_evaluations=[ - conversation_model.ConversationModelEvaluation(), - conversation_model.ConversationModelEvaluation(), - ], - ), - RuntimeError, - ) - async_pager = await client.list_conversation_model_evaluations(request={},) - assert async_pager.next_page_token == 'abc' - responses = [] - async for response in async_pager: # pragma: no branch - responses.append(response) - - assert len(responses) == 6 - assert all(isinstance(i, conversation_model.ConversationModelEvaluation) - for i in responses) - - -@pytest.mark.asyncio -async def test_list_conversation_model_evaluations_async_pages(): - client = ConversationModelsAsyncClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_conversation_model_evaluations), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - conversation_model.ListConversationModelEvaluationsResponse( - conversation_model_evaluations=[ - conversation_model.ConversationModelEvaluation(), - conversation_model.ConversationModelEvaluation(), - conversation_model.ConversationModelEvaluation(), - ], - next_page_token='abc', - ), - conversation_model.ListConversationModelEvaluationsResponse( - conversation_model_evaluations=[], - next_page_token='def', - ), - conversation_model.ListConversationModelEvaluationsResponse( - conversation_model_evaluations=[ - conversation_model.ConversationModelEvaluation(), - ], - next_page_token='ghi', - ), - conversation_model.ListConversationModelEvaluationsResponse( - conversation_model_evaluations=[ - conversation_model.ConversationModelEvaluation(), - conversation_model.ConversationModelEvaluation(), - ], - ), - RuntimeError, - ) - pages = [] - async for page_ in (await client.list_conversation_model_evaluations(request={})).pages: # pragma: no branch - pages.append(page_) - for page_, token in zip(pages, ['abc','def','ghi', '']): - assert page_.raw_page.next_page_token == token - -@pytest.mark.parametrize("request_type", [ - conversation_model.CreateConversationModelEvaluationRequest, - dict, -]) -def test_create_conversation_model_evaluation(request_type, transport: str = 'grpc'): - client = ConversationModelsClient( - 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_conversation_model_evaluation), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/spam') - response = client.create_conversation_model_evaluation(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_model.CreateConversationModelEvaluationRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -def test_create_conversation_model_evaluation_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = ConversationModelsClient( - 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_conversation_model_evaluation), - '__call__') as call: - client.create_conversation_model_evaluation() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == conversation_model.CreateConversationModelEvaluationRequest() - -@pytest.mark.asyncio -async def test_create_conversation_model_evaluation_async(transport: str = 'grpc_asyncio', request_type=conversation_model.CreateConversationModelEvaluationRequest): - client = ConversationModelsAsyncClient( - 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_conversation_model_evaluation), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name='operations/spam') - ) - response = await client.create_conversation_model_evaluation(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == conversation_model.CreateConversationModelEvaluationRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -@pytest.mark.asyncio -async def test_create_conversation_model_evaluation_async_from_dict(): - await test_create_conversation_model_evaluation_async(request_type=dict) - - -def test_create_conversation_model_evaluation_field_headers(): - client = ConversationModelsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value 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_model.CreateConversationModelEvaluationRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_conversation_model_evaluation), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') - client.create_conversation_model_evaluation(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_conversation_model_evaluation_field_headers_async(): - client = ConversationModelsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value 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_model.CreateConversationModelEvaluationRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_conversation_model_evaluation), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) - await client.create_conversation_model_evaluation(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_conversation_model_evaluation_flattened(): - client = ConversationModelsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_conversation_model_evaluation), - '__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_conversation_model_evaluation( - parent='parent_value', - conversation_model_evaluation=conversation_model.ConversationModelEvaluation(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] - arg = args[0].parent - mock_val = 'parent_value' - assert arg == mock_val - arg = args[0].conversation_model_evaluation - mock_val = conversation_model.ConversationModelEvaluation(name='name_value') - assert arg == mock_val - - -def test_create_conversation_model_evaluation_flattened_error(): - client = ConversationModelsClient( - 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_conversation_model_evaluation( - conversation_model.CreateConversationModelEvaluationRequest(), - parent='parent_value', - conversation_model_evaluation=conversation_model.ConversationModelEvaluation(name='name_value'), - ) - -@pytest.mark.asyncio -async def test_create_conversation_model_evaluation_flattened_async(): - client = ConversationModelsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_conversation_model_evaluation), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/op') - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name='operations/spam') - ) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.create_conversation_model_evaluation( - parent='parent_value', - conversation_model_evaluation=conversation_model.ConversationModelEvaluation(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] - arg = args[0].parent - mock_val = 'parent_value' - assert arg == mock_val - arg = args[0].conversation_model_evaluation - mock_val = conversation_model.ConversationModelEvaluation(name='name_value') - assert arg == mock_val - -@pytest.mark.asyncio -async def test_create_conversation_model_evaluation_flattened_error_async(): - client = ConversationModelsAsyncClient( - 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_conversation_model_evaluation( - conversation_model.CreateConversationModelEvaluationRequest(), - parent='parent_value', - conversation_model_evaluation=conversation_model.ConversationModelEvaluation(name='name_value'), - ) - - -@pytest.mark.parametrize("request_type", [ - gcd_conversation_model.CreateConversationModelRequest, - dict, -]) -def test_create_conversation_model_rest(request_type): - client = ConversationModelsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1'} - request_init["conversation_model"] = {'name': 'name_value', 'display_name': 'display_name_value', 'create_time': {'seconds': 751, 'nanos': 543}, 'datasets': [{'dataset': 'dataset_value'}], 'state': 1, 'language_code': 'language_code_value', 'article_suggestion_model_metadata': {'training_model_type': 2}, 'smart_reply_model_metadata': {'training_model_type': 2}} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name='operations/spam') - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.create_conversation_model(request) - - # Establish that the response is the type that we expect. - assert response.operation.name == "operations/spam" - - -def test_create_conversation_model_rest_required_fields(request_type=gcd_conversation_model.CreateConversationModelRequest): - transport_class = transports.ConversationModelsRestTransport - - request_init = {} - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - including_default_value_fields=False, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_conversation_model._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_conversation_model._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - - client = ConversationModelsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name='operations/spam') - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "post", - 'query_params': pb_request, - } - transcode_result['body'] = pb_request - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.create_conversation_model(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_create_conversation_model_rest_unset_required_fields(): - transport = transports.ConversationModelsRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.create_conversation_model._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("conversationModel", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_create_conversation_model_rest_interceptors(null_interceptor): - transport = transports.ConversationModelsRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.ConversationModelsRestInterceptor(), - ) - client = ConversationModelsClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(operation.Operation, "_set_result_from_operation"), \ - mock.patch.object(transports.ConversationModelsRestInterceptor, "post_create_conversation_model") as post, \ - mock.patch.object(transports.ConversationModelsRestInterceptor, "pre_create_conversation_model") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = gcd_conversation_model.CreateConversationModelRequest.pb(gcd_conversation_model.CreateConversationModelRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = json_format.MessageToJson(operations_pb2.Operation()) - - request = gcd_conversation_model.CreateConversationModelRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = operations_pb2.Operation() - - client.create_conversation_model(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_create_conversation_model_rest_bad_request(transport: str = 'rest', request_type=gcd_conversation_model.CreateConversationModelRequest): - client = ConversationModelsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1'} - request_init["conversation_model"] = {'name': 'name_value', 'display_name': 'display_name_value', 'create_time': {'seconds': 751, 'nanos': 543}, 'datasets': [{'dataset': 'dataset_value'}], 'state': 1, 'language_code': 'language_code_value', 'article_suggestion_model_metadata': {'training_model_type': 2}, 'smart_reply_model_metadata': {'training_model_type': 2}} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.create_conversation_model(request) - - -def test_create_conversation_model_rest_flattened(): - client = ConversationModelsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name='operations/spam') - - # get arguments that satisfy an http rule for this method - sample_request = {'parent': 'projects/sample1'} - - # get truthy value for each flattened field - mock_args = dict( - parent='parent_value', - conversation_model=gcd_conversation_model.ConversationModel(name='name_value'), - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.create_conversation_model(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v2/{parent=projects/*}/conversationModels" % client.transport._host, args[1]) - - -def test_create_conversation_model_rest_flattened_error(transport: str = 'rest'): - client = ConversationModelsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.create_conversation_model( - gcd_conversation_model.CreateConversationModelRequest(), - parent='parent_value', - conversation_model=gcd_conversation_model.ConversationModel(name='name_value'), - ) - - -def test_create_conversation_model_rest_error(): - client = ConversationModelsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - conversation_model.GetConversationModelRequest, - dict, -]) -def test_get_conversation_model_rest(request_type): - client = ConversationModelsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/conversationModels/sample2'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = conversation_model.ConversationModel( - name='name_value', - display_name='display_name_value', - state=conversation_model.ConversationModel.State.CREATING, - language_code='language_code_value', - article_suggestion_model_metadata=conversation_model.ArticleSuggestionModelMetadata(training_model_type=conversation_model.ConversationModel.ModelType.SMART_REPLY_DUAL_ENCODER_MODEL), - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - pb_return_value = conversation_model.ConversationModel.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.get_conversation_model(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, conversation_model.ConversationModel) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.state == conversation_model.ConversationModel.State.CREATING - assert response.language_code == 'language_code_value' - - -def test_get_conversation_model_rest_required_fields(request_type=conversation_model.GetConversationModelRequest): - transport_class = transports.ConversationModelsRestTransport - - request_init = {} - request_init["name"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - including_default_value_fields=False, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_conversation_model._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["name"] = 'name_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_conversation_model._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "name" in jsonified_request - assert jsonified_request["name"] == 'name_value' - - client = ConversationModelsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = conversation_model.ConversationModel() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "get", - 'query_params': pb_request, - } - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - - pb_return_value = conversation_model.ConversationModel.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.get_conversation_model(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_get_conversation_model_rest_unset_required_fields(): - transport = transports.ConversationModelsRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.get_conversation_model._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_get_conversation_model_rest_interceptors(null_interceptor): - transport = transports.ConversationModelsRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.ConversationModelsRestInterceptor(), - ) - client = ConversationModelsClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.ConversationModelsRestInterceptor, "post_get_conversation_model") as post, \ - mock.patch.object(transports.ConversationModelsRestInterceptor, "pre_get_conversation_model") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = conversation_model.GetConversationModelRequest.pb(conversation_model.GetConversationModelRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = conversation_model.ConversationModel.to_json(conversation_model.ConversationModel()) - - request = conversation_model.GetConversationModelRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = conversation_model.ConversationModel() - - client.get_conversation_model(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_get_conversation_model_rest_bad_request(transport: str = 'rest', request_type=conversation_model.GetConversationModelRequest): - client = ConversationModelsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/conversationModels/sample2'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.get_conversation_model(request) - - -def test_get_conversation_model_rest_flattened(): - client = ConversationModelsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = conversation_model.ConversationModel() - - # get arguments that satisfy an http rule for this method - sample_request = {'name': 'projects/sample1/conversationModels/sample2'} - - # get truthy value for each flattened field - mock_args = dict( - name='name_value', - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - pb_return_value = conversation_model.ConversationModel.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.get_conversation_model(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v2/{name=projects/*/conversationModels/*}" % client.transport._host, args[1]) - - -def test_get_conversation_model_rest_flattened_error(transport: str = 'rest'): - client = ConversationModelsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.get_conversation_model( - conversation_model.GetConversationModelRequest(), - name='name_value', - ) - - -def test_get_conversation_model_rest_error(): - client = ConversationModelsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - conversation_model.ListConversationModelsRequest, - dict, -]) -def test_list_conversation_models_rest(request_type): - client = ConversationModelsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = conversation_model.ListConversationModelsResponse( - next_page_token='next_page_token_value', - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - pb_return_value = conversation_model.ListConversationModelsResponse.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.list_conversation_models(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListConversationModelsPager) - assert response.next_page_token == 'next_page_token_value' - - -def test_list_conversation_models_rest_required_fields(request_type=conversation_model.ListConversationModelsRequest): - transport_class = transports.ConversationModelsRestTransport - - request_init = {} - request_init["parent"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - including_default_value_fields=False, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).list_conversation_models._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["parent"] = 'parent_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).list_conversation_models._get_unset_required_fields(jsonified_request) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("page_size", "page_token", )) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "parent" in jsonified_request - assert jsonified_request["parent"] == 'parent_value' - - client = ConversationModelsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = conversation_model.ListConversationModelsResponse() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "get", - 'query_params': pb_request, - } - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - - pb_return_value = conversation_model.ListConversationModelsResponse.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.list_conversation_models(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_list_conversation_models_rest_unset_required_fields(): - transport = transports.ConversationModelsRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.list_conversation_models._get_unset_required_fields({}) - assert set(unset_fields) == (set(("pageSize", "pageToken", )) & set(("parent", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_list_conversation_models_rest_interceptors(null_interceptor): - transport = transports.ConversationModelsRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.ConversationModelsRestInterceptor(), - ) - client = ConversationModelsClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.ConversationModelsRestInterceptor, "post_list_conversation_models") as post, \ - mock.patch.object(transports.ConversationModelsRestInterceptor, "pre_list_conversation_models") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = conversation_model.ListConversationModelsRequest.pb(conversation_model.ListConversationModelsRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = conversation_model.ListConversationModelsResponse.to_json(conversation_model.ListConversationModelsResponse()) - - request = conversation_model.ListConversationModelsRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = conversation_model.ListConversationModelsResponse() - - client.list_conversation_models(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_list_conversation_models_rest_bad_request(transport: str = 'rest', request_type=conversation_model.ListConversationModelsRequest): - client = ConversationModelsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.list_conversation_models(request) - - -def test_list_conversation_models_rest_flattened(): - client = ConversationModelsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = conversation_model.ListConversationModelsResponse() - - # get arguments that satisfy an http rule for this method - sample_request = {'parent': 'projects/sample1'} - - # get truthy value for each flattened field - mock_args = dict( - parent='parent_value', - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - pb_return_value = conversation_model.ListConversationModelsResponse.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.list_conversation_models(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v2/{parent=projects/*}/conversationModels" % client.transport._host, args[1]) - - -def test_list_conversation_models_rest_flattened_error(transport: str = 'rest'): - client = ConversationModelsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.list_conversation_models( - conversation_model.ListConversationModelsRequest(), - parent='parent_value', - ) - - -def test_list_conversation_models_rest_pager(transport: str = 'rest'): - client = ConversationModelsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # TODO(kbandes): remove this mock unless there's a good reason for it. - #with mock.patch.object(path_template, 'transcode') as transcode: - # Set the response as a series of pages - response = ( - conversation_model.ListConversationModelsResponse( - conversation_models=[ - conversation_model.ConversationModel(), - conversation_model.ConversationModel(), - conversation_model.ConversationModel(), - ], - next_page_token='abc', - ), - conversation_model.ListConversationModelsResponse( - conversation_models=[], - next_page_token='def', - ), - conversation_model.ListConversationModelsResponse( - conversation_models=[ - conversation_model.ConversationModel(), - ], - next_page_token='ghi', - ), - conversation_model.ListConversationModelsResponse( - conversation_models=[ - conversation_model.ConversationModel(), - conversation_model.ConversationModel(), - ], - ), - ) - # Two responses for two calls - response = response + response - - # Wrap the values into proper Response objs - response = tuple(conversation_model.ListConversationModelsResponse.to_json(x) for x in response) - return_values = tuple(Response() for i in response) - for return_val, response_val in zip(return_values, response): - return_val._content = response_val.encode('UTF-8') - return_val.status_code = 200 - req.side_effect = return_values - - sample_request = {'parent': 'projects/sample1'} - - pager = client.list_conversation_models(request=sample_request) - - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, conversation_model.ConversationModel) - for i in results) - - pages = list(client.list_conversation_models(request=sample_request).pages) - for page_, token in zip(pages, ['abc','def','ghi', '']): - assert page_.raw_page.next_page_token == token - - -@pytest.mark.parametrize("request_type", [ - conversation_model.DeleteConversationModelRequest, - dict, -]) -def test_delete_conversation_model_rest(request_type): - client = ConversationModelsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/conversationModels/sample2'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name='operations/spam') - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.delete_conversation_model(request) - - # Establish that the response is the type that we expect. - assert response.operation.name == "operations/spam" - - -def test_delete_conversation_model_rest_required_fields(request_type=conversation_model.DeleteConversationModelRequest): - transport_class = transports.ConversationModelsRestTransport - - request_init = {} - request_init["name"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - including_default_value_fields=False, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).delete_conversation_model._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["name"] = 'name_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).delete_conversation_model._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "name" in jsonified_request - assert jsonified_request["name"] == 'name_value' - - client = ConversationModelsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name='operations/spam') - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "delete", - 'query_params': pb_request, - } - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.delete_conversation_model(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_delete_conversation_model_rest_unset_required_fields(): - transport = transports.ConversationModelsRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.delete_conversation_model._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_delete_conversation_model_rest_interceptors(null_interceptor): - transport = transports.ConversationModelsRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.ConversationModelsRestInterceptor(), - ) - client = ConversationModelsClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(operation.Operation, "_set_result_from_operation"), \ - mock.patch.object(transports.ConversationModelsRestInterceptor, "post_delete_conversation_model") as post, \ - mock.patch.object(transports.ConversationModelsRestInterceptor, "pre_delete_conversation_model") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = conversation_model.DeleteConversationModelRequest.pb(conversation_model.DeleteConversationModelRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = json_format.MessageToJson(operations_pb2.Operation()) - - request = conversation_model.DeleteConversationModelRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = operations_pb2.Operation() - - client.delete_conversation_model(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_delete_conversation_model_rest_bad_request(transport: str = 'rest', request_type=conversation_model.DeleteConversationModelRequest): - client = ConversationModelsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/conversationModels/sample2'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.delete_conversation_model(request) - - -def test_delete_conversation_model_rest_flattened(): - client = ConversationModelsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name='operations/spam') - - # get arguments that satisfy an http rule for this method - sample_request = {'name': 'projects/sample1/conversationModels/sample2'} - - # get truthy value for each flattened field - mock_args = dict( - name='name_value', - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.delete_conversation_model(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v2/{name=projects/*/conversationModels/*}" % client.transport._host, args[1]) - - -def test_delete_conversation_model_rest_flattened_error(transport: str = 'rest'): - client = ConversationModelsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.delete_conversation_model( - conversation_model.DeleteConversationModelRequest(), - name='name_value', - ) - - -def test_delete_conversation_model_rest_error(): - client = ConversationModelsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - conversation_model.DeployConversationModelRequest, - dict, -]) -def test_deploy_conversation_model_rest(request_type): - client = ConversationModelsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/conversationModels/sample2'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name='operations/spam') - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.deploy_conversation_model(request) - - # Establish that the response is the type that we expect. - assert response.operation.name == "operations/spam" - - -def test_deploy_conversation_model_rest_required_fields(request_type=conversation_model.DeployConversationModelRequest): - transport_class = transports.ConversationModelsRestTransport - - request_init = {} - request_init["name"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - including_default_value_fields=False, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).deploy_conversation_model._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["name"] = 'name_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).deploy_conversation_model._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "name" in jsonified_request - assert jsonified_request["name"] == 'name_value' - - client = ConversationModelsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name='operations/spam') - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "post", - 'query_params': pb_request, - } - transcode_result['body'] = pb_request - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.deploy_conversation_model(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_deploy_conversation_model_rest_unset_required_fields(): - transport = transports.ConversationModelsRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.deploy_conversation_model._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_deploy_conversation_model_rest_interceptors(null_interceptor): - transport = transports.ConversationModelsRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.ConversationModelsRestInterceptor(), - ) - client = ConversationModelsClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(operation.Operation, "_set_result_from_operation"), \ - mock.patch.object(transports.ConversationModelsRestInterceptor, "post_deploy_conversation_model") as post, \ - mock.patch.object(transports.ConversationModelsRestInterceptor, "pre_deploy_conversation_model") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = conversation_model.DeployConversationModelRequest.pb(conversation_model.DeployConversationModelRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = json_format.MessageToJson(operations_pb2.Operation()) - - request = conversation_model.DeployConversationModelRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = operations_pb2.Operation() - - client.deploy_conversation_model(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_deploy_conversation_model_rest_bad_request(transport: str = 'rest', request_type=conversation_model.DeployConversationModelRequest): - client = ConversationModelsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/conversationModels/sample2'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.deploy_conversation_model(request) - - -def test_deploy_conversation_model_rest_error(): - client = ConversationModelsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - conversation_model.UndeployConversationModelRequest, - dict, -]) -def test_undeploy_conversation_model_rest(request_type): - client = ConversationModelsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/conversationModels/sample2'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name='operations/spam') - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.undeploy_conversation_model(request) - - # Establish that the response is the type that we expect. - assert response.operation.name == "operations/spam" - - -def test_undeploy_conversation_model_rest_required_fields(request_type=conversation_model.UndeployConversationModelRequest): - transport_class = transports.ConversationModelsRestTransport - - request_init = {} - request_init["name"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - including_default_value_fields=False, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).undeploy_conversation_model._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["name"] = 'name_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).undeploy_conversation_model._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "name" in jsonified_request - assert jsonified_request["name"] == 'name_value' - - client = ConversationModelsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name='operations/spam') - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "post", - 'query_params': pb_request, - } - transcode_result['body'] = pb_request - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.undeploy_conversation_model(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_undeploy_conversation_model_rest_unset_required_fields(): - transport = transports.ConversationModelsRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.undeploy_conversation_model._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_undeploy_conversation_model_rest_interceptors(null_interceptor): - transport = transports.ConversationModelsRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.ConversationModelsRestInterceptor(), - ) - client = ConversationModelsClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(operation.Operation, "_set_result_from_operation"), \ - mock.patch.object(transports.ConversationModelsRestInterceptor, "post_undeploy_conversation_model") as post, \ - mock.patch.object(transports.ConversationModelsRestInterceptor, "pre_undeploy_conversation_model") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = conversation_model.UndeployConversationModelRequest.pb(conversation_model.UndeployConversationModelRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = json_format.MessageToJson(operations_pb2.Operation()) - - request = conversation_model.UndeployConversationModelRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = operations_pb2.Operation() - - client.undeploy_conversation_model(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_undeploy_conversation_model_rest_bad_request(transport: str = 'rest', request_type=conversation_model.UndeployConversationModelRequest): - client = ConversationModelsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/conversationModels/sample2'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.undeploy_conversation_model(request) - - -def test_undeploy_conversation_model_rest_error(): - client = ConversationModelsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - conversation_model.GetConversationModelEvaluationRequest, - dict, -]) -def test_get_conversation_model_evaluation_rest(request_type): - client = ConversationModelsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/conversationModels/sample2/evaluations/sample3'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = conversation_model.ConversationModelEvaluation( - name='name_value', - display_name='display_name_value', - raw_human_eval_template_csv='raw_human_eval_template_csv_value', - smart_reply_metrics=conversation_model.SmartReplyMetrics(allowlist_coverage=0.19260000000000002), - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - pb_return_value = conversation_model.ConversationModelEvaluation.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.get_conversation_model_evaluation(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, conversation_model.ConversationModelEvaluation) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.raw_human_eval_template_csv == 'raw_human_eval_template_csv_value' - - -def test_get_conversation_model_evaluation_rest_required_fields(request_type=conversation_model.GetConversationModelEvaluationRequest): - transport_class = transports.ConversationModelsRestTransport - - request_init = {} - request_init["name"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - including_default_value_fields=False, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_conversation_model_evaluation._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["name"] = 'name_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_conversation_model_evaluation._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "name" in jsonified_request - assert jsonified_request["name"] == 'name_value' - - client = ConversationModelsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = conversation_model.ConversationModelEvaluation() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "get", - 'query_params': pb_request, - } - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - - pb_return_value = conversation_model.ConversationModelEvaluation.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.get_conversation_model_evaluation(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_get_conversation_model_evaluation_rest_unset_required_fields(): - transport = transports.ConversationModelsRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.get_conversation_model_evaluation._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_get_conversation_model_evaluation_rest_interceptors(null_interceptor): - transport = transports.ConversationModelsRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.ConversationModelsRestInterceptor(), - ) - client = ConversationModelsClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.ConversationModelsRestInterceptor, "post_get_conversation_model_evaluation") as post, \ - mock.patch.object(transports.ConversationModelsRestInterceptor, "pre_get_conversation_model_evaluation") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = conversation_model.GetConversationModelEvaluationRequest.pb(conversation_model.GetConversationModelEvaluationRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = conversation_model.ConversationModelEvaluation.to_json(conversation_model.ConversationModelEvaluation()) - - request = conversation_model.GetConversationModelEvaluationRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = conversation_model.ConversationModelEvaluation() - - client.get_conversation_model_evaluation(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_get_conversation_model_evaluation_rest_bad_request(transport: str = 'rest', request_type=conversation_model.GetConversationModelEvaluationRequest): - client = ConversationModelsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/conversationModels/sample2/evaluations/sample3'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.get_conversation_model_evaluation(request) - - -def test_get_conversation_model_evaluation_rest_flattened(): - client = ConversationModelsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = conversation_model.ConversationModelEvaluation() - - # get arguments that satisfy an http rule for this method - sample_request = {'name': 'projects/sample1/conversationModels/sample2/evaluations/sample3'} - - # get truthy value for each flattened field - mock_args = dict( - name='name_value', - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - pb_return_value = conversation_model.ConversationModelEvaluation.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.get_conversation_model_evaluation(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v2/{name=projects/*/conversationModels/*/evaluations/*}" % client.transport._host, args[1]) - - -def test_get_conversation_model_evaluation_rest_flattened_error(transport: str = 'rest'): - client = ConversationModelsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.get_conversation_model_evaluation( - conversation_model.GetConversationModelEvaluationRequest(), - name='name_value', - ) - - -def test_get_conversation_model_evaluation_rest_error(): - client = ConversationModelsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - conversation_model.ListConversationModelEvaluationsRequest, - dict, -]) -def test_list_conversation_model_evaluations_rest(request_type): - client = ConversationModelsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1/conversationModels/sample2'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = conversation_model.ListConversationModelEvaluationsResponse( - next_page_token='next_page_token_value', - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - pb_return_value = conversation_model.ListConversationModelEvaluationsResponse.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.list_conversation_model_evaluations(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListConversationModelEvaluationsPager) - assert response.next_page_token == 'next_page_token_value' - - -def test_list_conversation_model_evaluations_rest_required_fields(request_type=conversation_model.ListConversationModelEvaluationsRequest): - transport_class = transports.ConversationModelsRestTransport - - request_init = {} - request_init["parent"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - including_default_value_fields=False, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).list_conversation_model_evaluations._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["parent"] = 'parent_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).list_conversation_model_evaluations._get_unset_required_fields(jsonified_request) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("page_size", "page_token", )) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "parent" in jsonified_request - assert jsonified_request["parent"] == 'parent_value' - - client = ConversationModelsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = conversation_model.ListConversationModelEvaluationsResponse() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "get", - 'query_params': pb_request, - } - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - - pb_return_value = conversation_model.ListConversationModelEvaluationsResponse.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.list_conversation_model_evaluations(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_list_conversation_model_evaluations_rest_unset_required_fields(): - transport = transports.ConversationModelsRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.list_conversation_model_evaluations._get_unset_required_fields({}) - assert set(unset_fields) == (set(("pageSize", "pageToken", )) & set(("parent", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_list_conversation_model_evaluations_rest_interceptors(null_interceptor): - transport = transports.ConversationModelsRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.ConversationModelsRestInterceptor(), - ) - client = ConversationModelsClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.ConversationModelsRestInterceptor, "post_list_conversation_model_evaluations") as post, \ - mock.patch.object(transports.ConversationModelsRestInterceptor, "pre_list_conversation_model_evaluations") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = conversation_model.ListConversationModelEvaluationsRequest.pb(conversation_model.ListConversationModelEvaluationsRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = conversation_model.ListConversationModelEvaluationsResponse.to_json(conversation_model.ListConversationModelEvaluationsResponse()) - - request = conversation_model.ListConversationModelEvaluationsRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = conversation_model.ListConversationModelEvaluationsResponse() - - client.list_conversation_model_evaluations(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_list_conversation_model_evaluations_rest_bad_request(transport: str = 'rest', request_type=conversation_model.ListConversationModelEvaluationsRequest): - client = ConversationModelsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1/conversationModels/sample2'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.list_conversation_model_evaluations(request) - - -def test_list_conversation_model_evaluations_rest_flattened(): - client = ConversationModelsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = conversation_model.ListConversationModelEvaluationsResponse() - - # get arguments that satisfy an http rule for this method - sample_request = {'parent': 'projects/sample1/conversationModels/sample2'} - - # get truthy value for each flattened field - mock_args = dict( - parent='parent_value', - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - pb_return_value = conversation_model.ListConversationModelEvaluationsResponse.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.list_conversation_model_evaluations(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v2/{parent=projects/*/conversationModels/*}/evaluations" % client.transport._host, args[1]) - - -def test_list_conversation_model_evaluations_rest_flattened_error(transport: str = 'rest'): - client = ConversationModelsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.list_conversation_model_evaluations( - conversation_model.ListConversationModelEvaluationsRequest(), - parent='parent_value', - ) - - -def test_list_conversation_model_evaluations_rest_pager(transport: str = 'rest'): - client = ConversationModelsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # TODO(kbandes): remove this mock unless there's a good reason for it. - #with mock.patch.object(path_template, 'transcode') as transcode: - # Set the response as a series of pages - response = ( - conversation_model.ListConversationModelEvaluationsResponse( - conversation_model_evaluations=[ - conversation_model.ConversationModelEvaluation(), - conversation_model.ConversationModelEvaluation(), - conversation_model.ConversationModelEvaluation(), - ], - next_page_token='abc', - ), - conversation_model.ListConversationModelEvaluationsResponse( - conversation_model_evaluations=[], - next_page_token='def', - ), - conversation_model.ListConversationModelEvaluationsResponse( - conversation_model_evaluations=[ - conversation_model.ConversationModelEvaluation(), - ], - next_page_token='ghi', - ), - conversation_model.ListConversationModelEvaluationsResponse( - conversation_model_evaluations=[ - conversation_model.ConversationModelEvaluation(), - conversation_model.ConversationModelEvaluation(), - ], - ), - ) - # Two responses for two calls - response = response + response - - # Wrap the values into proper Response objs - response = tuple(conversation_model.ListConversationModelEvaluationsResponse.to_json(x) for x in response) - return_values = tuple(Response() for i in response) - for return_val, response_val in zip(return_values, response): - return_val._content = response_val.encode('UTF-8') - return_val.status_code = 200 - req.side_effect = return_values - - sample_request = {'parent': 'projects/sample1/conversationModels/sample2'} - - pager = client.list_conversation_model_evaluations(request=sample_request) - - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, conversation_model.ConversationModelEvaluation) - for i in results) - - pages = list(client.list_conversation_model_evaluations(request=sample_request).pages) - for page_, token in zip(pages, ['abc','def','ghi', '']): - assert page_.raw_page.next_page_token == token - - -@pytest.mark.parametrize("request_type", [ - conversation_model.CreateConversationModelEvaluationRequest, - dict, -]) -def test_create_conversation_model_evaluation_rest(request_type): - client = ConversationModelsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1/locations/sample2/conversationModels/sample3'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name='operations/spam') - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.create_conversation_model_evaluation(request) - - # Establish that the response is the type that we expect. - assert response.operation.name == "operations/spam" - - -def test_create_conversation_model_evaluation_rest_required_fields(request_type=conversation_model.CreateConversationModelEvaluationRequest): - transport_class = transports.ConversationModelsRestTransport - - request_init = {} - request_init["parent"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - including_default_value_fields=False, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_conversation_model_evaluation._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["parent"] = 'parent_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_conversation_model_evaluation._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "parent" in jsonified_request - assert jsonified_request["parent"] == 'parent_value' - - client = ConversationModelsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name='operations/spam') - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "post", - 'query_params': pb_request, - } - transcode_result['body'] = pb_request - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.create_conversation_model_evaluation(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_create_conversation_model_evaluation_rest_unset_required_fields(): - transport = transports.ConversationModelsRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.create_conversation_model_evaluation._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("parent", "conversationModelEvaluation", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_create_conversation_model_evaluation_rest_interceptors(null_interceptor): - transport = transports.ConversationModelsRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.ConversationModelsRestInterceptor(), - ) - client = ConversationModelsClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(operation.Operation, "_set_result_from_operation"), \ - mock.patch.object(transports.ConversationModelsRestInterceptor, "post_create_conversation_model_evaluation") as post, \ - mock.patch.object(transports.ConversationModelsRestInterceptor, "pre_create_conversation_model_evaluation") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = conversation_model.CreateConversationModelEvaluationRequest.pb(conversation_model.CreateConversationModelEvaluationRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = json_format.MessageToJson(operations_pb2.Operation()) - - request = conversation_model.CreateConversationModelEvaluationRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = operations_pb2.Operation() - - client.create_conversation_model_evaluation(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_create_conversation_model_evaluation_rest_bad_request(transport: str = 'rest', request_type=conversation_model.CreateConversationModelEvaluationRequest): - client = ConversationModelsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1/locations/sample2/conversationModels/sample3'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.create_conversation_model_evaluation(request) - - -def test_create_conversation_model_evaluation_rest_flattened(): - client = ConversationModelsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name='operations/spam') - - # get arguments that satisfy an http rule for this method - sample_request = {'parent': 'projects/sample1/locations/sample2/conversationModels/sample3'} - - # get truthy value for each flattened field - mock_args = dict( - parent='parent_value', - conversation_model_evaluation=conversation_model.ConversationModelEvaluation(name='name_value'), - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.create_conversation_model_evaluation(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v2/{parent=projects/*/locations/*/conversationModels/*}/evaluations" % client.transport._host, args[1]) - - -def test_create_conversation_model_evaluation_rest_flattened_error(transport: str = 'rest'): - client = ConversationModelsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.create_conversation_model_evaluation( - conversation_model.CreateConversationModelEvaluationRequest(), - parent='parent_value', - conversation_model_evaluation=conversation_model.ConversationModelEvaluation(name='name_value'), - ) - - -def test_create_conversation_model_evaluation_rest_error(): - client = ConversationModelsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -def test_credentials_transport_error(): - # It is an error to provide credentials and a transport instance. - transport = transports.ConversationModelsGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = ConversationModelsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # It is an error to provide a credentials file and a transport instance. - transport = transports.ConversationModelsGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = ConversationModelsClient( - client_options={"credentials_file": "credentials.json"}, - transport=transport, - ) - - # It is an error to provide an api_key and a transport instance. - transport = transports.ConversationModelsGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - options = client_options.ClientOptions() - options.api_key = "api_key" - with pytest.raises(ValueError): - client = ConversationModelsClient( - client_options=options, - transport=transport, - ) - - # It is an error to provide an api_key and a credential. - options = mock.Mock() - options.api_key = "api_key" - with pytest.raises(ValueError): - client = ConversationModelsClient( - client_options=options, - credentials=ga_credentials.AnonymousCredentials() - ) - - # It is an error to provide scopes and a transport instance. - transport = transports.ConversationModelsGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = ConversationModelsClient( - client_options={"scopes": ["1", "2"]}, - transport=transport, - ) - - -def test_transport_instance(): - # A client may be instantiated with a custom transport instance. - transport = transports.ConversationModelsGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - client = ConversationModelsClient(transport=transport) - assert client.transport is transport - -def test_transport_get_channel(): - # A client may be instantiated with a custom transport instance. - transport = transports.ConversationModelsGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - - transport = transports.ConversationModelsGrpcAsyncIOTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - -@pytest.mark.parametrize("transport_class", [ - transports.ConversationModelsGrpcTransport, - transports.ConversationModelsGrpcAsyncIOTransport, - transports.ConversationModelsRestTransport, -]) -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() - -@pytest.mark.parametrize("transport_name", [ - "grpc", - "rest", -]) -def test_transport_kind(transport_name): - transport = ConversationModelsClient.get_transport_class(transport_name)( - credentials=ga_credentials.AnonymousCredentials(), - ) - assert transport.kind == transport_name - -def test_transport_grpc_default(): - # A client should use the gRPC transport by default. - client = ConversationModelsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - assert isinstance( - client.transport, - transports.ConversationModelsGrpcTransport, - ) - -def test_conversation_models_base_transport_error(): - # Passing both a credentials object and credentials_file should raise an error - with pytest.raises(core_exceptions.DuplicateCredentialArgs): - transport = transports.ConversationModelsTransport( - credentials=ga_credentials.AnonymousCredentials(), - credentials_file="credentials.json" - ) - - -def test_conversation_models_base_transport(): - # Instantiate the base transport. - with mock.patch('google.cloud.dialogflow_v2.services.conversation_models.transports.ConversationModelsTransport.__init__') as Transport: - Transport.return_value = None - transport = transports.ConversationModelsTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Every method on the transport should just blindly - # raise NotImplementedError. - methods = ( - 'create_conversation_model', - 'get_conversation_model', - 'list_conversation_models', - 'delete_conversation_model', - 'deploy_conversation_model', - 'undeploy_conversation_model', - 'get_conversation_model_evaluation', - 'list_conversation_model_evaluations', - 'create_conversation_model_evaluation', - 'get_location', - 'list_locations', - 'get_operation', - 'cancel_operation', - 'list_operations', - ) - for method in methods: - with pytest.raises(NotImplementedError): - getattr(transport, method)(request=object()) - - with pytest.raises(NotImplementedError): - transport.close() - - # Additionally, the LRO client (a property) should - # also raise NotImplementedError - with pytest.raises(NotImplementedError): - transport.operations_client - - # Catch all for all remaining methods and properties - remainder = [ - 'kind', - ] - for r in remainder: - with pytest.raises(NotImplementedError): - getattr(transport, r)() - - -def test_conversation_models_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.conversation_models.transports.ConversationModelsTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.ConversationModelsTransport( - credentials_file="credentials.json", - quota_project_id="octopus", - ) - load_creds.assert_called_once_with("credentials.json", - scopes=None, - default_scopes=( - 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/dialogflow', -), - quota_project_id="octopus", - ) - - -def test_conversation_models_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.conversation_models.transports.ConversationModelsTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.ConversationModelsTransport() - adc.assert_called_once() - - -def test_conversation_models_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) - ConversationModelsClient() - adc.assert_called_once_with( - scopes=None, - default_scopes=( - 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/dialogflow', -), - quota_project_id=None, - ) - - -@pytest.mark.parametrize( - "transport_class", - [ - transports.ConversationModelsGrpcTransport, - transports.ConversationModelsGrpcAsyncIOTransport, - ], -) -def test_conversation_models_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.ConversationModelsGrpcTransport, - transports.ConversationModelsGrpcAsyncIOTransport, - transports.ConversationModelsRestTransport, - ], -) -def test_conversation_models_transport_auth_gdch_credentials(transport_class): - host = 'https://language.com' - api_audience_tests = [None, 'https://language2.com'] - api_audience_expect = [host, 'https://language2.com'] - for t, e in zip(api_audience_tests, api_audience_expect): - with mock.patch.object(google.auth, 'default', autospec=True) as adc: - gdch_mock = mock.MagicMock() - type(gdch_mock).with_gdch_audience = mock.PropertyMock(return_value=gdch_mock) - adc.return_value = (gdch_mock, None) - transport_class(host=host, api_audience=t) - gdch_mock.with_gdch_audience.assert_called_once_with( - e - ) - - -@pytest.mark.parametrize( - "transport_class,grpc_helpers", - [ - (transports.ConversationModelsGrpcTransport, grpc_helpers), - (transports.ConversationModelsGrpcAsyncIOTransport, grpc_helpers_async) - ], -) -def test_conversation_models_transport_create_channel(transport_class, grpc_helpers): - # If credentials and host are not provided, the transport class should use - # ADC credentials. - with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch.object( - grpc_helpers, "create_channel", autospec=True - ) as create_channel: - creds = ga_credentials.AnonymousCredentials() - adc.return_value = (creds, None) - transport_class( - quota_project_id="octopus", - scopes=["1", "2"] - ) - - create_channel.assert_called_with( - "dialogflow.googleapis.com:443", - credentials=creds, - credentials_file=None, - quota_project_id="octopus", - default_scopes=( - 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/dialogflow', -), - scopes=["1", "2"], - default_host="dialogflow.googleapis.com", - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - -@pytest.mark.parametrize("transport_class", [transports.ConversationModelsGrpcTransport, transports.ConversationModelsGrpcAsyncIOTransport]) -def test_conversation_models_grpc_transport_client_cert_source_for_mtls( - transport_class -): - cred = ga_credentials.AnonymousCredentials() - - # Check ssl_channel_credentials is used if provided. - with mock.patch.object(transport_class, "create_channel") as mock_create_channel: - mock_ssl_channel_creds = mock.Mock() - transport_class( - host="squid.clam.whelk", - credentials=cred, - ssl_channel_credentials=mock_ssl_channel_creds - ) - mock_create_channel.assert_called_once_with( - "squid.clam.whelk:443", - credentials=cred, - credentials_file=None, - scopes=None, - ssl_credentials=mock_ssl_channel_creds, - quota_project_id=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - # Check if ssl_channel_credentials is not provided, then client_cert_source_for_mtls - # is used. - with mock.patch.object(transport_class, "create_channel", return_value=mock.Mock()): - with mock.patch("grpc.ssl_channel_credentials") as mock_ssl_cred: - transport_class( - credentials=cred, - client_cert_source_for_mtls=client_cert_source_callback - ) - expected_cert, expected_key = client_cert_source_callback() - mock_ssl_cred.assert_called_once_with( - certificate_chain=expected_cert, - private_key=expected_key - ) - -def test_conversation_models_http_transport_client_cert_source_for_mtls(): - cred = ga_credentials.AnonymousCredentials() - with mock.patch("google.auth.transport.requests.AuthorizedSession.configure_mtls_channel") as mock_configure_mtls_channel: - transports.ConversationModelsRestTransport ( - credentials=cred, - client_cert_source_for_mtls=client_cert_source_callback - ) - mock_configure_mtls_channel.assert_called_once_with(client_cert_source_callback) - - -def test_conversation_models_rest_lro_client(): - client = ConversationModelsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - transport = client.transport - - # Ensure that we have a api-core operations client. - assert isinstance( - transport.operations_client, - operations_v1.AbstractOperationsClient, - ) - - # Ensure that subsequent calls to the property send the exact same object. - assert transport.operations_client is transport.operations_client - - -@pytest.mark.parametrize("transport_name", [ - "grpc", - "grpc_asyncio", - "rest", -]) -def test_conversation_models_host_no_port(transport_name): - client = ConversationModelsClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='dialogflow.googleapis.com'), - transport=transport_name, - ) - assert client.transport._host == ( - 'dialogflow.googleapis.com:443' - if transport_name in ['grpc', 'grpc_asyncio'] - else 'https://dialogflow.googleapis.com' - ) - -@pytest.mark.parametrize("transport_name", [ - "grpc", - "grpc_asyncio", - "rest", -]) -def test_conversation_models_host_with_port(transport_name): - client = ConversationModelsClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='dialogflow.googleapis.com:8000'), - transport=transport_name, - ) - assert client.transport._host == ( - 'dialogflow.googleapis.com:8000' - if transport_name in ['grpc', 'grpc_asyncio'] - else 'https://dialogflow.googleapis.com:8000' - ) - -@pytest.mark.parametrize("transport_name", [ - "rest", -]) -def test_conversation_models_client_transport_session_collision(transport_name): - creds1 = ga_credentials.AnonymousCredentials() - creds2 = ga_credentials.AnonymousCredentials() - client1 = ConversationModelsClient( - credentials=creds1, - transport=transport_name, - ) - client2 = ConversationModelsClient( - credentials=creds2, - transport=transport_name, - ) - session1 = client1.transport.create_conversation_model._session - session2 = client2.transport.create_conversation_model._session - assert session1 != session2 - session1 = client1.transport.get_conversation_model._session - session2 = client2.transport.get_conversation_model._session - assert session1 != session2 - session1 = client1.transport.list_conversation_models._session - session2 = client2.transport.list_conversation_models._session - assert session1 != session2 - session1 = client1.transport.delete_conversation_model._session - session2 = client2.transport.delete_conversation_model._session - assert session1 != session2 - session1 = client1.transport.deploy_conversation_model._session - session2 = client2.transport.deploy_conversation_model._session - assert session1 != session2 - session1 = client1.transport.undeploy_conversation_model._session - session2 = client2.transport.undeploy_conversation_model._session - assert session1 != session2 - session1 = client1.transport.get_conversation_model_evaluation._session - session2 = client2.transport.get_conversation_model_evaluation._session - assert session1 != session2 - session1 = client1.transport.list_conversation_model_evaluations._session - session2 = client2.transport.list_conversation_model_evaluations._session - assert session1 != session2 - session1 = client1.transport.create_conversation_model_evaluation._session - session2 = client2.transport.create_conversation_model_evaluation._session - assert session1 != session2 -def test_conversation_models_grpc_transport_channel(): - channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.ConversationModelsGrpcTransport( - 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_conversation_models_grpc_asyncio_transport_channel(): - channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.ConversationModelsGrpcAsyncIOTransport( - 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.ConversationModelsGrpcTransport, transports.ConversationModelsGrpcAsyncIOTransport]) -def test_conversation_models_transport_channel_mtls_with_client_cert_source( - transport_class -): - with mock.patch("grpc.ssl_channel_credentials", autospec=True) as grpc_ssl_channel_cred: - with mock.patch.object(transport_class, "create_channel") as grpc_create_channel: - mock_ssl_cred = mock.Mock() - grpc_ssl_channel_cred.return_value = mock_ssl_cred - - mock_grpc_channel = mock.Mock() - grpc_create_channel.return_value = mock_grpc_channel - - cred = ga_credentials.AnonymousCredentials() - with pytest.warns(DeprecationWarning): - with mock.patch.object(google.auth, 'default') as adc: - adc.return_value = (cred, None) - transport = transport_class( - host="squid.clam.whelk", - api_mtls_endpoint="mtls.squid.clam.whelk", - client_cert_source=client_cert_source_callback, - ) - adc.assert_called_once() - - grpc_ssl_channel_cred.assert_called_once_with( - certificate_chain=b"cert bytes", private_key=b"key bytes" - ) - grpc_create_channel.assert_called_once_with( - "mtls.squid.clam.whelk:443", - credentials=cred, - credentials_file=None, - scopes=None, - ssl_credentials=mock_ssl_cred, - quota_project_id=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - assert transport.grpc_channel == mock_grpc_channel - assert transport._ssl_channel_credentials == mock_ssl_cred - - -# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are -# removed from grpc/grpc_asyncio transport constructor. -@pytest.mark.parametrize("transport_class", [transports.ConversationModelsGrpcTransport, transports.ConversationModelsGrpcAsyncIOTransport]) -def test_conversation_models_transport_channel_mtls_with_adc( - transport_class -): - mock_ssl_cred = mock.Mock() - with mock.patch.multiple( - "google.auth.transport.grpc.SslCredentials", - __init__=mock.Mock(return_value=None), - ssl_credentials=mock.PropertyMock(return_value=mock_ssl_cred), - ): - with mock.patch.object(transport_class, "create_channel") as grpc_create_channel: - mock_grpc_channel = mock.Mock() - grpc_create_channel.return_value = mock_grpc_channel - mock_cred = mock.Mock() - - with pytest.warns(DeprecationWarning): - transport = transport_class( - host="squid.clam.whelk", - credentials=mock_cred, - api_mtls_endpoint="mtls.squid.clam.whelk", - client_cert_source=None, - ) - - grpc_create_channel.assert_called_once_with( - "mtls.squid.clam.whelk:443", - credentials=mock_cred, - credentials_file=None, - scopes=None, - ssl_credentials=mock_ssl_cred, - quota_project_id=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - assert transport.grpc_channel == mock_grpc_channel - - -def test_conversation_models_grpc_lro_client(): - client = ConversationModelsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - transport = client.transport - - # Ensure that we have a api-core operations client. - assert isinstance( - transport.operations_client, - operations_v1.OperationsClient, - ) - - # Ensure that subsequent calls to the property send the exact same object. - assert transport.operations_client is transport.operations_client - - -def test_conversation_models_grpc_lro_async_client(): - client = ConversationModelsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc_asyncio', - ) - transport = client.transport - - # Ensure that we have a api-core operations client. - assert isinstance( - transport.operations_client, - operations_v1.OperationsAsyncClient, - ) - - # Ensure that subsequent calls to the property send the exact same object. - assert transport.operations_client is transport.operations_client - - -def test_conversation_dataset_path(): - project = "squid" - location = "clam" - conversation_dataset = "whelk" - expected = "projects/{project}/locations/{location}/conversationDatasets/{conversation_dataset}".format(project=project, location=location, conversation_dataset=conversation_dataset, ) - actual = ConversationModelsClient.conversation_dataset_path(project, location, conversation_dataset) - assert expected == actual - - -def test_parse_conversation_dataset_path(): - expected = { - "project": "octopus", - "location": "oyster", - "conversation_dataset": "nudibranch", - } - path = ConversationModelsClient.conversation_dataset_path(**expected) - - # Check that the path construction is reversible. - actual = ConversationModelsClient.parse_conversation_dataset_path(path) - assert expected == actual - -def test_conversation_model_path(): - project = "cuttlefish" - location = "mussel" - conversation_model = "winkle" - expected = "projects/{project}/locations/{location}/conversationModels/{conversation_model}".format(project=project, location=location, conversation_model=conversation_model, ) - actual = ConversationModelsClient.conversation_model_path(project, location, conversation_model) - assert expected == actual - - -def test_parse_conversation_model_path(): - expected = { - "project": "nautilus", - "location": "scallop", - "conversation_model": "abalone", - } - path = ConversationModelsClient.conversation_model_path(**expected) - - # Check that the path construction is reversible. - actual = ConversationModelsClient.parse_conversation_model_path(path) - assert expected == actual - -def test_conversation_model_evaluation_path(): - project = "squid" - conversation_model = "clam" - evaluation = "whelk" - expected = "projects/{project}/conversationModels/{conversation_model}/evaluations/{evaluation}".format(project=project, conversation_model=conversation_model, evaluation=evaluation, ) - actual = ConversationModelsClient.conversation_model_evaluation_path(project, conversation_model, evaluation) - assert expected == actual - - -def test_parse_conversation_model_evaluation_path(): - expected = { - "project": "octopus", - "conversation_model": "oyster", - "evaluation": "nudibranch", - } - path = ConversationModelsClient.conversation_model_evaluation_path(**expected) - - # Check that the path construction is reversible. - actual = ConversationModelsClient.parse_conversation_model_evaluation_path(path) - assert expected == actual - -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, ) - actual = ConversationModelsClient.document_path(project, knowledge_base, document) - assert expected == actual - - -def test_parse_document_path(): - expected = { - "project": "nautilus", - "knowledge_base": "scallop", - "document": "abalone", - } - path = ConversationModelsClient.document_path(**expected) - - # Check that the path construction is reversible. - actual = ConversationModelsClient.parse_document_path(path) - assert expected == actual - -def test_common_billing_account_path(): - billing_account = "squid" - expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) - actual = ConversationModelsClient.common_billing_account_path(billing_account) - assert expected == actual - - -def test_parse_common_billing_account_path(): - expected = { - "billing_account": "clam", - } - path = ConversationModelsClient.common_billing_account_path(**expected) - - # Check that the path construction is reversible. - actual = ConversationModelsClient.parse_common_billing_account_path(path) - assert expected == actual - -def test_common_folder_path(): - folder = "whelk" - expected = "folders/{folder}".format(folder=folder, ) - actual = ConversationModelsClient.common_folder_path(folder) - assert expected == actual - - -def test_parse_common_folder_path(): - expected = { - "folder": "octopus", - } - path = ConversationModelsClient.common_folder_path(**expected) - - # Check that the path construction is reversible. - actual = ConversationModelsClient.parse_common_folder_path(path) - assert expected == actual - -def test_common_organization_path(): - organization = "oyster" - expected = "organizations/{organization}".format(organization=organization, ) - actual = ConversationModelsClient.common_organization_path(organization) - assert expected == actual - - -def test_parse_common_organization_path(): - expected = { - "organization": "nudibranch", - } - path = ConversationModelsClient.common_organization_path(**expected) - - # Check that the path construction is reversible. - actual = ConversationModelsClient.parse_common_organization_path(path) - assert expected == actual - -def test_common_project_path(): - project = "cuttlefish" - expected = "projects/{project}".format(project=project, ) - actual = ConversationModelsClient.common_project_path(project) - assert expected == actual - - -def test_parse_common_project_path(): - expected = { - "project": "mussel", - } - path = ConversationModelsClient.common_project_path(**expected) - - # Check that the path construction is reversible. - actual = ConversationModelsClient.parse_common_project_path(path) - assert expected == actual - -def test_common_location_path(): - project = "winkle" - location = "nautilus" - expected = "projects/{project}/locations/{location}".format(project=project, location=location, ) - actual = ConversationModelsClient.common_location_path(project, location) - assert expected == actual - - -def test_parse_common_location_path(): - expected = { - "project": "scallop", - "location": "abalone", - } - path = ConversationModelsClient.common_location_path(**expected) - - # Check that the path construction is reversible. - actual = ConversationModelsClient.parse_common_location_path(path) - assert expected == actual - - -def test_client_with_default_client_info(): - client_info = gapic_v1.client_info.ClientInfo() - - with mock.patch.object(transports.ConversationModelsTransport, '_prep_wrapped_messages') as prep: - client = ConversationModelsClient( - credentials=ga_credentials.AnonymousCredentials(), - client_info=client_info, - ) - prep.assert_called_once_with(client_info) - - with mock.patch.object(transports.ConversationModelsTransport, '_prep_wrapped_messages') as prep: - transport_class = ConversationModelsClient.get_transport_class() - transport = transport_class( - credentials=ga_credentials.AnonymousCredentials(), - client_info=client_info, - ) - prep.assert_called_once_with(client_info) - -@pytest.mark.asyncio -async def test_transport_close_async(): - client = ConversationModelsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - with mock.patch.object(type(getattr(client.transport, "grpc_channel")), "close") as close: - async with client: - close.assert_not_called() - close.assert_called_once() - - -def test_get_location_rest_bad_request(transport: str = 'rest', request_type=locations_pb2.GetLocationRequest): - client = ConversationModelsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - request = request_type() - request = json_format.ParseDict({'name': 'projects/sample1/locations/sample2'}, request) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.get_location(request) - -@pytest.mark.parametrize("request_type", [ - locations_pb2.GetLocationRequest, - dict, -]) -def test_get_location_rest(request_type): - client = ConversationModelsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request_init = {'name': 'projects/sample1/locations/sample2'} - request = request_type(**request_init) - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = locations_pb2.Location() - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.get_location(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, locations_pb2.Location) - -def test_list_locations_rest_bad_request(transport: str = 'rest', request_type=locations_pb2.ListLocationsRequest): - client = ConversationModelsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - request = request_type() - request = json_format.ParseDict({'name': 'projects/sample1'}, request) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.list_locations(request) - -@pytest.mark.parametrize("request_type", [ - locations_pb2.ListLocationsRequest, - dict, -]) -def test_list_locations_rest(request_type): - client = ConversationModelsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request_init = {'name': 'projects/sample1'} - request = request_type(**request_init) - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = locations_pb2.ListLocationsResponse() - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.list_locations(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, locations_pb2.ListLocationsResponse) - -def test_cancel_operation_rest_bad_request(transport: str = 'rest', request_type=operations_pb2.CancelOperationRequest): - client = ConversationModelsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - request = request_type() - request = json_format.ParseDict({'name': 'projects/sample1/operations/sample2'}, request) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.cancel_operation(request) - -@pytest.mark.parametrize("request_type", [ - operations_pb2.CancelOperationRequest, - dict, -]) -def test_cancel_operation_rest(request_type): - client = ConversationModelsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request_init = {'name': 'projects/sample1/operations/sample2'} - request = request_type(**request_init) - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = None - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = '{}' - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.cancel_operation(request) - - # Establish that the response is the type that we expect. - assert response is None - -def test_get_operation_rest_bad_request(transport: str = 'rest', request_type=operations_pb2.GetOperationRequest): - client = ConversationModelsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - request = request_type() - request = json_format.ParseDict({'name': 'projects/sample1/operations/sample2'}, request) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.get_operation(request) - -@pytest.mark.parametrize("request_type", [ - operations_pb2.GetOperationRequest, - dict, -]) -def test_get_operation_rest(request_type): - client = ConversationModelsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request_init = {'name': 'projects/sample1/operations/sample2'} - request = request_type(**request_init) - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation() - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.get_operation(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, operations_pb2.Operation) - -def test_list_operations_rest_bad_request(transport: str = 'rest', request_type=operations_pb2.ListOperationsRequest): - client = ConversationModelsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - request = request_type() - request = json_format.ParseDict({'name': 'projects/sample1'}, request) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.list_operations(request) - -@pytest.mark.parametrize("request_type", [ - operations_pb2.ListOperationsRequest, - dict, -]) -def test_list_operations_rest(request_type): - client = ConversationModelsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request_init = {'name': 'projects/sample1'} - request = request_type(**request_init) - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = operations_pb2.ListOperationsResponse() - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.list_operations(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, operations_pb2.ListOperationsResponse) - - -def test_cancel_operation(transport: str = "grpc"): - client = ConversationModelsClient( - 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 = operations_pb2.CancelOperationRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = None - response = client.cancel_operation(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 response is the type that we expect. - assert response is None -@pytest.mark.asyncio -async def test_cancel_operation_async(transport: str = "grpc"): - client = ConversationModelsAsyncClient( - 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 = operations_pb2.CancelOperationRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - None - ) - response = await client.cancel_operation(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 response is the type that we expect. - assert response is None - -def test_cancel_operation_field_headers(): - client = ConversationModelsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = operations_pb2.CancelOperationRequest() - request.name = "locations" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call: - call.return_value = None - - client.cancel_operation(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=locations",) in kw["metadata"] -@pytest.mark.asyncio -async def test_cancel_operation_field_headers_async(): - client = ConversationModelsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = operations_pb2.CancelOperationRequest() - request.name = "locations" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - None - ) - await client.cancel_operation(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=locations",) in kw["metadata"] - -def test_cancel_operation_from_dict(): - client = ConversationModelsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = None - - response = client.cancel_operation( - request={ - "name": "locations", - } - ) - call.assert_called() -@pytest.mark.asyncio -async def test_cancel_operation_from_dict_async(): - client = ConversationModelsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - None - ) - response = await client.cancel_operation( - request={ - "name": "locations", - } - ) - call.assert_called() - - -def test_get_operation(transport: str = "grpc"): - client = ConversationModelsClient( - 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 = operations_pb2.GetOperationRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_operation), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation() - response = client.get_operation(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 response is the type that we expect. - assert isinstance(response, operations_pb2.Operation) -@pytest.mark.asyncio -async def test_get_operation_async(transport: str = "grpc"): - client = ConversationModelsAsyncClient( - 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 = operations_pb2.GetOperationRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_operation), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation() - ) - response = await client.get_operation(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 response is the type that we expect. - assert isinstance(response, operations_pb2.Operation) - -def test_get_operation_field_headers(): - client = ConversationModelsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = operations_pb2.GetOperationRequest() - request.name = "locations" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_operation), "__call__") as call: - call.return_value = operations_pb2.Operation() - - client.get_operation(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=locations",) in kw["metadata"] -@pytest.mark.asyncio -async def test_get_operation_field_headers_async(): - client = ConversationModelsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = operations_pb2.GetOperationRequest() - request.name = "locations" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_operation), "__call__") as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation() - ) - await client.get_operation(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=locations",) in kw["metadata"] - -def test_get_operation_from_dict(): - client = ConversationModelsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_operation), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation() - - response = client.get_operation( - request={ - "name": "locations", - } - ) - call.assert_called() -@pytest.mark.asyncio -async def test_get_operation_from_dict_async(): - client = ConversationModelsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_operation), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation() - ) - response = await client.get_operation( - request={ - "name": "locations", - } - ) - call.assert_called() - - -def test_list_operations(transport: str = "grpc"): - client = ConversationModelsClient( - 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 = operations_pb2.ListOperationsRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_operations), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.ListOperationsResponse() - response = client.list_operations(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 response is the type that we expect. - assert isinstance(response, operations_pb2.ListOperationsResponse) -@pytest.mark.asyncio -async def test_list_operations_async(transport: str = "grpc"): - client = ConversationModelsAsyncClient( - 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 = operations_pb2.ListOperationsRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_operations), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.ListOperationsResponse() - ) - response = await client.list_operations(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 response is the type that we expect. - assert isinstance(response, operations_pb2.ListOperationsResponse) - -def test_list_operations_field_headers(): - client = ConversationModelsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = operations_pb2.ListOperationsRequest() - request.name = "locations" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_operations), "__call__") as call: - call.return_value = operations_pb2.ListOperationsResponse() - - client.list_operations(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=locations",) in kw["metadata"] -@pytest.mark.asyncio -async def test_list_operations_field_headers_async(): - client = ConversationModelsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = operations_pb2.ListOperationsRequest() - request.name = "locations" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_operations), "__call__") as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.ListOperationsResponse() - ) - await client.list_operations(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=locations",) in kw["metadata"] - -def test_list_operations_from_dict(): - client = ConversationModelsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_operations), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.ListOperationsResponse() - - response = client.list_operations( - request={ - "name": "locations", - } - ) - call.assert_called() -@pytest.mark.asyncio -async def test_list_operations_from_dict_async(): - client = ConversationModelsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_operations), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.ListOperationsResponse() - ) - response = await client.list_operations( - request={ - "name": "locations", - } - ) - call.assert_called() - - -def test_list_locations(transport: str = "grpc"): - client = ConversationModelsClient( - 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 = locations_pb2.ListLocationsRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_locations), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = locations_pb2.ListLocationsResponse() - response = client.list_locations(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 response is the type that we expect. - assert isinstance(response, locations_pb2.ListLocationsResponse) -@pytest.mark.asyncio -async def test_list_locations_async(transport: str = "grpc"): - client = ConversationModelsAsyncClient( - 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 = locations_pb2.ListLocationsRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_locations), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - locations_pb2.ListLocationsResponse() - ) - response = await client.list_locations(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 response is the type that we expect. - assert isinstance(response, locations_pb2.ListLocationsResponse) - -def test_list_locations_field_headers(): - client = ConversationModelsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = locations_pb2.ListLocationsRequest() - request.name = "locations" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_locations), "__call__") as call: - call.return_value = locations_pb2.ListLocationsResponse() - - client.list_locations(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=locations",) in kw["metadata"] -@pytest.mark.asyncio -async def test_list_locations_field_headers_async(): - client = ConversationModelsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = locations_pb2.ListLocationsRequest() - request.name = "locations" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_locations), "__call__") as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - locations_pb2.ListLocationsResponse() - ) - await client.list_locations(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=locations",) in kw["metadata"] - -def test_list_locations_from_dict(): - client = ConversationModelsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_locations), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = locations_pb2.ListLocationsResponse() - - response = client.list_locations( - request={ - "name": "locations", - } - ) - call.assert_called() -@pytest.mark.asyncio -async def test_list_locations_from_dict_async(): - client = ConversationModelsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_locations), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - locations_pb2.ListLocationsResponse() - ) - response = await client.list_locations( - request={ - "name": "locations", - } - ) - call.assert_called() - - -def test_get_location(transport: str = "grpc"): - client = ConversationModelsClient( - 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 = locations_pb2.GetLocationRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_location), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = locations_pb2.Location() - response = client.get_location(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 response is the type that we expect. - assert isinstance(response, locations_pb2.Location) -@pytest.mark.asyncio -async def test_get_location_async(transport: str = "grpc_asyncio"): - client = ConversationModelsAsyncClient( - 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 = locations_pb2.GetLocationRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_location), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - locations_pb2.Location() - ) - response = await client.get_location(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 response is the type that we expect. - assert isinstance(response, locations_pb2.Location) - -def test_get_location_field_headers(): - client = ConversationModelsClient( - credentials=ga_credentials.AnonymousCredentials()) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = locations_pb2.GetLocationRequest() - request.name = "locations/abc" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_location), "__call__") as call: - call.return_value = locations_pb2.Location() - - client.get_location(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=locations/abc",) in kw["metadata"] -@pytest.mark.asyncio -async def test_get_location_field_headers_async(): - client = ConversationModelsAsyncClient( - credentials=ga_credentials.AnonymousCredentials() - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = locations_pb2.GetLocationRequest() - request.name = "locations/abc" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_location), "__call__") as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - locations_pb2.Location() - ) - await client.get_location(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=locations/abc",) in kw["metadata"] - -def test_get_location_from_dict(): - client = ConversationModelsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_locations), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = locations_pb2.Location() - - response = client.get_location( - request={ - "name": "locations/abc", - } - ) - call.assert_called() -@pytest.mark.asyncio -async def test_get_location_from_dict_async(): - client = ConversationModelsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_locations), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - locations_pb2.Location() - ) - response = await client.get_location( - request={ - "name": "locations", - } - ) - call.assert_called() - - -def test_transport_close(): - transports = { - "rest": "_session", - "grpc": "_grpc_channel", - } - - for transport, close_name in transports.items(): - client = ConversationModelsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport - ) - with mock.patch.object(type(getattr(client.transport, close_name)), "close") as close: - with client: - close.assert_not_called() - close.assert_called_once() - -def test_client_ctx(): - transports = [ - 'rest', - 'grpc', - ] - for transport in transports: - client = ConversationModelsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport - ) - # Test client calls underlying transport. - with mock.patch.object(type(client.transport), "close") as close: - close.assert_not_called() - with client: - pass - close.assert_called() - -@pytest.mark.parametrize("client_class,transport_class", [ - (ConversationModelsClient, transports.ConversationModelsGrpcTransport), - (ConversationModelsAsyncClient, transports.ConversationModelsGrpcAsyncIOTransport), -]) -def test_api_key_credentials(client_class, transport_class): - with mock.patch.object( - google.auth._default, "get_api_key_credentials", create=True - ) as get_api_key_credentials: - mock_cred = mock.Mock() - get_api_key_credentials.return_value = mock_cred - options = client_options.ClientOptions() - options.api_key = "api_key" - 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=mock_cred, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) diff --git a/owl-bot-staging/v2/tests/unit/gapic/dialogflow_v2/test_conversation_profiles.py b/owl-bot-staging/v2/tests/unit/gapic/dialogflow_v2/test_conversation_profiles.py deleted file mode 100644 index 62a056319..000000000 --- a/owl-bot-staging/v2/tests/unit/gapic/dialogflow_v2/test_conversation_profiles.py +++ /dev/null @@ -1,5910 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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 -# try/except added for compatibility with python < 3.8 -try: - from unittest import mock - from unittest.mock import AsyncMock # pragma: NO COVER -except ImportError: # pragma: NO COVER - import mock - -import grpc -from grpc.experimental import aio -from collections.abc import Iterable -from google.protobuf import json_format -import json -import math -import pytest -from proto.marshal.rules.dates import DurationRule, TimestampRule -from proto.marshal.rules import wrappers -from requests import Response -from requests import Request, PreparedRequest -from requests.sessions import Session -from google.protobuf import json_format - -from google.api_core import client_options -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 -from google.api_core import operation_async # type: ignore -from google.api_core import operations_v1 -from google.api_core import path_template -from google.auth import credentials as ga_credentials -from google.auth.exceptions import MutualTLSChannelError -from google.cloud.dialogflow_v2.services.conversation_profiles import ConversationProfilesAsyncClient -from google.cloud.dialogflow_v2.services.conversation_profiles import ConversationProfilesClient -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.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.cloud.dialogflow_v2.types import participant -from google.cloud.location import locations_pb2 -from google.longrunning import operations_pb2 -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 - - -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 ConversationProfilesClient._get_default_mtls_endpoint(None) is None - assert ConversationProfilesClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint - assert ConversationProfilesClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint - assert ConversationProfilesClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint - assert ConversationProfilesClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint - assert ConversationProfilesClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi - - -@pytest.mark.parametrize("client_class,transport_name", [ - (ConversationProfilesClient, "grpc"), - (ConversationProfilesAsyncClient, "grpc_asyncio"), - (ConversationProfilesClient, "rest"), -]) -def test_conversation_profiles_client_from_service_account_info(client_class, transport_name): - 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, transport=transport_name) - assert client.transport._credentials == creds - assert isinstance(client, client_class) - - assert client.transport._host == ( - 'dialogflow.googleapis.com:443' - if transport_name in ['grpc', 'grpc_asyncio'] - else - 'https://dialogflow.googleapis.com' - ) - - -@pytest.mark.parametrize("transport_class,transport_name", [ - (transports.ConversationProfilesGrpcTransport, "grpc"), - (transports.ConversationProfilesGrpcAsyncIOTransport, "grpc_asyncio"), - (transports.ConversationProfilesRestTransport, "rest"), -]) -def test_conversation_profiles_client_service_account_always_use_jwt(transport_class, transport_name): - with mock.patch.object(service_account.Credentials, 'with_always_use_jwt_access', create=True) as use_jwt: - creds = service_account.Credentials(None, None, None) - transport = transport_class(credentials=creds, always_use_jwt_access=True) - use_jwt.assert_called_once_with(True) - - with mock.patch.object(service_account.Credentials, 'with_always_use_jwt_access', create=True) as use_jwt: - creds = service_account.Credentials(None, None, None) - transport = transport_class(credentials=creds, always_use_jwt_access=False) - use_jwt.assert_not_called() - - -@pytest.mark.parametrize("client_class,transport_name", [ - (ConversationProfilesClient, "grpc"), - (ConversationProfilesAsyncClient, "grpc_asyncio"), - (ConversationProfilesClient, "rest"), -]) -def test_conversation_profiles_client_from_service_account_file(client_class, transport_name): - 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", transport=transport_name) - assert client.transport._credentials == creds - assert isinstance(client, client_class) - - client = client_class.from_service_account_json("dummy/file/path.json", transport=transport_name) - assert client.transport._credentials == creds - assert isinstance(client, client_class) - - assert client.transport._host == ( - 'dialogflow.googleapis.com:443' - if transport_name in ['grpc', 'grpc_asyncio'] - else - 'https://dialogflow.googleapis.com' - ) - - -def test_conversation_profiles_client_get_transport_class(): - transport = ConversationProfilesClient.get_transport_class() - available_transports = [ - transports.ConversationProfilesGrpcTransport, - transports.ConversationProfilesRestTransport, - ] - assert transport in available_transports - - transport = ConversationProfilesClient.get_transport_class("grpc") - assert transport == transports.ConversationProfilesGrpcTransport - - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (ConversationProfilesClient, transports.ConversationProfilesGrpcTransport, "grpc"), - (ConversationProfilesAsyncClient, transports.ConversationProfilesGrpcAsyncIOTransport, "grpc_asyncio"), - (ConversationProfilesClient, transports.ConversationProfilesRestTransport, "rest"), -]) -@mock.patch.object(ConversationProfilesClient, "DEFAULT_ENDPOINT", modify_default_endpoint(ConversationProfilesClient)) -@mock.patch.object(ConversationProfilesAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(ConversationProfilesAsyncClient)) -def test_conversation_profiles_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(ConversationProfilesClient, '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(ConversationProfilesClient, 'get_transport_class') as gtc: - client = client_class(transport=transport_name) - gtc.assert_called() - - # Check the case api_endpoint is provided. - options = client_options.ClientOptions(api_endpoint="squid.clam.whelk") - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(transport=transport_name, client_options=options) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host="squid.clam.whelk", - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is - # "never". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is - # "always". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_MTLS_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # 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(transport=transport_name) - - # 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(transport=transport_name) - - # 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, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id="octopus", - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - # Check the case api_endpoint is provided - options = client_options.ClientOptions(api_audience="https://language.googleapis.com") - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience="https://language.googleapis.com" - ) - -@pytest.mark.parametrize("client_class,transport_class,transport_name,use_client_cert_env", [ - (ConversationProfilesClient, transports.ConversationProfilesGrpcTransport, "grpc", "true"), - (ConversationProfilesAsyncClient, transports.ConversationProfilesGrpcAsyncIOTransport, "grpc_asyncio", "true"), - (ConversationProfilesClient, transports.ConversationProfilesGrpcTransport, "grpc", "false"), - (ConversationProfilesAsyncClient, transports.ConversationProfilesGrpcAsyncIOTransport, "grpc_asyncio", "false"), - (ConversationProfilesClient, transports.ConversationProfilesRestTransport, "rest", "true"), - (ConversationProfilesClient, transports.ConversationProfilesRestTransport, "rest", "false"), -]) -@mock.patch.object(ConversationProfilesClient, "DEFAULT_ENDPOINT", modify_default_endpoint(ConversationProfilesClient)) -@mock.patch.object(ConversationProfilesAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(ConversationProfilesAsyncClient)) -@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) -def test_conversation_profiles_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, transport=transport_name) - - if use_client_cert_env == "false": - expected_client_cert_source = None - expected_host = client.DEFAULT_ENDPOINT - else: - expected_client_cert_source = client_cert_source_callback - expected_host = client.DEFAULT_MTLS_ENDPOINT - - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=expected_host, - scopes=None, - client_cert_source_for_mtls=expected_client_cert_source, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case ADC client cert is provided. Whether client cert is used depends on - # GOOGLE_API_USE_CLIENT_CERTIFICATE value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): - with mock.patch.object(transport_class, '__init__') as patched: - with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): - with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=client_cert_source_callback): - if use_client_cert_env == "false": - expected_host = client.DEFAULT_ENDPOINT - expected_client_cert_source = None - else: - expected_host = client.DEFAULT_MTLS_ENDPOINT - expected_client_cert_source = client_cert_source_callback - - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=expected_host, - scopes=None, - client_cert_source_for_mtls=expected_client_cert_source, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case client_cert_source and ADC client cert are not provided. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): - with mock.patch.object(transport_class, '__init__') as patched: - with mock.patch("google.auth.transport.mtls.has_default_client_cert_source", return_value=False): - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - -@pytest.mark.parametrize("client_class", [ - ConversationProfilesClient, ConversationProfilesAsyncClient -]) -@mock.patch.object(ConversationProfilesClient, "DEFAULT_ENDPOINT", modify_default_endpoint(ConversationProfilesClient)) -@mock.patch.object(ConversationProfilesAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(ConversationProfilesAsyncClient)) -def test_conversation_profiles_client_get_mtls_endpoint_and_cert_source(client_class): - mock_client_cert_source = mock.Mock() - - # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "true". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - mock_api_endpoint = "foo" - options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) - assert api_endpoint == mock_api_endpoint - assert cert_source == mock_client_cert_source - - # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "false". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): - mock_client_cert_source = mock.Mock() - mock_api_endpoint = "foo" - options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) - assert api_endpoint == mock_api_endpoint - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "never". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_ENDPOINT - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "always". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert doesn't exist. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=False): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_ENDPOINT - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert exists. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - 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=mock_client_cert_source): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT - assert cert_source == mock_client_cert_source - - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (ConversationProfilesClient, transports.ConversationProfilesGrpcTransport, "grpc"), - (ConversationProfilesAsyncClient, transports.ConversationProfilesGrpcAsyncIOTransport, "grpc_asyncio"), - (ConversationProfilesClient, transports.ConversationProfilesRestTransport, "rest"), -]) -def test_conversation_profiles_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, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=["1", "2"], - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - -@pytest.mark.parametrize("client_class,transport_class,transport_name,grpc_helpers", [ - (ConversationProfilesClient, transports.ConversationProfilesGrpcTransport, "grpc", grpc_helpers), - (ConversationProfilesAsyncClient, transports.ConversationProfilesGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), - (ConversationProfilesClient, transports.ConversationProfilesRestTransport, "rest", None), -]) -def test_conversation_profiles_client_client_options_credentials_file(client_class, transport_class, transport_name, grpc_helpers): - # 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, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file="credentials.json", - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - -def test_conversation_profiles_client_client_options_from_dict(): - with mock.patch('google.cloud.dialogflow_v2.services.conversation_profiles.transports.ConversationProfilesGrpcTransport.__init__') as grpc_transport: - grpc_transport.return_value = None - client = ConversationProfilesClient( - client_options={'api_endpoint': 'squid.clam.whelk'} - ) - grpc_transport.assert_called_once_with( - credentials=None, - credentials_file=None, - host="squid.clam.whelk", - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - -@pytest.mark.parametrize("client_class,transport_class,transport_name,grpc_helpers", [ - (ConversationProfilesClient, transports.ConversationProfilesGrpcTransport, "grpc", grpc_helpers), - (ConversationProfilesAsyncClient, transports.ConversationProfilesGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), -]) -def test_conversation_profiles_client_create_channel_credentials_file(client_class, transport_class, transport_name, grpc_helpers): - # 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, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file="credentials.json", - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # test that the credentials from file are saved and used as the credentials. - with mock.patch.object( - google.auth, "load_credentials_from_file", autospec=True - ) as load_creds, mock.patch.object( - google.auth, "default", autospec=True - ) as adc, mock.patch.object( - grpc_helpers, "create_channel" - ) as create_channel: - creds = ga_credentials.AnonymousCredentials() - file_creds = ga_credentials.AnonymousCredentials() - load_creds.return_value = (file_creds, None) - adc.return_value = (creds, None) - client = client_class(client_options=options, transport=transport_name) - create_channel.assert_called_with( - "dialogflow.googleapis.com:443", - credentials=file_creds, - credentials_file=None, - quota_project_id=None, - default_scopes=( - 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/dialogflow', -), - scopes=None, - default_host="dialogflow.googleapis.com", - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - -@pytest.mark.parametrize("request_type", [ - conversation_profile.ListConversationProfilesRequest, - dict, -]) -def test_list_conversation_profiles(request_type, transport: str = 'grpc'): - client = ConversationProfilesClient( - 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_conversation_profiles), - '__call__') as call: - # Designate an appropriate return value for the call. - 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' - - -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=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_conversation_profiles), - '__call__') as call: - client.list_conversation_profiles() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == conversation_profile.ListConversationProfilesRequest() - -@pytest.mark.asyncio -async def test_list_conversation_profiles_async(transport: str = 'grpc_asyncio', request_type=conversation_profile.ListConversationProfilesRequest): - client = ConversationProfilesAsyncClient( - 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_conversation_profiles), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(conversation_profile.ListConversationProfilesResponse( - 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' - - -@pytest.mark.asyncio -async def test_list_conversation_profiles_async_from_dict(): - await test_list_conversation_profiles_async(request_type=dict) - - -def test_list_conversation_profiles_field_headers(): - 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. - with mock.patch.object( - 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. - 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_conversation_profiles_field_headers_async(): - client = ConversationProfilesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value 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. - with mock.patch.object( - type(client.transport.list_conversation_profiles), - '__call__') as call: - 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. - 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_conversation_profiles_flattened(): - client = ConversationProfilesClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_conversation_profiles), - '__call__') 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', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - arg = args[0].parent - mock_val = 'parent_value' - assert arg == mock_val - - -def test_list_conversation_profiles_flattened_error(): - client = ConversationProfilesClient( - 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_conversation_profiles( - conversation_profile.ListConversationProfilesRequest(), - parent='parent_value', - ) - -@pytest.mark.asyncio -async def test_list_conversation_profiles_flattened_async(): - client = ConversationProfilesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_conversation_profiles), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = conversation_profile.ListConversationProfilesResponse() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(conversation_profile.ListConversationProfilesResponse()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.list_conversation_profiles( - 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] - arg = args[0].parent - mock_val = 'parent_value' - assert arg == mock_val - -@pytest.mark.asyncio -async def test_list_conversation_profiles_flattened_error_async(): - client = ConversationProfilesAsyncClient( - 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_conversation_profiles( - conversation_profile.ListConversationProfilesRequest(), - parent='parent_value', - ) - - -def test_list_conversation_profiles_pager(transport_name: str = "grpc"): - client = ConversationProfilesClient( - credentials=ga_credentials.AnonymousCredentials, - transport=transport_name, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_conversation_profiles), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - conversation_profile.ListConversationProfilesResponse( - conversation_profiles=[ - conversation_profile.ConversationProfile(), - conversation_profile.ConversationProfile(), - conversation_profile.ConversationProfile(), - ], - next_page_token='abc', - ), - conversation_profile.ListConversationProfilesResponse( - conversation_profiles=[], - next_page_token='def', - ), - conversation_profile.ListConversationProfilesResponse( - conversation_profiles=[ - conversation_profile.ConversationProfile(), - ], - next_page_token='ghi', - ), - conversation_profile.ListConversationProfilesResponse( - conversation_profiles=[ - conversation_profile.ConversationProfile(), - conversation_profile.ConversationProfile(), - ], - ), - RuntimeError, - ) - - metadata = () - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ('parent', ''), - )), - ) - pager = client.list_conversation_profiles(request={}) - - assert pager._metadata == metadata - - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, conversation_profile.ConversationProfile) - for i in results) -def test_list_conversation_profiles_pages(transport_name: str = "grpc"): - client = ConversationProfilesClient( - credentials=ga_credentials.AnonymousCredentials, - transport=transport_name, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_conversation_profiles), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - conversation_profile.ListConversationProfilesResponse( - conversation_profiles=[ - conversation_profile.ConversationProfile(), - conversation_profile.ConversationProfile(), - conversation_profile.ConversationProfile(), - ], - next_page_token='abc', - ), - conversation_profile.ListConversationProfilesResponse( - conversation_profiles=[], - next_page_token='def', - ), - conversation_profile.ListConversationProfilesResponse( - conversation_profiles=[ - conversation_profile.ConversationProfile(), - ], - next_page_token='ghi', - ), - conversation_profile.ListConversationProfilesResponse( - conversation_profiles=[ - conversation_profile.ConversationProfile(), - conversation_profile.ConversationProfile(), - ], - ), - RuntimeError, - ) - pages = list(client.list_conversation_profiles(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_conversation_profiles_async_pager(): - client = ConversationProfilesAsyncClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_conversation_profiles), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - conversation_profile.ListConversationProfilesResponse( - conversation_profiles=[ - conversation_profile.ConversationProfile(), - conversation_profile.ConversationProfile(), - conversation_profile.ConversationProfile(), - ], - next_page_token='abc', - ), - conversation_profile.ListConversationProfilesResponse( - conversation_profiles=[], - next_page_token='def', - ), - conversation_profile.ListConversationProfilesResponse( - conversation_profiles=[ - conversation_profile.ConversationProfile(), - ], - next_page_token='ghi', - ), - conversation_profile.ListConversationProfilesResponse( - conversation_profiles=[ - conversation_profile.ConversationProfile(), - conversation_profile.ConversationProfile(), - ], - ), - RuntimeError, - ) - async_pager = await client.list_conversation_profiles(request={},) - assert async_pager.next_page_token == 'abc' - responses = [] - async for response in async_pager: # pragma: no branch - responses.append(response) - - assert len(responses) == 6 - assert all(isinstance(i, conversation_profile.ConversationProfile) - for i in responses) - - -@pytest.mark.asyncio -async def test_list_conversation_profiles_async_pages(): - client = ConversationProfilesAsyncClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_conversation_profiles), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - conversation_profile.ListConversationProfilesResponse( - conversation_profiles=[ - conversation_profile.ConversationProfile(), - conversation_profile.ConversationProfile(), - conversation_profile.ConversationProfile(), - ], - next_page_token='abc', - ), - conversation_profile.ListConversationProfilesResponse( - conversation_profiles=[], - next_page_token='def', - ), - conversation_profile.ListConversationProfilesResponse( - conversation_profiles=[ - conversation_profile.ConversationProfile(), - ], - next_page_token='ghi', - ), - conversation_profile.ListConversationProfilesResponse( - conversation_profiles=[ - conversation_profile.ConversationProfile(), - conversation_profile.ConversationProfile(), - ], - ), - RuntimeError, - ) - pages = [] - async for page_ in (await client.list_conversation_profiles(request={})).pages: # pragma: no branch - pages.append(page_) - for page_, token in zip(pages, ['abc','def','ghi', '']): - assert page_.raw_page.next_page_token == token - -@pytest.mark.parametrize("request_type", [ - conversation_profile.GetConversationProfileRequest, - dict, -]) -def test_get_conversation_profile(request_type, transport: str = 'grpc'): - client = ConversationProfilesClient( - 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_conversation_profile), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = conversation_profile.ConversationProfile( - name='name_value', - display_name='display_name_value', - language_code='language_code_value', - time_zone='time_zone_value', - security_settings='security_settings_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' - assert response.time_zone == 'time_zone_value' - assert response.security_settings == 'security_settings_value' - - -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=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_conversation_profile), - '__call__') as call: - client.get_conversation_profile() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == conversation_profile.GetConversationProfileRequest() - -@pytest.mark.asyncio -async def test_get_conversation_profile_async(transport: str = 'grpc_asyncio', request_type=conversation_profile.GetConversationProfileRequest): - client = ConversationProfilesAsyncClient( - 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_conversation_profile), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(conversation_profile.ConversationProfile( - name='name_value', - display_name='display_name_value', - language_code='language_code_value', - time_zone='time_zone_value', - security_settings='security_settings_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' - assert response.time_zone == 'time_zone_value' - assert response.security_settings == 'security_settings_value' - - -@pytest.mark.asyncio -async def test_get_conversation_profile_async_from_dict(): - await test_get_conversation_profile_async(request_type=dict) - - -def test_get_conversation_profile_field_headers(): - 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. - with mock.patch.object( - 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. - 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_conversation_profile_field_headers_async(): - client = ConversationProfilesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value 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. - with mock.patch.object( - type(client.transport.get_conversation_profile), - '__call__') as call: - 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. - 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_conversation_profile_flattened(): - client = ConversationProfilesClient( - 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_profile), - '__call__') 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', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - arg = args[0].name - mock_val = 'name_value' - assert arg == mock_val - - -def test_get_conversation_profile_flattened_error(): - client = ConversationProfilesClient( - 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_conversation_profile( - conversation_profile.GetConversationProfileRequest(), - name='name_value', - ) - -@pytest.mark.asyncio -async def test_get_conversation_profile_flattened_async(): - client = ConversationProfilesAsyncClient( - 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_profile), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = conversation_profile.ConversationProfile() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(conversation_profile.ConversationProfile()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.get_conversation_profile( - 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] - arg = args[0].name - mock_val = 'name_value' - assert arg == mock_val - -@pytest.mark.asyncio -async def test_get_conversation_profile_flattened_error_async(): - client = ConversationProfilesAsyncClient( - 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_conversation_profile( - conversation_profile.GetConversationProfileRequest(), - name='name_value', - ) - - -@pytest.mark.parametrize("request_type", [ - gcd_conversation_profile.CreateConversationProfileRequest, - dict, -]) -def test_create_conversation_profile(request_type, transport: str = 'grpc'): - client = ConversationProfilesClient( - 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_conversation_profile), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcd_conversation_profile.ConversationProfile( - name='name_value', - display_name='display_name_value', - language_code='language_code_value', - time_zone='time_zone_value', - security_settings='security_settings_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' - assert response.time_zone == 'time_zone_value' - assert response.security_settings == 'security_settings_value' - - -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=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_conversation_profile), - '__call__') as call: - client.create_conversation_profile() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == gcd_conversation_profile.CreateConversationProfileRequest() - -@pytest.mark.asyncio -async def test_create_conversation_profile_async(transport: str = 'grpc_asyncio', request_type=gcd_conversation_profile.CreateConversationProfileRequest): - client = ConversationProfilesAsyncClient( - 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_conversation_profile), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gcd_conversation_profile.ConversationProfile( - name='name_value', - display_name='display_name_value', - language_code='language_code_value', - time_zone='time_zone_value', - security_settings='security_settings_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' - assert response.time_zone == 'time_zone_value' - assert response.security_settings == 'security_settings_value' - - -@pytest.mark.asyncio -async def test_create_conversation_profile_async_from_dict(): - await test_create_conversation_profile_async(request_type=dict) - - -def test_create_conversation_profile_field_headers(): - 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. - with mock.patch.object( - 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. - 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_conversation_profile_field_headers_async(): - client = ConversationProfilesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value 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. - with mock.patch.object( - type(client.transport.create_conversation_profile), - '__call__') as call: - 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. - 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_conversation_profile_flattened(): - client = ConversationProfilesClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_conversation_profile), - '__call__') 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( - parent='parent_value', - conversation_profile=gcd_conversation_profile.ConversationProfile(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] - arg = args[0].parent - mock_val = 'parent_value' - assert arg == mock_val - arg = args[0].conversation_profile - mock_val = gcd_conversation_profile.ConversationProfile(name='name_value') - assert arg == mock_val - - -def test_create_conversation_profile_flattened_error(): - client = ConversationProfilesClient( - 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_conversation_profile( - gcd_conversation_profile.CreateConversationProfileRequest(), - parent='parent_value', - conversation_profile=gcd_conversation_profile.ConversationProfile(name='name_value'), - ) - -@pytest.mark.asyncio -async def test_create_conversation_profile_flattened_async(): - client = ConversationProfilesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_conversation_profile), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcd_conversation_profile.ConversationProfile() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcd_conversation_profile.ConversationProfile()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.create_conversation_profile( - parent='parent_value', - conversation_profile=gcd_conversation_profile.ConversationProfile(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] - arg = args[0].parent - mock_val = 'parent_value' - assert arg == mock_val - arg = args[0].conversation_profile - mock_val = gcd_conversation_profile.ConversationProfile(name='name_value') - assert arg == mock_val - -@pytest.mark.asyncio -async def test_create_conversation_profile_flattened_error_async(): - client = ConversationProfilesAsyncClient( - 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_conversation_profile( - gcd_conversation_profile.CreateConversationProfileRequest(), - parent='parent_value', - conversation_profile=gcd_conversation_profile.ConversationProfile(name='name_value'), - ) - - -@pytest.mark.parametrize("request_type", [ - gcd_conversation_profile.UpdateConversationProfileRequest, - dict, -]) -def test_update_conversation_profile(request_type, transport: str = 'grpc'): - client = ConversationProfilesClient( - 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_conversation_profile), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcd_conversation_profile.ConversationProfile( - name='name_value', - display_name='display_name_value', - language_code='language_code_value', - time_zone='time_zone_value', - security_settings='security_settings_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' - assert response.time_zone == 'time_zone_value' - assert response.security_settings == 'security_settings_value' - - -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=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_conversation_profile), - '__call__') as call: - client.update_conversation_profile() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == gcd_conversation_profile.UpdateConversationProfileRequest() - -@pytest.mark.asyncio -async def test_update_conversation_profile_async(transport: str = 'grpc_asyncio', request_type=gcd_conversation_profile.UpdateConversationProfileRequest): - client = ConversationProfilesAsyncClient( - 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_conversation_profile), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gcd_conversation_profile.ConversationProfile( - name='name_value', - display_name='display_name_value', - language_code='language_code_value', - time_zone='time_zone_value', - security_settings='security_settings_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' - assert response.time_zone == 'time_zone_value' - assert response.security_settings == 'security_settings_value' - - -@pytest.mark.asyncio -async def test_update_conversation_profile_async_from_dict(): - await test_update_conversation_profile_async(request_type=dict) - - -def test_update_conversation_profile_field_headers(): - 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 = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - 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. - 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', - 'conversation_profile.name=name_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_update_conversation_profile_field_headers_async(): - client = ConversationProfilesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value 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 = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_conversation_profile), - '__call__') as call: - 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. - 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', - 'conversation_profile.name=name_value', - ) in kw['metadata'] - - -def test_update_conversation_profile_flattened(): - client = ConversationProfilesClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_conversation_profile), - '__call__') 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_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] - arg = args[0].conversation_profile - mock_val = gcd_conversation_profile.ConversationProfile(name='name_value') - assert arg == mock_val - arg = args[0].update_mask - mock_val = field_mask_pb2.FieldMask(paths=['paths_value']) - assert arg == mock_val - - -def test_update_conversation_profile_flattened_error(): - client = ConversationProfilesClient( - 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_conversation_profile( - gcd_conversation_profile.UpdateConversationProfileRequest(), - conversation_profile=gcd_conversation_profile.ConversationProfile(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - -@pytest.mark.asyncio -async def test_update_conversation_profile_flattened_async(): - client = ConversationProfilesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_conversation_profile), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcd_conversation_profile.ConversationProfile() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcd_conversation_profile.ConversationProfile()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.update_conversation_profile( - conversation_profile=gcd_conversation_profile.ConversationProfile(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] - arg = args[0].conversation_profile - mock_val = gcd_conversation_profile.ConversationProfile(name='name_value') - assert arg == mock_val - arg = args[0].update_mask - mock_val = field_mask_pb2.FieldMask(paths=['paths_value']) - assert arg == mock_val - -@pytest.mark.asyncio -async def test_update_conversation_profile_flattened_error_async(): - client = ConversationProfilesAsyncClient( - 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_conversation_profile( - gcd_conversation_profile.UpdateConversationProfileRequest(), - conversation_profile=gcd_conversation_profile.ConversationProfile(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - - -@pytest.mark.parametrize("request_type", [ - conversation_profile.DeleteConversationProfileRequest, - dict, -]) -def test_delete_conversation_profile(request_type, transport: str = 'grpc'): - client = ConversationProfilesClient( - 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_conversation_profile), - '__call__') 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. - assert response is None - - -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=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_conversation_profile), - '__call__') as call: - client.delete_conversation_profile() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == conversation_profile.DeleteConversationProfileRequest() - -@pytest.mark.asyncio -async def test_delete_conversation_profile_async(transport: str = 'grpc_asyncio', request_type=conversation_profile.DeleteConversationProfileRequest): - client = ConversationProfilesAsyncClient( - 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_conversation_profile), - '__call__') 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. - assert response is None - - -@pytest.mark.asyncio -async def test_delete_conversation_profile_async_from_dict(): - await test_delete_conversation_profile_async(request_type=dict) - - -def test_delete_conversation_profile_field_headers(): - 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. - with mock.patch.object( - 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. - 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_conversation_profile_field_headers_async(): - client = ConversationProfilesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value 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. - with mock.patch.object( - 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. - 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_conversation_profile_flattened(): - client = ConversationProfilesClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_conversation_profile), - '__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_conversation_profile( - 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] - arg = args[0].name - mock_val = 'name_value' - assert arg == mock_val - - -def test_delete_conversation_profile_flattened_error(): - client = ConversationProfilesClient( - 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_conversation_profile( - conversation_profile.DeleteConversationProfileRequest(), - name='name_value', - ) - -@pytest.mark.asyncio -async def test_delete_conversation_profile_flattened_async(): - client = ConversationProfilesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_conversation_profile), - '__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_conversation_profile( - 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] - arg = args[0].name - mock_val = 'name_value' - assert arg == mock_val - -@pytest.mark.asyncio -async def test_delete_conversation_profile_flattened_error_async(): - client = ConversationProfilesAsyncClient( - 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_conversation_profile( - conversation_profile.DeleteConversationProfileRequest(), - name='name_value', - ) - - -@pytest.mark.parametrize("request_type", [ - gcd_conversation_profile.SetSuggestionFeatureConfigRequest, - dict, -]) -def test_set_suggestion_feature_config(request_type, transport: str = 'grpc'): - client = ConversationProfilesClient( - 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.set_suggestion_feature_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/spam') - response = client.set_suggestion_feature_config(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.SetSuggestionFeatureConfigRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -def test_set_suggestion_feature_config_empty_call(): - # 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=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.set_suggestion_feature_config), - '__call__') as call: - client.set_suggestion_feature_config() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == gcd_conversation_profile.SetSuggestionFeatureConfigRequest() - -@pytest.mark.asyncio -async def test_set_suggestion_feature_config_async(transport: str = 'grpc_asyncio', request_type=gcd_conversation_profile.SetSuggestionFeatureConfigRequest): - client = ConversationProfilesAsyncClient( - 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.set_suggestion_feature_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name='operations/spam') - ) - response = await client.set_suggestion_feature_config(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.SetSuggestionFeatureConfigRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -@pytest.mark.asyncio -async def test_set_suggestion_feature_config_async_from_dict(): - await test_set_suggestion_feature_config_async(request_type=dict) - - -def test_set_suggestion_feature_config_field_headers(): - 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.SetSuggestionFeatureConfigRequest() - - request.conversation_profile = 'conversation_profile_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.set_suggestion_feature_config), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') - client.set_suggestion_feature_config(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', - 'conversation_profile=conversation_profile_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_set_suggestion_feature_config_field_headers_async(): - client = ConversationProfilesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value 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.SetSuggestionFeatureConfigRequest() - - request.conversation_profile = 'conversation_profile_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.set_suggestion_feature_config), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) - await client.set_suggestion_feature_config(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', - 'conversation_profile=conversation_profile_value', - ) in kw['metadata'] - - -def test_set_suggestion_feature_config_flattened(): - client = ConversationProfilesClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.set_suggestion_feature_config), - '__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.set_suggestion_feature_config( - conversation_profile='conversation_profile_value', - participant_role=participant.Participant.Role.HUMAN_AGENT, - suggestion_feature_config=gcd_conversation_profile.HumanAgentAssistantConfig.SuggestionFeatureConfig(suggestion_feature=gcd_conversation_profile.SuggestionFeature(type_=gcd_conversation_profile.SuggestionFeature.Type.ARTICLE_SUGGESTION)), - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - arg = args[0].conversation_profile - mock_val = 'conversation_profile_value' - assert arg == mock_val - arg = args[0].participant_role - mock_val = participant.Participant.Role.HUMAN_AGENT - assert arg == mock_val - arg = args[0].suggestion_feature_config - mock_val = gcd_conversation_profile.HumanAgentAssistantConfig.SuggestionFeatureConfig(suggestion_feature=gcd_conversation_profile.SuggestionFeature(type_=gcd_conversation_profile.SuggestionFeature.Type.ARTICLE_SUGGESTION)) - assert arg == mock_val - - -def test_set_suggestion_feature_config_flattened_error(): - client = ConversationProfilesClient( - 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.set_suggestion_feature_config( - gcd_conversation_profile.SetSuggestionFeatureConfigRequest(), - conversation_profile='conversation_profile_value', - participant_role=participant.Participant.Role.HUMAN_AGENT, - suggestion_feature_config=gcd_conversation_profile.HumanAgentAssistantConfig.SuggestionFeatureConfig(suggestion_feature=gcd_conversation_profile.SuggestionFeature(type_=gcd_conversation_profile.SuggestionFeature.Type.ARTICLE_SUGGESTION)), - ) - -@pytest.mark.asyncio -async def test_set_suggestion_feature_config_flattened_async(): - client = ConversationProfilesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.set_suggestion_feature_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/op') - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name='operations/spam') - ) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.set_suggestion_feature_config( - conversation_profile='conversation_profile_value', - participant_role=participant.Participant.Role.HUMAN_AGENT, - suggestion_feature_config=gcd_conversation_profile.HumanAgentAssistantConfig.SuggestionFeatureConfig(suggestion_feature=gcd_conversation_profile.SuggestionFeature(type_=gcd_conversation_profile.SuggestionFeature.Type.ARTICLE_SUGGESTION)), - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - arg = args[0].conversation_profile - mock_val = 'conversation_profile_value' - assert arg == mock_val - arg = args[0].participant_role - mock_val = participant.Participant.Role.HUMAN_AGENT - assert arg == mock_val - arg = args[0].suggestion_feature_config - mock_val = gcd_conversation_profile.HumanAgentAssistantConfig.SuggestionFeatureConfig(suggestion_feature=gcd_conversation_profile.SuggestionFeature(type_=gcd_conversation_profile.SuggestionFeature.Type.ARTICLE_SUGGESTION)) - assert arg == mock_val - -@pytest.mark.asyncio -async def test_set_suggestion_feature_config_flattened_error_async(): - client = ConversationProfilesAsyncClient( - 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.set_suggestion_feature_config( - gcd_conversation_profile.SetSuggestionFeatureConfigRequest(), - conversation_profile='conversation_profile_value', - participant_role=participant.Participant.Role.HUMAN_AGENT, - suggestion_feature_config=gcd_conversation_profile.HumanAgentAssistantConfig.SuggestionFeatureConfig(suggestion_feature=gcd_conversation_profile.SuggestionFeature(type_=gcd_conversation_profile.SuggestionFeature.Type.ARTICLE_SUGGESTION)), - ) - - -@pytest.mark.parametrize("request_type", [ - gcd_conversation_profile.ClearSuggestionFeatureConfigRequest, - dict, -]) -def test_clear_suggestion_feature_config(request_type, transport: str = 'grpc'): - client = ConversationProfilesClient( - 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.clear_suggestion_feature_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/spam') - response = client.clear_suggestion_feature_config(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.ClearSuggestionFeatureConfigRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -def test_clear_suggestion_feature_config_empty_call(): - # 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=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.clear_suggestion_feature_config), - '__call__') as call: - client.clear_suggestion_feature_config() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == gcd_conversation_profile.ClearSuggestionFeatureConfigRequest() - -@pytest.mark.asyncio -async def test_clear_suggestion_feature_config_async(transport: str = 'grpc_asyncio', request_type=gcd_conversation_profile.ClearSuggestionFeatureConfigRequest): - client = ConversationProfilesAsyncClient( - 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.clear_suggestion_feature_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name='operations/spam') - ) - response = await client.clear_suggestion_feature_config(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.ClearSuggestionFeatureConfigRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -@pytest.mark.asyncio -async def test_clear_suggestion_feature_config_async_from_dict(): - await test_clear_suggestion_feature_config_async(request_type=dict) - - -def test_clear_suggestion_feature_config_field_headers(): - 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.ClearSuggestionFeatureConfigRequest() - - request.conversation_profile = 'conversation_profile_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.clear_suggestion_feature_config), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') - client.clear_suggestion_feature_config(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', - 'conversation_profile=conversation_profile_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_clear_suggestion_feature_config_field_headers_async(): - client = ConversationProfilesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value 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.ClearSuggestionFeatureConfigRequest() - - request.conversation_profile = 'conversation_profile_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.clear_suggestion_feature_config), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) - await client.clear_suggestion_feature_config(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', - 'conversation_profile=conversation_profile_value', - ) in kw['metadata'] - - -def test_clear_suggestion_feature_config_flattened(): - client = ConversationProfilesClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.clear_suggestion_feature_config), - '__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.clear_suggestion_feature_config( - conversation_profile='conversation_profile_value', - participant_role=participant.Participant.Role.HUMAN_AGENT, - suggestion_feature_type=gcd_conversation_profile.SuggestionFeature.Type.ARTICLE_SUGGESTION, - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - arg = args[0].conversation_profile - mock_val = 'conversation_profile_value' - assert arg == mock_val - arg = args[0].participant_role - mock_val = participant.Participant.Role.HUMAN_AGENT - assert arg == mock_val - arg = args[0].suggestion_feature_type - mock_val = gcd_conversation_profile.SuggestionFeature.Type.ARTICLE_SUGGESTION - assert arg == mock_val - - -def test_clear_suggestion_feature_config_flattened_error(): - client = ConversationProfilesClient( - 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.clear_suggestion_feature_config( - gcd_conversation_profile.ClearSuggestionFeatureConfigRequest(), - conversation_profile='conversation_profile_value', - participant_role=participant.Participant.Role.HUMAN_AGENT, - suggestion_feature_type=gcd_conversation_profile.SuggestionFeature.Type.ARTICLE_SUGGESTION, - ) - -@pytest.mark.asyncio -async def test_clear_suggestion_feature_config_flattened_async(): - client = ConversationProfilesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.clear_suggestion_feature_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/op') - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name='operations/spam') - ) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.clear_suggestion_feature_config( - conversation_profile='conversation_profile_value', - participant_role=participant.Participant.Role.HUMAN_AGENT, - suggestion_feature_type=gcd_conversation_profile.SuggestionFeature.Type.ARTICLE_SUGGESTION, - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - arg = args[0].conversation_profile - mock_val = 'conversation_profile_value' - assert arg == mock_val - arg = args[0].participant_role - mock_val = participant.Participant.Role.HUMAN_AGENT - assert arg == mock_val - arg = args[0].suggestion_feature_type - mock_val = gcd_conversation_profile.SuggestionFeature.Type.ARTICLE_SUGGESTION - assert arg == mock_val - -@pytest.mark.asyncio -async def test_clear_suggestion_feature_config_flattened_error_async(): - client = ConversationProfilesAsyncClient( - 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.clear_suggestion_feature_config( - gcd_conversation_profile.ClearSuggestionFeatureConfigRequest(), - conversation_profile='conversation_profile_value', - participant_role=participant.Participant.Role.HUMAN_AGENT, - suggestion_feature_type=gcd_conversation_profile.SuggestionFeature.Type.ARTICLE_SUGGESTION, - ) - - -@pytest.mark.parametrize("request_type", [ - conversation_profile.ListConversationProfilesRequest, - dict, -]) -def test_list_conversation_profiles_rest(request_type): - client = ConversationProfilesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = conversation_profile.ListConversationProfilesResponse( - next_page_token='next_page_token_value', - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - pb_return_value = conversation_profile.ListConversationProfilesResponse.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.list_conversation_profiles(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListConversationProfilesPager) - assert response.next_page_token == 'next_page_token_value' - - -def test_list_conversation_profiles_rest_required_fields(request_type=conversation_profile.ListConversationProfilesRequest): - transport_class = transports.ConversationProfilesRestTransport - - request_init = {} - request_init["parent"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - including_default_value_fields=False, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).list_conversation_profiles._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["parent"] = 'parent_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).list_conversation_profiles._get_unset_required_fields(jsonified_request) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("page_size", "page_token", )) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "parent" in jsonified_request - assert jsonified_request["parent"] == 'parent_value' - - client = ConversationProfilesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = conversation_profile.ListConversationProfilesResponse() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "get", - 'query_params': pb_request, - } - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - - pb_return_value = conversation_profile.ListConversationProfilesResponse.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.list_conversation_profiles(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_list_conversation_profiles_rest_unset_required_fields(): - transport = transports.ConversationProfilesRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.list_conversation_profiles._get_unset_required_fields({}) - assert set(unset_fields) == (set(("pageSize", "pageToken", )) & set(("parent", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_list_conversation_profiles_rest_interceptors(null_interceptor): - transport = transports.ConversationProfilesRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.ConversationProfilesRestInterceptor(), - ) - client = ConversationProfilesClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.ConversationProfilesRestInterceptor, "post_list_conversation_profiles") as post, \ - mock.patch.object(transports.ConversationProfilesRestInterceptor, "pre_list_conversation_profiles") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = conversation_profile.ListConversationProfilesRequest.pb(conversation_profile.ListConversationProfilesRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = conversation_profile.ListConversationProfilesResponse.to_json(conversation_profile.ListConversationProfilesResponse()) - - request = conversation_profile.ListConversationProfilesRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = conversation_profile.ListConversationProfilesResponse() - - client.list_conversation_profiles(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_list_conversation_profiles_rest_bad_request(transport: str = 'rest', request_type=conversation_profile.ListConversationProfilesRequest): - client = ConversationProfilesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.list_conversation_profiles(request) - - -def test_list_conversation_profiles_rest_flattened(): - client = ConversationProfilesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = conversation_profile.ListConversationProfilesResponse() - - # get arguments that satisfy an http rule for this method - sample_request = {'parent': 'projects/sample1'} - - # get truthy value for each flattened field - mock_args = dict( - parent='parent_value', - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - pb_return_value = conversation_profile.ListConversationProfilesResponse.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.list_conversation_profiles(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v2/{parent=projects/*}/conversationProfiles" % client.transport._host, args[1]) - - -def test_list_conversation_profiles_rest_flattened_error(transport: str = 'rest'): - client = ConversationProfilesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.list_conversation_profiles( - conversation_profile.ListConversationProfilesRequest(), - parent='parent_value', - ) - - -def test_list_conversation_profiles_rest_pager(transport: str = 'rest'): - client = ConversationProfilesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # TODO(kbandes): remove this mock unless there's a good reason for it. - #with mock.patch.object(path_template, 'transcode') as transcode: - # Set the response as a series of pages - response = ( - conversation_profile.ListConversationProfilesResponse( - conversation_profiles=[ - conversation_profile.ConversationProfile(), - conversation_profile.ConversationProfile(), - conversation_profile.ConversationProfile(), - ], - next_page_token='abc', - ), - conversation_profile.ListConversationProfilesResponse( - conversation_profiles=[], - next_page_token='def', - ), - conversation_profile.ListConversationProfilesResponse( - conversation_profiles=[ - conversation_profile.ConversationProfile(), - ], - next_page_token='ghi', - ), - conversation_profile.ListConversationProfilesResponse( - conversation_profiles=[ - conversation_profile.ConversationProfile(), - conversation_profile.ConversationProfile(), - ], - ), - ) - # Two responses for two calls - response = response + response - - # Wrap the values into proper Response objs - response = tuple(conversation_profile.ListConversationProfilesResponse.to_json(x) for x in response) - return_values = tuple(Response() for i in response) - for return_val, response_val in zip(return_values, response): - return_val._content = response_val.encode('UTF-8') - return_val.status_code = 200 - req.side_effect = return_values - - sample_request = {'parent': 'projects/sample1'} - - pager = client.list_conversation_profiles(request=sample_request) - - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, conversation_profile.ConversationProfile) - for i in results) - - pages = list(client.list_conversation_profiles(request=sample_request).pages) - for page_, token in zip(pages, ['abc','def','ghi', '']): - assert page_.raw_page.next_page_token == token - - -@pytest.mark.parametrize("request_type", [ - conversation_profile.GetConversationProfileRequest, - dict, -]) -def test_get_conversation_profile_rest(request_type): - client = ConversationProfilesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/conversationProfiles/sample2'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = conversation_profile.ConversationProfile( - name='name_value', - display_name='display_name_value', - language_code='language_code_value', - time_zone='time_zone_value', - security_settings='security_settings_value', - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - pb_return_value = conversation_profile.ConversationProfile.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.get_conversation_profile(request) - - # 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' - assert response.time_zone == 'time_zone_value' - assert response.security_settings == 'security_settings_value' - - -def test_get_conversation_profile_rest_required_fields(request_type=conversation_profile.GetConversationProfileRequest): - transport_class = transports.ConversationProfilesRestTransport - - request_init = {} - request_init["name"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - including_default_value_fields=False, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_conversation_profile._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["name"] = 'name_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_conversation_profile._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "name" in jsonified_request - assert jsonified_request["name"] == 'name_value' - - client = ConversationProfilesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = conversation_profile.ConversationProfile() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "get", - 'query_params': pb_request, - } - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - - pb_return_value = conversation_profile.ConversationProfile.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.get_conversation_profile(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_get_conversation_profile_rest_unset_required_fields(): - transport = transports.ConversationProfilesRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.get_conversation_profile._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_get_conversation_profile_rest_interceptors(null_interceptor): - transport = transports.ConversationProfilesRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.ConversationProfilesRestInterceptor(), - ) - client = ConversationProfilesClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.ConversationProfilesRestInterceptor, "post_get_conversation_profile") as post, \ - mock.patch.object(transports.ConversationProfilesRestInterceptor, "pre_get_conversation_profile") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = conversation_profile.GetConversationProfileRequest.pb(conversation_profile.GetConversationProfileRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = conversation_profile.ConversationProfile.to_json(conversation_profile.ConversationProfile()) - - request = conversation_profile.GetConversationProfileRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = conversation_profile.ConversationProfile() - - client.get_conversation_profile(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_get_conversation_profile_rest_bad_request(transport: str = 'rest', request_type=conversation_profile.GetConversationProfileRequest): - client = ConversationProfilesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/conversationProfiles/sample2'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.get_conversation_profile(request) - - -def test_get_conversation_profile_rest_flattened(): - client = ConversationProfilesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = conversation_profile.ConversationProfile() - - # get arguments that satisfy an http rule for this method - sample_request = {'name': 'projects/sample1/conversationProfiles/sample2'} - - # get truthy value for each flattened field - mock_args = dict( - name='name_value', - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - pb_return_value = conversation_profile.ConversationProfile.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.get_conversation_profile(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v2/{name=projects/*/conversationProfiles/*}" % client.transport._host, args[1]) - - -def test_get_conversation_profile_rest_flattened_error(transport: str = 'rest'): - client = ConversationProfilesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.get_conversation_profile( - conversation_profile.GetConversationProfileRequest(), - name='name_value', - ) - - -def test_get_conversation_profile_rest_error(): - client = ConversationProfilesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - gcd_conversation_profile.CreateConversationProfileRequest, - dict, -]) -def test_create_conversation_profile_rest(request_type): - client = ConversationProfilesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1'} - request_init["conversation_profile"] = {'name': 'name_value', 'display_name': 'display_name_value', 'create_time': {'seconds': 751, 'nanos': 543}, 'update_time': {}, 'automated_agent_config': {'agent': 'agent_value'}, 'human_agent_assistant_config': {'notification_config': {'topic': 'topic_value', 'message_format': 1}, 'human_agent_suggestion_config': {'feature_configs': [{'suggestion_feature': {'type_': 1}, 'enable_event_based_suggestion': True, 'suggestion_trigger_settings': {'no_smalltalk': True, 'only_end_user': True}, 'query_config': {'knowledge_base_query_source': {'knowledge_bases': ['knowledge_bases_value1', 'knowledge_bases_value2']}, 'document_query_source': {'documents': ['documents_value1', 'documents_value2']}, 'dialogflow_query_source': {'agent': 'agent_value'}, 'max_results': 1207, 'confidence_threshold': 0.2106, 'context_filter_settings': {'drop_handoff_messages': True, 'drop_virtual_agent_messages': True, 'drop_ivr_messages': True}}, 'conversation_model_config': {'model': 'model_value'}, 'conversation_process_config': {'recent_sentences_count': 2352}}], 'group_suggestion_responses': True}, 'end_user_suggestion_config': {}, 'message_analysis_config': {'enable_entity_extraction': True, 'enable_sentiment_analysis': True}}, 'human_agent_handoff_config': {'live_person_config': {'account_number': 'account_number_value'}, 'salesforce_live_agent_config': {'organization_id': 'organization_id_value', 'deployment_id': 'deployment_id_value', 'button_id': 'button_id_value', 'endpoint_domain': 'endpoint_domain_value'}}, 'notification_config': {}, 'logging_config': {'enable_stackdriver_logging': True}, 'new_message_event_notification_config': {}, 'stt_config': {'speech_model_variant': 1, 'model': 'model_value'}, 'language_code': 'language_code_value', 'time_zone': 'time_zone_value', 'security_settings': 'security_settings_value', 'tts_config': {'speaking_rate': 0.1373, 'pitch': 0.536, 'volume_gain_db': 0.1467, 'effects_profile_id': ['effects_profile_id_value1', 'effects_profile_id_value2'], 'voice': {'name': 'name_value', 'ssml_gender': 1}}} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = gcd_conversation_profile.ConversationProfile( - name='name_value', - display_name='display_name_value', - language_code='language_code_value', - time_zone='time_zone_value', - security_settings='security_settings_value', - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - pb_return_value = gcd_conversation_profile.ConversationProfile.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.create_conversation_profile(request) - - # 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' - assert response.time_zone == 'time_zone_value' - assert response.security_settings == 'security_settings_value' - - -def test_create_conversation_profile_rest_required_fields(request_type=gcd_conversation_profile.CreateConversationProfileRequest): - transport_class = transports.ConversationProfilesRestTransport - - request_init = {} - request_init["parent"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - including_default_value_fields=False, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_conversation_profile._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["parent"] = 'parent_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_conversation_profile._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "parent" in jsonified_request - assert jsonified_request["parent"] == 'parent_value' - - client = ConversationProfilesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = gcd_conversation_profile.ConversationProfile() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "post", - 'query_params': pb_request, - } - transcode_result['body'] = pb_request - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - - pb_return_value = gcd_conversation_profile.ConversationProfile.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.create_conversation_profile(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_create_conversation_profile_rest_unset_required_fields(): - transport = transports.ConversationProfilesRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.create_conversation_profile._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("parent", "conversationProfile", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_create_conversation_profile_rest_interceptors(null_interceptor): - transport = transports.ConversationProfilesRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.ConversationProfilesRestInterceptor(), - ) - client = ConversationProfilesClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.ConversationProfilesRestInterceptor, "post_create_conversation_profile") as post, \ - mock.patch.object(transports.ConversationProfilesRestInterceptor, "pre_create_conversation_profile") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = gcd_conversation_profile.CreateConversationProfileRequest.pb(gcd_conversation_profile.CreateConversationProfileRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = gcd_conversation_profile.ConversationProfile.to_json(gcd_conversation_profile.ConversationProfile()) - - request = gcd_conversation_profile.CreateConversationProfileRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = gcd_conversation_profile.ConversationProfile() - - client.create_conversation_profile(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_create_conversation_profile_rest_bad_request(transport: str = 'rest', request_type=gcd_conversation_profile.CreateConversationProfileRequest): - client = ConversationProfilesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1'} - request_init["conversation_profile"] = {'name': 'name_value', 'display_name': 'display_name_value', 'create_time': {'seconds': 751, 'nanos': 543}, 'update_time': {}, 'automated_agent_config': {'agent': 'agent_value'}, 'human_agent_assistant_config': {'notification_config': {'topic': 'topic_value', 'message_format': 1}, 'human_agent_suggestion_config': {'feature_configs': [{'suggestion_feature': {'type_': 1}, 'enable_event_based_suggestion': True, 'suggestion_trigger_settings': {'no_smalltalk': True, 'only_end_user': True}, 'query_config': {'knowledge_base_query_source': {'knowledge_bases': ['knowledge_bases_value1', 'knowledge_bases_value2']}, 'document_query_source': {'documents': ['documents_value1', 'documents_value2']}, 'dialogflow_query_source': {'agent': 'agent_value'}, 'max_results': 1207, 'confidence_threshold': 0.2106, 'context_filter_settings': {'drop_handoff_messages': True, 'drop_virtual_agent_messages': True, 'drop_ivr_messages': True}}, 'conversation_model_config': {'model': 'model_value'}, 'conversation_process_config': {'recent_sentences_count': 2352}}], 'group_suggestion_responses': True}, 'end_user_suggestion_config': {}, 'message_analysis_config': {'enable_entity_extraction': True, 'enable_sentiment_analysis': True}}, 'human_agent_handoff_config': {'live_person_config': {'account_number': 'account_number_value'}, 'salesforce_live_agent_config': {'organization_id': 'organization_id_value', 'deployment_id': 'deployment_id_value', 'button_id': 'button_id_value', 'endpoint_domain': 'endpoint_domain_value'}}, 'notification_config': {}, 'logging_config': {'enable_stackdriver_logging': True}, 'new_message_event_notification_config': {}, 'stt_config': {'speech_model_variant': 1, 'model': 'model_value'}, 'language_code': 'language_code_value', 'time_zone': 'time_zone_value', 'security_settings': 'security_settings_value', 'tts_config': {'speaking_rate': 0.1373, 'pitch': 0.536, 'volume_gain_db': 0.1467, 'effects_profile_id': ['effects_profile_id_value1', 'effects_profile_id_value2'], 'voice': {'name': 'name_value', 'ssml_gender': 1}}} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.create_conversation_profile(request) - - -def test_create_conversation_profile_rest_flattened(): - client = ConversationProfilesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = gcd_conversation_profile.ConversationProfile() - - # get arguments that satisfy an http rule for this method - sample_request = {'parent': 'projects/sample1'} - - # get truthy value for each flattened field - mock_args = dict( - parent='parent_value', - conversation_profile=gcd_conversation_profile.ConversationProfile(name='name_value'), - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - pb_return_value = gcd_conversation_profile.ConversationProfile.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.create_conversation_profile(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v2/{parent=projects/*}/conversationProfiles" % client.transport._host, args[1]) - - -def test_create_conversation_profile_rest_flattened_error(transport: str = 'rest'): - client = ConversationProfilesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.create_conversation_profile( - gcd_conversation_profile.CreateConversationProfileRequest(), - parent='parent_value', - conversation_profile=gcd_conversation_profile.ConversationProfile(name='name_value'), - ) - - -def test_create_conversation_profile_rest_error(): - client = ConversationProfilesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - gcd_conversation_profile.UpdateConversationProfileRequest, - dict, -]) -def test_update_conversation_profile_rest(request_type): - client = ConversationProfilesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'conversation_profile': {'name': 'projects/sample1/conversationProfiles/sample2'}} - request_init["conversation_profile"] = {'name': 'projects/sample1/conversationProfiles/sample2', 'display_name': 'display_name_value', 'create_time': {'seconds': 751, 'nanos': 543}, 'update_time': {}, 'automated_agent_config': {'agent': 'agent_value'}, 'human_agent_assistant_config': {'notification_config': {'topic': 'topic_value', 'message_format': 1}, 'human_agent_suggestion_config': {'feature_configs': [{'suggestion_feature': {'type_': 1}, 'enable_event_based_suggestion': True, 'suggestion_trigger_settings': {'no_smalltalk': True, 'only_end_user': True}, 'query_config': {'knowledge_base_query_source': {'knowledge_bases': ['knowledge_bases_value1', 'knowledge_bases_value2']}, 'document_query_source': {'documents': ['documents_value1', 'documents_value2']}, 'dialogflow_query_source': {'agent': 'agent_value'}, 'max_results': 1207, 'confidence_threshold': 0.2106, 'context_filter_settings': {'drop_handoff_messages': True, 'drop_virtual_agent_messages': True, 'drop_ivr_messages': True}}, 'conversation_model_config': {'model': 'model_value'}, 'conversation_process_config': {'recent_sentences_count': 2352}}], 'group_suggestion_responses': True}, 'end_user_suggestion_config': {}, 'message_analysis_config': {'enable_entity_extraction': True, 'enable_sentiment_analysis': True}}, 'human_agent_handoff_config': {'live_person_config': {'account_number': 'account_number_value'}, 'salesforce_live_agent_config': {'organization_id': 'organization_id_value', 'deployment_id': 'deployment_id_value', 'button_id': 'button_id_value', 'endpoint_domain': 'endpoint_domain_value'}}, 'notification_config': {}, 'logging_config': {'enable_stackdriver_logging': True}, 'new_message_event_notification_config': {}, 'stt_config': {'speech_model_variant': 1, 'model': 'model_value'}, 'language_code': 'language_code_value', 'time_zone': 'time_zone_value', 'security_settings': 'security_settings_value', 'tts_config': {'speaking_rate': 0.1373, 'pitch': 0.536, 'volume_gain_db': 0.1467, 'effects_profile_id': ['effects_profile_id_value1', 'effects_profile_id_value2'], 'voice': {'name': 'name_value', 'ssml_gender': 1}}} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = gcd_conversation_profile.ConversationProfile( - name='name_value', - display_name='display_name_value', - language_code='language_code_value', - time_zone='time_zone_value', - security_settings='security_settings_value', - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - pb_return_value = gcd_conversation_profile.ConversationProfile.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.update_conversation_profile(request) - - # 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' - assert response.time_zone == 'time_zone_value' - assert response.security_settings == 'security_settings_value' - - -def test_update_conversation_profile_rest_required_fields(request_type=gcd_conversation_profile.UpdateConversationProfileRequest): - transport_class = transports.ConversationProfilesRestTransport - - request_init = {} - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - including_default_value_fields=False, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).update_conversation_profile._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).update_conversation_profile._get_unset_required_fields(jsonified_request) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("update_mask", )) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - - client = ConversationProfilesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = gcd_conversation_profile.ConversationProfile() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "patch", - 'query_params': pb_request, - } - transcode_result['body'] = pb_request - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - - pb_return_value = gcd_conversation_profile.ConversationProfile.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.update_conversation_profile(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_update_conversation_profile_rest_unset_required_fields(): - transport = transports.ConversationProfilesRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.update_conversation_profile._get_unset_required_fields({}) - assert set(unset_fields) == (set(("updateMask", )) & set(("conversationProfile", "updateMask", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_update_conversation_profile_rest_interceptors(null_interceptor): - transport = transports.ConversationProfilesRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.ConversationProfilesRestInterceptor(), - ) - client = ConversationProfilesClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.ConversationProfilesRestInterceptor, "post_update_conversation_profile") as post, \ - mock.patch.object(transports.ConversationProfilesRestInterceptor, "pre_update_conversation_profile") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = gcd_conversation_profile.UpdateConversationProfileRequest.pb(gcd_conversation_profile.UpdateConversationProfileRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = gcd_conversation_profile.ConversationProfile.to_json(gcd_conversation_profile.ConversationProfile()) - - request = gcd_conversation_profile.UpdateConversationProfileRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = gcd_conversation_profile.ConversationProfile() - - client.update_conversation_profile(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_update_conversation_profile_rest_bad_request(transport: str = 'rest', request_type=gcd_conversation_profile.UpdateConversationProfileRequest): - client = ConversationProfilesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'conversation_profile': {'name': 'projects/sample1/conversationProfiles/sample2'}} - request_init["conversation_profile"] = {'name': 'projects/sample1/conversationProfiles/sample2', 'display_name': 'display_name_value', 'create_time': {'seconds': 751, 'nanos': 543}, 'update_time': {}, 'automated_agent_config': {'agent': 'agent_value'}, 'human_agent_assistant_config': {'notification_config': {'topic': 'topic_value', 'message_format': 1}, 'human_agent_suggestion_config': {'feature_configs': [{'suggestion_feature': {'type_': 1}, 'enable_event_based_suggestion': True, 'suggestion_trigger_settings': {'no_smalltalk': True, 'only_end_user': True}, 'query_config': {'knowledge_base_query_source': {'knowledge_bases': ['knowledge_bases_value1', 'knowledge_bases_value2']}, 'document_query_source': {'documents': ['documents_value1', 'documents_value2']}, 'dialogflow_query_source': {'agent': 'agent_value'}, 'max_results': 1207, 'confidence_threshold': 0.2106, 'context_filter_settings': {'drop_handoff_messages': True, 'drop_virtual_agent_messages': True, 'drop_ivr_messages': True}}, 'conversation_model_config': {'model': 'model_value'}, 'conversation_process_config': {'recent_sentences_count': 2352}}], 'group_suggestion_responses': True}, 'end_user_suggestion_config': {}, 'message_analysis_config': {'enable_entity_extraction': True, 'enable_sentiment_analysis': True}}, 'human_agent_handoff_config': {'live_person_config': {'account_number': 'account_number_value'}, 'salesforce_live_agent_config': {'organization_id': 'organization_id_value', 'deployment_id': 'deployment_id_value', 'button_id': 'button_id_value', 'endpoint_domain': 'endpoint_domain_value'}}, 'notification_config': {}, 'logging_config': {'enable_stackdriver_logging': True}, 'new_message_event_notification_config': {}, 'stt_config': {'speech_model_variant': 1, 'model': 'model_value'}, 'language_code': 'language_code_value', 'time_zone': 'time_zone_value', 'security_settings': 'security_settings_value', 'tts_config': {'speaking_rate': 0.1373, 'pitch': 0.536, 'volume_gain_db': 0.1467, 'effects_profile_id': ['effects_profile_id_value1', 'effects_profile_id_value2'], 'voice': {'name': 'name_value', 'ssml_gender': 1}}} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.update_conversation_profile(request) - - -def test_update_conversation_profile_rest_flattened(): - client = ConversationProfilesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = gcd_conversation_profile.ConversationProfile() - - # get arguments that satisfy an http rule for this method - sample_request = {'conversation_profile': {'name': 'projects/sample1/conversationProfiles/sample2'}} - - # get truthy value for each flattened field - mock_args = dict( - conversation_profile=gcd_conversation_profile.ConversationProfile(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - pb_return_value = gcd_conversation_profile.ConversationProfile.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.update_conversation_profile(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v2/{conversation_profile.name=projects/*/conversationProfiles/*}" % client.transport._host, args[1]) - - -def test_update_conversation_profile_rest_flattened_error(transport: str = 'rest'): - client = ConversationProfilesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.update_conversation_profile( - gcd_conversation_profile.UpdateConversationProfileRequest(), - conversation_profile=gcd_conversation_profile.ConversationProfile(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - - -def test_update_conversation_profile_rest_error(): - client = ConversationProfilesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - conversation_profile.DeleteConversationProfileRequest, - dict, -]) -def test_delete_conversation_profile_rest(request_type): - client = ConversationProfilesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/conversationProfiles/sample2'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = None - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = '' - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.delete_conversation_profile(request) - - # Establish that the response is the type that we expect. - assert response is None - - -def test_delete_conversation_profile_rest_required_fields(request_type=conversation_profile.DeleteConversationProfileRequest): - transport_class = transports.ConversationProfilesRestTransport - - request_init = {} - request_init["name"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - including_default_value_fields=False, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).delete_conversation_profile._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["name"] = 'name_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).delete_conversation_profile._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "name" in jsonified_request - assert jsonified_request["name"] == 'name_value' - - client = ConversationProfilesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = None - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "delete", - 'query_params': pb_request, - } - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - json_return_value = '' - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.delete_conversation_profile(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_delete_conversation_profile_rest_unset_required_fields(): - transport = transports.ConversationProfilesRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.delete_conversation_profile._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_delete_conversation_profile_rest_interceptors(null_interceptor): - transport = transports.ConversationProfilesRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.ConversationProfilesRestInterceptor(), - ) - client = ConversationProfilesClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.ConversationProfilesRestInterceptor, "pre_delete_conversation_profile") as pre: - pre.assert_not_called() - pb_message = conversation_profile.DeleteConversationProfileRequest.pb(conversation_profile.DeleteConversationProfileRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - - request = conversation_profile.DeleteConversationProfileRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - - client.delete_conversation_profile(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - - -def test_delete_conversation_profile_rest_bad_request(transport: str = 'rest', request_type=conversation_profile.DeleteConversationProfileRequest): - client = ConversationProfilesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/conversationProfiles/sample2'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.delete_conversation_profile(request) - - -def test_delete_conversation_profile_rest_flattened(): - client = ConversationProfilesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = None - - # get arguments that satisfy an http rule for this method - sample_request = {'name': 'projects/sample1/conversationProfiles/sample2'} - - # get truthy value for each flattened field - mock_args = dict( - name='name_value', - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = '' - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.delete_conversation_profile(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v2/{name=projects/*/conversationProfiles/*}" % client.transport._host, args[1]) - - -def test_delete_conversation_profile_rest_flattened_error(transport: str = 'rest'): - client = ConversationProfilesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.delete_conversation_profile( - conversation_profile.DeleteConversationProfileRequest(), - name='name_value', - ) - - -def test_delete_conversation_profile_rest_error(): - client = ConversationProfilesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - gcd_conversation_profile.SetSuggestionFeatureConfigRequest, - dict, -]) -def test_set_suggestion_feature_config_rest(request_type): - client = ConversationProfilesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'conversation_profile': 'projects/sample1/conversationProfiles/sample2'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name='operations/spam') - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.set_suggestion_feature_config(request) - - # Establish that the response is the type that we expect. - assert response.operation.name == "operations/spam" - - -def test_set_suggestion_feature_config_rest_required_fields(request_type=gcd_conversation_profile.SetSuggestionFeatureConfigRequest): - transport_class = transports.ConversationProfilesRestTransport - - request_init = {} - request_init["conversation_profile"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - including_default_value_fields=False, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).set_suggestion_feature_config._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["conversationProfile"] = 'conversation_profile_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).set_suggestion_feature_config._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "conversationProfile" in jsonified_request - assert jsonified_request["conversationProfile"] == 'conversation_profile_value' - - client = ConversationProfilesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name='operations/spam') - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "post", - 'query_params': pb_request, - } - transcode_result['body'] = pb_request - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.set_suggestion_feature_config(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_set_suggestion_feature_config_rest_unset_required_fields(): - transport = transports.ConversationProfilesRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.set_suggestion_feature_config._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("conversationProfile", "participantRole", "suggestionFeatureConfig", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_set_suggestion_feature_config_rest_interceptors(null_interceptor): - transport = transports.ConversationProfilesRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.ConversationProfilesRestInterceptor(), - ) - client = ConversationProfilesClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(operation.Operation, "_set_result_from_operation"), \ - mock.patch.object(transports.ConversationProfilesRestInterceptor, "post_set_suggestion_feature_config") as post, \ - mock.patch.object(transports.ConversationProfilesRestInterceptor, "pre_set_suggestion_feature_config") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = gcd_conversation_profile.SetSuggestionFeatureConfigRequest.pb(gcd_conversation_profile.SetSuggestionFeatureConfigRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = json_format.MessageToJson(operations_pb2.Operation()) - - request = gcd_conversation_profile.SetSuggestionFeatureConfigRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = operations_pb2.Operation() - - client.set_suggestion_feature_config(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_set_suggestion_feature_config_rest_bad_request(transport: str = 'rest', request_type=gcd_conversation_profile.SetSuggestionFeatureConfigRequest): - client = ConversationProfilesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'conversation_profile': 'projects/sample1/conversationProfiles/sample2'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.set_suggestion_feature_config(request) - - -def test_set_suggestion_feature_config_rest_flattened(): - client = ConversationProfilesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name='operations/spam') - - # get arguments that satisfy an http rule for this method - sample_request = {'conversation_profile': 'projects/sample1/conversationProfiles/sample2'} - - # get truthy value for each flattened field - mock_args = dict( - conversation_profile='conversation_profile_value', - participant_role=participant.Participant.Role.HUMAN_AGENT, - suggestion_feature_config=gcd_conversation_profile.HumanAgentAssistantConfig.SuggestionFeatureConfig(suggestion_feature=gcd_conversation_profile.SuggestionFeature(type_=gcd_conversation_profile.SuggestionFeature.Type.ARTICLE_SUGGESTION)), - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.set_suggestion_feature_config(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v2/{conversation_profile=projects/*/conversationProfiles/*}:setSuggestionFeatureConfig" % client.transport._host, args[1]) - - -def test_set_suggestion_feature_config_rest_flattened_error(transport: str = 'rest'): - client = ConversationProfilesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.set_suggestion_feature_config( - gcd_conversation_profile.SetSuggestionFeatureConfigRequest(), - conversation_profile='conversation_profile_value', - participant_role=participant.Participant.Role.HUMAN_AGENT, - suggestion_feature_config=gcd_conversation_profile.HumanAgentAssistantConfig.SuggestionFeatureConfig(suggestion_feature=gcd_conversation_profile.SuggestionFeature(type_=gcd_conversation_profile.SuggestionFeature.Type.ARTICLE_SUGGESTION)), - ) - - -def test_set_suggestion_feature_config_rest_error(): - client = ConversationProfilesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - gcd_conversation_profile.ClearSuggestionFeatureConfigRequest, - dict, -]) -def test_clear_suggestion_feature_config_rest(request_type): - client = ConversationProfilesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'conversation_profile': 'projects/sample1/conversationProfiles/sample2'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name='operations/spam') - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.clear_suggestion_feature_config(request) - - # Establish that the response is the type that we expect. - assert response.operation.name == "operations/spam" - - -def test_clear_suggestion_feature_config_rest_required_fields(request_type=gcd_conversation_profile.ClearSuggestionFeatureConfigRequest): - transport_class = transports.ConversationProfilesRestTransport - - request_init = {} - request_init["conversation_profile"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - including_default_value_fields=False, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).clear_suggestion_feature_config._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["conversationProfile"] = 'conversation_profile_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).clear_suggestion_feature_config._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "conversationProfile" in jsonified_request - assert jsonified_request["conversationProfile"] == 'conversation_profile_value' - - client = ConversationProfilesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name='operations/spam') - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "post", - 'query_params': pb_request, - } - transcode_result['body'] = pb_request - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.clear_suggestion_feature_config(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_clear_suggestion_feature_config_rest_unset_required_fields(): - transport = transports.ConversationProfilesRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.clear_suggestion_feature_config._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("conversationProfile", "participantRole", "suggestionFeatureType", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_clear_suggestion_feature_config_rest_interceptors(null_interceptor): - transport = transports.ConversationProfilesRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.ConversationProfilesRestInterceptor(), - ) - client = ConversationProfilesClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(operation.Operation, "_set_result_from_operation"), \ - mock.patch.object(transports.ConversationProfilesRestInterceptor, "post_clear_suggestion_feature_config") as post, \ - mock.patch.object(transports.ConversationProfilesRestInterceptor, "pre_clear_suggestion_feature_config") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = gcd_conversation_profile.ClearSuggestionFeatureConfigRequest.pb(gcd_conversation_profile.ClearSuggestionFeatureConfigRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = json_format.MessageToJson(operations_pb2.Operation()) - - request = gcd_conversation_profile.ClearSuggestionFeatureConfigRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = operations_pb2.Operation() - - client.clear_suggestion_feature_config(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_clear_suggestion_feature_config_rest_bad_request(transport: str = 'rest', request_type=gcd_conversation_profile.ClearSuggestionFeatureConfigRequest): - client = ConversationProfilesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'conversation_profile': 'projects/sample1/conversationProfiles/sample2'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.clear_suggestion_feature_config(request) - - -def test_clear_suggestion_feature_config_rest_flattened(): - client = ConversationProfilesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name='operations/spam') - - # get arguments that satisfy an http rule for this method - sample_request = {'conversation_profile': 'projects/sample1/conversationProfiles/sample2'} - - # get truthy value for each flattened field - mock_args = dict( - conversation_profile='conversation_profile_value', - participant_role=participant.Participant.Role.HUMAN_AGENT, - suggestion_feature_type=gcd_conversation_profile.SuggestionFeature.Type.ARTICLE_SUGGESTION, - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.clear_suggestion_feature_config(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v2/{conversation_profile=projects/*/conversationProfiles/*}:clearSuggestionFeatureConfig" % client.transport._host, args[1]) - - -def test_clear_suggestion_feature_config_rest_flattened_error(transport: str = 'rest'): - client = ConversationProfilesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.clear_suggestion_feature_config( - gcd_conversation_profile.ClearSuggestionFeatureConfigRequest(), - conversation_profile='conversation_profile_value', - participant_role=participant.Participant.Role.HUMAN_AGENT, - suggestion_feature_type=gcd_conversation_profile.SuggestionFeature.Type.ARTICLE_SUGGESTION, - ) - - -def test_clear_suggestion_feature_config_rest_error(): - client = ConversationProfilesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -def test_credentials_transport_error(): - # It is an error to provide credentials and a transport instance. - transport = transports.ConversationProfilesGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = ConversationProfilesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # It is an error to provide a credentials file and a transport instance. - transport = transports.ConversationProfilesGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = ConversationProfilesClient( - client_options={"credentials_file": "credentials.json"}, - transport=transport, - ) - - # It is an error to provide an api_key and a transport instance. - transport = transports.ConversationProfilesGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - options = client_options.ClientOptions() - options.api_key = "api_key" - with pytest.raises(ValueError): - client = ConversationProfilesClient( - client_options=options, - transport=transport, - ) - - # It is an error to provide an api_key and a credential. - options = mock.Mock() - options.api_key = "api_key" - with pytest.raises(ValueError): - client = ConversationProfilesClient( - client_options=options, - credentials=ga_credentials.AnonymousCredentials() - ) - - # It is an error to provide scopes and a transport instance. - transport = transports.ConversationProfilesGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = ConversationProfilesClient( - client_options={"scopes": ["1", "2"]}, - transport=transport, - ) - - -def test_transport_instance(): - # A client may be instantiated with a custom transport instance. - transport = transports.ConversationProfilesGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - client = ConversationProfilesClient(transport=transport) - assert client.transport is transport - -def test_transport_get_channel(): - # A client may be instantiated with a custom transport instance. - transport = transports.ConversationProfilesGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - - transport = transports.ConversationProfilesGrpcAsyncIOTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - -@pytest.mark.parametrize("transport_class", [ - transports.ConversationProfilesGrpcTransport, - transports.ConversationProfilesGrpcAsyncIOTransport, - transports.ConversationProfilesRestTransport, -]) -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() - -@pytest.mark.parametrize("transport_name", [ - "grpc", - "rest", -]) -def test_transport_kind(transport_name): - transport = ConversationProfilesClient.get_transport_class(transport_name)( - credentials=ga_credentials.AnonymousCredentials(), - ) - assert transport.kind == transport_name - -def test_transport_grpc_default(): - # A client should use the gRPC transport by default. - 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(core_exceptions.DuplicateCredentialArgs): - transport = transports.ConversationProfilesTransport( - credentials=ga_credentials.AnonymousCredentials(), - credentials_file="credentials.json" - ) - - -def test_conversation_profiles_base_transport(): - # Instantiate the base transport. - with mock.patch('google.cloud.dialogflow_v2.services.conversation_profiles.transports.ConversationProfilesTransport.__init__') as Transport: - Transport.return_value = None - transport = transports.ConversationProfilesTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Every method on the transport should just blindly - # raise NotImplementedError. - methods = ( - 'list_conversation_profiles', - 'get_conversation_profile', - 'create_conversation_profile', - 'update_conversation_profile', - 'delete_conversation_profile', - 'set_suggestion_feature_config', - 'clear_suggestion_feature_config', - 'get_location', - 'list_locations', - 'get_operation', - 'cancel_operation', - 'list_operations', - ) - for method in methods: - with pytest.raises(NotImplementedError): - getattr(transport, method)(request=object()) - - with pytest.raises(NotImplementedError): - transport.close() - - # Additionally, the LRO client (a property) should - # also raise NotImplementedError - with pytest.raises(NotImplementedError): - transport.operations_client - - # Catch all for all remaining methods and properties - remainder = [ - 'kind', - ] - for r in remainder: - with pytest.raises(NotImplementedError): - getattr(transport, r)() - - -def test_conversation_profiles_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.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", - ) - load_creds.assert_called_once_with("credentials.json", - scopes=None, - default_scopes=( - 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/dialogflow', -), - quota_project_id="octopus", - ) - - -def test_conversation_profiles_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.conversation_profiles.transports.ConversationProfilesTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.ConversationProfilesTransport() - adc.assert_called_once() - - -def test_conversation_profiles_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) - 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, - ) - - -@pytest.mark.parametrize( - "transport_class", - [ - transports.ConversationProfilesGrpcTransport, - transports.ConversationProfilesGrpcAsyncIOTransport, - ], -) -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(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, - transports.ConversationProfilesRestTransport, - ], -) -def test_conversation_profiles_transport_auth_gdch_credentials(transport_class): - host = 'https://language.com' - api_audience_tests = [None, 'https://language2.com'] - api_audience_expect = [host, 'https://language2.com'] - for t, e in zip(api_audience_tests, api_audience_expect): - with mock.patch.object(google.auth, 'default', autospec=True) as adc: - gdch_mock = mock.MagicMock() - type(gdch_mock).with_gdch_audience = mock.PropertyMock(return_value=gdch_mock) - adc.return_value = (gdch_mock, None) - transport_class(host=host, api_audience=t) - gdch_mock.with_gdch_audience.assert_called_once_with( - e - ) - - -@pytest.mark.parametrize( - "transport_class,grpc_helpers", - [ - (transports.ConversationProfilesGrpcTransport, grpc_helpers), - (transports.ConversationProfilesGrpcAsyncIOTransport, grpc_helpers_async) - ], -) -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", [transports.ConversationProfilesGrpcTransport, transports.ConversationProfilesGrpcAsyncIOTransport]) -def test_conversation_profiles_grpc_transport_client_cert_source_for_mtls( - transport_class -): - cred = ga_credentials.AnonymousCredentials() - - # Check ssl_channel_credentials is used if provided. - with mock.patch.object(transport_class, "create_channel") as mock_create_channel: - mock_ssl_channel_creds = mock.Mock() - transport_class( - host="squid.clam.whelk", - credentials=cred, - ssl_channel_credentials=mock_ssl_channel_creds - ) - mock_create_channel.assert_called_once_with( - "squid.clam.whelk:443", - credentials=cred, - credentials_file=None, - scopes=None, - ssl_credentials=mock_ssl_channel_creds, - quota_project_id=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - # Check if ssl_channel_credentials is not provided, then client_cert_source_for_mtls - # is used. - with mock.patch.object(transport_class, "create_channel", return_value=mock.Mock()): - with mock.patch("grpc.ssl_channel_credentials") as mock_ssl_cred: - transport_class( - credentials=cred, - client_cert_source_for_mtls=client_cert_source_callback - ) - expected_cert, expected_key = client_cert_source_callback() - mock_ssl_cred.assert_called_once_with( - certificate_chain=expected_cert, - private_key=expected_key - ) - -def test_conversation_profiles_http_transport_client_cert_source_for_mtls(): - cred = ga_credentials.AnonymousCredentials() - with mock.patch("google.auth.transport.requests.AuthorizedSession.configure_mtls_channel") as mock_configure_mtls_channel: - transports.ConversationProfilesRestTransport ( - credentials=cred, - client_cert_source_for_mtls=client_cert_source_callback - ) - mock_configure_mtls_channel.assert_called_once_with(client_cert_source_callback) - - -def test_conversation_profiles_rest_lro_client(): - client = ConversationProfilesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - transport = client.transport - - # Ensure that we have a api-core operations client. - assert isinstance( - transport.operations_client, - operations_v1.AbstractOperationsClient, - ) - - # Ensure that subsequent calls to the property send the exact same object. - assert transport.operations_client is transport.operations_client - - -@pytest.mark.parametrize("transport_name", [ - "grpc", - "grpc_asyncio", - "rest", -]) -def test_conversation_profiles_host_no_port(transport_name): - client = ConversationProfilesClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='dialogflow.googleapis.com'), - transport=transport_name, - ) - assert client.transport._host == ( - 'dialogflow.googleapis.com:443' - if transport_name in ['grpc', 'grpc_asyncio'] - else 'https://dialogflow.googleapis.com' - ) - -@pytest.mark.parametrize("transport_name", [ - "grpc", - "grpc_asyncio", - "rest", -]) -def test_conversation_profiles_host_with_port(transport_name): - client = ConversationProfilesClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='dialogflow.googleapis.com:8000'), - transport=transport_name, - ) - assert client.transport._host == ( - 'dialogflow.googleapis.com:8000' - if transport_name in ['grpc', 'grpc_asyncio'] - else 'https://dialogflow.googleapis.com:8000' - ) - -@pytest.mark.parametrize("transport_name", [ - "rest", -]) -def test_conversation_profiles_client_transport_session_collision(transport_name): - creds1 = ga_credentials.AnonymousCredentials() - creds2 = ga_credentials.AnonymousCredentials() - client1 = ConversationProfilesClient( - credentials=creds1, - transport=transport_name, - ) - client2 = ConversationProfilesClient( - credentials=creds2, - transport=transport_name, - ) - session1 = client1.transport.list_conversation_profiles._session - session2 = client2.transport.list_conversation_profiles._session - assert session1 != session2 - session1 = client1.transport.get_conversation_profile._session - session2 = client2.transport.get_conversation_profile._session - assert session1 != session2 - session1 = client1.transport.create_conversation_profile._session - session2 = client2.transport.create_conversation_profile._session - assert session1 != session2 - session1 = client1.transport.update_conversation_profile._session - session2 = client2.transport.update_conversation_profile._session - assert session1 != session2 - session1 = client1.transport.delete_conversation_profile._session - session2 = client2.transport.delete_conversation_profile._session - assert session1 != session2 - session1 = client1.transport.set_suggestion_feature_config._session - session2 = client2.transport.set_suggestion_feature_config._session - assert session1 != session2 - session1 = client1.transport.clear_suggestion_feature_config._session - session2 = client2.transport.clear_suggestion_feature_config._session - assert session1 != session2 -def test_conversation_profiles_grpc_transport_channel(): - channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.ConversationProfilesGrpcTransport( - 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_conversation_profiles_grpc_asyncio_transport_channel(): - channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.ConversationProfilesGrpcAsyncIOTransport( - 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.ConversationProfilesGrpcTransport, transports.ConversationProfilesGrpcAsyncIOTransport]) -def test_conversation_profiles_transport_channel_mtls_with_client_cert_source( - transport_class -): - with mock.patch("grpc.ssl_channel_credentials", autospec=True) as grpc_ssl_channel_cred: - with mock.patch.object(transport_class, "create_channel") as grpc_create_channel: - mock_ssl_cred = mock.Mock() - grpc_ssl_channel_cred.return_value = mock_ssl_cred - - mock_grpc_channel = mock.Mock() - grpc_create_channel.return_value = mock_grpc_channel - - cred = ga_credentials.AnonymousCredentials() - with pytest.warns(DeprecationWarning): - with mock.patch.object(google.auth, 'default') as adc: - adc.return_value = (cred, None) - transport = transport_class( - host="squid.clam.whelk", - api_mtls_endpoint="mtls.squid.clam.whelk", - client_cert_source=client_cert_source_callback, - ) - adc.assert_called_once() - - grpc_ssl_channel_cred.assert_called_once_with( - certificate_chain=b"cert bytes", private_key=b"key bytes" - ) - grpc_create_channel.assert_called_once_with( - "mtls.squid.clam.whelk:443", - credentials=cred, - credentials_file=None, - scopes=None, - ssl_credentials=mock_ssl_cred, - quota_project_id=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - assert transport.grpc_channel == mock_grpc_channel - assert transport._ssl_channel_credentials == mock_ssl_cred - - -# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are -# removed from grpc/grpc_asyncio transport constructor. -@pytest.mark.parametrize("transport_class", [transports.ConversationProfilesGrpcTransport, transports.ConversationProfilesGrpcAsyncIOTransport]) -def test_conversation_profiles_transport_channel_mtls_with_adc( - transport_class -): - mock_ssl_cred = mock.Mock() - with mock.patch.multiple( - "google.auth.transport.grpc.SslCredentials", - __init__=mock.Mock(return_value=None), - ssl_credentials=mock.PropertyMock(return_value=mock_ssl_cred), - ): - with mock.patch.object(transport_class, "create_channel") as grpc_create_channel: - mock_grpc_channel = mock.Mock() - grpc_create_channel.return_value = mock_grpc_channel - mock_cred = mock.Mock() - - with pytest.warns(DeprecationWarning): - transport = transport_class( - host="squid.clam.whelk", - credentials=mock_cred, - api_mtls_endpoint="mtls.squid.clam.whelk", - client_cert_source=None, - ) - - grpc_create_channel.assert_called_once_with( - "mtls.squid.clam.whelk:443", - credentials=mock_cred, - credentials_file=None, - scopes=None, - ssl_credentials=mock_ssl_cred, - quota_project_id=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - assert transport.grpc_channel == mock_grpc_channel - - -def test_conversation_profiles_grpc_lro_client(): - client = ConversationProfilesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - transport = client.transport - - # Ensure that we have a api-core operations client. - assert isinstance( - transport.operations_client, - operations_v1.OperationsClient, - ) - - # Ensure that subsequent calls to the property send the exact same object. - assert transport.operations_client is transport.operations_client - - -def test_conversation_profiles_grpc_lro_async_client(): - client = ConversationProfilesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc_asyncio', - ) - transport = client.transport - - # Ensure that we have a api-core operations client. - assert isinstance( - transport.operations_client, - operations_v1.OperationsAsyncClient, - ) - - # Ensure that subsequent calls to the property send the exact same object. - assert transport.operations_client is transport.operations_client - - -def test_agent_path(): - project = "squid" - expected = "projects/{project}/agent".format(project=project, ) - actual = ConversationProfilesClient.agent_path(project) - assert expected == actual - - -def test_parse_agent_path(): - expected = { - "project": "clam", - } - path = ConversationProfilesClient.agent_path(**expected) - - # Check that the path construction is reversible. - actual = ConversationProfilesClient.parse_agent_path(path) - assert expected == actual - -def test_conversation_model_path(): - project = "whelk" - 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, ) - actual = ConversationProfilesClient.conversation_profile_path(project, conversation_profile) - assert expected == actual - - -def test_parse_conversation_profile_path(): - expected = { - "project": "scallop", - "conversation_profile": "abalone", - } - path = ConversationProfilesClient.conversation_profile_path(**expected) - - # Check that the path construction is reversible. - actual = ConversationProfilesClient.parse_conversation_profile_path(path) - assert expected == actual - -def test_cx_security_settings_path(): - project = "squid" - location = "clam" - security_settings = "whelk" - expected = "projects/{project}/locations/{location}/securitySettings/{security_settings}".format(project=project, location=location, security_settings=security_settings, ) - actual = ConversationProfilesClient.cx_security_settings_path(project, location, security_settings) - assert expected == actual - - -def test_parse_cx_security_settings_path(): - expected = { - "project": "octopus", - "location": "oyster", - "security_settings": "nudibranch", - } - path = ConversationProfilesClient.cx_security_settings_path(**expected) - - # Check that the path construction is reversible. - actual = ConversationProfilesClient.parse_cx_security_settings_path(path) - assert expected == actual - -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, ) - actual = ConversationProfilesClient.document_path(project, knowledge_base, document) - assert expected == actual - - -def test_parse_document_path(): - expected = { - "project": "nautilus", - "knowledge_base": "scallop", - "document": "abalone", - } - path = ConversationProfilesClient.document_path(**expected) - - # Check that the path construction is reversible. - actual = ConversationProfilesClient.parse_document_path(path) - assert expected == actual - -def test_knowledge_base_path(): - project = "squid" - knowledge_base = "clam" - expected = "projects/{project}/knowledgeBases/{knowledge_base}".format(project=project, knowledge_base=knowledge_base, ) - actual = ConversationProfilesClient.knowledge_base_path(project, knowledge_base) - assert expected == actual - - -def test_parse_knowledge_base_path(): - expected = { - "project": "whelk", - "knowledge_base": "octopus", - } - path = ConversationProfilesClient.knowledge_base_path(**expected) - - # Check that the path construction is reversible. - actual = ConversationProfilesClient.parse_knowledge_base_path(path) - assert expected == actual - -def test_common_billing_account_path(): - billing_account = "oyster" - expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) - actual = ConversationProfilesClient.common_billing_account_path(billing_account) - assert expected == actual - - -def test_parse_common_billing_account_path(): - expected = { - "billing_account": "nudibranch", - } - path = ConversationProfilesClient.common_billing_account_path(**expected) - - # Check that the path construction is reversible. - actual = ConversationProfilesClient.parse_common_billing_account_path(path) - assert expected == actual - -def test_common_folder_path(): - folder = "cuttlefish" - expected = "folders/{folder}".format(folder=folder, ) - actual = ConversationProfilesClient.common_folder_path(folder) - assert expected == actual - - -def test_parse_common_folder_path(): - expected = { - "folder": "mussel", - } - path = ConversationProfilesClient.common_folder_path(**expected) - - # Check that the path construction is reversible. - actual = ConversationProfilesClient.parse_common_folder_path(path) - assert expected == actual - -def test_common_organization_path(): - organization = "winkle" - expected = "organizations/{organization}".format(organization=organization, ) - actual = ConversationProfilesClient.common_organization_path(organization) - assert expected == actual - - -def test_parse_common_organization_path(): - expected = { - "organization": "nautilus", - } - path = ConversationProfilesClient.common_organization_path(**expected) - - # Check that the path construction is reversible. - actual = ConversationProfilesClient.parse_common_organization_path(path) - assert expected == actual - -def test_common_project_path(): - project = "scallop" - expected = "projects/{project}".format(project=project, ) - actual = ConversationProfilesClient.common_project_path(project) - assert expected == actual - - -def test_parse_common_project_path(): - expected = { - "project": "abalone", - } - path = ConversationProfilesClient.common_project_path(**expected) - - # Check that the path construction is reversible. - actual = ConversationProfilesClient.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 = ConversationProfilesClient.common_location_path(project, location) - assert expected == actual - - -def test_parse_common_location_path(): - expected = { - "project": "whelk", - "location": "octopus", - } - path = ConversationProfilesClient.common_location_path(**expected) - - # Check that the path construction is reversible. - actual = ConversationProfilesClient.parse_common_location_path(path) - assert expected == actual - - -def test_client_with_default_client_info(): - client_info = gapic_v1.client_info.ClientInfo() - - with mock.patch.object(transports.ConversationProfilesTransport, '_prep_wrapped_messages') as prep: - client = ConversationProfilesClient( - credentials=ga_credentials.AnonymousCredentials(), - client_info=client_info, - ) - prep.assert_called_once_with(client_info) - - with mock.patch.object(transports.ConversationProfilesTransport, '_prep_wrapped_messages') as prep: - transport_class = ConversationProfilesClient.get_transport_class() - transport = transport_class( - credentials=ga_credentials.AnonymousCredentials(), - client_info=client_info, - ) - prep.assert_called_once_with(client_info) - -@pytest.mark.asyncio -async def test_transport_close_async(): - client = ConversationProfilesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - with mock.patch.object(type(getattr(client.transport, "grpc_channel")), "close") as close: - async with client: - close.assert_not_called() - close.assert_called_once() - - -def test_get_location_rest_bad_request(transport: str = 'rest', request_type=locations_pb2.GetLocationRequest): - client = ConversationProfilesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - request = request_type() - request = json_format.ParseDict({'name': 'projects/sample1/locations/sample2'}, request) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.get_location(request) - -@pytest.mark.parametrize("request_type", [ - locations_pb2.GetLocationRequest, - dict, -]) -def test_get_location_rest(request_type): - client = ConversationProfilesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request_init = {'name': 'projects/sample1/locations/sample2'} - request = request_type(**request_init) - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = locations_pb2.Location() - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.get_location(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, locations_pb2.Location) - -def test_list_locations_rest_bad_request(transport: str = 'rest', request_type=locations_pb2.ListLocationsRequest): - client = ConversationProfilesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - request = request_type() - request = json_format.ParseDict({'name': 'projects/sample1'}, request) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.list_locations(request) - -@pytest.mark.parametrize("request_type", [ - locations_pb2.ListLocationsRequest, - dict, -]) -def test_list_locations_rest(request_type): - client = ConversationProfilesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request_init = {'name': 'projects/sample1'} - request = request_type(**request_init) - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = locations_pb2.ListLocationsResponse() - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.list_locations(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, locations_pb2.ListLocationsResponse) - -def test_cancel_operation_rest_bad_request(transport: str = 'rest', request_type=operations_pb2.CancelOperationRequest): - client = ConversationProfilesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - request = request_type() - request = json_format.ParseDict({'name': 'projects/sample1/operations/sample2'}, request) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.cancel_operation(request) - -@pytest.mark.parametrize("request_type", [ - operations_pb2.CancelOperationRequest, - dict, -]) -def test_cancel_operation_rest(request_type): - client = ConversationProfilesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request_init = {'name': 'projects/sample1/operations/sample2'} - request = request_type(**request_init) - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = None - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = '{}' - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.cancel_operation(request) - - # Establish that the response is the type that we expect. - assert response is None - -def test_get_operation_rest_bad_request(transport: str = 'rest', request_type=operations_pb2.GetOperationRequest): - client = ConversationProfilesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - request = request_type() - request = json_format.ParseDict({'name': 'projects/sample1/operations/sample2'}, request) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.get_operation(request) - -@pytest.mark.parametrize("request_type", [ - operations_pb2.GetOperationRequest, - dict, -]) -def test_get_operation_rest(request_type): - client = ConversationProfilesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request_init = {'name': 'projects/sample1/operations/sample2'} - request = request_type(**request_init) - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation() - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.get_operation(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, operations_pb2.Operation) - -def test_list_operations_rest_bad_request(transport: str = 'rest', request_type=operations_pb2.ListOperationsRequest): - client = ConversationProfilesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - request = request_type() - request = json_format.ParseDict({'name': 'projects/sample1'}, request) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.list_operations(request) - -@pytest.mark.parametrize("request_type", [ - operations_pb2.ListOperationsRequest, - dict, -]) -def test_list_operations_rest(request_type): - client = ConversationProfilesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request_init = {'name': 'projects/sample1'} - request = request_type(**request_init) - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = operations_pb2.ListOperationsResponse() - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.list_operations(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, operations_pb2.ListOperationsResponse) - - -def test_cancel_operation(transport: str = "grpc"): - client = ConversationProfilesClient( - 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 = operations_pb2.CancelOperationRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = None - response = client.cancel_operation(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 response is the type that we expect. - assert response is None -@pytest.mark.asyncio -async def test_cancel_operation_async(transport: str = "grpc"): - client = ConversationProfilesAsyncClient( - 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 = operations_pb2.CancelOperationRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - None - ) - response = await client.cancel_operation(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 response is the type that we expect. - assert response is None - -def test_cancel_operation_field_headers(): - 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 = operations_pb2.CancelOperationRequest() - request.name = "locations" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call: - call.return_value = None - - client.cancel_operation(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=locations",) in kw["metadata"] -@pytest.mark.asyncio -async def test_cancel_operation_field_headers_async(): - client = ConversationProfilesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = operations_pb2.CancelOperationRequest() - request.name = "locations" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - None - ) - await client.cancel_operation(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=locations",) in kw["metadata"] - -def test_cancel_operation_from_dict(): - client = ConversationProfilesClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = None - - response = client.cancel_operation( - request={ - "name": "locations", - } - ) - call.assert_called() -@pytest.mark.asyncio -async def test_cancel_operation_from_dict_async(): - client = ConversationProfilesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - None - ) - response = await client.cancel_operation( - request={ - "name": "locations", - } - ) - call.assert_called() - - -def test_get_operation(transport: str = "grpc"): - client = ConversationProfilesClient( - 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 = operations_pb2.GetOperationRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_operation), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation() - response = client.get_operation(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 response is the type that we expect. - assert isinstance(response, operations_pb2.Operation) -@pytest.mark.asyncio -async def test_get_operation_async(transport: str = "grpc"): - client = ConversationProfilesAsyncClient( - 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 = operations_pb2.GetOperationRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_operation), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation() - ) - response = await client.get_operation(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 response is the type that we expect. - assert isinstance(response, operations_pb2.Operation) - -def test_get_operation_field_headers(): - 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 = operations_pb2.GetOperationRequest() - request.name = "locations" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_operation), "__call__") as call: - call.return_value = operations_pb2.Operation() - - client.get_operation(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=locations",) in kw["metadata"] -@pytest.mark.asyncio -async def test_get_operation_field_headers_async(): - client = ConversationProfilesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = operations_pb2.GetOperationRequest() - request.name = "locations" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_operation), "__call__") as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation() - ) - await client.get_operation(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=locations",) in kw["metadata"] - -def test_get_operation_from_dict(): - client = ConversationProfilesClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_operation), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation() - - response = client.get_operation( - request={ - "name": "locations", - } - ) - call.assert_called() -@pytest.mark.asyncio -async def test_get_operation_from_dict_async(): - client = ConversationProfilesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_operation), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation() - ) - response = await client.get_operation( - request={ - "name": "locations", - } - ) - call.assert_called() - - -def test_list_operations(transport: str = "grpc"): - client = ConversationProfilesClient( - 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 = operations_pb2.ListOperationsRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_operations), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.ListOperationsResponse() - response = client.list_operations(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 response is the type that we expect. - assert isinstance(response, operations_pb2.ListOperationsResponse) -@pytest.mark.asyncio -async def test_list_operations_async(transport: str = "grpc"): - client = ConversationProfilesAsyncClient( - 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 = operations_pb2.ListOperationsRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_operations), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.ListOperationsResponse() - ) - response = await client.list_operations(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 response is the type that we expect. - assert isinstance(response, operations_pb2.ListOperationsResponse) - -def test_list_operations_field_headers(): - 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 = operations_pb2.ListOperationsRequest() - request.name = "locations" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_operations), "__call__") as call: - call.return_value = operations_pb2.ListOperationsResponse() - - client.list_operations(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=locations",) in kw["metadata"] -@pytest.mark.asyncio -async def test_list_operations_field_headers_async(): - client = ConversationProfilesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = operations_pb2.ListOperationsRequest() - request.name = "locations" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_operations), "__call__") as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.ListOperationsResponse() - ) - await client.list_operations(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=locations",) in kw["metadata"] - -def test_list_operations_from_dict(): - client = ConversationProfilesClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_operations), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.ListOperationsResponse() - - response = client.list_operations( - request={ - "name": "locations", - } - ) - call.assert_called() -@pytest.mark.asyncio -async def test_list_operations_from_dict_async(): - client = ConversationProfilesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_operations), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.ListOperationsResponse() - ) - response = await client.list_operations( - request={ - "name": "locations", - } - ) - call.assert_called() - - -def test_list_locations(transport: str = "grpc"): - client = ConversationProfilesClient( - 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 = locations_pb2.ListLocationsRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_locations), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = locations_pb2.ListLocationsResponse() - response = client.list_locations(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 response is the type that we expect. - assert isinstance(response, locations_pb2.ListLocationsResponse) -@pytest.mark.asyncio -async def test_list_locations_async(transport: str = "grpc"): - client = ConversationProfilesAsyncClient( - 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 = locations_pb2.ListLocationsRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_locations), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - locations_pb2.ListLocationsResponse() - ) - response = await client.list_locations(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 response is the type that we expect. - assert isinstance(response, locations_pb2.ListLocationsResponse) - -def test_list_locations_field_headers(): - 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 = locations_pb2.ListLocationsRequest() - request.name = "locations" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_locations), "__call__") as call: - call.return_value = locations_pb2.ListLocationsResponse() - - client.list_locations(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=locations",) in kw["metadata"] -@pytest.mark.asyncio -async def test_list_locations_field_headers_async(): - client = ConversationProfilesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = locations_pb2.ListLocationsRequest() - request.name = "locations" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_locations), "__call__") as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - locations_pb2.ListLocationsResponse() - ) - await client.list_locations(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=locations",) in kw["metadata"] - -def test_list_locations_from_dict(): - client = ConversationProfilesClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_locations), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = locations_pb2.ListLocationsResponse() - - response = client.list_locations( - request={ - "name": "locations", - } - ) - call.assert_called() -@pytest.mark.asyncio -async def test_list_locations_from_dict_async(): - client = ConversationProfilesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_locations), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - locations_pb2.ListLocationsResponse() - ) - response = await client.list_locations( - request={ - "name": "locations", - } - ) - call.assert_called() - - -def test_get_location(transport: str = "grpc"): - client = ConversationProfilesClient( - 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 = locations_pb2.GetLocationRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_location), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = locations_pb2.Location() - response = client.get_location(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 response is the type that we expect. - assert isinstance(response, locations_pb2.Location) -@pytest.mark.asyncio -async def test_get_location_async(transport: str = "grpc_asyncio"): - client = ConversationProfilesAsyncClient( - 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 = locations_pb2.GetLocationRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_location), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - locations_pb2.Location() - ) - response = await client.get_location(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 response is the type that we expect. - assert isinstance(response, locations_pb2.Location) - -def test_get_location_field_headers(): - 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 = locations_pb2.GetLocationRequest() - request.name = "locations/abc" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_location), "__call__") as call: - call.return_value = locations_pb2.Location() - - client.get_location(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=locations/abc",) in kw["metadata"] -@pytest.mark.asyncio -async def test_get_location_field_headers_async(): - client = ConversationProfilesAsyncClient( - credentials=ga_credentials.AnonymousCredentials() - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = locations_pb2.GetLocationRequest() - request.name = "locations/abc" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_location), "__call__") as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - locations_pb2.Location() - ) - await client.get_location(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=locations/abc",) in kw["metadata"] - -def test_get_location_from_dict(): - client = ConversationProfilesClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_locations), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = locations_pb2.Location() - - response = client.get_location( - request={ - "name": "locations/abc", - } - ) - call.assert_called() -@pytest.mark.asyncio -async def test_get_location_from_dict_async(): - client = ConversationProfilesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_locations), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - locations_pb2.Location() - ) - response = await client.get_location( - request={ - "name": "locations", - } - ) - call.assert_called() - - -def test_transport_close(): - transports = { - "rest": "_session", - "grpc": "_grpc_channel", - } - - for transport, close_name in transports.items(): - client = ConversationProfilesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport - ) - with mock.patch.object(type(getattr(client.transport, close_name)), "close") as close: - with client: - close.assert_not_called() - close.assert_called_once() - -def test_client_ctx(): - transports = [ - 'rest', - 'grpc', - ] - for transport in transports: - client = ConversationProfilesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport - ) - # Test client calls underlying transport. - with mock.patch.object(type(client.transport), "close") as close: - close.assert_not_called() - with client: - pass - close.assert_called() - -@pytest.mark.parametrize("client_class,transport_class", [ - (ConversationProfilesClient, transports.ConversationProfilesGrpcTransport), - (ConversationProfilesAsyncClient, transports.ConversationProfilesGrpcAsyncIOTransport), -]) -def test_api_key_credentials(client_class, transport_class): - with mock.patch.object( - google.auth._default, "get_api_key_credentials", create=True - ) as get_api_key_credentials: - mock_cred = mock.Mock() - get_api_key_credentials.return_value = mock_cred - options = client_options.ClientOptions() - options.api_key = "api_key" - 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=mock_cred, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) diff --git a/owl-bot-staging/v2/tests/unit/gapic/dialogflow_v2/test_conversations.py b/owl-bot-staging/v2/tests/unit/gapic/dialogflow_v2/test_conversations.py deleted file mode 100644 index ee0a8b39a..000000000 --- a/owl-bot-staging/v2/tests/unit/gapic/dialogflow_v2/test_conversations.py +++ /dev/null @@ -1,5548 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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 -# try/except added for compatibility with python < 3.8 -try: - from unittest import mock - from unittest.mock import AsyncMock # pragma: NO COVER -except ImportError: # pragma: NO COVER - import mock - -import grpc -from grpc.experimental import aio -from collections.abc import Iterable -from google.protobuf import json_format -import json -import math -import pytest -from proto.marshal.rules.dates import DurationRule, TimestampRule -from proto.marshal.rules import wrappers -from requests import Response -from requests import Request, PreparedRequest -from requests.sessions import Session -from google.protobuf import json_format - -from google.api_core import client_options -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import grpc_helpers -from google.api_core import grpc_helpers_async -from google.api_core import path_template -from google.auth import credentials as ga_credentials -from google.auth.exceptions import MutualTLSChannelError -from google.cloud.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.types import conversation -from google.cloud.dialogflow_v2.types import conversation as gcd_conversation -from google.cloud.dialogflow_v2.types import participant -from google.cloud.location import locations_pb2 -from google.longrunning import operations_pb2 -from google.oauth2 import service_account -from google.protobuf import timestamp_pb2 # type: ignore -import google.auth - - -def client_cert_source_callback(): - return b"cert bytes", b"key bytes" - - -# If default endpoint is localhost, then default mtls endpoint will be the same. -# This method modifies the default endpoint so the client can produce a different -# mtls endpoint for endpoint testing purposes. -def modify_default_endpoint(client): - return "foo.googleapis.com" if ("localhost" in client.DEFAULT_ENDPOINT) else client.DEFAULT_ENDPOINT - - -def test__get_default_mtls_endpoint(): - api_endpoint = "example.googleapis.com" - api_mtls_endpoint = "example.mtls.googleapis.com" - sandbox_endpoint = "example.sandbox.googleapis.com" - sandbox_mtls_endpoint = "example.mtls.sandbox.googleapis.com" - non_googleapi = "api.example.com" - - assert ConversationsClient._get_default_mtls_endpoint(None) is None - assert ConversationsClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint - assert ConversationsClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint - assert ConversationsClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint - assert ConversationsClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint - assert ConversationsClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi - - -@pytest.mark.parametrize("client_class,transport_name", [ - (ConversationsClient, "grpc"), - (ConversationsAsyncClient, "grpc_asyncio"), - (ConversationsClient, "rest"), -]) -def test_conversations_client_from_service_account_info(client_class, transport_name): - 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, transport=transport_name) - assert client.transport._credentials == creds - assert isinstance(client, client_class) - - assert client.transport._host == ( - 'dialogflow.googleapis.com:443' - if transport_name in ['grpc', 'grpc_asyncio'] - else - 'https://dialogflow.googleapis.com' - ) - - -@pytest.mark.parametrize("transport_class,transport_name", [ - (transports.ConversationsGrpcTransport, "grpc"), - (transports.ConversationsGrpcAsyncIOTransport, "grpc_asyncio"), - (transports.ConversationsRestTransport, "rest"), -]) -def test_conversations_client_service_account_always_use_jwt(transport_class, transport_name): - with mock.patch.object(service_account.Credentials, 'with_always_use_jwt_access', create=True) as use_jwt: - creds = service_account.Credentials(None, None, None) - transport = transport_class(credentials=creds, always_use_jwt_access=True) - use_jwt.assert_called_once_with(True) - - with mock.patch.object(service_account.Credentials, 'with_always_use_jwt_access', create=True) as use_jwt: - creds = service_account.Credentials(None, None, None) - transport = transport_class(credentials=creds, always_use_jwt_access=False) - use_jwt.assert_not_called() - - -@pytest.mark.parametrize("client_class,transport_name", [ - (ConversationsClient, "grpc"), - (ConversationsAsyncClient, "grpc_asyncio"), - (ConversationsClient, "rest"), -]) -def test_conversations_client_from_service_account_file(client_class, transport_name): - 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", transport=transport_name) - assert client.transport._credentials == creds - assert isinstance(client, client_class) - - client = client_class.from_service_account_json("dummy/file/path.json", transport=transport_name) - assert client.transport._credentials == creds - assert isinstance(client, client_class) - - assert client.transport._host == ( - 'dialogflow.googleapis.com:443' - if transport_name in ['grpc', 'grpc_asyncio'] - else - 'https://dialogflow.googleapis.com' - ) - - -def test_conversations_client_get_transport_class(): - transport = ConversationsClient.get_transport_class() - available_transports = [ - transports.ConversationsGrpcTransport, - transports.ConversationsRestTransport, - ] - assert transport in available_transports - - transport = ConversationsClient.get_transport_class("grpc") - assert transport == transports.ConversationsGrpcTransport - - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (ConversationsClient, transports.ConversationsGrpcTransport, "grpc"), - (ConversationsAsyncClient, transports.ConversationsGrpcAsyncIOTransport, "grpc_asyncio"), - (ConversationsClient, transports.ConversationsRestTransport, "rest"), -]) -@mock.patch.object(ConversationsClient, "DEFAULT_ENDPOINT", modify_default_endpoint(ConversationsClient)) -@mock.patch.object(ConversationsAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(ConversationsAsyncClient)) -def test_conversations_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(ConversationsClient, '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(ConversationsClient, 'get_transport_class') as gtc: - client = client_class(transport=transport_name) - gtc.assert_called() - - # Check the case api_endpoint is provided. - options = client_options.ClientOptions(api_endpoint="squid.clam.whelk") - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(transport=transport_name, client_options=options) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host="squid.clam.whelk", - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is - # "never". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is - # "always". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_MTLS_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # 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(transport=transport_name) - - # 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(transport=transport_name) - - # 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, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id="octopus", - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - # Check the case api_endpoint is provided - options = client_options.ClientOptions(api_audience="https://language.googleapis.com") - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience="https://language.googleapis.com" - ) - -@pytest.mark.parametrize("client_class,transport_class,transport_name,use_client_cert_env", [ - (ConversationsClient, transports.ConversationsGrpcTransport, "grpc", "true"), - (ConversationsAsyncClient, transports.ConversationsGrpcAsyncIOTransport, "grpc_asyncio", "true"), - (ConversationsClient, transports.ConversationsGrpcTransport, "grpc", "false"), - (ConversationsAsyncClient, transports.ConversationsGrpcAsyncIOTransport, "grpc_asyncio", "false"), - (ConversationsClient, transports.ConversationsRestTransport, "rest", "true"), - (ConversationsClient, transports.ConversationsRestTransport, "rest", "false"), -]) -@mock.patch.object(ConversationsClient, "DEFAULT_ENDPOINT", modify_default_endpoint(ConversationsClient)) -@mock.patch.object(ConversationsAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(ConversationsAsyncClient)) -@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) -def test_conversations_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, transport=transport_name) - - if use_client_cert_env == "false": - expected_client_cert_source = None - expected_host = client.DEFAULT_ENDPOINT - else: - expected_client_cert_source = client_cert_source_callback - expected_host = client.DEFAULT_MTLS_ENDPOINT - - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=expected_host, - scopes=None, - client_cert_source_for_mtls=expected_client_cert_source, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case ADC client cert is provided. Whether client cert is used depends on - # GOOGLE_API_USE_CLIENT_CERTIFICATE value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): - with mock.patch.object(transport_class, '__init__') as patched: - with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): - with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=client_cert_source_callback): - if use_client_cert_env == "false": - expected_host = client.DEFAULT_ENDPOINT - expected_client_cert_source = None - else: - expected_host = client.DEFAULT_MTLS_ENDPOINT - expected_client_cert_source = client_cert_source_callback - - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=expected_host, - scopes=None, - client_cert_source_for_mtls=expected_client_cert_source, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case client_cert_source and ADC client cert are not provided. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): - with mock.patch.object(transport_class, '__init__') as patched: - with mock.patch("google.auth.transport.mtls.has_default_client_cert_source", return_value=False): - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - -@pytest.mark.parametrize("client_class", [ - ConversationsClient, ConversationsAsyncClient -]) -@mock.patch.object(ConversationsClient, "DEFAULT_ENDPOINT", modify_default_endpoint(ConversationsClient)) -@mock.patch.object(ConversationsAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(ConversationsAsyncClient)) -def test_conversations_client_get_mtls_endpoint_and_cert_source(client_class): - mock_client_cert_source = mock.Mock() - - # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "true". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - mock_api_endpoint = "foo" - options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) - assert api_endpoint == mock_api_endpoint - assert cert_source == mock_client_cert_source - - # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "false". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): - mock_client_cert_source = mock.Mock() - mock_api_endpoint = "foo" - options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) - assert api_endpoint == mock_api_endpoint - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "never". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_ENDPOINT - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "always". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert doesn't exist. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=False): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_ENDPOINT - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert exists. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - 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=mock_client_cert_source): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT - assert cert_source == mock_client_cert_source - - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (ConversationsClient, transports.ConversationsGrpcTransport, "grpc"), - (ConversationsAsyncClient, transports.ConversationsGrpcAsyncIOTransport, "grpc_asyncio"), - (ConversationsClient, transports.ConversationsRestTransport, "rest"), -]) -def test_conversations_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, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=["1", "2"], - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - -@pytest.mark.parametrize("client_class,transport_class,transport_name,grpc_helpers", [ - (ConversationsClient, transports.ConversationsGrpcTransport, "grpc", grpc_helpers), - (ConversationsAsyncClient, transports.ConversationsGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), - (ConversationsClient, transports.ConversationsRestTransport, "rest", None), -]) -def test_conversations_client_client_options_credentials_file(client_class, transport_class, transport_name, grpc_helpers): - # 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, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file="credentials.json", - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - -def test_conversations_client_client_options_from_dict(): - with mock.patch('google.cloud.dialogflow_v2.services.conversations.transports.ConversationsGrpcTransport.__init__') as grpc_transport: - grpc_transport.return_value = None - client = ConversationsClient( - client_options={'api_endpoint': 'squid.clam.whelk'} - ) - grpc_transport.assert_called_once_with( - credentials=None, - credentials_file=None, - host="squid.clam.whelk", - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - -@pytest.mark.parametrize("client_class,transport_class,transport_name,grpc_helpers", [ - (ConversationsClient, transports.ConversationsGrpcTransport, "grpc", grpc_helpers), - (ConversationsAsyncClient, transports.ConversationsGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), -]) -def test_conversations_client_create_channel_credentials_file(client_class, transport_class, transport_name, grpc_helpers): - # 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, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file="credentials.json", - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # test that the credentials from file are saved and used as the credentials. - with mock.patch.object( - google.auth, "load_credentials_from_file", autospec=True - ) as load_creds, mock.patch.object( - google.auth, "default", autospec=True - ) as adc, mock.patch.object( - grpc_helpers, "create_channel" - ) as create_channel: - creds = ga_credentials.AnonymousCredentials() - file_creds = ga_credentials.AnonymousCredentials() - load_creds.return_value = (file_creds, None) - adc.return_value = (creds, None) - client = client_class(client_options=options, transport=transport_name) - create_channel.assert_called_with( - "dialogflow.googleapis.com:443", - credentials=file_creds, - credentials_file=None, - quota_project_id=None, - default_scopes=( - 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/dialogflow', -), - scopes=None, - default_host="dialogflow.googleapis.com", - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - -@pytest.mark.parametrize("request_type", [ - gcd_conversation.CreateConversationRequest, - dict, -]) -def test_create_conversation(request_type, transport: str = 'grpc'): - client = ConversationsClient( - 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_conversation), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcd_conversation.Conversation( - name='name_value', - lifecycle_state=gcd_conversation.Conversation.LifecycleState.IN_PROGRESS, - 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 - - -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=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_conversation), - '__call__') as call: - client.create_conversation() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == gcd_conversation.CreateConversationRequest() - -@pytest.mark.asyncio -async def test_create_conversation_async(transport: str = 'grpc_asyncio', request_type=gcd_conversation.CreateConversationRequest): - client = ConversationsAsyncClient( - 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_conversation), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gcd_conversation.Conversation( - name='name_value', - lifecycle_state=gcd_conversation.Conversation.LifecycleState.IN_PROGRESS, - conversation_profile='conversation_profile_value', - 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 - - -@pytest.mark.asyncio -async def test_create_conversation_async_from_dict(): - await test_create_conversation_async(request_type=dict) - - -def test_create_conversation_field_headers(): - 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. - with mock.patch.object( - 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. - 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_conversation_field_headers_async(): - 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. - with mock.patch.object( - type(client.transport.create_conversation), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcd_conversation.Conversation()) - 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] == 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_conversation_flattened(): - 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.create_conversation), - '__call__') 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( - parent='parent_value', - conversation=gcd_conversation.Conversation(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] - arg = args[0].parent - mock_val = 'parent_value' - assert arg == mock_val - arg = args[0].conversation - mock_val = gcd_conversation.Conversation(name='name_value') - assert arg == mock_val - - -def test_create_conversation_flattened_error(): - client = ConversationsClient( - 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_conversation( - gcd_conversation.CreateConversationRequest(), - parent='parent_value', - conversation=gcd_conversation.Conversation(name='name_value'), - ) - -@pytest.mark.asyncio -async def test_create_conversation_flattened_async(): - 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.create_conversation), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcd_conversation.Conversation() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcd_conversation.Conversation()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.create_conversation( - parent='parent_value', - conversation=gcd_conversation.Conversation(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] - arg = args[0].parent - mock_val = 'parent_value' - assert arg == mock_val - arg = args[0].conversation - mock_val = gcd_conversation.Conversation(name='name_value') - assert arg == mock_val - -@pytest.mark.asyncio -async def test_create_conversation_flattened_error_async(): - client = ConversationsAsyncClient( - 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_conversation( - gcd_conversation.CreateConversationRequest(), - parent='parent_value', - conversation=gcd_conversation.Conversation(name='name_value'), - ) - - -@pytest.mark.parametrize("request_type", [ - conversation.ListConversationsRequest, - dict, -]) -def test_list_conversations(request_type, transport: str = 'grpc'): - client = ConversationsClient( - 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_conversations), - '__call__') as call: - # Designate an appropriate return value for the call. - 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' - - -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=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_conversations), - '__call__') as call: - client.list_conversations() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == conversation.ListConversationsRequest() - -@pytest.mark.asyncio -async def test_list_conversations_async(transport: str = 'grpc_asyncio', request_type=conversation.ListConversationsRequest): - client = ConversationsAsyncClient( - 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_conversations), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(conversation.ListConversationsResponse( - 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' - - -@pytest.mark.asyncio -async def test_list_conversations_async_from_dict(): - await test_list_conversations_async(request_type=dict) - - -def test_list_conversations_field_headers(): - 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. - with mock.patch.object( - 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. - 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_conversations_field_headers_async(): - 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. - with mock.patch.object( - type(client.transport.list_conversations), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(conversation.ListConversationsResponse()) - 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] == 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_conversations_flattened(): - 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_conversations), - '__call__') 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', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - arg = args[0].parent - mock_val = 'parent_value' - assert arg == mock_val - - -def test_list_conversations_flattened_error(): - client = ConversationsClient( - 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_conversations( - conversation.ListConversationsRequest(), - parent='parent_value', - ) - -@pytest.mark.asyncio -async def test_list_conversations_flattened_async(): - 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_conversations), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = conversation.ListConversationsResponse() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(conversation.ListConversationsResponse()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.list_conversations( - 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] - arg = args[0].parent - mock_val = 'parent_value' - assert arg == mock_val - -@pytest.mark.asyncio -async def test_list_conversations_flattened_error_async(): - client = ConversationsAsyncClient( - 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_conversations( - conversation.ListConversationsRequest(), - parent='parent_value', - ) - - -def test_list_conversations_pager(transport_name: str = "grpc"): - client = ConversationsClient( - credentials=ga_credentials.AnonymousCredentials, - transport=transport_name, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_conversations), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - conversation.ListConversationsResponse( - conversations=[ - conversation.Conversation(), - conversation.Conversation(), - conversation.Conversation(), - ], - next_page_token='abc', - ), - conversation.ListConversationsResponse( - conversations=[], - next_page_token='def', - ), - conversation.ListConversationsResponse( - conversations=[ - conversation.Conversation(), - ], - next_page_token='ghi', - ), - conversation.ListConversationsResponse( - conversations=[ - conversation.Conversation(), - conversation.Conversation(), - ], - ), - RuntimeError, - ) - - metadata = () - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ('parent', ''), - )), - ) - pager = client.list_conversations(request={}) - - assert pager._metadata == metadata - - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, conversation.Conversation) - for i in results) -def test_list_conversations_pages(transport_name: str = "grpc"): - client = ConversationsClient( - credentials=ga_credentials.AnonymousCredentials, - transport=transport_name, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_conversations), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - conversation.ListConversationsResponse( - conversations=[ - conversation.Conversation(), - conversation.Conversation(), - conversation.Conversation(), - ], - next_page_token='abc', - ), - conversation.ListConversationsResponse( - conversations=[], - next_page_token='def', - ), - conversation.ListConversationsResponse( - conversations=[ - conversation.Conversation(), - ], - next_page_token='ghi', - ), - conversation.ListConversationsResponse( - conversations=[ - conversation.Conversation(), - conversation.Conversation(), - ], - ), - RuntimeError, - ) - pages = list(client.list_conversations(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_conversations_async_pager(): - 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_conversations), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - conversation.ListConversationsResponse( - conversations=[ - conversation.Conversation(), - conversation.Conversation(), - conversation.Conversation(), - ], - next_page_token='abc', - ), - conversation.ListConversationsResponse( - conversations=[], - next_page_token='def', - ), - conversation.ListConversationsResponse( - conversations=[ - conversation.Conversation(), - ], - next_page_token='ghi', - ), - conversation.ListConversationsResponse( - conversations=[ - conversation.Conversation(), - conversation.Conversation(), - ], - ), - RuntimeError, - ) - async_pager = await client.list_conversations(request={},) - assert async_pager.next_page_token == 'abc' - responses = [] - async for response in async_pager: # pragma: no branch - responses.append(response) - - assert len(responses) == 6 - assert all(isinstance(i, conversation.Conversation) - for i in responses) - - -@pytest.mark.asyncio -async def test_list_conversations_async_pages(): - 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_conversations), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - conversation.ListConversationsResponse( - conversations=[ - conversation.Conversation(), - conversation.Conversation(), - conversation.Conversation(), - ], - next_page_token='abc', - ), - conversation.ListConversationsResponse( - conversations=[], - next_page_token='def', - ), - conversation.ListConversationsResponse( - conversations=[ - conversation.Conversation(), - ], - next_page_token='ghi', - ), - conversation.ListConversationsResponse( - conversations=[ - conversation.Conversation(), - conversation.Conversation(), - ], - ), - RuntimeError, - ) - pages = [] - async for page_ in (await client.list_conversations(request={})).pages: # pragma: no branch - pages.append(page_) - for page_, token in zip(pages, ['abc','def','ghi', '']): - assert page_.raw_page.next_page_token == token - -@pytest.mark.parametrize("request_type", [ - conversation.GetConversationRequest, - dict, -]) -def test_get_conversation(request_type, transport: str = 'grpc'): - client = ConversationsClient( - 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_conversation), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = conversation.Conversation( - name='name_value', - lifecycle_state=conversation.Conversation.LifecycleState.IN_PROGRESS, - 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 - - -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=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_conversation), - '__call__') as call: - client.get_conversation() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == conversation.GetConversationRequest() - -@pytest.mark.asyncio -async def test_get_conversation_async(transport: str = 'grpc_asyncio', request_type=conversation.GetConversationRequest): - client = ConversationsAsyncClient( - 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_conversation), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(conversation.Conversation( - name='name_value', - lifecycle_state=conversation.Conversation.LifecycleState.IN_PROGRESS, - conversation_profile='conversation_profile_value', - 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 - - -@pytest.mark.asyncio -async def test_get_conversation_async_from_dict(): - await test_get_conversation_async(request_type=dict) - - -def test_get_conversation_field_headers(): - 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. - 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_conversation_field_headers_async(): - 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. - with mock.patch.object( - type(client.transport.get_conversation), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(conversation.Conversation()) - 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] == 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_conversation_flattened(): - 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', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - arg = args[0].name - mock_val = 'name_value' - assert arg == mock_val - - -def test_get_conversation_flattened_error(): - client = ConversationsClient( - 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_conversation( - conversation.GetConversationRequest(), - name='name_value', - ) - -@pytest.mark.asyncio -async def test_get_conversation_flattened_async(): - 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: - # Designate an appropriate return value for the call. - call.return_value = conversation.Conversation() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(conversation.Conversation()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.get_conversation( - 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] - arg = args[0].name - mock_val = 'name_value' - assert arg == mock_val - -@pytest.mark.asyncio -async def test_get_conversation_flattened_error_async(): - client = ConversationsAsyncClient( - 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_conversation( - conversation.GetConversationRequest(), - name='name_value', - ) - - -@pytest.mark.parametrize("request_type", [ - conversation.CompleteConversationRequest, - dict, -]) -def test_complete_conversation(request_type, transport: str = 'grpc'): - client = ConversationsClient( - 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.complete_conversation), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = conversation.Conversation( - name='name_value', - lifecycle_state=conversation.Conversation.LifecycleState.IN_PROGRESS, - 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 - - -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=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.complete_conversation), - '__call__') as call: - client.complete_conversation() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == conversation.CompleteConversationRequest() - -@pytest.mark.asyncio -async def test_complete_conversation_async(transport: str = 'grpc_asyncio', request_type=conversation.CompleteConversationRequest): - client = ConversationsAsyncClient( - 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.complete_conversation), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(conversation.Conversation( - name='name_value', - lifecycle_state=conversation.Conversation.LifecycleState.IN_PROGRESS, - conversation_profile='conversation_profile_value', - 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 - - -@pytest.mark.asyncio -async def test_complete_conversation_async_from_dict(): - await test_complete_conversation_async(request_type=dict) - - -def test_complete_conversation_field_headers(): - 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. - with mock.patch.object( - 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. - 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_complete_conversation_field_headers_async(): - 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. - with mock.patch.object( - type(client.transport.complete_conversation), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(conversation.Conversation()) - 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] == 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_complete_conversation_flattened(): - 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.complete_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.complete_conversation( - 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] - arg = args[0].name - mock_val = 'name_value' - assert arg == mock_val - - -def test_complete_conversation_flattened_error(): - client = ConversationsClient( - 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.complete_conversation( - conversation.CompleteConversationRequest(), - name='name_value', - ) - -@pytest.mark.asyncio -async def test_complete_conversation_flattened_async(): - 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.complete_conversation), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = conversation.Conversation() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(conversation.Conversation()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.complete_conversation( - 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] - arg = args[0].name - mock_val = 'name_value' - assert arg == mock_val - -@pytest.mark.asyncio -async def test_complete_conversation_flattened_error_async(): - client = ConversationsAsyncClient( - 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.complete_conversation( - conversation.CompleteConversationRequest(), - name='name_value', - ) - - -@pytest.mark.parametrize("request_type", [ - conversation.ListMessagesRequest, - dict, -]) -def test_list_messages(request_type, transport: str = 'grpc'): - client = ConversationsClient( - 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_messages), - '__call__') as call: - # Designate an appropriate return value for the call. - 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' - - -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=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_messages), - '__call__') as call: - client.list_messages() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == conversation.ListMessagesRequest() - -@pytest.mark.asyncio -async def test_list_messages_async(transport: str = 'grpc_asyncio', request_type=conversation.ListMessagesRequest): - client = ConversationsAsyncClient( - 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_messages), - '__call__') as call: - # Designate an appropriate return value for the call. - 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' - - -@pytest.mark.asyncio -async def test_list_messages_async_from_dict(): - await test_list_messages_async(request_type=dict) - - -def test_list_messages_field_headers(): - 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. - 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_messages_field_headers_async(): - 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. - with mock.patch.object( - type(client.transport.list_messages), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(conversation.ListMessagesResponse()) - 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] == 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_messages_flattened(): - 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', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - arg = args[0].parent - mock_val = 'parent_value' - assert arg == mock_val - - -def test_list_messages_flattened_error(): - client = ConversationsClient( - 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_messages( - conversation.ListMessagesRequest(), - parent='parent_value', - ) - -@pytest.mark.asyncio -async def test_list_messages_flattened_async(): - 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: - # Designate an appropriate return value for the call. - call.return_value = conversation.ListMessagesResponse() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(conversation.ListMessagesResponse()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.list_messages( - 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] - arg = args[0].parent - mock_val = 'parent_value' - assert arg == mock_val - -@pytest.mark.asyncio -async def test_list_messages_flattened_error_async(): - client = ConversationsAsyncClient( - 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_messages( - conversation.ListMessagesRequest(), - parent='parent_value', - ) - - -def test_list_messages_pager(transport_name: str = "grpc"): - client = ConversationsClient( - credentials=ga_credentials.AnonymousCredentials, - transport=transport_name, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_messages), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - conversation.ListMessagesResponse( - messages=[ - participant.Message(), - participant.Message(), - participant.Message(), - ], - next_page_token='abc', - ), - conversation.ListMessagesResponse( - messages=[], - next_page_token='def', - ), - conversation.ListMessagesResponse( - messages=[ - participant.Message(), - ], - next_page_token='ghi', - ), - conversation.ListMessagesResponse( - messages=[ - participant.Message(), - participant.Message(), - ], - ), - RuntimeError, - ) - - metadata = () - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ('parent', ''), - )), - ) - pager = client.list_messages(request={}) - - assert pager._metadata == metadata - - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, participant.Message) - for i in results) -def test_list_messages_pages(transport_name: str = "grpc"): - client = ConversationsClient( - credentials=ga_credentials.AnonymousCredentials, - transport=transport_name, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_messages), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - conversation.ListMessagesResponse( - messages=[ - participant.Message(), - participant.Message(), - participant.Message(), - ], - next_page_token='abc', - ), - conversation.ListMessagesResponse( - messages=[], - next_page_token='def', - ), - conversation.ListMessagesResponse( - messages=[ - participant.Message(), - ], - next_page_token='ghi', - ), - conversation.ListMessagesResponse( - messages=[ - participant.Message(), - participant.Message(), - ], - ), - RuntimeError, - ) - pages = list(client.list_messages(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_messages_async_pager(): - 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__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - conversation.ListMessagesResponse( - messages=[ - participant.Message(), - participant.Message(), - participant.Message(), - ], - next_page_token='abc', - ), - conversation.ListMessagesResponse( - messages=[], - next_page_token='def', - ), - conversation.ListMessagesResponse( - messages=[ - participant.Message(), - ], - next_page_token='ghi', - ), - conversation.ListMessagesResponse( - messages=[ - participant.Message(), - participant.Message(), - ], - ), - RuntimeError, - ) - async_pager = await client.list_messages(request={},) - assert async_pager.next_page_token == 'abc' - responses = [] - async for response in async_pager: # pragma: no branch - responses.append(response) - - assert len(responses) == 6 - assert all(isinstance(i, participant.Message) - for i in responses) - - -@pytest.mark.asyncio -async def test_list_messages_async_pages(): - 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__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - conversation.ListMessagesResponse( - messages=[ - participant.Message(), - participant.Message(), - participant.Message(), - ], - next_page_token='abc', - ), - conversation.ListMessagesResponse( - messages=[], - next_page_token='def', - ), - conversation.ListMessagesResponse( - messages=[ - participant.Message(), - ], - next_page_token='ghi', - ), - conversation.ListMessagesResponse( - messages=[ - participant.Message(), - participant.Message(), - ], - ), - RuntimeError, - ) - pages = [] - async for page_ in (await client.list_messages(request={})).pages: # pragma: no branch - pages.append(page_) - for page_, token in zip(pages, ['abc','def','ghi', '']): - assert page_.raw_page.next_page_token == token - -@pytest.mark.parametrize("request_type", [ - gcd_conversation.SuggestConversationSummaryRequest, - dict, -]) -def test_suggest_conversation_summary(request_type, transport: str = 'grpc'): - client = ConversationsClient( - 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.suggest_conversation_summary), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcd_conversation.SuggestConversationSummaryResponse( - latest_message='latest_message_value', - context_size=1311, - ) - response = client.suggest_conversation_summary(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.SuggestConversationSummaryRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, gcd_conversation.SuggestConversationSummaryResponse) - assert response.latest_message == 'latest_message_value' - assert response.context_size == 1311 - - -def test_suggest_conversation_summary_empty_call(): - # 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=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.suggest_conversation_summary), - '__call__') as call: - client.suggest_conversation_summary() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == gcd_conversation.SuggestConversationSummaryRequest() - -@pytest.mark.asyncio -async def test_suggest_conversation_summary_async(transport: str = 'grpc_asyncio', request_type=gcd_conversation.SuggestConversationSummaryRequest): - client = ConversationsAsyncClient( - 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.suggest_conversation_summary), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gcd_conversation.SuggestConversationSummaryResponse( - latest_message='latest_message_value', - context_size=1311, - )) - response = await client.suggest_conversation_summary(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.SuggestConversationSummaryRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, gcd_conversation.SuggestConversationSummaryResponse) - assert response.latest_message == 'latest_message_value' - assert response.context_size == 1311 - - -@pytest.mark.asyncio -async def test_suggest_conversation_summary_async_from_dict(): - await test_suggest_conversation_summary_async(request_type=dict) - - -def test_suggest_conversation_summary_field_headers(): - 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.SuggestConversationSummaryRequest() - - request.conversation = 'conversation_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.suggest_conversation_summary), - '__call__') as call: - call.return_value = gcd_conversation.SuggestConversationSummaryResponse() - client.suggest_conversation_summary(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', - 'conversation=conversation_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_suggest_conversation_summary_field_headers_async(): - 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.SuggestConversationSummaryRequest() - - request.conversation = 'conversation_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.suggest_conversation_summary), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcd_conversation.SuggestConversationSummaryResponse()) - await client.suggest_conversation_summary(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', - 'conversation=conversation_value', - ) in kw['metadata'] - - -def test_suggest_conversation_summary_flattened(): - 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.suggest_conversation_summary), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcd_conversation.SuggestConversationSummaryResponse() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.suggest_conversation_summary( - conversation='conversation_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] - arg = args[0].conversation - mock_val = 'conversation_value' - assert arg == mock_val - - -def test_suggest_conversation_summary_flattened_error(): - client = ConversationsClient( - 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.suggest_conversation_summary( - gcd_conversation.SuggestConversationSummaryRequest(), - conversation='conversation_value', - ) - -@pytest.mark.asyncio -async def test_suggest_conversation_summary_flattened_async(): - 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.suggest_conversation_summary), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcd_conversation.SuggestConversationSummaryResponse() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcd_conversation.SuggestConversationSummaryResponse()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.suggest_conversation_summary( - conversation='conversation_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - arg = args[0].conversation - mock_val = 'conversation_value' - assert arg == mock_val - -@pytest.mark.asyncio -async def test_suggest_conversation_summary_flattened_error_async(): - client = ConversationsAsyncClient( - 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.suggest_conversation_summary( - gcd_conversation.SuggestConversationSummaryRequest(), - conversation='conversation_value', - ) - - -@pytest.mark.parametrize("request_type", [ - gcd_conversation.CreateConversationRequest, - dict, -]) -def test_create_conversation_rest(request_type): - client = ConversationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1'} - request_init["conversation"] = {'name': 'name_value', 'lifecycle_state': 1, 'conversation_profile': 'conversation_profile_value', 'phone_number': {'phone_number': 'phone_number_value'}, 'start_time': {'seconds': 751, 'nanos': 543}, 'end_time': {}, 'conversation_stage': 1} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = gcd_conversation.Conversation( - name='name_value', - lifecycle_state=gcd_conversation.Conversation.LifecycleState.IN_PROGRESS, - conversation_profile='conversation_profile_value', - conversation_stage=gcd_conversation.Conversation.ConversationStage.VIRTUAL_AGENT_STAGE, - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - pb_return_value = gcd_conversation.Conversation.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.create_conversation(request) - - # 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 - - -def test_create_conversation_rest_required_fields(request_type=gcd_conversation.CreateConversationRequest): - transport_class = transports.ConversationsRestTransport - - request_init = {} - request_init["parent"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - including_default_value_fields=False, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_conversation._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["parent"] = 'parent_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_conversation._get_unset_required_fields(jsonified_request) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("conversation_id", )) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "parent" in jsonified_request - assert jsonified_request["parent"] == 'parent_value' - - client = ConversationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = gcd_conversation.Conversation() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "post", - 'query_params': pb_request, - } - transcode_result['body'] = pb_request - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - - pb_return_value = gcd_conversation.Conversation.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.create_conversation(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_create_conversation_rest_unset_required_fields(): - transport = transports.ConversationsRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.create_conversation._get_unset_required_fields({}) - assert set(unset_fields) == (set(("conversationId", )) & set(("parent", "conversation", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_create_conversation_rest_interceptors(null_interceptor): - transport = transports.ConversationsRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.ConversationsRestInterceptor(), - ) - client = ConversationsClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.ConversationsRestInterceptor, "post_create_conversation") as post, \ - mock.patch.object(transports.ConversationsRestInterceptor, "pre_create_conversation") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = gcd_conversation.CreateConversationRequest.pb(gcd_conversation.CreateConversationRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = gcd_conversation.Conversation.to_json(gcd_conversation.Conversation()) - - request = gcd_conversation.CreateConversationRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = gcd_conversation.Conversation() - - client.create_conversation(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_create_conversation_rest_bad_request(transport: str = 'rest', request_type=gcd_conversation.CreateConversationRequest): - client = ConversationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1'} - request_init["conversation"] = {'name': 'name_value', 'lifecycle_state': 1, 'conversation_profile': 'conversation_profile_value', 'phone_number': {'phone_number': 'phone_number_value'}, 'start_time': {'seconds': 751, 'nanos': 543}, 'end_time': {}, 'conversation_stage': 1} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.create_conversation(request) - - -def test_create_conversation_rest_flattened(): - client = ConversationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = gcd_conversation.Conversation() - - # get arguments that satisfy an http rule for this method - sample_request = {'parent': 'projects/sample1'} - - # get truthy value for each flattened field - mock_args = dict( - parent='parent_value', - conversation=gcd_conversation.Conversation(name='name_value'), - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - pb_return_value = gcd_conversation.Conversation.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.create_conversation(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v2/{parent=projects/*}/conversations" % client.transport._host, args[1]) - - -def test_create_conversation_rest_flattened_error(transport: str = 'rest'): - client = ConversationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.create_conversation( - gcd_conversation.CreateConversationRequest(), - parent='parent_value', - conversation=gcd_conversation.Conversation(name='name_value'), - ) - - -def test_create_conversation_rest_error(): - client = ConversationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - conversation.ListConversationsRequest, - dict, -]) -def test_list_conversations_rest(request_type): - client = ConversationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = conversation.ListConversationsResponse( - next_page_token='next_page_token_value', - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - pb_return_value = conversation.ListConversationsResponse.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.list_conversations(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListConversationsPager) - assert response.next_page_token == 'next_page_token_value' - - -def test_list_conversations_rest_required_fields(request_type=conversation.ListConversationsRequest): - transport_class = transports.ConversationsRestTransport - - request_init = {} - request_init["parent"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - including_default_value_fields=False, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).list_conversations._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["parent"] = 'parent_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).list_conversations._get_unset_required_fields(jsonified_request) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("filter", "page_size", "page_token", )) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "parent" in jsonified_request - assert jsonified_request["parent"] == 'parent_value' - - client = ConversationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = conversation.ListConversationsResponse() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "get", - 'query_params': pb_request, - } - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - - pb_return_value = conversation.ListConversationsResponse.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.list_conversations(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_list_conversations_rest_unset_required_fields(): - transport = transports.ConversationsRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.list_conversations._get_unset_required_fields({}) - assert set(unset_fields) == (set(("filter", "pageSize", "pageToken", )) & set(("parent", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_list_conversations_rest_interceptors(null_interceptor): - transport = transports.ConversationsRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.ConversationsRestInterceptor(), - ) - client = ConversationsClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.ConversationsRestInterceptor, "post_list_conversations") as post, \ - mock.patch.object(transports.ConversationsRestInterceptor, "pre_list_conversations") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = conversation.ListConversationsRequest.pb(conversation.ListConversationsRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = conversation.ListConversationsResponse.to_json(conversation.ListConversationsResponse()) - - request = conversation.ListConversationsRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = conversation.ListConversationsResponse() - - client.list_conversations(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_list_conversations_rest_bad_request(transport: str = 'rest', request_type=conversation.ListConversationsRequest): - client = ConversationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.list_conversations(request) - - -def test_list_conversations_rest_flattened(): - client = ConversationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = conversation.ListConversationsResponse() - - # get arguments that satisfy an http rule for this method - sample_request = {'parent': 'projects/sample1'} - - # get truthy value for each flattened field - mock_args = dict( - parent='parent_value', - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - pb_return_value = conversation.ListConversationsResponse.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.list_conversations(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v2/{parent=projects/*}/conversations" % client.transport._host, args[1]) - - -def test_list_conversations_rest_flattened_error(transport: str = 'rest'): - client = ConversationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.list_conversations( - conversation.ListConversationsRequest(), - parent='parent_value', - ) - - -def test_list_conversations_rest_pager(transport: str = 'rest'): - client = ConversationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # TODO(kbandes): remove this mock unless there's a good reason for it. - #with mock.patch.object(path_template, 'transcode') as transcode: - # Set the response as a series of pages - response = ( - conversation.ListConversationsResponse( - conversations=[ - conversation.Conversation(), - conversation.Conversation(), - conversation.Conversation(), - ], - next_page_token='abc', - ), - conversation.ListConversationsResponse( - conversations=[], - next_page_token='def', - ), - conversation.ListConversationsResponse( - conversations=[ - conversation.Conversation(), - ], - next_page_token='ghi', - ), - conversation.ListConversationsResponse( - conversations=[ - conversation.Conversation(), - conversation.Conversation(), - ], - ), - ) - # Two responses for two calls - response = response + response - - # Wrap the values into proper Response objs - response = tuple(conversation.ListConversationsResponse.to_json(x) for x in response) - return_values = tuple(Response() for i in response) - for return_val, response_val in zip(return_values, response): - return_val._content = response_val.encode('UTF-8') - return_val.status_code = 200 - req.side_effect = return_values - - sample_request = {'parent': 'projects/sample1'} - - pager = client.list_conversations(request=sample_request) - - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, conversation.Conversation) - for i in results) - - pages = list(client.list_conversations(request=sample_request).pages) - for page_, token in zip(pages, ['abc','def','ghi', '']): - assert page_.raw_page.next_page_token == token - - -@pytest.mark.parametrize("request_type", [ - conversation.GetConversationRequest, - dict, -]) -def test_get_conversation_rest(request_type): - client = ConversationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/conversations/sample2'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = conversation.Conversation( - name='name_value', - lifecycle_state=conversation.Conversation.LifecycleState.IN_PROGRESS, - conversation_profile='conversation_profile_value', - conversation_stage=conversation.Conversation.ConversationStage.VIRTUAL_AGENT_STAGE, - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - pb_return_value = conversation.Conversation.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.get_conversation(request) - - # 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 - - -def test_get_conversation_rest_required_fields(request_type=conversation.GetConversationRequest): - transport_class = transports.ConversationsRestTransport - - request_init = {} - request_init["name"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - including_default_value_fields=False, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_conversation._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["name"] = 'name_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_conversation._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "name" in jsonified_request - assert jsonified_request["name"] == 'name_value' - - client = ConversationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = conversation.Conversation() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "get", - 'query_params': pb_request, - } - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - - pb_return_value = conversation.Conversation.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.get_conversation(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_get_conversation_rest_unset_required_fields(): - transport = transports.ConversationsRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.get_conversation._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_get_conversation_rest_interceptors(null_interceptor): - transport = transports.ConversationsRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.ConversationsRestInterceptor(), - ) - client = ConversationsClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.ConversationsRestInterceptor, "post_get_conversation") as post, \ - mock.patch.object(transports.ConversationsRestInterceptor, "pre_get_conversation") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = conversation.GetConversationRequest.pb(conversation.GetConversationRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = conversation.Conversation.to_json(conversation.Conversation()) - - request = conversation.GetConversationRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = conversation.Conversation() - - client.get_conversation(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_get_conversation_rest_bad_request(transport: str = 'rest', request_type=conversation.GetConversationRequest): - client = ConversationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/conversations/sample2'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.get_conversation(request) - - -def test_get_conversation_rest_flattened(): - client = ConversationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = conversation.Conversation() - - # get arguments that satisfy an http rule for this method - sample_request = {'name': 'projects/sample1/conversations/sample2'} - - # get truthy value for each flattened field - mock_args = dict( - name='name_value', - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - pb_return_value = conversation.Conversation.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.get_conversation(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v2/{name=projects/*/conversations/*}" % client.transport._host, args[1]) - - -def test_get_conversation_rest_flattened_error(transport: str = 'rest'): - client = ConversationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.get_conversation( - conversation.GetConversationRequest(), - name='name_value', - ) - - -def test_get_conversation_rest_error(): - client = ConversationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - conversation.CompleteConversationRequest, - dict, -]) -def test_complete_conversation_rest(request_type): - client = ConversationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/conversations/sample2'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = conversation.Conversation( - name='name_value', - lifecycle_state=conversation.Conversation.LifecycleState.IN_PROGRESS, - conversation_profile='conversation_profile_value', - conversation_stage=conversation.Conversation.ConversationStage.VIRTUAL_AGENT_STAGE, - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - pb_return_value = conversation.Conversation.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.complete_conversation(request) - - # 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 - - -def test_complete_conversation_rest_required_fields(request_type=conversation.CompleteConversationRequest): - transport_class = transports.ConversationsRestTransport - - request_init = {} - request_init["name"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - including_default_value_fields=False, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).complete_conversation._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["name"] = 'name_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).complete_conversation._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "name" in jsonified_request - assert jsonified_request["name"] == 'name_value' - - client = ConversationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = conversation.Conversation() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "post", - 'query_params': pb_request, - } - transcode_result['body'] = pb_request - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - - pb_return_value = conversation.Conversation.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.complete_conversation(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_complete_conversation_rest_unset_required_fields(): - transport = transports.ConversationsRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.complete_conversation._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_complete_conversation_rest_interceptors(null_interceptor): - transport = transports.ConversationsRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.ConversationsRestInterceptor(), - ) - client = ConversationsClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.ConversationsRestInterceptor, "post_complete_conversation") as post, \ - mock.patch.object(transports.ConversationsRestInterceptor, "pre_complete_conversation") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = conversation.CompleteConversationRequest.pb(conversation.CompleteConversationRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = conversation.Conversation.to_json(conversation.Conversation()) - - request = conversation.CompleteConversationRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = conversation.Conversation() - - client.complete_conversation(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_complete_conversation_rest_bad_request(transport: str = 'rest', request_type=conversation.CompleteConversationRequest): - client = ConversationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/conversations/sample2'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.complete_conversation(request) - - -def test_complete_conversation_rest_flattened(): - client = ConversationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = conversation.Conversation() - - # get arguments that satisfy an http rule for this method - sample_request = {'name': 'projects/sample1/conversations/sample2'} - - # get truthy value for each flattened field - mock_args = dict( - name='name_value', - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - pb_return_value = conversation.Conversation.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.complete_conversation(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v2/{name=projects/*/conversations/*}:complete" % client.transport._host, args[1]) - - -def test_complete_conversation_rest_flattened_error(transport: str = 'rest'): - client = ConversationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.complete_conversation( - conversation.CompleteConversationRequest(), - name='name_value', - ) - - -def test_complete_conversation_rest_error(): - client = ConversationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - conversation.ListMessagesRequest, - dict, -]) -def test_list_messages_rest(request_type): - client = ConversationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1/conversations/sample2'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = conversation.ListMessagesResponse( - next_page_token='next_page_token_value', - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - pb_return_value = conversation.ListMessagesResponse.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.list_messages(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListMessagesPager) - assert response.next_page_token == 'next_page_token_value' - - -def test_list_messages_rest_required_fields(request_type=conversation.ListMessagesRequest): - transport_class = transports.ConversationsRestTransport - - request_init = {} - request_init["parent"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - including_default_value_fields=False, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).list_messages._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["parent"] = 'parent_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).list_messages._get_unset_required_fields(jsonified_request) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("filter", "page_size", "page_token", )) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "parent" in jsonified_request - assert jsonified_request["parent"] == 'parent_value' - - client = ConversationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = conversation.ListMessagesResponse() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "get", - 'query_params': pb_request, - } - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - - pb_return_value = conversation.ListMessagesResponse.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.list_messages(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_list_messages_rest_unset_required_fields(): - transport = transports.ConversationsRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.list_messages._get_unset_required_fields({}) - assert set(unset_fields) == (set(("filter", "pageSize", "pageToken", )) & set(("parent", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_list_messages_rest_interceptors(null_interceptor): - transport = transports.ConversationsRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.ConversationsRestInterceptor(), - ) - client = ConversationsClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.ConversationsRestInterceptor, "post_list_messages") as post, \ - mock.patch.object(transports.ConversationsRestInterceptor, "pre_list_messages") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = conversation.ListMessagesRequest.pb(conversation.ListMessagesRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = conversation.ListMessagesResponse.to_json(conversation.ListMessagesResponse()) - - request = conversation.ListMessagesRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = conversation.ListMessagesResponse() - - client.list_messages(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_list_messages_rest_bad_request(transport: str = 'rest', request_type=conversation.ListMessagesRequest): - client = ConversationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1/conversations/sample2'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.list_messages(request) - - -def test_list_messages_rest_flattened(): - client = ConversationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = conversation.ListMessagesResponse() - - # get arguments that satisfy an http rule for this method - sample_request = {'parent': 'projects/sample1/conversations/sample2'} - - # get truthy value for each flattened field - mock_args = dict( - parent='parent_value', - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - pb_return_value = conversation.ListMessagesResponse.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.list_messages(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v2/{parent=projects/*/conversations/*}/messages" % client.transport._host, args[1]) - - -def test_list_messages_rest_flattened_error(transport: str = 'rest'): - client = ConversationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.list_messages( - conversation.ListMessagesRequest(), - parent='parent_value', - ) - - -def test_list_messages_rest_pager(transport: str = 'rest'): - client = ConversationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # TODO(kbandes): remove this mock unless there's a good reason for it. - #with mock.patch.object(path_template, 'transcode') as transcode: - # Set the response as a series of pages - response = ( - conversation.ListMessagesResponse( - messages=[ - participant.Message(), - participant.Message(), - participant.Message(), - ], - next_page_token='abc', - ), - conversation.ListMessagesResponse( - messages=[], - next_page_token='def', - ), - conversation.ListMessagesResponse( - messages=[ - participant.Message(), - ], - next_page_token='ghi', - ), - conversation.ListMessagesResponse( - messages=[ - participant.Message(), - participant.Message(), - ], - ), - ) - # Two responses for two calls - response = response + response - - # Wrap the values into proper Response objs - response = tuple(conversation.ListMessagesResponse.to_json(x) for x in response) - return_values = tuple(Response() for i in response) - for return_val, response_val in zip(return_values, response): - return_val._content = response_val.encode('UTF-8') - return_val.status_code = 200 - req.side_effect = return_values - - sample_request = {'parent': 'projects/sample1/conversations/sample2'} - - pager = client.list_messages(request=sample_request) - - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, participant.Message) - for i in results) - - pages = list(client.list_messages(request=sample_request).pages) - for page_, token in zip(pages, ['abc','def','ghi', '']): - assert page_.raw_page.next_page_token == token - - -@pytest.mark.parametrize("request_type", [ - gcd_conversation.SuggestConversationSummaryRequest, - dict, -]) -def test_suggest_conversation_summary_rest(request_type): - client = ConversationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'conversation': 'projects/sample1/conversations/sample2'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = gcd_conversation.SuggestConversationSummaryResponse( - latest_message='latest_message_value', - context_size=1311, - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - pb_return_value = gcd_conversation.SuggestConversationSummaryResponse.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.suggest_conversation_summary(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, gcd_conversation.SuggestConversationSummaryResponse) - assert response.latest_message == 'latest_message_value' - assert response.context_size == 1311 - - -def test_suggest_conversation_summary_rest_required_fields(request_type=gcd_conversation.SuggestConversationSummaryRequest): - transport_class = transports.ConversationsRestTransport - - request_init = {} - request_init["conversation"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - including_default_value_fields=False, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).suggest_conversation_summary._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["conversation"] = 'conversation_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).suggest_conversation_summary._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "conversation" in jsonified_request - assert jsonified_request["conversation"] == 'conversation_value' - - client = ConversationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = gcd_conversation.SuggestConversationSummaryResponse() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "post", - 'query_params': pb_request, - } - transcode_result['body'] = pb_request - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - - pb_return_value = gcd_conversation.SuggestConversationSummaryResponse.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.suggest_conversation_summary(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_suggest_conversation_summary_rest_unset_required_fields(): - transport = transports.ConversationsRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.suggest_conversation_summary._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("conversation", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_suggest_conversation_summary_rest_interceptors(null_interceptor): - transport = transports.ConversationsRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.ConversationsRestInterceptor(), - ) - client = ConversationsClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.ConversationsRestInterceptor, "post_suggest_conversation_summary") as post, \ - mock.patch.object(transports.ConversationsRestInterceptor, "pre_suggest_conversation_summary") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = gcd_conversation.SuggestConversationSummaryRequest.pb(gcd_conversation.SuggestConversationSummaryRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = gcd_conversation.SuggestConversationSummaryResponse.to_json(gcd_conversation.SuggestConversationSummaryResponse()) - - request = gcd_conversation.SuggestConversationSummaryRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = gcd_conversation.SuggestConversationSummaryResponse() - - client.suggest_conversation_summary(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_suggest_conversation_summary_rest_bad_request(transport: str = 'rest', request_type=gcd_conversation.SuggestConversationSummaryRequest): - client = ConversationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'conversation': 'projects/sample1/conversations/sample2'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.suggest_conversation_summary(request) - - -def test_suggest_conversation_summary_rest_flattened(): - client = ConversationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = gcd_conversation.SuggestConversationSummaryResponse() - - # get arguments that satisfy an http rule for this method - sample_request = {'conversation': 'projects/sample1/conversations/sample2'} - - # get truthy value for each flattened field - mock_args = dict( - conversation='conversation_value', - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - pb_return_value = gcd_conversation.SuggestConversationSummaryResponse.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.suggest_conversation_summary(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v2/{conversation=projects/*/conversations/*}/suggestions:suggestConversationSummary" % client.transport._host, args[1]) - - -def test_suggest_conversation_summary_rest_flattened_error(transport: str = 'rest'): - client = ConversationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.suggest_conversation_summary( - gcd_conversation.SuggestConversationSummaryRequest(), - conversation='conversation_value', - ) - - -def test_suggest_conversation_summary_rest_error(): - client = ConversationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -def test_credentials_transport_error(): - # It is an error to provide credentials and a transport instance. - transport = transports.ConversationsGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = ConversationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # It is an error to provide a credentials file and a transport instance. - transport = transports.ConversationsGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = ConversationsClient( - client_options={"credentials_file": "credentials.json"}, - transport=transport, - ) - - # It is an error to provide an api_key and a transport instance. - transport = transports.ConversationsGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - options = client_options.ClientOptions() - options.api_key = "api_key" - with pytest.raises(ValueError): - client = ConversationsClient( - client_options=options, - transport=transport, - ) - - # It is an error to provide an api_key and a credential. - options = mock.Mock() - options.api_key = "api_key" - with pytest.raises(ValueError): - client = ConversationsClient( - client_options=options, - credentials=ga_credentials.AnonymousCredentials() - ) - - # It is an error to provide scopes and a transport instance. - transport = transports.ConversationsGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = ConversationsClient( - client_options={"scopes": ["1", "2"]}, - transport=transport, - ) - - -def test_transport_instance(): - # A client may be instantiated with a custom transport instance. - transport = transports.ConversationsGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - client = ConversationsClient(transport=transport) - assert client.transport is transport - -def test_transport_get_channel(): - # A client may be instantiated with a custom transport instance. - transport = transports.ConversationsGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - - transport = transports.ConversationsGrpcAsyncIOTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - -@pytest.mark.parametrize("transport_class", [ - transports.ConversationsGrpcTransport, - transports.ConversationsGrpcAsyncIOTransport, - transports.ConversationsRestTransport, -]) -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() - -@pytest.mark.parametrize("transport_name", [ - "grpc", - "rest", -]) -def test_transport_kind(transport_name): - transport = ConversationsClient.get_transport_class(transport_name)( - credentials=ga_credentials.AnonymousCredentials(), - ) - assert transport.kind == transport_name - -def test_transport_grpc_default(): - # A client should use the gRPC transport by default. - 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(core_exceptions.DuplicateCredentialArgs): - transport = transports.ConversationsTransport( - credentials=ga_credentials.AnonymousCredentials(), - credentials_file="credentials.json" - ) - - -def test_conversations_base_transport(): - # Instantiate the base transport. - with mock.patch('google.cloud.dialogflow_v2.services.conversations.transports.ConversationsTransport.__init__') as Transport: - Transport.return_value = None - transport = transports.ConversationsTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Every method on the transport should just blindly - # raise NotImplementedError. - methods = ( - 'create_conversation', - 'list_conversations', - 'get_conversation', - 'complete_conversation', - 'list_messages', - 'suggest_conversation_summary', - 'get_location', - 'list_locations', - 'get_operation', - 'cancel_operation', - 'list_operations', - ) - for method in methods: - with pytest.raises(NotImplementedError): - getattr(transport, method)(request=object()) - - with pytest.raises(NotImplementedError): - transport.close() - - # Catch all for all remaining methods and properties - remainder = [ - 'kind', - ] - for r in remainder: - with pytest.raises(NotImplementedError): - getattr(transport, r)() - - -def test_conversations_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.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", - ) - - -def test_conversations_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.conversations.transports.ConversationsTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.ConversationsTransport() - adc.assert_called_once() - - -def test_conversations_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) - 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, - ) - - -@pytest.mark.parametrize( - "transport_class", - [ - transports.ConversationsGrpcTransport, - transports.ConversationsGrpcAsyncIOTransport, - ], -) -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(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, - transports.ConversationsRestTransport, - ], -) -def test_conversations_transport_auth_gdch_credentials(transport_class): - host = 'https://language.com' - api_audience_tests = [None, 'https://language2.com'] - api_audience_expect = [host, 'https://language2.com'] - for t, e in zip(api_audience_tests, api_audience_expect): - with mock.patch.object(google.auth, 'default', autospec=True) as adc: - gdch_mock = mock.MagicMock() - type(gdch_mock).with_gdch_audience = mock.PropertyMock(return_value=gdch_mock) - adc.return_value = (gdch_mock, None) - transport_class(host=host, api_audience=t) - gdch_mock.with_gdch_audience.assert_called_once_with( - e - ) - - -@pytest.mark.parametrize( - "transport_class,grpc_helpers", - [ - (transports.ConversationsGrpcTransport, grpc_helpers), - (transports.ConversationsGrpcAsyncIOTransport, grpc_helpers_async) - ], -) -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", [transports.ConversationsGrpcTransport, transports.ConversationsGrpcAsyncIOTransport]) -def test_conversations_grpc_transport_client_cert_source_for_mtls( - transport_class -): - cred = ga_credentials.AnonymousCredentials() - - # Check ssl_channel_credentials is used if provided. - with mock.patch.object(transport_class, "create_channel") as mock_create_channel: - mock_ssl_channel_creds = mock.Mock() - transport_class( - host="squid.clam.whelk", - credentials=cred, - ssl_channel_credentials=mock_ssl_channel_creds - ) - mock_create_channel.assert_called_once_with( - "squid.clam.whelk:443", - credentials=cred, - credentials_file=None, - scopes=None, - ssl_credentials=mock_ssl_channel_creds, - quota_project_id=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - # Check if ssl_channel_credentials is not provided, then client_cert_source_for_mtls - # is used. - with mock.patch.object(transport_class, "create_channel", return_value=mock.Mock()): - with mock.patch("grpc.ssl_channel_credentials") as mock_ssl_cred: - transport_class( - credentials=cred, - client_cert_source_for_mtls=client_cert_source_callback - ) - expected_cert, expected_key = client_cert_source_callback() - mock_ssl_cred.assert_called_once_with( - certificate_chain=expected_cert, - private_key=expected_key - ) - -def test_conversations_http_transport_client_cert_source_for_mtls(): - cred = ga_credentials.AnonymousCredentials() - with mock.patch("google.auth.transport.requests.AuthorizedSession.configure_mtls_channel") as mock_configure_mtls_channel: - transports.ConversationsRestTransport ( - credentials=cred, - client_cert_source_for_mtls=client_cert_source_callback - ) - mock_configure_mtls_channel.assert_called_once_with(client_cert_source_callback) - - -@pytest.mark.parametrize("transport_name", [ - "grpc", - "grpc_asyncio", - "rest", -]) -def test_conversations_host_no_port(transport_name): - client = ConversationsClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='dialogflow.googleapis.com'), - transport=transport_name, - ) - assert client.transport._host == ( - 'dialogflow.googleapis.com:443' - if transport_name in ['grpc', 'grpc_asyncio'] - else 'https://dialogflow.googleapis.com' - ) - -@pytest.mark.parametrize("transport_name", [ - "grpc", - "grpc_asyncio", - "rest", -]) -def test_conversations_host_with_port(transport_name): - client = ConversationsClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='dialogflow.googleapis.com:8000'), - transport=transport_name, - ) - assert client.transport._host == ( - 'dialogflow.googleapis.com:8000' - if transport_name in ['grpc', 'grpc_asyncio'] - else 'https://dialogflow.googleapis.com:8000' - ) - -@pytest.mark.parametrize("transport_name", [ - "rest", -]) -def test_conversations_client_transport_session_collision(transport_name): - creds1 = ga_credentials.AnonymousCredentials() - creds2 = ga_credentials.AnonymousCredentials() - client1 = ConversationsClient( - credentials=creds1, - transport=transport_name, - ) - client2 = ConversationsClient( - credentials=creds2, - transport=transport_name, - ) - session1 = client1.transport.create_conversation._session - session2 = client2.transport.create_conversation._session - assert session1 != session2 - session1 = client1.transport.list_conversations._session - session2 = client2.transport.list_conversations._session - assert session1 != session2 - session1 = client1.transport.get_conversation._session - session2 = client2.transport.get_conversation._session - assert session1 != session2 - session1 = client1.transport.complete_conversation._session - session2 = client2.transport.complete_conversation._session - assert session1 != session2 - session1 = client1.transport.list_messages._session - session2 = client2.transport.list_messages._session - assert session1 != session2 - session1 = client1.transport.suggest_conversation_summary._session - session2 = client2.transport.suggest_conversation_summary._session - assert session1 != session2 -def test_conversations_grpc_transport_channel(): - channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.ConversationsGrpcTransport( - 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_conversations_grpc_asyncio_transport_channel(): - channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.ConversationsGrpcAsyncIOTransport( - 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.ConversationsGrpcTransport, transports.ConversationsGrpcAsyncIOTransport]) -def test_conversations_transport_channel_mtls_with_client_cert_source( - transport_class -): - with mock.patch("grpc.ssl_channel_credentials", autospec=True) as grpc_ssl_channel_cred: - with mock.patch.object(transport_class, "create_channel") as grpc_create_channel: - mock_ssl_cred = mock.Mock() - grpc_ssl_channel_cred.return_value = mock_ssl_cred - - mock_grpc_channel = mock.Mock() - grpc_create_channel.return_value = mock_grpc_channel - - cred = ga_credentials.AnonymousCredentials() - with pytest.warns(DeprecationWarning): - with mock.patch.object(google.auth, 'default') as adc: - adc.return_value = (cred, None) - transport = transport_class( - host="squid.clam.whelk", - api_mtls_endpoint="mtls.squid.clam.whelk", - client_cert_source=client_cert_source_callback, - ) - adc.assert_called_once() - - grpc_ssl_channel_cred.assert_called_once_with( - certificate_chain=b"cert bytes", private_key=b"key bytes" - ) - grpc_create_channel.assert_called_once_with( - "mtls.squid.clam.whelk:443", - credentials=cred, - credentials_file=None, - scopes=None, - ssl_credentials=mock_ssl_cred, - quota_project_id=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - assert transport.grpc_channel == mock_grpc_channel - assert transport._ssl_channel_credentials == mock_ssl_cred - - -# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are -# removed from grpc/grpc_asyncio transport constructor. -@pytest.mark.parametrize("transport_class", [transports.ConversationsGrpcTransport, transports.ConversationsGrpcAsyncIOTransport]) -def test_conversations_transport_channel_mtls_with_adc( - transport_class -): - mock_ssl_cred = mock.Mock() - with mock.patch.multiple( - "google.auth.transport.grpc.SslCredentials", - __init__=mock.Mock(return_value=None), - ssl_credentials=mock.PropertyMock(return_value=mock_ssl_cred), - ): - with mock.patch.object(transport_class, "create_channel") as grpc_create_channel: - mock_grpc_channel = mock.Mock() - grpc_create_channel.return_value = mock_grpc_channel - mock_cred = mock.Mock() - - with pytest.warns(DeprecationWarning): - transport = transport_class( - host="squid.clam.whelk", - credentials=mock_cred, - api_mtls_endpoint="mtls.squid.clam.whelk", - client_cert_source=None, - ) - - grpc_create_channel.assert_called_once_with( - "mtls.squid.clam.whelk:443", - credentials=mock_cred, - credentials_file=None, - scopes=None, - ssl_credentials=mock_ssl_cred, - quota_project_id=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - assert transport.grpc_channel == mock_grpc_channel - - -def test_answer_record_path(): - project = "squid" - answer_record = "clam" - expected = "projects/{project}/answerRecords/{answer_record}".format(project=project, answer_record=answer_record, ) - actual = ConversationsClient.answer_record_path(project, answer_record) - assert expected == actual - - -def test_parse_answer_record_path(): - expected = { - "project": "whelk", - "answer_record": "octopus", - } - path = ConversationsClient.answer_record_path(**expected) - - # Check that the path construction is reversible. - actual = ConversationsClient.parse_answer_record_path(path) - assert expected == actual - -def test_conversation_path(): - project = "oyster" - conversation = "nudibranch" - expected = "projects/{project}/conversations/{conversation}".format(project=project, conversation=conversation, ) - actual = ConversationsClient.conversation_path(project, conversation) - assert expected == actual - - -def test_parse_conversation_path(): - expected = { - "project": "cuttlefish", - "conversation": "mussel", - } - path = ConversationsClient.conversation_path(**expected) - - # Check that the path construction is reversible. - actual = ConversationsClient.parse_conversation_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, ) - actual = ConversationsClient.conversation_profile_path(project, conversation_profile) - assert expected == actual - - -def test_parse_conversation_profile_path(): - expected = { - "project": "scallop", - "conversation_profile": "abalone", - } - path = ConversationsClient.conversation_profile_path(**expected) - - # Check that the path construction is reversible. - actual = ConversationsClient.parse_conversation_profile_path(path) - assert expected == actual - -def test_message_path(): - project = "squid" - conversation = "clam" - message = "whelk" - expected = "projects/{project}/conversations/{conversation}/messages/{message}".format(project=project, conversation=conversation, message=message, ) - actual = ConversationsClient.message_path(project, conversation, message) - assert expected == actual - - -def test_parse_message_path(): - expected = { - "project": "octopus", - "conversation": "oyster", - "message": "nudibranch", - } - path = ConversationsClient.message_path(**expected) - - # Check that the path construction is reversible. - actual = ConversationsClient.parse_message_path(path) - assert expected == actual - -def test_common_billing_account_path(): - billing_account = "cuttlefish" - expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) - actual = ConversationsClient.common_billing_account_path(billing_account) - assert expected == actual - - -def test_parse_common_billing_account_path(): - expected = { - "billing_account": "mussel", - } - path = ConversationsClient.common_billing_account_path(**expected) - - # Check that the path construction is reversible. - actual = ConversationsClient.parse_common_billing_account_path(path) - assert expected == actual - -def test_common_folder_path(): - folder = "winkle" - expected = "folders/{folder}".format(folder=folder, ) - actual = ConversationsClient.common_folder_path(folder) - assert expected == actual - - -def test_parse_common_folder_path(): - expected = { - "folder": "nautilus", - } - path = ConversationsClient.common_folder_path(**expected) - - # Check that the path construction is reversible. - actual = ConversationsClient.parse_common_folder_path(path) - assert expected == actual - -def test_common_organization_path(): - organization = "scallop" - expected = "organizations/{organization}".format(organization=organization, ) - actual = ConversationsClient.common_organization_path(organization) - assert expected == actual - - -def test_parse_common_organization_path(): - expected = { - "organization": "abalone", - } - path = ConversationsClient.common_organization_path(**expected) - - # Check that the path construction is reversible. - actual = ConversationsClient.parse_common_organization_path(path) - assert expected == actual - -def test_common_project_path(): - project = "squid" - expected = "projects/{project}".format(project=project, ) - actual = ConversationsClient.common_project_path(project) - assert expected == actual - - -def test_parse_common_project_path(): - expected = { - "project": "clam", - } - path = ConversationsClient.common_project_path(**expected) - - # Check that the path construction is reversible. - actual = ConversationsClient.parse_common_project_path(path) - assert expected == actual - -def test_common_location_path(): - project = "whelk" - location = "octopus" - expected = "projects/{project}/locations/{location}".format(project=project, location=location, ) - actual = ConversationsClient.common_location_path(project, location) - assert expected == actual - - -def test_parse_common_location_path(): - expected = { - "project": "oyster", - "location": "nudibranch", - } - path = ConversationsClient.common_location_path(**expected) - - # Check that the path construction is reversible. - actual = ConversationsClient.parse_common_location_path(path) - assert expected == actual - - -def test_client_with_default_client_info(): - client_info = gapic_v1.client_info.ClientInfo() - - with mock.patch.object(transports.ConversationsTransport, '_prep_wrapped_messages') as prep: - client = ConversationsClient( - credentials=ga_credentials.AnonymousCredentials(), - client_info=client_info, - ) - prep.assert_called_once_with(client_info) - - with mock.patch.object(transports.ConversationsTransport, '_prep_wrapped_messages') as prep: - transport_class = ConversationsClient.get_transport_class() - transport = transport_class( - credentials=ga_credentials.AnonymousCredentials(), - client_info=client_info, - ) - prep.assert_called_once_with(client_info) - -@pytest.mark.asyncio -async def test_transport_close_async(): - client = ConversationsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - with mock.patch.object(type(getattr(client.transport, "grpc_channel")), "close") as close: - async with client: - close.assert_not_called() - close.assert_called_once() - - -def test_get_location_rest_bad_request(transport: str = 'rest', request_type=locations_pb2.GetLocationRequest): - client = ConversationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - request = request_type() - request = json_format.ParseDict({'name': 'projects/sample1/locations/sample2'}, request) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.get_location(request) - -@pytest.mark.parametrize("request_type", [ - locations_pb2.GetLocationRequest, - dict, -]) -def test_get_location_rest(request_type): - client = ConversationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request_init = {'name': 'projects/sample1/locations/sample2'} - request = request_type(**request_init) - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = locations_pb2.Location() - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.get_location(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, locations_pb2.Location) - -def test_list_locations_rest_bad_request(transport: str = 'rest', request_type=locations_pb2.ListLocationsRequest): - client = ConversationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - request = request_type() - request = json_format.ParseDict({'name': 'projects/sample1'}, request) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.list_locations(request) - -@pytest.mark.parametrize("request_type", [ - locations_pb2.ListLocationsRequest, - dict, -]) -def test_list_locations_rest(request_type): - client = ConversationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request_init = {'name': 'projects/sample1'} - request = request_type(**request_init) - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = locations_pb2.ListLocationsResponse() - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.list_locations(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, locations_pb2.ListLocationsResponse) - -def test_cancel_operation_rest_bad_request(transport: str = 'rest', request_type=operations_pb2.CancelOperationRequest): - client = ConversationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - request = request_type() - request = json_format.ParseDict({'name': 'projects/sample1/operations/sample2'}, request) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.cancel_operation(request) - -@pytest.mark.parametrize("request_type", [ - operations_pb2.CancelOperationRequest, - dict, -]) -def test_cancel_operation_rest(request_type): - client = ConversationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request_init = {'name': 'projects/sample1/operations/sample2'} - request = request_type(**request_init) - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = None - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = '{}' - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.cancel_operation(request) - - # Establish that the response is the type that we expect. - assert response is None - -def test_get_operation_rest_bad_request(transport: str = 'rest', request_type=operations_pb2.GetOperationRequest): - client = ConversationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - request = request_type() - request = json_format.ParseDict({'name': 'projects/sample1/operations/sample2'}, request) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.get_operation(request) - -@pytest.mark.parametrize("request_type", [ - operations_pb2.GetOperationRequest, - dict, -]) -def test_get_operation_rest(request_type): - client = ConversationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request_init = {'name': 'projects/sample1/operations/sample2'} - request = request_type(**request_init) - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation() - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.get_operation(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, operations_pb2.Operation) - -def test_list_operations_rest_bad_request(transport: str = 'rest', request_type=operations_pb2.ListOperationsRequest): - client = ConversationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - request = request_type() - request = json_format.ParseDict({'name': 'projects/sample1'}, request) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.list_operations(request) - -@pytest.mark.parametrize("request_type", [ - operations_pb2.ListOperationsRequest, - dict, -]) -def test_list_operations_rest(request_type): - client = ConversationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request_init = {'name': 'projects/sample1'} - request = request_type(**request_init) - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = operations_pb2.ListOperationsResponse() - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.list_operations(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, operations_pb2.ListOperationsResponse) - - -def test_cancel_operation(transport: str = "grpc"): - client = ConversationsClient( - 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 = operations_pb2.CancelOperationRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = None - response = client.cancel_operation(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 response is the type that we expect. - assert response is None -@pytest.mark.asyncio -async def test_cancel_operation_async(transport: str = "grpc"): - client = ConversationsAsyncClient( - 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 = operations_pb2.CancelOperationRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - None - ) - response = await client.cancel_operation(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 response is the type that we expect. - assert response is None - -def test_cancel_operation_field_headers(): - 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 = operations_pb2.CancelOperationRequest() - request.name = "locations" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call: - call.return_value = None - - client.cancel_operation(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=locations",) in kw["metadata"] -@pytest.mark.asyncio -async def test_cancel_operation_field_headers_async(): - 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 = operations_pb2.CancelOperationRequest() - request.name = "locations" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - None - ) - await client.cancel_operation(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=locations",) in kw["metadata"] - -def test_cancel_operation_from_dict(): - 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.cancel_operation), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = None - - response = client.cancel_operation( - request={ - "name": "locations", - } - ) - call.assert_called() -@pytest.mark.asyncio -async def test_cancel_operation_from_dict_async(): - 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.cancel_operation), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - None - ) - response = await client.cancel_operation( - request={ - "name": "locations", - } - ) - call.assert_called() - - -def test_get_operation(transport: str = "grpc"): - client = ConversationsClient( - 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 = operations_pb2.GetOperationRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_operation), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation() - response = client.get_operation(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 response is the type that we expect. - assert isinstance(response, operations_pb2.Operation) -@pytest.mark.asyncio -async def test_get_operation_async(transport: str = "grpc"): - client = ConversationsAsyncClient( - 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 = operations_pb2.GetOperationRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_operation), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation() - ) - response = await client.get_operation(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 response is the type that we expect. - assert isinstance(response, operations_pb2.Operation) - -def test_get_operation_field_headers(): - 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 = operations_pb2.GetOperationRequest() - request.name = "locations" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_operation), "__call__") as call: - call.return_value = operations_pb2.Operation() - - client.get_operation(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=locations",) in kw["metadata"] -@pytest.mark.asyncio -async def test_get_operation_field_headers_async(): - 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 = operations_pb2.GetOperationRequest() - request.name = "locations" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_operation), "__call__") as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation() - ) - await client.get_operation(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=locations",) in kw["metadata"] - -def test_get_operation_from_dict(): - 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_operation), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation() - - response = client.get_operation( - request={ - "name": "locations", - } - ) - call.assert_called() -@pytest.mark.asyncio -async def test_get_operation_from_dict_async(): - 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_operation), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation() - ) - response = await client.get_operation( - request={ - "name": "locations", - } - ) - call.assert_called() - - -def test_list_operations(transport: str = "grpc"): - client = ConversationsClient( - 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 = operations_pb2.ListOperationsRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_operations), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.ListOperationsResponse() - response = client.list_operations(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 response is the type that we expect. - assert isinstance(response, operations_pb2.ListOperationsResponse) -@pytest.mark.asyncio -async def test_list_operations_async(transport: str = "grpc"): - client = ConversationsAsyncClient( - 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 = operations_pb2.ListOperationsRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_operations), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.ListOperationsResponse() - ) - response = await client.list_operations(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 response is the type that we expect. - assert isinstance(response, operations_pb2.ListOperationsResponse) - -def test_list_operations_field_headers(): - 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 = operations_pb2.ListOperationsRequest() - request.name = "locations" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_operations), "__call__") as call: - call.return_value = operations_pb2.ListOperationsResponse() - - client.list_operations(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=locations",) in kw["metadata"] -@pytest.mark.asyncio -async def test_list_operations_field_headers_async(): - 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 = operations_pb2.ListOperationsRequest() - request.name = "locations" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_operations), "__call__") as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.ListOperationsResponse() - ) - await client.list_operations(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=locations",) in kw["metadata"] - -def test_list_operations_from_dict(): - 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_operations), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.ListOperationsResponse() - - response = client.list_operations( - request={ - "name": "locations", - } - ) - call.assert_called() -@pytest.mark.asyncio -async def test_list_operations_from_dict_async(): - 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_operations), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.ListOperationsResponse() - ) - response = await client.list_operations( - request={ - "name": "locations", - } - ) - call.assert_called() - - -def test_list_locations(transport: str = "grpc"): - client = ConversationsClient( - 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 = locations_pb2.ListLocationsRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_locations), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = locations_pb2.ListLocationsResponse() - response = client.list_locations(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 response is the type that we expect. - assert isinstance(response, locations_pb2.ListLocationsResponse) -@pytest.mark.asyncio -async def test_list_locations_async(transport: str = "grpc"): - client = ConversationsAsyncClient( - 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 = locations_pb2.ListLocationsRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_locations), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - locations_pb2.ListLocationsResponse() - ) - response = await client.list_locations(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 response is the type that we expect. - assert isinstance(response, locations_pb2.ListLocationsResponse) - -def test_list_locations_field_headers(): - 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 = locations_pb2.ListLocationsRequest() - request.name = "locations" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_locations), "__call__") as call: - call.return_value = locations_pb2.ListLocationsResponse() - - client.list_locations(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=locations",) in kw["metadata"] -@pytest.mark.asyncio -async def test_list_locations_field_headers_async(): - 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 = locations_pb2.ListLocationsRequest() - request.name = "locations" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_locations), "__call__") as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - locations_pb2.ListLocationsResponse() - ) - await client.list_locations(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=locations",) in kw["metadata"] - -def test_list_locations_from_dict(): - 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_locations), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = locations_pb2.ListLocationsResponse() - - response = client.list_locations( - request={ - "name": "locations", - } - ) - call.assert_called() -@pytest.mark.asyncio -async def test_list_locations_from_dict_async(): - 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_locations), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - locations_pb2.ListLocationsResponse() - ) - response = await client.list_locations( - request={ - "name": "locations", - } - ) - call.assert_called() - - -def test_get_location(transport: str = "grpc"): - client = ConversationsClient( - 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 = locations_pb2.GetLocationRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_location), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = locations_pb2.Location() - response = client.get_location(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 response is the type that we expect. - assert isinstance(response, locations_pb2.Location) -@pytest.mark.asyncio -async def test_get_location_async(transport: str = "grpc_asyncio"): - client = ConversationsAsyncClient( - 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 = locations_pb2.GetLocationRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_location), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - locations_pb2.Location() - ) - response = await client.get_location(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 response is the type that we expect. - assert isinstance(response, locations_pb2.Location) - -def test_get_location_field_headers(): - 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 = locations_pb2.GetLocationRequest() - request.name = "locations/abc" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_location), "__call__") as call: - call.return_value = locations_pb2.Location() - - client.get_location(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=locations/abc",) in kw["metadata"] -@pytest.mark.asyncio -async def test_get_location_field_headers_async(): - 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 = locations_pb2.GetLocationRequest() - request.name = "locations/abc" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_location), "__call__") as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - locations_pb2.Location() - ) - await client.get_location(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=locations/abc",) in kw["metadata"] - -def test_get_location_from_dict(): - 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_locations), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = locations_pb2.Location() - - response = client.get_location( - request={ - "name": "locations/abc", - } - ) - call.assert_called() -@pytest.mark.asyncio -async def test_get_location_from_dict_async(): - 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_locations), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - locations_pb2.Location() - ) - response = await client.get_location( - request={ - "name": "locations", - } - ) - call.assert_called() - - -def test_transport_close(): - transports = { - "rest": "_session", - "grpc": "_grpc_channel", - } - - for transport, close_name in transports.items(): - client = ConversationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport - ) - with mock.patch.object(type(getattr(client.transport, close_name)), "close") as close: - with client: - close.assert_not_called() - close.assert_called_once() - -def test_client_ctx(): - transports = [ - 'rest', - 'grpc', - ] - for transport in transports: - client = ConversationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport - ) - # Test client calls underlying transport. - with mock.patch.object(type(client.transport), "close") as close: - close.assert_not_called() - with client: - pass - close.assert_called() - -@pytest.mark.parametrize("client_class,transport_class", [ - (ConversationsClient, transports.ConversationsGrpcTransport), - (ConversationsAsyncClient, transports.ConversationsGrpcAsyncIOTransport), -]) -def test_api_key_credentials(client_class, transport_class): - with mock.patch.object( - google.auth._default, "get_api_key_credentials", create=True - ) as get_api_key_credentials: - mock_cred = mock.Mock() - get_api_key_credentials.return_value = mock_cred - options = client_options.ClientOptions() - options.api_key = "api_key" - 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=mock_cred, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) diff --git a/owl-bot-staging/v2/tests/unit/gapic/dialogflow_v2/test_documents.py b/owl-bot-staging/v2/tests/unit/gapic/dialogflow_v2/test_documents.py deleted file mode 100644 index 2140693be..000000000 --- a/owl-bot-staging/v2/tests/unit/gapic/dialogflow_v2/test_documents.py +++ /dev/null @@ -1,5920 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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 -# try/except added for compatibility with python < 3.8 -try: - from unittest import mock - from unittest.mock import AsyncMock # pragma: NO COVER -except ImportError: # pragma: NO COVER - import mock - -import grpc -from grpc.experimental import aio -from collections.abc import Iterable -from google.protobuf import json_format -import json -import math -import pytest -from proto.marshal.rules.dates import DurationRule, TimestampRule -from proto.marshal.rules import wrappers -from requests import Response -from requests import Request, PreparedRequest -from requests.sessions import Session -from google.protobuf import json_format - -from google.api_core import client_options -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 -from google.api_core import operation_async # type: ignore -from google.api_core import operations_v1 -from google.api_core import path_template -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.types import document -from google.cloud.dialogflow_v2.types import document as gcd_document -from google.cloud.dialogflow_v2.types import gcs -from google.cloud.location import locations_pb2 -from google.longrunning import operations_pb2 -from google.oauth2 import service_account -from google.protobuf import any_pb2 # type: ignore -from google.protobuf import empty_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 - - -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 DocumentsClient._get_default_mtls_endpoint(None) is None - assert DocumentsClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint - assert DocumentsClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint - assert DocumentsClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint - assert DocumentsClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint - assert DocumentsClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi - - -@pytest.mark.parametrize("client_class,transport_name", [ - (DocumentsClient, "grpc"), - (DocumentsAsyncClient, "grpc_asyncio"), - (DocumentsClient, "rest"), -]) -def test_documents_client_from_service_account_info(client_class, transport_name): - 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, transport=transport_name) - assert client.transport._credentials == creds - assert isinstance(client, client_class) - - assert client.transport._host == ( - 'dialogflow.googleapis.com:443' - if transport_name in ['grpc', 'grpc_asyncio'] - else - 'https://dialogflow.googleapis.com' - ) - - -@pytest.mark.parametrize("transport_class,transport_name", [ - (transports.DocumentsGrpcTransport, "grpc"), - (transports.DocumentsGrpcAsyncIOTransport, "grpc_asyncio"), - (transports.DocumentsRestTransport, "rest"), -]) -def test_documents_client_service_account_always_use_jwt(transport_class, transport_name): - with mock.patch.object(service_account.Credentials, 'with_always_use_jwt_access', create=True) as use_jwt: - creds = service_account.Credentials(None, None, None) - transport = transport_class(credentials=creds, always_use_jwt_access=True) - use_jwt.assert_called_once_with(True) - - with mock.patch.object(service_account.Credentials, 'with_always_use_jwt_access', create=True) as use_jwt: - creds = service_account.Credentials(None, None, None) - transport = transport_class(credentials=creds, always_use_jwt_access=False) - use_jwt.assert_not_called() - - -@pytest.mark.parametrize("client_class,transport_name", [ - (DocumentsClient, "grpc"), - (DocumentsAsyncClient, "grpc_asyncio"), - (DocumentsClient, "rest"), -]) -def test_documents_client_from_service_account_file(client_class, transport_name): - 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", transport=transport_name) - assert client.transport._credentials == creds - assert isinstance(client, client_class) - - client = client_class.from_service_account_json("dummy/file/path.json", transport=transport_name) - assert client.transport._credentials == creds - assert isinstance(client, client_class) - - assert client.transport._host == ( - 'dialogflow.googleapis.com:443' - if transport_name in ['grpc', 'grpc_asyncio'] - else - 'https://dialogflow.googleapis.com' - ) - - -def test_documents_client_get_transport_class(): - transport = DocumentsClient.get_transport_class() - available_transports = [ - transports.DocumentsGrpcTransport, - transports.DocumentsRestTransport, - ] - assert transport in available_transports - - transport = DocumentsClient.get_transport_class("grpc") - assert transport == transports.DocumentsGrpcTransport - - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (DocumentsClient, transports.DocumentsGrpcTransport, "grpc"), - (DocumentsAsyncClient, transports.DocumentsGrpcAsyncIOTransport, "grpc_asyncio"), - (DocumentsClient, transports.DocumentsRestTransport, "rest"), -]) -@mock.patch.object(DocumentsClient, "DEFAULT_ENDPOINT", modify_default_endpoint(DocumentsClient)) -@mock.patch.object(DocumentsAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(DocumentsAsyncClient)) -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=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(DocumentsClient, 'get_transport_class') as gtc: - client = client_class(transport=transport_name) - gtc.assert_called() - - # Check the case api_endpoint is provided. - options = client_options.ClientOptions(api_endpoint="squid.clam.whelk") - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(transport=transport_name, client_options=options) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host="squid.clam.whelk", - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is - # "never". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is - # "always". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_MTLS_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # 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(transport=transport_name) - - # 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(transport=transport_name) - - # 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, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id="octopus", - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - # Check the case api_endpoint is provided - options = client_options.ClientOptions(api_audience="https://language.googleapis.com") - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience="https://language.googleapis.com" - ) - -@pytest.mark.parametrize("client_class,transport_class,transport_name,use_client_cert_env", [ - (DocumentsClient, transports.DocumentsGrpcTransport, "grpc", "true"), - (DocumentsAsyncClient, transports.DocumentsGrpcAsyncIOTransport, "grpc_asyncio", "true"), - (DocumentsClient, transports.DocumentsGrpcTransport, "grpc", "false"), - (DocumentsAsyncClient, transports.DocumentsGrpcAsyncIOTransport, "grpc_asyncio", "false"), - (DocumentsClient, transports.DocumentsRestTransport, "rest", "true"), - (DocumentsClient, transports.DocumentsRestTransport, "rest", "false"), -]) -@mock.patch.object(DocumentsClient, "DEFAULT_ENDPOINT", modify_default_endpoint(DocumentsClient)) -@mock.patch.object(DocumentsAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(DocumentsAsyncClient)) -@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) -def test_documents_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, transport=transport_name) - - if use_client_cert_env == "false": - expected_client_cert_source = None - expected_host = client.DEFAULT_ENDPOINT - else: - expected_client_cert_source = client_cert_source_callback - expected_host = client.DEFAULT_MTLS_ENDPOINT - - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=expected_host, - scopes=None, - client_cert_source_for_mtls=expected_client_cert_source, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case ADC client cert is provided. Whether client cert is used depends on - # GOOGLE_API_USE_CLIENT_CERTIFICATE value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): - with mock.patch.object(transport_class, '__init__') as patched: - with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): - with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=client_cert_source_callback): - if use_client_cert_env == "false": - expected_host = client.DEFAULT_ENDPOINT - expected_client_cert_source = None - else: - expected_host = client.DEFAULT_MTLS_ENDPOINT - expected_client_cert_source = client_cert_source_callback - - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=expected_host, - scopes=None, - client_cert_source_for_mtls=expected_client_cert_source, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case client_cert_source and ADC client cert are not provided. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): - with mock.patch.object(transport_class, '__init__') as patched: - with mock.patch("google.auth.transport.mtls.has_default_client_cert_source", return_value=False): - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - -@pytest.mark.parametrize("client_class", [ - DocumentsClient, DocumentsAsyncClient -]) -@mock.patch.object(DocumentsClient, "DEFAULT_ENDPOINT", modify_default_endpoint(DocumentsClient)) -@mock.patch.object(DocumentsAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(DocumentsAsyncClient)) -def test_documents_client_get_mtls_endpoint_and_cert_source(client_class): - mock_client_cert_source = mock.Mock() - - # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "true". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - mock_api_endpoint = "foo" - options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) - assert api_endpoint == mock_api_endpoint - assert cert_source == mock_client_cert_source - - # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "false". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): - mock_client_cert_source = mock.Mock() - mock_api_endpoint = "foo" - options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) - assert api_endpoint == mock_api_endpoint - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "never". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_ENDPOINT - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "always". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert doesn't exist. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=False): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_ENDPOINT - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert exists. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - 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=mock_client_cert_source): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT - assert cert_source == mock_client_cert_source - - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (DocumentsClient, transports.DocumentsGrpcTransport, "grpc"), - (DocumentsAsyncClient, transports.DocumentsGrpcAsyncIOTransport, "grpc_asyncio"), - (DocumentsClient, transports.DocumentsRestTransport, "rest"), -]) -def test_documents_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, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=["1", "2"], - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - -@pytest.mark.parametrize("client_class,transport_class,transport_name,grpc_helpers", [ - (DocumentsClient, transports.DocumentsGrpcTransport, "grpc", grpc_helpers), - (DocumentsAsyncClient, transports.DocumentsGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), - (DocumentsClient, transports.DocumentsRestTransport, "rest", None), -]) -def test_documents_client_client_options_credentials_file(client_class, transport_class, transport_name, grpc_helpers): - # 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, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file="credentials.json", - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - -def test_documents_client_client_options_from_dict(): - with mock.patch('google.cloud.dialogflow_v2.services.documents.transports.DocumentsGrpcTransport.__init__') as grpc_transport: - grpc_transport.return_value = None - client = DocumentsClient( - client_options={'api_endpoint': 'squid.clam.whelk'} - ) - grpc_transport.assert_called_once_with( - credentials=None, - credentials_file=None, - host="squid.clam.whelk", - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - -@pytest.mark.parametrize("client_class,transport_class,transport_name,grpc_helpers", [ - (DocumentsClient, transports.DocumentsGrpcTransport, "grpc", grpc_helpers), - (DocumentsAsyncClient, transports.DocumentsGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), -]) -def test_documents_client_create_channel_credentials_file(client_class, transport_class, transport_name, grpc_helpers): - # 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, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file="credentials.json", - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # test that the credentials from file are saved and used as the credentials. - with mock.patch.object( - google.auth, "load_credentials_from_file", autospec=True - ) as load_creds, mock.patch.object( - google.auth, "default", autospec=True - ) as adc, mock.patch.object( - grpc_helpers, "create_channel" - ) as create_channel: - creds = ga_credentials.AnonymousCredentials() - file_creds = ga_credentials.AnonymousCredentials() - load_creds.return_value = (file_creds, None) - adc.return_value = (creds, None) - client = client_class(client_options=options, transport=transport_name) - create_channel.assert_called_with( - "dialogflow.googleapis.com:443", - credentials=file_creds, - credentials_file=None, - quota_project_id=None, - default_scopes=( - 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/dialogflow', -), - scopes=None, - default_host="dialogflow.googleapis.com", - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - -@pytest.mark.parametrize("request_type", [ - document.ListDocumentsRequest, - dict, -]) -def test_list_documents(request_type, transport: str = 'grpc'): - client = DocumentsClient( - 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_documents), - '__call__') as call: - # Designate an appropriate return value for the call. - 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' - - -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=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_documents), - '__call__') as call: - client.list_documents() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == document.ListDocumentsRequest() - -@pytest.mark.asyncio -async def test_list_documents_async(transport: str = 'grpc_asyncio', request_type=document.ListDocumentsRequest): - client = DocumentsAsyncClient( - 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_documents), - '__call__') as call: - # Designate an appropriate return value for the call. - 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' - - -@pytest.mark.asyncio -async def test_list_documents_async_from_dict(): - await test_list_documents_async(request_type=dict) - - -def test_list_documents_field_headers(): - 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. - 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_documents_field_headers_async(): - 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. - with mock.patch.object( - type(client.transport.list_documents), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(document.ListDocumentsResponse()) - 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] == 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_documents_flattened(): - 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', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - arg = args[0].parent - mock_val = 'parent_value' - assert arg == mock_val - - -def test_list_documents_flattened_error(): - client = DocumentsClient( - 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_documents( - document.ListDocumentsRequest(), - parent='parent_value', - ) - -@pytest.mark.asyncio -async def test_list_documents_flattened_async(): - 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: - # Designate an appropriate return value for the call. - call.return_value = document.ListDocumentsResponse() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(document.ListDocumentsResponse()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.list_documents( - 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] - arg = args[0].parent - mock_val = 'parent_value' - assert arg == mock_val - -@pytest.mark.asyncio -async def test_list_documents_flattened_error_async(): - client = DocumentsAsyncClient( - 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_documents( - document.ListDocumentsRequest(), - parent='parent_value', - ) - - -def test_list_documents_pager(transport_name: str = "grpc"): - client = DocumentsClient( - credentials=ga_credentials.AnonymousCredentials, - transport=transport_name, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_documents), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - document.ListDocumentsResponse( - documents=[ - document.Document(), - document.Document(), - document.Document(), - ], - next_page_token='abc', - ), - document.ListDocumentsResponse( - documents=[], - next_page_token='def', - ), - document.ListDocumentsResponse( - documents=[ - document.Document(), - ], - next_page_token='ghi', - ), - document.ListDocumentsResponse( - documents=[ - document.Document(), - document.Document(), - ], - ), - RuntimeError, - ) - - metadata = () - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ('parent', ''), - )), - ) - pager = client.list_documents(request={}) - - assert pager._metadata == metadata - - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, document.Document) - for i in results) -def test_list_documents_pages(transport_name: str = "grpc"): - client = DocumentsClient( - credentials=ga_credentials.AnonymousCredentials, - transport=transport_name, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_documents), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - document.ListDocumentsResponse( - documents=[ - document.Document(), - document.Document(), - document.Document(), - ], - next_page_token='abc', - ), - document.ListDocumentsResponse( - documents=[], - next_page_token='def', - ), - document.ListDocumentsResponse( - documents=[ - document.Document(), - ], - next_page_token='ghi', - ), - document.ListDocumentsResponse( - documents=[ - document.Document(), - document.Document(), - ], - ), - RuntimeError, - ) - pages = list(client.list_documents(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_documents_async_pager(): - 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__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - document.ListDocumentsResponse( - documents=[ - document.Document(), - document.Document(), - document.Document(), - ], - next_page_token='abc', - ), - document.ListDocumentsResponse( - documents=[], - next_page_token='def', - ), - document.ListDocumentsResponse( - documents=[ - document.Document(), - ], - next_page_token='ghi', - ), - document.ListDocumentsResponse( - documents=[ - document.Document(), - document.Document(), - ], - ), - RuntimeError, - ) - async_pager = await client.list_documents(request={},) - assert async_pager.next_page_token == 'abc' - responses = [] - async for response in async_pager: # pragma: no branch - responses.append(response) - - assert len(responses) == 6 - assert all(isinstance(i, document.Document) - for i in responses) - - -@pytest.mark.asyncio -async def test_list_documents_async_pages(): - 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__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - document.ListDocumentsResponse( - documents=[ - document.Document(), - document.Document(), - document.Document(), - ], - next_page_token='abc', - ), - document.ListDocumentsResponse( - documents=[], - next_page_token='def', - ), - document.ListDocumentsResponse( - documents=[ - document.Document(), - ], - next_page_token='ghi', - ), - document.ListDocumentsResponse( - documents=[ - document.Document(), - document.Document(), - ], - ), - RuntimeError, - ) - pages = [] - async for page_ in (await client.list_documents(request={})).pages: # pragma: no branch - pages.append(page_) - for page_, token in zip(pages, ['abc','def','ghi', '']): - assert page_.raw_page.next_page_token == token - -@pytest.mark.parametrize("request_type", [ - document.GetDocumentRequest, - dict, -]) -def test_get_document(request_type, transport: str = 'grpc'): - client = DocumentsClient( - 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_document), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = document.Document( - name='name_value', - display_name='display_name_value', - mime_type='mime_type_value', - knowledge_types=[document.Document.KnowledgeType.FAQ], - enable_auto_reload=True, - state=document.Document.State.CREATING, - 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 - assert response.state == document.Document.State.CREATING - - -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=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_document), - '__call__') as call: - client.get_document() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == document.GetDocumentRequest() - -@pytest.mark.asyncio -async def test_get_document_async(transport: str = 'grpc_asyncio', request_type=document.GetDocumentRequest): - client = DocumentsAsyncClient( - 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_document), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(document.Document( - name='name_value', - display_name='display_name_value', - mime_type='mime_type_value', - knowledge_types=[document.Document.KnowledgeType.FAQ], - enable_auto_reload=True, - state=document.Document.State.CREATING, - )) - 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 - assert response.state == document.Document.State.CREATING - - -@pytest.mark.asyncio -async def test_get_document_async_from_dict(): - await test_get_document_async(request_type=dict) - - -def test_get_document_field_headers(): - 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. - 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_document_field_headers_async(): - 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. - 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_document_flattened(): - 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', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - arg = args[0].name - mock_val = 'name_value' - assert arg == mock_val - - -def test_get_document_flattened_error(): - client = DocumentsClient( - 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_document( - document.GetDocumentRequest(), - name='name_value', - ) - -@pytest.mark.asyncio -async def test_get_document_flattened_async(): - 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: - # Designate an appropriate return value for the call. - call.return_value = document.Document() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(document.Document()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.get_document( - 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] - arg = args[0].name - mock_val = 'name_value' - assert arg == mock_val - -@pytest.mark.asyncio -async def test_get_document_flattened_error_async(): - client = DocumentsAsyncClient( - 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_document( - document.GetDocumentRequest(), - name='name_value', - ) - - -@pytest.mark.parametrize("request_type", [ - gcd_document.CreateDocumentRequest, - dict, -]) -def test_create_document(request_type, transport: str = 'grpc'): - client = DocumentsClient( - 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_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. - assert isinstance(response, future.Future) - - -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=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_document), - '__call__') as call: - client.create_document() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == gcd_document.CreateDocumentRequest() - -@pytest.mark.asyncio -async def test_create_document_async(transport: str = 'grpc_asyncio', request_type=gcd_document.CreateDocumentRequest): - client = DocumentsAsyncClient( - 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_document), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name='operations/spam') - ) - response = await client.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. - assert isinstance(response, future.Future) - - -@pytest.mark.asyncio -async def test_create_document_async_from_dict(): - await test_create_document_async(request_type=dict) - - -def test_create_document_field_headers(): - 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. - 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_document_field_headers_async(): - 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. - with mock.patch.object( - type(client.transport.create_document), - '__call__') as call: - 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. - 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_document_flattened(): - 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( - parent='parent_value', - document=gcd_document.Document(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] - arg = args[0].parent - mock_val = 'parent_value' - assert arg == mock_val - arg = args[0].document - mock_val = gcd_document.Document(name='name_value') - assert arg == mock_val - - -def test_create_document_flattened_error(): - client = DocumentsClient( - 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_document( - gcd_document.CreateDocumentRequest(), - parent='parent_value', - document=gcd_document.Document(name='name_value'), - ) - -@pytest.mark.asyncio -async def test_create_document_flattened_async(): - 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: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/op') - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name='operations/spam') - ) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.create_document( - parent='parent_value', - document=gcd_document.Document(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] - arg = args[0].parent - mock_val = 'parent_value' - assert arg == mock_val - arg = args[0].document - mock_val = gcd_document.Document(name='name_value') - assert arg == mock_val - -@pytest.mark.asyncio -async def test_create_document_flattened_error_async(): - client = DocumentsAsyncClient( - 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_document( - gcd_document.CreateDocumentRequest(), - parent='parent_value', - document=gcd_document.Document(name='name_value'), - ) - - -@pytest.mark.parametrize("request_type", [ - document.ImportDocumentsRequest, - dict, -]) -def test_import_documents(request_type, transport: str = 'grpc'): - client = DocumentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.import_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. - assert isinstance(response, future.Future) - - -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=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.import_documents), - '__call__') as call: - client.import_documents() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == document.ImportDocumentsRequest() - -@pytest.mark.asyncio -async def test_import_documents_async(transport: str = 'grpc_asyncio', request_type=document.ImportDocumentsRequest): - client = DocumentsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.import_documents), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name='operations/spam') - ) - response = await client.import_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. - assert isinstance(response, future.Future) - - -@pytest.mark.asyncio -async def test_import_documents_async_from_dict(): - await test_import_documents_async(request_type=dict) - - -def test_import_documents_field_headers(): - 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. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'parent=parent_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_import_documents_field_headers_async(): - 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. - with mock.patch.object( - type(client.transport.import_documents), - '__call__') as call: - 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. - 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'] - - -@pytest.mark.parametrize("request_type", [ - document.DeleteDocumentRequest, - dict, -]) -def test_delete_document(request_type, transport: str = 'grpc'): - client = DocumentsClient( - 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_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. - assert isinstance(response, future.Future) - - -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=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_document), - '__call__') as call: - client.delete_document() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == document.DeleteDocumentRequest() - -@pytest.mark.asyncio -async def test_delete_document_async(transport: str = 'grpc_asyncio', request_type=document.DeleteDocumentRequest): - client = DocumentsAsyncClient( - 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_document), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name='operations/spam') - ) - response = await client.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. - assert isinstance(response, future.Future) - - -@pytest.mark.asyncio -async def test_delete_document_async_from_dict(): - await test_delete_document_async(request_type=dict) - - -def test_delete_document_field_headers(): - 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. - 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_document_field_headers_async(): - 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. - with mock.patch.object( - type(client.transport.delete_document), - '__call__') as call: - 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. - 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_document_flattened(): - 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', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - arg = args[0].name - mock_val = 'name_value' - assert arg == mock_val - - -def test_delete_document_flattened_error(): - client = DocumentsClient( - 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_document( - document.DeleteDocumentRequest(), - name='name_value', - ) - -@pytest.mark.asyncio -async def test_delete_document_flattened_async(): - 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: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/op') - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name='operations/spam') - ) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.delete_document( - 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] - arg = args[0].name - mock_val = 'name_value' - assert arg == mock_val - -@pytest.mark.asyncio -async def test_delete_document_flattened_error_async(): - client = DocumentsAsyncClient( - 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_document( - document.DeleteDocumentRequest(), - name='name_value', - ) - - -@pytest.mark.parametrize("request_type", [ - gcd_document.UpdateDocumentRequest, - dict, -]) -def test_update_document(request_type, transport: str = 'grpc'): - client = DocumentsClient( - 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_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. - assert isinstance(response, future.Future) - - -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=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_document), - '__call__') as call: - client.update_document() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == gcd_document.UpdateDocumentRequest() - -@pytest.mark.asyncio -async def test_update_document_async(transport: str = 'grpc_asyncio', request_type=gcd_document.UpdateDocumentRequest): - client = DocumentsAsyncClient( - 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_document), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name='operations/spam') - ) - response = await client.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. - assert isinstance(response, future.Future) - - -@pytest.mark.asyncio -async def test_update_document_async_from_dict(): - await test_update_document_async(request_type=dict) - - -def test_update_document_field_headers(): - 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 = '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. - 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', - 'document.name=name_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_update_document_field_headers_async(): - 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 = '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 = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) - 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] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'document.name=name_value', - ) in kw['metadata'] - - -def test_update_document_flattened(): - 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_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] - arg = args[0].document - mock_val = gcd_document.Document(name='name_value') - assert arg == mock_val - arg = args[0].update_mask - mock_val = field_mask_pb2.FieldMask(paths=['paths_value']) - assert arg == mock_val - - -def test_update_document_flattened_error(): - client = DocumentsClient( - 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_document( - gcd_document.UpdateDocumentRequest(), - document=gcd_document.Document(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - -@pytest.mark.asyncio -async def test_update_document_flattened_async(): - 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: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/op') - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name='operations/spam') - ) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.update_document( - document=gcd_document.Document(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] - arg = args[0].document - mock_val = gcd_document.Document(name='name_value') - assert arg == mock_val - arg = args[0].update_mask - mock_val = field_mask_pb2.FieldMask(paths=['paths_value']) - assert arg == mock_val - -@pytest.mark.asyncio -async def test_update_document_flattened_error_async(): - client = DocumentsAsyncClient( - 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_document( - gcd_document.UpdateDocumentRequest(), - document=gcd_document.Document(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - - -@pytest.mark.parametrize("request_type", [ - document.ReloadDocumentRequest, - dict, -]) -def test_reload_document(request_type, transport: str = 'grpc'): - client = DocumentsClient( - 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.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. - assert isinstance(response, future.Future) - - -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=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.reload_document), - '__call__') as call: - client.reload_document() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == document.ReloadDocumentRequest() - -@pytest.mark.asyncio -async def test_reload_document_async(transport: str = 'grpc_asyncio', request_type=document.ReloadDocumentRequest): - client = DocumentsAsyncClient( - 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.reload_document), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name='operations/spam') - ) - response = await client.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. - assert isinstance(response, future.Future) - - -@pytest.mark.asyncio -async def test_reload_document_async_from_dict(): - await test_reload_document_async(request_type=dict) - - -def test_reload_document_field_headers(): - 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. - 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_reload_document_field_headers_async(): - 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. - with mock.patch.object( - type(client.transport.reload_document), - '__call__') as call: - 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. - 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_reload_document_flattened(): - 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( - name='name_value', - content_uri='content_uri_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] - arg = args[0].name - mock_val = 'name_value' - assert arg == mock_val - assert args[0].content_uri == 'content_uri_value' - - -def test_reload_document_flattened_error(): - client = DocumentsClient( - 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.reload_document( - document.ReloadDocumentRequest(), - name='name_value', - content_uri='content_uri_value', - ) - -@pytest.mark.asyncio -async def test_reload_document_flattened_async(): - 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: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/op') - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name='operations/spam') - ) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.reload_document( - name='name_value', - content_uri='content_uri_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - arg = args[0].name - mock_val = 'name_value' - assert arg == mock_val - assert args[0].content_uri == 'content_uri_value' - -@pytest.mark.asyncio -async def test_reload_document_flattened_error_async(): - client = DocumentsAsyncClient( - 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.reload_document( - document.ReloadDocumentRequest(), - name='name_value', - content_uri='content_uri_value', - ) - - -@pytest.mark.parametrize("request_type", [ - document.ExportDocumentRequest, - dict, -]) -def test_export_document(request_type, transport: str = 'grpc'): - client = DocumentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.export_document), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/spam') - response = client.export_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.ExportDocumentRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -def test_export_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=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.export_document), - '__call__') as call: - client.export_document() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == document.ExportDocumentRequest() - -@pytest.mark.asyncio -async def test_export_document_async(transport: str = 'grpc_asyncio', request_type=document.ExportDocumentRequest): - client = DocumentsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.export_document), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name='operations/spam') - ) - response = await client.export_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.ExportDocumentRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -@pytest.mark.asyncio -async def test_export_document_async_from_dict(): - await test_export_document_async(request_type=dict) - - -def test_export_document_field_headers(): - 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.ExportDocumentRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.export_document), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') - client.export_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] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'name=name_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_export_document_field_headers_async(): - 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.ExportDocumentRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.export_document), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) - await client.export_document(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'] - - -@pytest.mark.parametrize("request_type", [ - document.ListDocumentsRequest, - dict, -]) -def test_list_documents_rest(request_type): - client = DocumentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1/knowledgeBases/sample2'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = document.ListDocumentsResponse( - next_page_token='next_page_token_value', - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - pb_return_value = document.ListDocumentsResponse.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.list_documents(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListDocumentsPager) - assert response.next_page_token == 'next_page_token_value' - - -def test_list_documents_rest_required_fields(request_type=document.ListDocumentsRequest): - transport_class = transports.DocumentsRestTransport - - request_init = {} - request_init["parent"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - including_default_value_fields=False, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).list_documents._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["parent"] = 'parent_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).list_documents._get_unset_required_fields(jsonified_request) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("filter", "page_size", "page_token", )) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "parent" in jsonified_request - assert jsonified_request["parent"] == 'parent_value' - - client = DocumentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = document.ListDocumentsResponse() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "get", - 'query_params': pb_request, - } - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - - pb_return_value = document.ListDocumentsResponse.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.list_documents(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_list_documents_rest_unset_required_fields(): - transport = transports.DocumentsRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.list_documents._get_unset_required_fields({}) - assert set(unset_fields) == (set(("filter", "pageSize", "pageToken", )) & set(("parent", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_list_documents_rest_interceptors(null_interceptor): - transport = transports.DocumentsRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.DocumentsRestInterceptor(), - ) - client = DocumentsClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.DocumentsRestInterceptor, "post_list_documents") as post, \ - mock.patch.object(transports.DocumentsRestInterceptor, "pre_list_documents") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = document.ListDocumentsRequest.pb(document.ListDocumentsRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = document.ListDocumentsResponse.to_json(document.ListDocumentsResponse()) - - request = document.ListDocumentsRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = document.ListDocumentsResponse() - - client.list_documents(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_list_documents_rest_bad_request(transport: str = 'rest', request_type=document.ListDocumentsRequest): - client = DocumentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1/knowledgeBases/sample2'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.list_documents(request) - - -def test_list_documents_rest_flattened(): - client = DocumentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = document.ListDocumentsResponse() - - # get arguments that satisfy an http rule for this method - sample_request = {'parent': 'projects/sample1/knowledgeBases/sample2'} - - # get truthy value for each flattened field - mock_args = dict( - parent='parent_value', - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - pb_return_value = document.ListDocumentsResponse.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.list_documents(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v2/{parent=projects/*/knowledgeBases/*}/documents" % client.transport._host, args[1]) - - -def test_list_documents_rest_flattened_error(transport: str = 'rest'): - client = DocumentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.list_documents( - document.ListDocumentsRequest(), - parent='parent_value', - ) - - -def test_list_documents_rest_pager(transport: str = 'rest'): - client = DocumentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # TODO(kbandes): remove this mock unless there's a good reason for it. - #with mock.patch.object(path_template, 'transcode') as transcode: - # Set the response as a series of pages - response = ( - document.ListDocumentsResponse( - documents=[ - document.Document(), - document.Document(), - document.Document(), - ], - next_page_token='abc', - ), - document.ListDocumentsResponse( - documents=[], - next_page_token='def', - ), - document.ListDocumentsResponse( - documents=[ - document.Document(), - ], - next_page_token='ghi', - ), - document.ListDocumentsResponse( - documents=[ - document.Document(), - document.Document(), - ], - ), - ) - # Two responses for two calls - response = response + response - - # Wrap the values into proper Response objs - response = tuple(document.ListDocumentsResponse.to_json(x) for x in response) - return_values = tuple(Response() for i in response) - for return_val, response_val in zip(return_values, response): - return_val._content = response_val.encode('UTF-8') - return_val.status_code = 200 - req.side_effect = return_values - - sample_request = {'parent': 'projects/sample1/knowledgeBases/sample2'} - - pager = client.list_documents(request=sample_request) - - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, document.Document) - for i in results) - - pages = list(client.list_documents(request=sample_request).pages) - for page_, token in zip(pages, ['abc','def','ghi', '']): - assert page_.raw_page.next_page_token == token - - -@pytest.mark.parametrize("request_type", [ - document.GetDocumentRequest, - dict, -]) -def test_get_document_rest(request_type): - client = DocumentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/knowledgeBases/sample2/documents/sample3'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = document.Document( - name='name_value', - display_name='display_name_value', - mime_type='mime_type_value', - knowledge_types=[document.Document.KnowledgeType.FAQ], - enable_auto_reload=True, - state=document.Document.State.CREATING, - content_uri='content_uri_value', - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - pb_return_value = document.Document.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.get_document(request) - - # 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 - assert response.state == document.Document.State.CREATING - - -def test_get_document_rest_required_fields(request_type=document.GetDocumentRequest): - transport_class = transports.DocumentsRestTransport - - request_init = {} - request_init["name"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - including_default_value_fields=False, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_document._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["name"] = 'name_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_document._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "name" in jsonified_request - assert jsonified_request["name"] == 'name_value' - - client = DocumentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = document.Document() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "get", - 'query_params': pb_request, - } - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - - pb_return_value = document.Document.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.get_document(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_get_document_rest_unset_required_fields(): - transport = transports.DocumentsRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.get_document._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_get_document_rest_interceptors(null_interceptor): - transport = transports.DocumentsRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.DocumentsRestInterceptor(), - ) - client = DocumentsClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.DocumentsRestInterceptor, "post_get_document") as post, \ - mock.patch.object(transports.DocumentsRestInterceptor, "pre_get_document") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = document.GetDocumentRequest.pb(document.GetDocumentRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = document.Document.to_json(document.Document()) - - request = document.GetDocumentRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = document.Document() - - client.get_document(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_get_document_rest_bad_request(transport: str = 'rest', request_type=document.GetDocumentRequest): - client = DocumentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/knowledgeBases/sample2/documents/sample3'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.get_document(request) - - -def test_get_document_rest_flattened(): - client = DocumentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = document.Document() - - # get arguments that satisfy an http rule for this method - sample_request = {'name': 'projects/sample1/knowledgeBases/sample2/documents/sample3'} - - # get truthy value for each flattened field - mock_args = dict( - name='name_value', - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - pb_return_value = document.Document.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.get_document(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v2/{name=projects/*/knowledgeBases/*/documents/*}" % client.transport._host, args[1]) - - -def test_get_document_rest_flattened_error(transport: str = 'rest'): - client = DocumentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.get_document( - document.GetDocumentRequest(), - name='name_value', - ) - - -def test_get_document_rest_error(): - client = DocumentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - gcd_document.CreateDocumentRequest, - dict, -]) -def test_create_document_rest(request_type): - client = DocumentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1/knowledgeBases/sample2'} - request_init["document"] = {'name': 'name_value', 'display_name': 'display_name_value', 'mime_type': 'mime_type_value', 'knowledge_types': [1], 'content_uri': 'content_uri_value', 'raw_content': b'raw_content_blob', 'enable_auto_reload': True, 'latest_reload_status': {'time': {'seconds': 751, 'nanos': 543}, 'status': {'code': 411, 'message': 'message_value', 'details': [{'type_url': 'type.googleapis.com/google.protobuf.Duration', 'value': b'\x08\x0c\x10\xdb\x07'}]}}, 'metadata': {}, 'state': 1} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name='operations/spam') - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.create_document(request) - - # Establish that the response is the type that we expect. - assert response.operation.name == "operations/spam" - - -def test_create_document_rest_required_fields(request_type=gcd_document.CreateDocumentRequest): - transport_class = transports.DocumentsRestTransport - - request_init = {} - request_init["parent"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - including_default_value_fields=False, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_document._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["parent"] = 'parent_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_document._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "parent" in jsonified_request - assert jsonified_request["parent"] == 'parent_value' - - client = DocumentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name='operations/spam') - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "post", - 'query_params': pb_request, - } - transcode_result['body'] = pb_request - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.create_document(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_create_document_rest_unset_required_fields(): - transport = transports.DocumentsRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.create_document._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("parent", "document", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_create_document_rest_interceptors(null_interceptor): - transport = transports.DocumentsRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.DocumentsRestInterceptor(), - ) - client = DocumentsClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(operation.Operation, "_set_result_from_operation"), \ - mock.patch.object(transports.DocumentsRestInterceptor, "post_create_document") as post, \ - mock.patch.object(transports.DocumentsRestInterceptor, "pre_create_document") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = gcd_document.CreateDocumentRequest.pb(gcd_document.CreateDocumentRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = json_format.MessageToJson(operations_pb2.Operation()) - - request = gcd_document.CreateDocumentRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = operations_pb2.Operation() - - client.create_document(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_create_document_rest_bad_request(transport: str = 'rest', request_type=gcd_document.CreateDocumentRequest): - client = DocumentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1/knowledgeBases/sample2'} - request_init["document"] = {'name': 'name_value', 'display_name': 'display_name_value', 'mime_type': 'mime_type_value', 'knowledge_types': [1], 'content_uri': 'content_uri_value', 'raw_content': b'raw_content_blob', 'enable_auto_reload': True, 'latest_reload_status': {'time': {'seconds': 751, 'nanos': 543}, 'status': {'code': 411, 'message': 'message_value', 'details': [{'type_url': 'type.googleapis.com/google.protobuf.Duration', 'value': b'\x08\x0c\x10\xdb\x07'}]}}, 'metadata': {}, 'state': 1} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.create_document(request) - - -def test_create_document_rest_flattened(): - client = DocumentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name='operations/spam') - - # get arguments that satisfy an http rule for this method - sample_request = {'parent': 'projects/sample1/knowledgeBases/sample2'} - - # get truthy value for each flattened field - mock_args = dict( - parent='parent_value', - document=gcd_document.Document(name='name_value'), - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.create_document(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v2/{parent=projects/*/knowledgeBases/*}/documents" % client.transport._host, args[1]) - - -def test_create_document_rest_flattened_error(transport: str = 'rest'): - client = DocumentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.create_document( - gcd_document.CreateDocumentRequest(), - parent='parent_value', - document=gcd_document.Document(name='name_value'), - ) - - -def test_create_document_rest_error(): - client = DocumentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - document.ImportDocumentsRequest, - dict, -]) -def test_import_documents_rest(request_type): - client = DocumentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1/knowledgeBases/sample2'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name='operations/spam') - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.import_documents(request) - - # Establish that the response is the type that we expect. - assert response.operation.name == "operations/spam" - - -def test_import_documents_rest_required_fields(request_type=document.ImportDocumentsRequest): - transport_class = transports.DocumentsRestTransport - - request_init = {} - request_init["parent"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - including_default_value_fields=False, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).import_documents._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["parent"] = 'parent_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).import_documents._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "parent" in jsonified_request - assert jsonified_request["parent"] == 'parent_value' - - client = DocumentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name='operations/spam') - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "post", - 'query_params': pb_request, - } - transcode_result['body'] = pb_request - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.import_documents(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_import_documents_rest_unset_required_fields(): - transport = transports.DocumentsRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.import_documents._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("parent", "documentTemplate", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_import_documents_rest_interceptors(null_interceptor): - transport = transports.DocumentsRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.DocumentsRestInterceptor(), - ) - client = DocumentsClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(operation.Operation, "_set_result_from_operation"), \ - mock.patch.object(transports.DocumentsRestInterceptor, "post_import_documents") as post, \ - mock.patch.object(transports.DocumentsRestInterceptor, "pre_import_documents") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = document.ImportDocumentsRequest.pb(document.ImportDocumentsRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = json_format.MessageToJson(operations_pb2.Operation()) - - request = document.ImportDocumentsRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = operations_pb2.Operation() - - client.import_documents(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_import_documents_rest_bad_request(transport: str = 'rest', request_type=document.ImportDocumentsRequest): - client = DocumentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1/knowledgeBases/sample2'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.import_documents(request) - - -def test_import_documents_rest_error(): - client = DocumentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - document.DeleteDocumentRequest, - dict, -]) -def test_delete_document_rest(request_type): - client = DocumentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/knowledgeBases/sample2/documents/sample3'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name='operations/spam') - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.delete_document(request) - - # Establish that the response is the type that we expect. - assert response.operation.name == "operations/spam" - - -def test_delete_document_rest_required_fields(request_type=document.DeleteDocumentRequest): - transport_class = transports.DocumentsRestTransport - - request_init = {} - request_init["name"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - including_default_value_fields=False, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).delete_document._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["name"] = 'name_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).delete_document._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "name" in jsonified_request - assert jsonified_request["name"] == 'name_value' - - client = DocumentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name='operations/spam') - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "delete", - 'query_params': pb_request, - } - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.delete_document(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_delete_document_rest_unset_required_fields(): - transport = transports.DocumentsRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.delete_document._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_delete_document_rest_interceptors(null_interceptor): - transport = transports.DocumentsRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.DocumentsRestInterceptor(), - ) - client = DocumentsClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(operation.Operation, "_set_result_from_operation"), \ - mock.patch.object(transports.DocumentsRestInterceptor, "post_delete_document") as post, \ - mock.patch.object(transports.DocumentsRestInterceptor, "pre_delete_document") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = document.DeleteDocumentRequest.pb(document.DeleteDocumentRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = json_format.MessageToJson(operations_pb2.Operation()) - - request = document.DeleteDocumentRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = operations_pb2.Operation() - - client.delete_document(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_delete_document_rest_bad_request(transport: str = 'rest', request_type=document.DeleteDocumentRequest): - client = DocumentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/knowledgeBases/sample2/documents/sample3'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.delete_document(request) - - -def test_delete_document_rest_flattened(): - client = DocumentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name='operations/spam') - - # get arguments that satisfy an http rule for this method - sample_request = {'name': 'projects/sample1/knowledgeBases/sample2/documents/sample3'} - - # get truthy value for each flattened field - mock_args = dict( - name='name_value', - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.delete_document(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v2/{name=projects/*/knowledgeBases/*/documents/*}" % client.transport._host, args[1]) - - -def test_delete_document_rest_flattened_error(transport: str = 'rest'): - client = DocumentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.delete_document( - document.DeleteDocumentRequest(), - name='name_value', - ) - - -def test_delete_document_rest_error(): - client = DocumentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - gcd_document.UpdateDocumentRequest, - dict, -]) -def test_update_document_rest(request_type): - client = DocumentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'document': {'name': 'projects/sample1/knowledgeBases/sample2/documents/sample3'}} - request_init["document"] = {'name': 'projects/sample1/knowledgeBases/sample2/documents/sample3', 'display_name': 'display_name_value', 'mime_type': 'mime_type_value', 'knowledge_types': [1], 'content_uri': 'content_uri_value', 'raw_content': b'raw_content_blob', 'enable_auto_reload': True, 'latest_reload_status': {'time': {'seconds': 751, 'nanos': 543}, 'status': {'code': 411, 'message': 'message_value', 'details': [{'type_url': 'type.googleapis.com/google.protobuf.Duration', 'value': b'\x08\x0c\x10\xdb\x07'}]}}, 'metadata': {}, 'state': 1} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name='operations/spam') - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.update_document(request) - - # Establish that the response is the type that we expect. - assert response.operation.name == "operations/spam" - - -def test_update_document_rest_required_fields(request_type=gcd_document.UpdateDocumentRequest): - transport_class = transports.DocumentsRestTransport - - request_init = {} - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - including_default_value_fields=False, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).update_document._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).update_document._get_unset_required_fields(jsonified_request) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("update_mask", )) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - - client = DocumentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name='operations/spam') - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "patch", - 'query_params': pb_request, - } - transcode_result['body'] = pb_request - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.update_document(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_update_document_rest_unset_required_fields(): - transport = transports.DocumentsRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.update_document._get_unset_required_fields({}) - assert set(unset_fields) == (set(("updateMask", )) & set(("document", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_update_document_rest_interceptors(null_interceptor): - transport = transports.DocumentsRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.DocumentsRestInterceptor(), - ) - client = DocumentsClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(operation.Operation, "_set_result_from_operation"), \ - mock.patch.object(transports.DocumentsRestInterceptor, "post_update_document") as post, \ - mock.patch.object(transports.DocumentsRestInterceptor, "pre_update_document") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = gcd_document.UpdateDocumentRequest.pb(gcd_document.UpdateDocumentRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = json_format.MessageToJson(operations_pb2.Operation()) - - request = gcd_document.UpdateDocumentRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = operations_pb2.Operation() - - client.update_document(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_update_document_rest_bad_request(transport: str = 'rest', request_type=gcd_document.UpdateDocumentRequest): - client = DocumentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'document': {'name': 'projects/sample1/knowledgeBases/sample2/documents/sample3'}} - request_init["document"] = {'name': 'projects/sample1/knowledgeBases/sample2/documents/sample3', 'display_name': 'display_name_value', 'mime_type': 'mime_type_value', 'knowledge_types': [1], 'content_uri': 'content_uri_value', 'raw_content': b'raw_content_blob', 'enable_auto_reload': True, 'latest_reload_status': {'time': {'seconds': 751, 'nanos': 543}, 'status': {'code': 411, 'message': 'message_value', 'details': [{'type_url': 'type.googleapis.com/google.protobuf.Duration', 'value': b'\x08\x0c\x10\xdb\x07'}]}}, 'metadata': {}, 'state': 1} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.update_document(request) - - -def test_update_document_rest_flattened(): - client = DocumentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name='operations/spam') - - # get arguments that satisfy an http rule for this method - sample_request = {'document': {'name': 'projects/sample1/knowledgeBases/sample2/documents/sample3'}} - - # get truthy value for each flattened field - mock_args = dict( - document=gcd_document.Document(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.update_document(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v2/{document.name=projects/*/knowledgeBases/*/documents/*}" % client.transport._host, args[1]) - - -def test_update_document_rest_flattened_error(transport: str = 'rest'): - client = DocumentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.update_document( - gcd_document.UpdateDocumentRequest(), - document=gcd_document.Document(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - - -def test_update_document_rest_error(): - client = DocumentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - document.ReloadDocumentRequest, - dict, -]) -def test_reload_document_rest(request_type): - client = DocumentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/knowledgeBases/sample2/documents/sample3'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name='operations/spam') - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.reload_document(request) - - # Establish that the response is the type that we expect. - assert response.operation.name == "operations/spam" - - -def test_reload_document_rest_required_fields(request_type=document.ReloadDocumentRequest): - transport_class = transports.DocumentsRestTransport - - request_init = {} - request_init["name"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - including_default_value_fields=False, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).reload_document._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["name"] = 'name_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).reload_document._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "name" in jsonified_request - assert jsonified_request["name"] == 'name_value' - - client = DocumentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name='operations/spam') - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "post", - 'query_params': pb_request, - } - transcode_result['body'] = pb_request - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.reload_document(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_reload_document_rest_unset_required_fields(): - transport = transports.DocumentsRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.reload_document._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_reload_document_rest_interceptors(null_interceptor): - transport = transports.DocumentsRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.DocumentsRestInterceptor(), - ) - client = DocumentsClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(operation.Operation, "_set_result_from_operation"), \ - mock.patch.object(transports.DocumentsRestInterceptor, "post_reload_document") as post, \ - mock.patch.object(transports.DocumentsRestInterceptor, "pre_reload_document") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = document.ReloadDocumentRequest.pb(document.ReloadDocumentRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = json_format.MessageToJson(operations_pb2.Operation()) - - request = document.ReloadDocumentRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = operations_pb2.Operation() - - client.reload_document(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_reload_document_rest_bad_request(transport: str = 'rest', request_type=document.ReloadDocumentRequest): - client = DocumentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/knowledgeBases/sample2/documents/sample3'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.reload_document(request) - - -def test_reload_document_rest_flattened(): - client = DocumentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name='operations/spam') - - # get arguments that satisfy an http rule for this method - sample_request = {'name': 'projects/sample1/knowledgeBases/sample2/documents/sample3'} - - # get truthy value for each flattened field - mock_args = dict( - name='name_value', - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.reload_document(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v2/{name=projects/*/knowledgeBases/*/documents/*}:reload" % client.transport._host, args[1]) - - -def test_reload_document_rest_flattened_error(transport: str = 'rest'): - client = DocumentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.reload_document( - document.ReloadDocumentRequest(), - name='name_value', - content_uri='content_uri_value', - ) - - -def test_reload_document_rest_error(): - client = DocumentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - document.ExportDocumentRequest, - dict, -]) -def test_export_document_rest(request_type): - client = DocumentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/knowledgeBases/sample2/documents/sample3'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name='operations/spam') - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.export_document(request) - - # Establish that the response is the type that we expect. - assert response.operation.name == "operations/spam" - - -def test_export_document_rest_required_fields(request_type=document.ExportDocumentRequest): - transport_class = transports.DocumentsRestTransport - - request_init = {} - request_init["name"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - including_default_value_fields=False, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).export_document._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["name"] = 'name_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).export_document._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "name" in jsonified_request - assert jsonified_request["name"] == 'name_value' - - client = DocumentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name='operations/spam') - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "post", - 'query_params': pb_request, - } - transcode_result['body'] = pb_request - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.export_document(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_export_document_rest_unset_required_fields(): - transport = transports.DocumentsRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.export_document._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_export_document_rest_interceptors(null_interceptor): - transport = transports.DocumentsRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.DocumentsRestInterceptor(), - ) - client = DocumentsClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(operation.Operation, "_set_result_from_operation"), \ - mock.patch.object(transports.DocumentsRestInterceptor, "post_export_document") as post, \ - mock.patch.object(transports.DocumentsRestInterceptor, "pre_export_document") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = document.ExportDocumentRequest.pb(document.ExportDocumentRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = json_format.MessageToJson(operations_pb2.Operation()) - - request = document.ExportDocumentRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = operations_pb2.Operation() - - client.export_document(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_export_document_rest_bad_request(transport: str = 'rest', request_type=document.ExportDocumentRequest): - client = DocumentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/knowledgeBases/sample2/documents/sample3'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.export_document(request) - - -def test_export_document_rest_error(): - client = DocumentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -def test_credentials_transport_error(): - # It is an error to provide credentials and a transport instance. - transport = transports.DocumentsGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = DocumentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # It is an error to provide a credentials file and a transport instance. - transport = transports.DocumentsGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = DocumentsClient( - client_options={"credentials_file": "credentials.json"}, - transport=transport, - ) - - # It is an error to provide an api_key and a transport instance. - transport = transports.DocumentsGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - options = client_options.ClientOptions() - options.api_key = "api_key" - with pytest.raises(ValueError): - client = DocumentsClient( - client_options=options, - transport=transport, - ) - - # It is an error to provide an api_key and a credential. - options = mock.Mock() - options.api_key = "api_key" - with pytest.raises(ValueError): - client = DocumentsClient( - client_options=options, - credentials=ga_credentials.AnonymousCredentials() - ) - - # It is an error to provide scopes and a transport instance. - transport = transports.DocumentsGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = DocumentsClient( - client_options={"scopes": ["1", "2"]}, - transport=transport, - ) - - -def test_transport_instance(): - # A client may be instantiated with a custom transport instance. - transport = transports.DocumentsGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - client = DocumentsClient(transport=transport) - assert client.transport is transport - -def test_transport_get_channel(): - # A client may be instantiated with a custom transport instance. - transport = transports.DocumentsGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - - transport = transports.DocumentsGrpcAsyncIOTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - -@pytest.mark.parametrize("transport_class", [ - transports.DocumentsGrpcTransport, - transports.DocumentsGrpcAsyncIOTransport, - transports.DocumentsRestTransport, -]) -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() - -@pytest.mark.parametrize("transport_name", [ - "grpc", - "rest", -]) -def test_transport_kind(transport_name): - transport = DocumentsClient.get_transport_class(transport_name)( - credentials=ga_credentials.AnonymousCredentials(), - ) - assert transport.kind == transport_name - -def test_transport_grpc_default(): - # A client should use the gRPC transport by default. - 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(core_exceptions.DuplicateCredentialArgs): - transport = transports.DocumentsTransport( - credentials=ga_credentials.AnonymousCredentials(), - credentials_file="credentials.json" - ) - - -def test_documents_base_transport(): - # Instantiate the base transport. - with mock.patch('google.cloud.dialogflow_v2.services.documents.transports.DocumentsTransport.__init__') as Transport: - Transport.return_value = None - transport = transports.DocumentsTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Every method on the transport should just blindly - # raise NotImplementedError. - methods = ( - 'list_documents', - 'get_document', - 'create_document', - 'import_documents', - 'delete_document', - 'update_document', - 'reload_document', - 'export_document', - 'get_location', - 'list_locations', - 'get_operation', - 'cancel_operation', - 'list_operations', - ) - for method in methods: - with pytest.raises(NotImplementedError): - getattr(transport, method)(request=object()) - - with pytest.raises(NotImplementedError): - transport.close() - - # Additionally, the LRO client (a property) should - # also raise NotImplementedError - with pytest.raises(NotImplementedError): - transport.operations_client - - # Catch all for all remaining methods and properties - remainder = [ - 'kind', - ] - for r in remainder: - with pytest.raises(NotImplementedError): - getattr(transport, r)() - - -def test_documents_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.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", - ) - - -def test_documents_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.documents.transports.DocumentsTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.DocumentsTransport() - adc.assert_called_once() - - -def test_documents_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) - 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, - ) - - -@pytest.mark.parametrize( - "transport_class", - [ - transports.DocumentsGrpcTransport, - transports.DocumentsGrpcAsyncIOTransport, - ], -) -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(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, - transports.DocumentsRestTransport, - ], -) -def test_documents_transport_auth_gdch_credentials(transport_class): - host = 'https://language.com' - api_audience_tests = [None, 'https://language2.com'] - api_audience_expect = [host, 'https://language2.com'] - for t, e in zip(api_audience_tests, api_audience_expect): - with mock.patch.object(google.auth, 'default', autospec=True) as adc: - gdch_mock = mock.MagicMock() - type(gdch_mock).with_gdch_audience = mock.PropertyMock(return_value=gdch_mock) - adc.return_value = (gdch_mock, None) - transport_class(host=host, api_audience=t) - gdch_mock.with_gdch_audience.assert_called_once_with( - e - ) - - -@pytest.mark.parametrize( - "transport_class,grpc_helpers", - [ - (transports.DocumentsGrpcTransport, grpc_helpers), - (transports.DocumentsGrpcAsyncIOTransport, grpc_helpers_async) - ], -) -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", [transports.DocumentsGrpcTransport, transports.DocumentsGrpcAsyncIOTransport]) -def test_documents_grpc_transport_client_cert_source_for_mtls( - transport_class -): - cred = ga_credentials.AnonymousCredentials() - - # Check ssl_channel_credentials is used if provided. - with mock.patch.object(transport_class, "create_channel") as mock_create_channel: - mock_ssl_channel_creds = mock.Mock() - transport_class( - host="squid.clam.whelk", - credentials=cred, - ssl_channel_credentials=mock_ssl_channel_creds - ) - mock_create_channel.assert_called_once_with( - "squid.clam.whelk:443", - credentials=cred, - credentials_file=None, - scopes=None, - ssl_credentials=mock_ssl_channel_creds, - quota_project_id=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - # Check if ssl_channel_credentials is not provided, then client_cert_source_for_mtls - # is used. - with mock.patch.object(transport_class, "create_channel", return_value=mock.Mock()): - with mock.patch("grpc.ssl_channel_credentials") as mock_ssl_cred: - transport_class( - credentials=cred, - client_cert_source_for_mtls=client_cert_source_callback - ) - expected_cert, expected_key = client_cert_source_callback() - mock_ssl_cred.assert_called_once_with( - certificate_chain=expected_cert, - private_key=expected_key - ) - -def test_documents_http_transport_client_cert_source_for_mtls(): - cred = ga_credentials.AnonymousCredentials() - with mock.patch("google.auth.transport.requests.AuthorizedSession.configure_mtls_channel") as mock_configure_mtls_channel: - transports.DocumentsRestTransport ( - credentials=cred, - client_cert_source_for_mtls=client_cert_source_callback - ) - mock_configure_mtls_channel.assert_called_once_with(client_cert_source_callback) - - -def test_documents_rest_lro_client(): - client = DocumentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - transport = client.transport - - # Ensure that we have a api-core operations client. - assert isinstance( - transport.operations_client, - operations_v1.AbstractOperationsClient, - ) - - # Ensure that subsequent calls to the property send the exact same object. - assert transport.operations_client is transport.operations_client - - -@pytest.mark.parametrize("transport_name", [ - "grpc", - "grpc_asyncio", - "rest", -]) -def test_documents_host_no_port(transport_name): - client = DocumentsClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='dialogflow.googleapis.com'), - transport=transport_name, - ) - assert client.transport._host == ( - 'dialogflow.googleapis.com:443' - if transport_name in ['grpc', 'grpc_asyncio'] - else 'https://dialogflow.googleapis.com' - ) - -@pytest.mark.parametrize("transport_name", [ - "grpc", - "grpc_asyncio", - "rest", -]) -def test_documents_host_with_port(transport_name): - client = DocumentsClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='dialogflow.googleapis.com:8000'), - transport=transport_name, - ) - assert client.transport._host == ( - 'dialogflow.googleapis.com:8000' - if transport_name in ['grpc', 'grpc_asyncio'] - else 'https://dialogflow.googleapis.com:8000' - ) - -@pytest.mark.parametrize("transport_name", [ - "rest", -]) -def test_documents_client_transport_session_collision(transport_name): - creds1 = ga_credentials.AnonymousCredentials() - creds2 = ga_credentials.AnonymousCredentials() - client1 = DocumentsClient( - credentials=creds1, - transport=transport_name, - ) - client2 = DocumentsClient( - credentials=creds2, - transport=transport_name, - ) - session1 = client1.transport.list_documents._session - session2 = client2.transport.list_documents._session - assert session1 != session2 - session1 = client1.transport.get_document._session - session2 = client2.transport.get_document._session - assert session1 != session2 - session1 = client1.transport.create_document._session - session2 = client2.transport.create_document._session - assert session1 != session2 - session1 = client1.transport.import_documents._session - session2 = client2.transport.import_documents._session - assert session1 != session2 - session1 = client1.transport.delete_document._session - session2 = client2.transport.delete_document._session - assert session1 != session2 - session1 = client1.transport.update_document._session - session2 = client2.transport.update_document._session - assert session1 != session2 - session1 = client1.transport.reload_document._session - session2 = client2.transport.reload_document._session - assert session1 != session2 - session1 = client1.transport.export_document._session - session2 = client2.transport.export_document._session - assert session1 != session2 -def test_documents_grpc_transport_channel(): - channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.DocumentsGrpcTransport( - 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_documents_grpc_asyncio_transport_channel(): - channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.DocumentsGrpcAsyncIOTransport( - 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.DocumentsGrpcTransport, transports.DocumentsGrpcAsyncIOTransport]) -def test_documents_transport_channel_mtls_with_client_cert_source( - transport_class -): - with mock.patch("grpc.ssl_channel_credentials", autospec=True) as grpc_ssl_channel_cred: - with mock.patch.object(transport_class, "create_channel") as grpc_create_channel: - mock_ssl_cred = mock.Mock() - grpc_ssl_channel_cred.return_value = mock_ssl_cred - - mock_grpc_channel = mock.Mock() - grpc_create_channel.return_value = mock_grpc_channel - - cred = ga_credentials.AnonymousCredentials() - with pytest.warns(DeprecationWarning): - with mock.patch.object(google.auth, 'default') as adc: - adc.return_value = (cred, None) - transport = transport_class( - host="squid.clam.whelk", - api_mtls_endpoint="mtls.squid.clam.whelk", - client_cert_source=client_cert_source_callback, - ) - adc.assert_called_once() - - grpc_ssl_channel_cred.assert_called_once_with( - certificate_chain=b"cert bytes", private_key=b"key bytes" - ) - grpc_create_channel.assert_called_once_with( - "mtls.squid.clam.whelk:443", - credentials=cred, - credentials_file=None, - scopes=None, - ssl_credentials=mock_ssl_cred, - quota_project_id=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - assert transport.grpc_channel == mock_grpc_channel - assert transport._ssl_channel_credentials == mock_ssl_cred - - -# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are -# removed from grpc/grpc_asyncio transport constructor. -@pytest.mark.parametrize("transport_class", [transports.DocumentsGrpcTransport, transports.DocumentsGrpcAsyncIOTransport]) -def test_documents_transport_channel_mtls_with_adc( - transport_class -): - mock_ssl_cred = mock.Mock() - with mock.patch.multiple( - "google.auth.transport.grpc.SslCredentials", - __init__=mock.Mock(return_value=None), - ssl_credentials=mock.PropertyMock(return_value=mock_ssl_cred), - ): - with mock.patch.object(transport_class, "create_channel") as grpc_create_channel: - mock_grpc_channel = mock.Mock() - grpc_create_channel.return_value = mock_grpc_channel - mock_cred = mock.Mock() - - with pytest.warns(DeprecationWarning): - transport = transport_class( - host="squid.clam.whelk", - credentials=mock_cred, - api_mtls_endpoint="mtls.squid.clam.whelk", - client_cert_source=None, - ) - - grpc_create_channel.assert_called_once_with( - "mtls.squid.clam.whelk:443", - credentials=mock_cred, - credentials_file=None, - scopes=None, - ssl_credentials=mock_ssl_cred, - quota_project_id=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - assert transport.grpc_channel == mock_grpc_channel - - -def test_documents_grpc_lro_client(): - client = DocumentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - transport = client.transport - - # Ensure that we have a api-core operations client. - assert isinstance( - transport.operations_client, - operations_v1.OperationsClient, - ) - - # Ensure that subsequent calls to the property send the exact same object. - assert transport.operations_client is transport.operations_client - - -def test_documents_grpc_lro_async_client(): - client = DocumentsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc_asyncio', - ) - transport = client.transport - - # Ensure that we have a api-core operations client. - assert isinstance( - transport.operations_client, - operations_v1.OperationsAsyncClient, - ) - - # Ensure that subsequent calls to the property send the exact same object. - assert transport.operations_client is transport.operations_client - - -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, ) - actual = DocumentsClient.document_path(project, knowledge_base, document) - assert expected == actual - - -def test_parse_document_path(): - expected = { - "project": "octopus", - "knowledge_base": "oyster", - "document": "nudibranch", - } - path = DocumentsClient.document_path(**expected) - - # Check that the path construction is reversible. - actual = DocumentsClient.parse_document_path(path) - assert expected == actual - -def test_common_billing_account_path(): - billing_account = "cuttlefish" - expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) - actual = DocumentsClient.common_billing_account_path(billing_account) - assert expected == actual - - -def test_parse_common_billing_account_path(): - expected = { - "billing_account": "mussel", - } - path = DocumentsClient.common_billing_account_path(**expected) - - # Check that the path construction is reversible. - actual = DocumentsClient.parse_common_billing_account_path(path) - assert expected == actual - -def test_common_folder_path(): - folder = "winkle" - expected = "folders/{folder}".format(folder=folder, ) - actual = DocumentsClient.common_folder_path(folder) - assert expected == actual - - -def test_parse_common_folder_path(): - expected = { - "folder": "nautilus", - } - path = DocumentsClient.common_folder_path(**expected) - - # Check that the path construction is reversible. - actual = DocumentsClient.parse_common_folder_path(path) - assert expected == actual - -def test_common_organization_path(): - organization = "scallop" - expected = "organizations/{organization}".format(organization=organization, ) - actual = DocumentsClient.common_organization_path(organization) - assert expected == actual - - -def test_parse_common_organization_path(): - expected = { - "organization": "abalone", - } - path = DocumentsClient.common_organization_path(**expected) - - # Check that the path construction is reversible. - actual = DocumentsClient.parse_common_organization_path(path) - assert expected == actual - -def test_common_project_path(): - project = "squid" - expected = "projects/{project}".format(project=project, ) - actual = DocumentsClient.common_project_path(project) - assert expected == actual - - -def test_parse_common_project_path(): - expected = { - "project": "clam", - } - path = DocumentsClient.common_project_path(**expected) - - # Check that the path construction is reversible. - actual = DocumentsClient.parse_common_project_path(path) - assert expected == actual - -def test_common_location_path(): - project = "whelk" - location = "octopus" - expected = "projects/{project}/locations/{location}".format(project=project, location=location, ) - actual = DocumentsClient.common_location_path(project, location) - assert expected == actual - - -def test_parse_common_location_path(): - expected = { - "project": "oyster", - "location": "nudibranch", - } - path = DocumentsClient.common_location_path(**expected) - - # Check that the path construction is reversible. - actual = DocumentsClient.parse_common_location_path(path) - assert expected == actual - - -def test_client_with_default_client_info(): - client_info = gapic_v1.client_info.ClientInfo() - - with mock.patch.object(transports.DocumentsTransport, '_prep_wrapped_messages') as prep: - client = DocumentsClient( - credentials=ga_credentials.AnonymousCredentials(), - client_info=client_info, - ) - prep.assert_called_once_with(client_info) - - with mock.patch.object(transports.DocumentsTransport, '_prep_wrapped_messages') as prep: - transport_class = DocumentsClient.get_transport_class() - transport = transport_class( - credentials=ga_credentials.AnonymousCredentials(), - client_info=client_info, - ) - prep.assert_called_once_with(client_info) - -@pytest.mark.asyncio -async def test_transport_close_async(): - client = DocumentsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - with mock.patch.object(type(getattr(client.transport, "grpc_channel")), "close") as close: - async with client: - close.assert_not_called() - close.assert_called_once() - - -def test_get_location_rest_bad_request(transport: str = 'rest', request_type=locations_pb2.GetLocationRequest): - client = DocumentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - request = request_type() - request = json_format.ParseDict({'name': 'projects/sample1/locations/sample2'}, request) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.get_location(request) - -@pytest.mark.parametrize("request_type", [ - locations_pb2.GetLocationRequest, - dict, -]) -def test_get_location_rest(request_type): - client = DocumentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request_init = {'name': 'projects/sample1/locations/sample2'} - request = request_type(**request_init) - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = locations_pb2.Location() - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.get_location(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, locations_pb2.Location) - -def test_list_locations_rest_bad_request(transport: str = 'rest', request_type=locations_pb2.ListLocationsRequest): - client = DocumentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - request = request_type() - request = json_format.ParseDict({'name': 'projects/sample1'}, request) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.list_locations(request) - -@pytest.mark.parametrize("request_type", [ - locations_pb2.ListLocationsRequest, - dict, -]) -def test_list_locations_rest(request_type): - client = DocumentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request_init = {'name': 'projects/sample1'} - request = request_type(**request_init) - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = locations_pb2.ListLocationsResponse() - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.list_locations(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, locations_pb2.ListLocationsResponse) - -def test_cancel_operation_rest_bad_request(transport: str = 'rest', request_type=operations_pb2.CancelOperationRequest): - client = DocumentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - request = request_type() - request = json_format.ParseDict({'name': 'projects/sample1/operations/sample2'}, request) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.cancel_operation(request) - -@pytest.mark.parametrize("request_type", [ - operations_pb2.CancelOperationRequest, - dict, -]) -def test_cancel_operation_rest(request_type): - client = DocumentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request_init = {'name': 'projects/sample1/operations/sample2'} - request = request_type(**request_init) - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = None - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = '{}' - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.cancel_operation(request) - - # Establish that the response is the type that we expect. - assert response is None - -def test_get_operation_rest_bad_request(transport: str = 'rest', request_type=operations_pb2.GetOperationRequest): - client = DocumentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - request = request_type() - request = json_format.ParseDict({'name': 'projects/sample1/operations/sample2'}, request) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.get_operation(request) - -@pytest.mark.parametrize("request_type", [ - operations_pb2.GetOperationRequest, - dict, -]) -def test_get_operation_rest(request_type): - client = DocumentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request_init = {'name': 'projects/sample1/operations/sample2'} - request = request_type(**request_init) - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation() - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.get_operation(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, operations_pb2.Operation) - -def test_list_operations_rest_bad_request(transport: str = 'rest', request_type=operations_pb2.ListOperationsRequest): - client = DocumentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - request = request_type() - request = json_format.ParseDict({'name': 'projects/sample1'}, request) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.list_operations(request) - -@pytest.mark.parametrize("request_type", [ - operations_pb2.ListOperationsRequest, - dict, -]) -def test_list_operations_rest(request_type): - client = DocumentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request_init = {'name': 'projects/sample1'} - request = request_type(**request_init) - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = operations_pb2.ListOperationsResponse() - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.list_operations(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, operations_pb2.ListOperationsResponse) - - -def test_cancel_operation(transport: str = "grpc"): - client = DocumentsClient( - 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 = operations_pb2.CancelOperationRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = None - response = client.cancel_operation(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 response is the type that we expect. - assert response is None -@pytest.mark.asyncio -async def test_cancel_operation_async(transport: str = "grpc"): - client = DocumentsAsyncClient( - 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 = operations_pb2.CancelOperationRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - None - ) - response = await client.cancel_operation(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 response is the type that we expect. - assert response is None - -def test_cancel_operation_field_headers(): - 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 = operations_pb2.CancelOperationRequest() - request.name = "locations" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call: - call.return_value = None - - client.cancel_operation(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=locations",) in kw["metadata"] -@pytest.mark.asyncio -async def test_cancel_operation_field_headers_async(): - 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 = operations_pb2.CancelOperationRequest() - request.name = "locations" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - None - ) - await client.cancel_operation(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=locations",) in kw["metadata"] - -def test_cancel_operation_from_dict(): - 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.cancel_operation), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = None - - response = client.cancel_operation( - request={ - "name": "locations", - } - ) - call.assert_called() -@pytest.mark.asyncio -async def test_cancel_operation_from_dict_async(): - 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.cancel_operation), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - None - ) - response = await client.cancel_operation( - request={ - "name": "locations", - } - ) - call.assert_called() - - -def test_get_operation(transport: str = "grpc"): - client = DocumentsClient( - 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 = operations_pb2.GetOperationRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_operation), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation() - response = client.get_operation(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 response is the type that we expect. - assert isinstance(response, operations_pb2.Operation) -@pytest.mark.asyncio -async def test_get_operation_async(transport: str = "grpc"): - client = DocumentsAsyncClient( - 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 = operations_pb2.GetOperationRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_operation), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation() - ) - response = await client.get_operation(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 response is the type that we expect. - assert isinstance(response, operations_pb2.Operation) - -def test_get_operation_field_headers(): - 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 = operations_pb2.GetOperationRequest() - request.name = "locations" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_operation), "__call__") as call: - call.return_value = operations_pb2.Operation() - - client.get_operation(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=locations",) in kw["metadata"] -@pytest.mark.asyncio -async def test_get_operation_field_headers_async(): - 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 = operations_pb2.GetOperationRequest() - request.name = "locations" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_operation), "__call__") as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation() - ) - await client.get_operation(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=locations",) in kw["metadata"] - -def test_get_operation_from_dict(): - 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_operation), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation() - - response = client.get_operation( - request={ - "name": "locations", - } - ) - call.assert_called() -@pytest.mark.asyncio -async def test_get_operation_from_dict_async(): - 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_operation), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation() - ) - response = await client.get_operation( - request={ - "name": "locations", - } - ) - call.assert_called() - - -def test_list_operations(transport: str = "grpc"): - client = DocumentsClient( - 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 = operations_pb2.ListOperationsRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_operations), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.ListOperationsResponse() - response = client.list_operations(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 response is the type that we expect. - assert isinstance(response, operations_pb2.ListOperationsResponse) -@pytest.mark.asyncio -async def test_list_operations_async(transport: str = "grpc"): - client = DocumentsAsyncClient( - 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 = operations_pb2.ListOperationsRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_operations), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.ListOperationsResponse() - ) - response = await client.list_operations(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 response is the type that we expect. - assert isinstance(response, operations_pb2.ListOperationsResponse) - -def test_list_operations_field_headers(): - 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 = operations_pb2.ListOperationsRequest() - request.name = "locations" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_operations), "__call__") as call: - call.return_value = operations_pb2.ListOperationsResponse() - - client.list_operations(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=locations",) in kw["metadata"] -@pytest.mark.asyncio -async def test_list_operations_field_headers_async(): - 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 = operations_pb2.ListOperationsRequest() - request.name = "locations" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_operations), "__call__") as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.ListOperationsResponse() - ) - await client.list_operations(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=locations",) in kw["metadata"] - -def test_list_operations_from_dict(): - 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_operations), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.ListOperationsResponse() - - response = client.list_operations( - request={ - "name": "locations", - } - ) - call.assert_called() -@pytest.mark.asyncio -async def test_list_operations_from_dict_async(): - 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_operations), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.ListOperationsResponse() - ) - response = await client.list_operations( - request={ - "name": "locations", - } - ) - call.assert_called() - - -def test_list_locations(transport: str = "grpc"): - client = DocumentsClient( - 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 = locations_pb2.ListLocationsRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_locations), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = locations_pb2.ListLocationsResponse() - response = client.list_locations(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 response is the type that we expect. - assert isinstance(response, locations_pb2.ListLocationsResponse) -@pytest.mark.asyncio -async def test_list_locations_async(transport: str = "grpc"): - client = DocumentsAsyncClient( - 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 = locations_pb2.ListLocationsRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_locations), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - locations_pb2.ListLocationsResponse() - ) - response = await client.list_locations(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 response is the type that we expect. - assert isinstance(response, locations_pb2.ListLocationsResponse) - -def test_list_locations_field_headers(): - 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 = locations_pb2.ListLocationsRequest() - request.name = "locations" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_locations), "__call__") as call: - call.return_value = locations_pb2.ListLocationsResponse() - - client.list_locations(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=locations",) in kw["metadata"] -@pytest.mark.asyncio -async def test_list_locations_field_headers_async(): - 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 = locations_pb2.ListLocationsRequest() - request.name = "locations" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_locations), "__call__") as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - locations_pb2.ListLocationsResponse() - ) - await client.list_locations(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=locations",) in kw["metadata"] - -def test_list_locations_from_dict(): - 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_locations), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = locations_pb2.ListLocationsResponse() - - response = client.list_locations( - request={ - "name": "locations", - } - ) - call.assert_called() -@pytest.mark.asyncio -async def test_list_locations_from_dict_async(): - 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_locations), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - locations_pb2.ListLocationsResponse() - ) - response = await client.list_locations( - request={ - "name": "locations", - } - ) - call.assert_called() - - -def test_get_location(transport: str = "grpc"): - client = DocumentsClient( - 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 = locations_pb2.GetLocationRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_location), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = locations_pb2.Location() - response = client.get_location(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 response is the type that we expect. - assert isinstance(response, locations_pb2.Location) -@pytest.mark.asyncio -async def test_get_location_async(transport: str = "grpc_asyncio"): - client = DocumentsAsyncClient( - 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 = locations_pb2.GetLocationRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_location), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - locations_pb2.Location() - ) - response = await client.get_location(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 response is the type that we expect. - assert isinstance(response, locations_pb2.Location) - -def test_get_location_field_headers(): - 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 = locations_pb2.GetLocationRequest() - request.name = "locations/abc" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_location), "__call__") as call: - call.return_value = locations_pb2.Location() - - client.get_location(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=locations/abc",) in kw["metadata"] -@pytest.mark.asyncio -async def test_get_location_field_headers_async(): - 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 = locations_pb2.GetLocationRequest() - request.name = "locations/abc" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_location), "__call__") as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - locations_pb2.Location() - ) - await client.get_location(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=locations/abc",) in kw["metadata"] - -def test_get_location_from_dict(): - 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_locations), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = locations_pb2.Location() - - response = client.get_location( - request={ - "name": "locations/abc", - } - ) - call.assert_called() -@pytest.mark.asyncio -async def test_get_location_from_dict_async(): - 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_locations), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - locations_pb2.Location() - ) - response = await client.get_location( - request={ - "name": "locations", - } - ) - call.assert_called() - - -def test_transport_close(): - transports = { - "rest": "_session", - "grpc": "_grpc_channel", - } - - for transport, close_name in transports.items(): - client = DocumentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport - ) - with mock.patch.object(type(getattr(client.transport, close_name)), "close") as close: - with client: - close.assert_not_called() - close.assert_called_once() - -def test_client_ctx(): - transports = [ - 'rest', - 'grpc', - ] - for transport in transports: - client = DocumentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport - ) - # Test client calls underlying transport. - with mock.patch.object(type(client.transport), "close") as close: - close.assert_not_called() - with client: - pass - close.assert_called() - -@pytest.mark.parametrize("client_class,transport_class", [ - (DocumentsClient, transports.DocumentsGrpcTransport), - (DocumentsAsyncClient, transports.DocumentsGrpcAsyncIOTransport), -]) -def test_api_key_credentials(client_class, transport_class): - with mock.patch.object( - google.auth._default, "get_api_key_credentials", create=True - ) as get_api_key_credentials: - mock_cred = mock.Mock() - get_api_key_credentials.return_value = mock_cred - options = client_options.ClientOptions() - options.api_key = "api_key" - 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=mock_cred, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) diff --git a/owl-bot-staging/v2/tests/unit/gapic/dialogflow_v2/test_entity_types.py b/owl-bot-staging/v2/tests/unit/gapic/dialogflow_v2/test_entity_types.py deleted file mode 100644 index 571beb59b..000000000 --- a/owl-bot-staging/v2/tests/unit/gapic/dialogflow_v2/test_entity_types.py +++ /dev/null @@ -1,7145 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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 -# try/except added for compatibility with python < 3.8 -try: - from unittest import mock - from unittest.mock import AsyncMock # pragma: NO COVER -except ImportError: # pragma: NO COVER - import mock - -import grpc -from grpc.experimental import aio -from collections.abc import Iterable -from google.protobuf import json_format -import json -import math -import pytest -from proto.marshal.rules.dates import DurationRule, TimestampRule -from proto.marshal.rules import wrappers -from requests import Response -from requests import Request, PreparedRequest -from requests.sessions import Session -from google.protobuf import json_format - -from google.api_core import client_options -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 -from google.api_core import operation_async # type: ignore -from google.api_core import operations_v1 -from google.api_core import path_template -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.types import entity_type -from google.cloud.dialogflow_v2.types import entity_type as gcd_entity_type -from google.cloud.location import locations_pb2 -from google.longrunning import operations_pb2 -from google.oauth2 import service_account -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 -import google.auth - - -def client_cert_source_callback(): - return b"cert bytes", b"key bytes" - - -# If default endpoint is localhost, then default mtls endpoint will be the same. -# This method modifies the default endpoint so the client can produce a different -# mtls endpoint for endpoint testing purposes. -def modify_default_endpoint(client): - return "foo.googleapis.com" if ("localhost" in client.DEFAULT_ENDPOINT) else client.DEFAULT_ENDPOINT - - -def test__get_default_mtls_endpoint(): - api_endpoint = "example.googleapis.com" - api_mtls_endpoint = "example.mtls.googleapis.com" - sandbox_endpoint = "example.sandbox.googleapis.com" - sandbox_mtls_endpoint = "example.mtls.sandbox.googleapis.com" - non_googleapi = "api.example.com" - - assert EntityTypesClient._get_default_mtls_endpoint(None) is None - assert EntityTypesClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint - assert EntityTypesClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint - assert EntityTypesClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint - assert EntityTypesClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint - assert EntityTypesClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi - - -@pytest.mark.parametrize("client_class,transport_name", [ - (EntityTypesClient, "grpc"), - (EntityTypesAsyncClient, "grpc_asyncio"), - (EntityTypesClient, "rest"), -]) -def test_entity_types_client_from_service_account_info(client_class, transport_name): - 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, transport=transport_name) - assert client.transport._credentials == creds - assert isinstance(client, client_class) - - assert client.transport._host == ( - 'dialogflow.googleapis.com:443' - if transport_name in ['grpc', 'grpc_asyncio'] - else - 'https://dialogflow.googleapis.com' - ) - - -@pytest.mark.parametrize("transport_class,transport_name", [ - (transports.EntityTypesGrpcTransport, "grpc"), - (transports.EntityTypesGrpcAsyncIOTransport, "grpc_asyncio"), - (transports.EntityTypesRestTransport, "rest"), -]) -def test_entity_types_client_service_account_always_use_jwt(transport_class, transport_name): - with mock.patch.object(service_account.Credentials, 'with_always_use_jwt_access', create=True) as use_jwt: - creds = service_account.Credentials(None, None, None) - transport = transport_class(credentials=creds, always_use_jwt_access=True) - use_jwt.assert_called_once_with(True) - - with mock.patch.object(service_account.Credentials, 'with_always_use_jwt_access', create=True) as use_jwt: - creds = service_account.Credentials(None, None, None) - transport = transport_class(credentials=creds, always_use_jwt_access=False) - use_jwt.assert_not_called() - - -@pytest.mark.parametrize("client_class,transport_name", [ - (EntityTypesClient, "grpc"), - (EntityTypesAsyncClient, "grpc_asyncio"), - (EntityTypesClient, "rest"), -]) -def test_entity_types_client_from_service_account_file(client_class, transport_name): - 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", transport=transport_name) - assert client.transport._credentials == creds - assert isinstance(client, client_class) - - client = client_class.from_service_account_json("dummy/file/path.json", transport=transport_name) - assert client.transport._credentials == creds - assert isinstance(client, client_class) - - assert client.transport._host == ( - 'dialogflow.googleapis.com:443' - if transport_name in ['grpc', 'grpc_asyncio'] - else - 'https://dialogflow.googleapis.com' - ) - - -def test_entity_types_client_get_transport_class(): - transport = EntityTypesClient.get_transport_class() - available_transports = [ - transports.EntityTypesGrpcTransport, - transports.EntityTypesRestTransport, - ] - assert transport in available_transports - - transport = EntityTypesClient.get_transport_class("grpc") - assert transport == transports.EntityTypesGrpcTransport - - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (EntityTypesClient, transports.EntityTypesGrpcTransport, "grpc"), - (EntityTypesAsyncClient, transports.EntityTypesGrpcAsyncIOTransport, "grpc_asyncio"), - (EntityTypesClient, transports.EntityTypesRestTransport, "rest"), -]) -@mock.patch.object(EntityTypesClient, "DEFAULT_ENDPOINT", modify_default_endpoint(EntityTypesClient)) -@mock.patch.object(EntityTypesAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(EntityTypesAsyncClient)) -def test_entity_types_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(EntityTypesClient, '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(EntityTypesClient, 'get_transport_class') as gtc: - client = client_class(transport=transport_name) - gtc.assert_called() - - # Check the case api_endpoint is provided. - options = client_options.ClientOptions(api_endpoint="squid.clam.whelk") - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(transport=transport_name, client_options=options) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host="squid.clam.whelk", - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is - # "never". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is - # "always". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_MTLS_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # 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(transport=transport_name) - - # 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(transport=transport_name) - - # 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, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id="octopus", - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - # Check the case api_endpoint is provided - options = client_options.ClientOptions(api_audience="https://language.googleapis.com") - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience="https://language.googleapis.com" - ) - -@pytest.mark.parametrize("client_class,transport_class,transport_name,use_client_cert_env", [ - (EntityTypesClient, transports.EntityTypesGrpcTransport, "grpc", "true"), - (EntityTypesAsyncClient, transports.EntityTypesGrpcAsyncIOTransport, "grpc_asyncio", "true"), - (EntityTypesClient, transports.EntityTypesGrpcTransport, "grpc", "false"), - (EntityTypesAsyncClient, transports.EntityTypesGrpcAsyncIOTransport, "grpc_asyncio", "false"), - (EntityTypesClient, transports.EntityTypesRestTransport, "rest", "true"), - (EntityTypesClient, transports.EntityTypesRestTransport, "rest", "false"), -]) -@mock.patch.object(EntityTypesClient, "DEFAULT_ENDPOINT", modify_default_endpoint(EntityTypesClient)) -@mock.patch.object(EntityTypesAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(EntityTypesAsyncClient)) -@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) -def test_entity_types_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, transport=transport_name) - - if use_client_cert_env == "false": - expected_client_cert_source = None - expected_host = client.DEFAULT_ENDPOINT - else: - expected_client_cert_source = client_cert_source_callback - expected_host = client.DEFAULT_MTLS_ENDPOINT - - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=expected_host, - scopes=None, - client_cert_source_for_mtls=expected_client_cert_source, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case ADC client cert is provided. Whether client cert is used depends on - # GOOGLE_API_USE_CLIENT_CERTIFICATE value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): - with mock.patch.object(transport_class, '__init__') as patched: - with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): - with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=client_cert_source_callback): - if use_client_cert_env == "false": - expected_host = client.DEFAULT_ENDPOINT - expected_client_cert_source = None - else: - expected_host = client.DEFAULT_MTLS_ENDPOINT - expected_client_cert_source = client_cert_source_callback - - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=expected_host, - scopes=None, - client_cert_source_for_mtls=expected_client_cert_source, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case client_cert_source and ADC client cert are not provided. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): - with mock.patch.object(transport_class, '__init__') as patched: - with mock.patch("google.auth.transport.mtls.has_default_client_cert_source", return_value=False): - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - -@pytest.mark.parametrize("client_class", [ - EntityTypesClient, EntityTypesAsyncClient -]) -@mock.patch.object(EntityTypesClient, "DEFAULT_ENDPOINT", modify_default_endpoint(EntityTypesClient)) -@mock.patch.object(EntityTypesAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(EntityTypesAsyncClient)) -def test_entity_types_client_get_mtls_endpoint_and_cert_source(client_class): - mock_client_cert_source = mock.Mock() - - # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "true". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - mock_api_endpoint = "foo" - options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) - assert api_endpoint == mock_api_endpoint - assert cert_source == mock_client_cert_source - - # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "false". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): - mock_client_cert_source = mock.Mock() - mock_api_endpoint = "foo" - options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) - assert api_endpoint == mock_api_endpoint - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "never". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_ENDPOINT - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "always". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert doesn't exist. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=False): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_ENDPOINT - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert exists. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - 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=mock_client_cert_source): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT - assert cert_source == mock_client_cert_source - - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (EntityTypesClient, transports.EntityTypesGrpcTransport, "grpc"), - (EntityTypesAsyncClient, transports.EntityTypesGrpcAsyncIOTransport, "grpc_asyncio"), - (EntityTypesClient, transports.EntityTypesRestTransport, "rest"), -]) -def test_entity_types_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, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=["1", "2"], - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - -@pytest.mark.parametrize("client_class,transport_class,transport_name,grpc_helpers", [ - (EntityTypesClient, transports.EntityTypesGrpcTransport, "grpc", grpc_helpers), - (EntityTypesAsyncClient, transports.EntityTypesGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), - (EntityTypesClient, transports.EntityTypesRestTransport, "rest", None), -]) -def test_entity_types_client_client_options_credentials_file(client_class, transport_class, transport_name, grpc_helpers): - # 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, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file="credentials.json", - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - -def test_entity_types_client_client_options_from_dict(): - with mock.patch('google.cloud.dialogflow_v2.services.entity_types.transports.EntityTypesGrpcTransport.__init__') as grpc_transport: - grpc_transport.return_value = None - client = EntityTypesClient( - client_options={'api_endpoint': 'squid.clam.whelk'} - ) - grpc_transport.assert_called_once_with( - credentials=None, - credentials_file=None, - host="squid.clam.whelk", - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - -@pytest.mark.parametrize("client_class,transport_class,transport_name,grpc_helpers", [ - (EntityTypesClient, transports.EntityTypesGrpcTransport, "grpc", grpc_helpers), - (EntityTypesAsyncClient, transports.EntityTypesGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), -]) -def test_entity_types_client_create_channel_credentials_file(client_class, transport_class, transport_name, grpc_helpers): - # 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, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file="credentials.json", - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # test that the credentials from file are saved and used as the credentials. - with mock.patch.object( - google.auth, "load_credentials_from_file", autospec=True - ) as load_creds, mock.patch.object( - google.auth, "default", autospec=True - ) as adc, mock.patch.object( - grpc_helpers, "create_channel" - ) as create_channel: - creds = ga_credentials.AnonymousCredentials() - file_creds = ga_credentials.AnonymousCredentials() - load_creds.return_value = (file_creds, None) - adc.return_value = (creds, None) - client = client_class(client_options=options, transport=transport_name) - create_channel.assert_called_with( - "dialogflow.googleapis.com:443", - credentials=file_creds, - credentials_file=None, - quota_project_id=None, - default_scopes=( - 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/dialogflow', -), - scopes=None, - default_host="dialogflow.googleapis.com", - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - -@pytest.mark.parametrize("request_type", [ - entity_type.ListEntityTypesRequest, - dict, -]) -def test_list_entity_types(request_type, transport: str = 'grpc'): - client = EntityTypesClient( - 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_entity_types), - '__call__') as call: - # Designate an appropriate return value for the call. - 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' - - -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=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_entity_types), - '__call__') as call: - client.list_entity_types() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == entity_type.ListEntityTypesRequest() - -@pytest.mark.asyncio -async def test_list_entity_types_async(transport: str = 'grpc_asyncio', request_type=entity_type.ListEntityTypesRequest): - client = EntityTypesAsyncClient( - 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_entity_types), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(entity_type.ListEntityTypesResponse( - 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' - - -@pytest.mark.asyncio -async def test_list_entity_types_async_from_dict(): - await test_list_entity_types_async(request_type=dict) - - -def test_list_entity_types_field_headers(): - 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. - with mock.patch.object( - 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. - 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_entity_types_field_headers_async(): - 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. - with mock.patch.object( - type(client.transport.list_entity_types), - '__call__') as call: - 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. - 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_entity_types_flattened(): - 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.list_entity_types), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = entity_type.ListEntityTypesResponse() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.list_entity_types( - parent='parent_value', - language_code='language_code_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] - arg = args[0].parent - mock_val = 'parent_value' - assert arg == mock_val - arg = args[0].language_code - mock_val = 'language_code_value' - assert arg == mock_val - - -def test_list_entity_types_flattened_error(): - client = EntityTypesClient( - 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_entity_types( - entity_type.ListEntityTypesRequest(), - parent='parent_value', - language_code='language_code_value', - ) - -@pytest.mark.asyncio -async def test_list_entity_types_flattened_async(): - 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.list_entity_types), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = entity_type.ListEntityTypesResponse() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(entity_type.ListEntityTypesResponse()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.list_entity_types( - parent='parent_value', - language_code='language_code_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - arg = args[0].parent - mock_val = 'parent_value' - assert arg == mock_val - arg = args[0].language_code - mock_val = 'language_code_value' - assert arg == mock_val - -@pytest.mark.asyncio -async def test_list_entity_types_flattened_error_async(): - client = EntityTypesAsyncClient( - 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_entity_types( - entity_type.ListEntityTypesRequest(), - parent='parent_value', - language_code='language_code_value', - ) - - -def test_list_entity_types_pager(transport_name: str = "grpc"): - client = EntityTypesClient( - credentials=ga_credentials.AnonymousCredentials, - transport=transport_name, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_entity_types), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - entity_type.ListEntityTypesResponse( - entity_types=[ - entity_type.EntityType(), - entity_type.EntityType(), - entity_type.EntityType(), - ], - next_page_token='abc', - ), - entity_type.ListEntityTypesResponse( - entity_types=[], - next_page_token='def', - ), - entity_type.ListEntityTypesResponse( - entity_types=[ - entity_type.EntityType(), - ], - next_page_token='ghi', - ), - entity_type.ListEntityTypesResponse( - entity_types=[ - entity_type.EntityType(), - entity_type.EntityType(), - ], - ), - RuntimeError, - ) - - metadata = () - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ('parent', ''), - )), - ) - pager = client.list_entity_types(request={}) - - assert pager._metadata == metadata - - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, entity_type.EntityType) - for i in results) -def test_list_entity_types_pages(transport_name: str = "grpc"): - client = EntityTypesClient( - credentials=ga_credentials.AnonymousCredentials, - transport=transport_name, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_entity_types), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - entity_type.ListEntityTypesResponse( - entity_types=[ - entity_type.EntityType(), - entity_type.EntityType(), - entity_type.EntityType(), - ], - next_page_token='abc', - ), - entity_type.ListEntityTypesResponse( - entity_types=[], - next_page_token='def', - ), - entity_type.ListEntityTypesResponse( - entity_types=[ - entity_type.EntityType(), - ], - next_page_token='ghi', - ), - entity_type.ListEntityTypesResponse( - entity_types=[ - entity_type.EntityType(), - entity_type.EntityType(), - ], - ), - RuntimeError, - ) - pages = list(client.list_entity_types(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_entity_types_async_pager(): - 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.list_entity_types), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - entity_type.ListEntityTypesResponse( - entity_types=[ - entity_type.EntityType(), - entity_type.EntityType(), - entity_type.EntityType(), - ], - next_page_token='abc', - ), - entity_type.ListEntityTypesResponse( - entity_types=[], - next_page_token='def', - ), - entity_type.ListEntityTypesResponse( - entity_types=[ - entity_type.EntityType(), - ], - next_page_token='ghi', - ), - entity_type.ListEntityTypesResponse( - entity_types=[ - entity_type.EntityType(), - entity_type.EntityType(), - ], - ), - RuntimeError, - ) - async_pager = await client.list_entity_types(request={},) - assert async_pager.next_page_token == 'abc' - responses = [] - async for response in async_pager: # pragma: no branch - responses.append(response) - - assert len(responses) == 6 - assert all(isinstance(i, entity_type.EntityType) - for i in responses) - - -@pytest.mark.asyncio -async def test_list_entity_types_async_pages(): - 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.list_entity_types), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - entity_type.ListEntityTypesResponse( - entity_types=[ - entity_type.EntityType(), - entity_type.EntityType(), - entity_type.EntityType(), - ], - next_page_token='abc', - ), - entity_type.ListEntityTypesResponse( - entity_types=[], - next_page_token='def', - ), - entity_type.ListEntityTypesResponse( - entity_types=[ - entity_type.EntityType(), - ], - next_page_token='ghi', - ), - entity_type.ListEntityTypesResponse( - entity_types=[ - entity_type.EntityType(), - entity_type.EntityType(), - ], - ), - RuntimeError, - ) - pages = [] - async for page_ in (await client.list_entity_types(request={})).pages: # pragma: no branch - pages.append(page_) - for page_, token in zip(pages, ['abc','def','ghi', '']): - assert page_.raw_page.next_page_token == token - -@pytest.mark.parametrize("request_type", [ - entity_type.GetEntityTypeRequest, - dict, -]) -def test_get_entity_type(request_type, transport: str = 'grpc'): - client = EntityTypesClient( - 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_entity_type), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = entity_type.EntityType( - name='name_value', - display_name='display_name_value', - kind=entity_type.EntityType.Kind.KIND_MAP, - 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 - - -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=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_entity_type), - '__call__') as call: - client.get_entity_type() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == entity_type.GetEntityTypeRequest() - -@pytest.mark.asyncio -async def test_get_entity_type_async(transport: str = 'grpc_asyncio', request_type=entity_type.GetEntityTypeRequest): - client = EntityTypesAsyncClient( - 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_entity_type), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(entity_type.EntityType( - name='name_value', - display_name='display_name_value', - kind=entity_type.EntityType.Kind.KIND_MAP, - auto_expansion_mode=entity_type.EntityType.AutoExpansionMode.AUTO_EXPANSION_MODE_DEFAULT, - 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 - - -@pytest.mark.asyncio -async def test_get_entity_type_async_from_dict(): - await test_get_entity_type_async(request_type=dict) - - -def test_get_entity_type_field_headers(): - 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. - 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_entity_type_field_headers_async(): - 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. - with mock.patch.object( - type(client.transport.get_entity_type), - '__call__') as call: - 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. - 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_entity_type_flattened(): - client = EntityTypesClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_entity_type), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = entity_type.EntityType() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.get_entity_type( - name='name_value', - language_code='language_code_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] - arg = args[0].name - mock_val = 'name_value' - assert arg == mock_val - arg = args[0].language_code - mock_val = 'language_code_value' - assert arg == mock_val - - -def test_get_entity_type_flattened_error(): - client = EntityTypesClient( - 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_entity_type( - entity_type.GetEntityTypeRequest(), - name='name_value', - language_code='language_code_value', - ) - -@pytest.mark.asyncio -async def test_get_entity_type_flattened_async(): - 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: - # Designate an appropriate return value for the call. - call.return_value = entity_type.EntityType() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(entity_type.EntityType()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.get_entity_type( - name='name_value', - language_code='language_code_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - arg = args[0].name - mock_val = 'name_value' - assert arg == mock_val - arg = args[0].language_code - mock_val = 'language_code_value' - assert arg == mock_val - -@pytest.mark.asyncio -async def test_get_entity_type_flattened_error_async(): - client = EntityTypesAsyncClient( - 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_entity_type( - entity_type.GetEntityTypeRequest(), - name='name_value', - language_code='language_code_value', - ) - - -@pytest.mark.parametrize("request_type", [ - gcd_entity_type.CreateEntityTypeRequest, - dict, -]) -def test_create_entity_type(request_type, transport: str = 'grpc'): - client = EntityTypesClient( - 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_entity_type), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcd_entity_type.EntityType( - name='name_value', - display_name='display_name_value', - kind=gcd_entity_type.EntityType.Kind.KIND_MAP, - 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 - - -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=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_entity_type), - '__call__') as call: - client.create_entity_type() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == gcd_entity_type.CreateEntityTypeRequest() - -@pytest.mark.asyncio -async def test_create_entity_type_async(transport: str = 'grpc_asyncio', request_type=gcd_entity_type.CreateEntityTypeRequest): - client = EntityTypesAsyncClient( - 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_entity_type), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gcd_entity_type.EntityType( - name='name_value', - display_name='display_name_value', - kind=gcd_entity_type.EntityType.Kind.KIND_MAP, - auto_expansion_mode=gcd_entity_type.EntityType.AutoExpansionMode.AUTO_EXPANSION_MODE_DEFAULT, - 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 - - -@pytest.mark.asyncio -async def test_create_entity_type_async_from_dict(): - await test_create_entity_type_async(request_type=dict) - - -def test_create_entity_type_field_headers(): - 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. - with mock.patch.object( - 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. - 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_entity_type_field_headers_async(): - 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. - with mock.patch.object( - type(client.transport.create_entity_type), - '__call__') as call: - 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. - 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_entity_type_flattened(): - 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.create_entity_type), - '__call__') 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( - parent='parent_value', - entity_type=gcd_entity_type.EntityType(name='name_value'), - language_code='language_code_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] - arg = args[0].parent - mock_val = 'parent_value' - assert arg == mock_val - arg = args[0].entity_type - mock_val = gcd_entity_type.EntityType(name='name_value') - assert arg == mock_val - arg = args[0].language_code - mock_val = 'language_code_value' - assert arg == mock_val - - -def test_create_entity_type_flattened_error(): - client = EntityTypesClient( - 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_entity_type( - gcd_entity_type.CreateEntityTypeRequest(), - parent='parent_value', - entity_type=gcd_entity_type.EntityType(name='name_value'), - language_code='language_code_value', - ) - -@pytest.mark.asyncio -async def test_create_entity_type_flattened_async(): - 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.create_entity_type), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcd_entity_type.EntityType() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcd_entity_type.EntityType()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.create_entity_type( - parent='parent_value', - entity_type=gcd_entity_type.EntityType(name='name_value'), - language_code='language_code_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - arg = args[0].parent - mock_val = 'parent_value' - assert arg == mock_val - arg = args[0].entity_type - mock_val = gcd_entity_type.EntityType(name='name_value') - assert arg == mock_val - arg = args[0].language_code - mock_val = 'language_code_value' - assert arg == mock_val - -@pytest.mark.asyncio -async def test_create_entity_type_flattened_error_async(): - client = EntityTypesAsyncClient( - 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_entity_type( - gcd_entity_type.CreateEntityTypeRequest(), - parent='parent_value', - entity_type=gcd_entity_type.EntityType(name='name_value'), - language_code='language_code_value', - ) - - -@pytest.mark.parametrize("request_type", [ - gcd_entity_type.UpdateEntityTypeRequest, - dict, -]) -def test_update_entity_type(request_type, transport: str = 'grpc'): - client = EntityTypesClient( - 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_entity_type), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcd_entity_type.EntityType( - name='name_value', - display_name='display_name_value', - kind=gcd_entity_type.EntityType.Kind.KIND_MAP, - 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 - - -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=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_entity_type), - '__call__') as call: - client.update_entity_type() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == gcd_entity_type.UpdateEntityTypeRequest() - -@pytest.mark.asyncio -async def test_update_entity_type_async(transport: str = 'grpc_asyncio', request_type=gcd_entity_type.UpdateEntityTypeRequest): - client = EntityTypesAsyncClient( - 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_entity_type), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gcd_entity_type.EntityType( - name='name_value', - display_name='display_name_value', - kind=gcd_entity_type.EntityType.Kind.KIND_MAP, - auto_expansion_mode=gcd_entity_type.EntityType.AutoExpansionMode.AUTO_EXPANSION_MODE_DEFAULT, - 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 - - -@pytest.mark.asyncio -async def test_update_entity_type_async_from_dict(): - await test_update_entity_type_async(request_type=dict) - - -def test_update_entity_type_field_headers(): - 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 = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - 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. - 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', - 'entity_type.name=name_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_update_entity_type_field_headers_async(): - 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 = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_entity_type), - '__call__') as call: - 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. - 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', - 'entity_type.name=name_value', - ) in kw['metadata'] - - -def test_update_entity_type_flattened(): - 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.update_entity_type), - '__call__') 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', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - arg = args[0].entity_type - mock_val = gcd_entity_type.EntityType(name='name_value') - assert arg == mock_val - arg = args[0].language_code - mock_val = 'language_code_value' - assert arg == mock_val - - -def test_update_entity_type_flattened_error(): - client = EntityTypesClient( - 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_entity_type( - gcd_entity_type.UpdateEntityTypeRequest(), - entity_type=gcd_entity_type.EntityType(name='name_value'), - language_code='language_code_value', - ) - -@pytest.mark.asyncio -async def test_update_entity_type_flattened_async(): - 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.update_entity_type), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcd_entity_type.EntityType() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcd_entity_type.EntityType()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.update_entity_type( - entity_type=gcd_entity_type.EntityType(name='name_value'), - language_code='language_code_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - arg = args[0].entity_type - mock_val = gcd_entity_type.EntityType(name='name_value') - assert arg == mock_val - arg = args[0].language_code - mock_val = 'language_code_value' - assert arg == mock_val - -@pytest.mark.asyncio -async def test_update_entity_type_flattened_error_async(): - client = EntityTypesAsyncClient( - 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_entity_type( - gcd_entity_type.UpdateEntityTypeRequest(), - entity_type=gcd_entity_type.EntityType(name='name_value'), - language_code='language_code_value', - ) - - -@pytest.mark.parametrize("request_type", [ - entity_type.DeleteEntityTypeRequest, - dict, -]) -def test_delete_entity_type(request_type, transport: str = 'grpc'): - client = EntityTypesClient( - 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_entity_type), - '__call__') 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. - assert response is None - - -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=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_entity_type), - '__call__') as call: - client.delete_entity_type() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == entity_type.DeleteEntityTypeRequest() - -@pytest.mark.asyncio -async def test_delete_entity_type_async(transport: str = 'grpc_asyncio', request_type=entity_type.DeleteEntityTypeRequest): - client = EntityTypesAsyncClient( - 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_entity_type), - '__call__') 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. - assert response is None - - -@pytest.mark.asyncio -async def test_delete_entity_type_async_from_dict(): - await test_delete_entity_type_async(request_type=dict) - - -def test_delete_entity_type_field_headers(): - 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. - with mock.patch.object( - 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. - 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_entity_type_field_headers_async(): - 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. - with mock.patch.object( - 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. - 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_entity_type_flattened(): - 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.delete_entity_type), - '__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_entity_type( - 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] - arg = args[0].name - mock_val = 'name_value' - assert arg == mock_val - - -def test_delete_entity_type_flattened_error(): - client = EntityTypesClient( - 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_entity_type( - entity_type.DeleteEntityTypeRequest(), - name='name_value', - ) - -@pytest.mark.asyncio -async def test_delete_entity_type_flattened_async(): - 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.delete_entity_type), - '__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_entity_type( - 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] - arg = args[0].name - mock_val = 'name_value' - assert arg == mock_val - -@pytest.mark.asyncio -async def test_delete_entity_type_flattened_error_async(): - client = EntityTypesAsyncClient( - 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_entity_type( - entity_type.DeleteEntityTypeRequest(), - name='name_value', - ) - - -@pytest.mark.parametrize("request_type", [ - entity_type.BatchUpdateEntityTypesRequest, - dict, -]) -def test_batch_update_entity_types(request_type, transport: str = 'grpc'): - client = EntityTypesClient( - 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.batch_update_entity_types), - '__call__') 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. - assert isinstance(response, future.Future) - - -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=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.batch_update_entity_types), - '__call__') as call: - client.batch_update_entity_types() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == entity_type.BatchUpdateEntityTypesRequest() - -@pytest.mark.asyncio -async def test_batch_update_entity_types_async(transport: str = 'grpc_asyncio', request_type=entity_type.BatchUpdateEntityTypesRequest): - client = EntityTypesAsyncClient( - 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.batch_update_entity_types), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name='operations/spam') - ) - response = await client.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. - assert isinstance(response, future.Future) - - -@pytest.mark.asyncio -async def test_batch_update_entity_types_async_from_dict(): - await test_batch_update_entity_types_async(request_type=dict) - - -def test_batch_update_entity_types_field_headers(): - 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. - with mock.patch.object( - 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. - 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_batch_update_entity_types_field_headers_async(): - 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. - with mock.patch.object( - type(client.transport.batch_update_entity_types), - '__call__') as call: - 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. - 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'] - - -@pytest.mark.parametrize("request_type", [ - entity_type.BatchDeleteEntityTypesRequest, - dict, -]) -def test_batch_delete_entity_types(request_type, transport: str = 'grpc'): - client = EntityTypesClient( - 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.batch_delete_entity_types), - '__call__') 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. - assert isinstance(response, future.Future) - - -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=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.batch_delete_entity_types), - '__call__') as call: - client.batch_delete_entity_types() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == entity_type.BatchDeleteEntityTypesRequest() - -@pytest.mark.asyncio -async def test_batch_delete_entity_types_async(transport: str = 'grpc_asyncio', request_type=entity_type.BatchDeleteEntityTypesRequest): - client = EntityTypesAsyncClient( - 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.batch_delete_entity_types), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name='operations/spam') - ) - response = await client.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. - assert isinstance(response, future.Future) - - -@pytest.mark.asyncio -async def test_batch_delete_entity_types_async_from_dict(): - await test_batch_delete_entity_types_async(request_type=dict) - - -def test_batch_delete_entity_types_field_headers(): - 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. - with mock.patch.object( - 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. - 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_batch_delete_entity_types_field_headers_async(): - 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. - with mock.patch.object( - type(client.transport.batch_delete_entity_types), - '__call__') as call: - 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. - 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_batch_delete_entity_types_flattened(): - 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.batch_delete_entity_types), - '__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.batch_delete_entity_types( - parent='parent_value', - entity_type_names=['entity_type_names_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] - arg = args[0].parent - mock_val = 'parent_value' - assert arg == mock_val - arg = args[0].entity_type_names - mock_val = ['entity_type_names_value'] - assert arg == mock_val - - -def test_batch_delete_entity_types_flattened_error(): - client = EntityTypesClient( - 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.batch_delete_entity_types( - entity_type.BatchDeleteEntityTypesRequest(), - parent='parent_value', - entity_type_names=['entity_type_names_value'], - ) - -@pytest.mark.asyncio -async def test_batch_delete_entity_types_flattened_async(): - 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.batch_delete_entity_types), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/op') - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name='operations/spam') - ) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.batch_delete_entity_types( - parent='parent_value', - entity_type_names=['entity_type_names_value'], - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - arg = args[0].parent - mock_val = 'parent_value' - assert arg == mock_val - arg = args[0].entity_type_names - mock_val = ['entity_type_names_value'] - assert arg == mock_val - -@pytest.mark.asyncio -async def test_batch_delete_entity_types_flattened_error_async(): - client = EntityTypesAsyncClient( - 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.batch_delete_entity_types( - entity_type.BatchDeleteEntityTypesRequest(), - parent='parent_value', - entity_type_names=['entity_type_names_value'], - ) - - -@pytest.mark.parametrize("request_type", [ - entity_type.BatchCreateEntitiesRequest, - dict, -]) -def test_batch_create_entities(request_type, transport: str = 'grpc'): - client = EntityTypesClient( - 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.batch_create_entities), - '__call__') 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. - assert isinstance(response, future.Future) - - -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=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.batch_create_entities), - '__call__') as call: - client.batch_create_entities() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == entity_type.BatchCreateEntitiesRequest() - -@pytest.mark.asyncio -async def test_batch_create_entities_async(transport: str = 'grpc_asyncio', request_type=entity_type.BatchCreateEntitiesRequest): - client = EntityTypesAsyncClient( - 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.batch_create_entities), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name='operations/spam') - ) - response = await client.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. - assert isinstance(response, future.Future) - - -@pytest.mark.asyncio -async def test_batch_create_entities_async_from_dict(): - await test_batch_create_entities_async(request_type=dict) - - -def test_batch_create_entities_field_headers(): - 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. - with mock.patch.object( - 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. - 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_batch_create_entities_field_headers_async(): - 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. - with mock.patch.object( - type(client.transport.batch_create_entities), - '__call__') as call: - 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. - 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_batch_create_entities_flattened(): - 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.batch_create_entities), - '__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.batch_create_entities( - parent='parent_value', - entities=[entity_type.EntityType.Entity(value='value_value')], - language_code='language_code_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] - arg = args[0].parent - mock_val = 'parent_value' - assert arg == mock_val - arg = args[0].entities - mock_val = [entity_type.EntityType.Entity(value='value_value')] - assert arg == mock_val - arg = args[0].language_code - mock_val = 'language_code_value' - assert arg == mock_val - - -def test_batch_create_entities_flattened_error(): - client = EntityTypesClient( - 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.batch_create_entities( - entity_type.BatchCreateEntitiesRequest(), - parent='parent_value', - entities=[entity_type.EntityType.Entity(value='value_value')], - language_code='language_code_value', - ) - -@pytest.mark.asyncio -async def test_batch_create_entities_flattened_async(): - 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.batch_create_entities), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/op') - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name='operations/spam') - ) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.batch_create_entities( - parent='parent_value', - entities=[entity_type.EntityType.Entity(value='value_value')], - language_code='language_code_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - arg = args[0].parent - mock_val = 'parent_value' - assert arg == mock_val - arg = args[0].entities - mock_val = [entity_type.EntityType.Entity(value='value_value')] - assert arg == mock_val - arg = args[0].language_code - mock_val = 'language_code_value' - assert arg == mock_val - -@pytest.mark.asyncio -async def test_batch_create_entities_flattened_error_async(): - client = EntityTypesAsyncClient( - 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.batch_create_entities( - entity_type.BatchCreateEntitiesRequest(), - parent='parent_value', - entities=[entity_type.EntityType.Entity(value='value_value')], - language_code='language_code_value', - ) - - -@pytest.mark.parametrize("request_type", [ - entity_type.BatchUpdateEntitiesRequest, - dict, -]) -def test_batch_update_entities(request_type, transport: str = 'grpc'): - client = EntityTypesClient( - 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.batch_update_entities), - '__call__') 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. - assert isinstance(response, future.Future) - - -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=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.batch_update_entities), - '__call__') as call: - client.batch_update_entities() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == entity_type.BatchUpdateEntitiesRequest() - -@pytest.mark.asyncio -async def test_batch_update_entities_async(transport: str = 'grpc_asyncio', request_type=entity_type.BatchUpdateEntitiesRequest): - client = EntityTypesAsyncClient( - 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.batch_update_entities), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name='operations/spam') - ) - response = await client.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. - assert isinstance(response, future.Future) - - -@pytest.mark.asyncio -async def test_batch_update_entities_async_from_dict(): - await test_batch_update_entities_async(request_type=dict) - - -def test_batch_update_entities_field_headers(): - 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. - with mock.patch.object( - 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. - 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_batch_update_entities_field_headers_async(): - 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. - with mock.patch.object( - type(client.transport.batch_update_entities), - '__call__') as call: - 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. - 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_batch_update_entities_flattened(): - 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.batch_update_entities), - '__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.batch_update_entities( - parent='parent_value', - entities=[entity_type.EntityType.Entity(value='value_value')], - language_code='language_code_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] - arg = args[0].parent - mock_val = 'parent_value' - assert arg == mock_val - arg = args[0].entities - mock_val = [entity_type.EntityType.Entity(value='value_value')] - assert arg == mock_val - arg = args[0].language_code - mock_val = 'language_code_value' - assert arg == mock_val - - -def test_batch_update_entities_flattened_error(): - client = EntityTypesClient( - 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.batch_update_entities( - entity_type.BatchUpdateEntitiesRequest(), - parent='parent_value', - entities=[entity_type.EntityType.Entity(value='value_value')], - language_code='language_code_value', - ) - -@pytest.mark.asyncio -async def test_batch_update_entities_flattened_async(): - 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.batch_update_entities), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/op') - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name='operations/spam') - ) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.batch_update_entities( - parent='parent_value', - entities=[entity_type.EntityType.Entity(value='value_value')], - language_code='language_code_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - arg = args[0].parent - mock_val = 'parent_value' - assert arg == mock_val - arg = args[0].entities - mock_val = [entity_type.EntityType.Entity(value='value_value')] - assert arg == mock_val - arg = args[0].language_code - mock_val = 'language_code_value' - assert arg == mock_val - -@pytest.mark.asyncio -async def test_batch_update_entities_flattened_error_async(): - client = EntityTypesAsyncClient( - 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.batch_update_entities( - entity_type.BatchUpdateEntitiesRequest(), - parent='parent_value', - entities=[entity_type.EntityType.Entity(value='value_value')], - language_code='language_code_value', - ) - - -@pytest.mark.parametrize("request_type", [ - entity_type.BatchDeleteEntitiesRequest, - dict, -]) -def test_batch_delete_entities(request_type, transport: str = 'grpc'): - client = EntityTypesClient( - 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.batch_delete_entities), - '__call__') 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. - assert isinstance(response, future.Future) - - -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=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.batch_delete_entities), - '__call__') as call: - client.batch_delete_entities() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == entity_type.BatchDeleteEntitiesRequest() - -@pytest.mark.asyncio -async def test_batch_delete_entities_async(transport: str = 'grpc_asyncio', request_type=entity_type.BatchDeleteEntitiesRequest): - client = EntityTypesAsyncClient( - 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.batch_delete_entities), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name='operations/spam') - ) - response = await client.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. - assert isinstance(response, future.Future) - - -@pytest.mark.asyncio -async def test_batch_delete_entities_async_from_dict(): - await test_batch_delete_entities_async(request_type=dict) - - -def test_batch_delete_entities_field_headers(): - 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. - with mock.patch.object( - 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. - 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_batch_delete_entities_field_headers_async(): - 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. - with mock.patch.object( - type(client.transport.batch_delete_entities), - '__call__') as call: - 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. - 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_batch_delete_entities_flattened(): - 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.batch_delete_entities), - '__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.batch_delete_entities( - parent='parent_value', - entity_values=['entity_values_value'], - language_code='language_code_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] - arg = args[0].parent - mock_val = 'parent_value' - assert arg == mock_val - arg = args[0].entity_values - mock_val = ['entity_values_value'] - assert arg == mock_val - arg = args[0].language_code - mock_val = 'language_code_value' - assert arg == mock_val - - -def test_batch_delete_entities_flattened_error(): - client = EntityTypesClient( - 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.batch_delete_entities( - entity_type.BatchDeleteEntitiesRequest(), - parent='parent_value', - entity_values=['entity_values_value'], - language_code='language_code_value', - ) - -@pytest.mark.asyncio -async def test_batch_delete_entities_flattened_async(): - 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.batch_delete_entities), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/op') - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name='operations/spam') - ) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.batch_delete_entities( - parent='parent_value', - entity_values=['entity_values_value'], - language_code='language_code_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - arg = args[0].parent - mock_val = 'parent_value' - assert arg == mock_val - arg = args[0].entity_values - mock_val = ['entity_values_value'] - assert arg == mock_val - arg = args[0].language_code - mock_val = 'language_code_value' - assert arg == mock_val - -@pytest.mark.asyncio -async def test_batch_delete_entities_flattened_error_async(): - client = EntityTypesAsyncClient( - 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.batch_delete_entities( - entity_type.BatchDeleteEntitiesRequest(), - parent='parent_value', - entity_values=['entity_values_value'], - language_code='language_code_value', - ) - - -@pytest.mark.parametrize("request_type", [ - entity_type.ListEntityTypesRequest, - dict, -]) -def test_list_entity_types_rest(request_type): - client = EntityTypesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1/agent'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = entity_type.ListEntityTypesResponse( - next_page_token='next_page_token_value', - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - pb_return_value = entity_type.ListEntityTypesResponse.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.list_entity_types(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListEntityTypesPager) - assert response.next_page_token == 'next_page_token_value' - - -def test_list_entity_types_rest_required_fields(request_type=entity_type.ListEntityTypesRequest): - transport_class = transports.EntityTypesRestTransport - - request_init = {} - request_init["parent"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - including_default_value_fields=False, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).list_entity_types._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["parent"] = 'parent_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).list_entity_types._get_unset_required_fields(jsonified_request) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("language_code", "page_size", "page_token", )) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "parent" in jsonified_request - assert jsonified_request["parent"] == 'parent_value' - - client = EntityTypesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = entity_type.ListEntityTypesResponse() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "get", - 'query_params': pb_request, - } - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - - pb_return_value = entity_type.ListEntityTypesResponse.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.list_entity_types(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_list_entity_types_rest_unset_required_fields(): - transport = transports.EntityTypesRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.list_entity_types._get_unset_required_fields({}) - assert set(unset_fields) == (set(("languageCode", "pageSize", "pageToken", )) & set(("parent", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_list_entity_types_rest_interceptors(null_interceptor): - transport = transports.EntityTypesRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.EntityTypesRestInterceptor(), - ) - client = EntityTypesClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.EntityTypesRestInterceptor, "post_list_entity_types") as post, \ - mock.patch.object(transports.EntityTypesRestInterceptor, "pre_list_entity_types") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = entity_type.ListEntityTypesRequest.pb(entity_type.ListEntityTypesRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = entity_type.ListEntityTypesResponse.to_json(entity_type.ListEntityTypesResponse()) - - request = entity_type.ListEntityTypesRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = entity_type.ListEntityTypesResponse() - - client.list_entity_types(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_list_entity_types_rest_bad_request(transport: str = 'rest', request_type=entity_type.ListEntityTypesRequest): - client = EntityTypesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1/agent'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.list_entity_types(request) - - -def test_list_entity_types_rest_flattened(): - client = EntityTypesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = entity_type.ListEntityTypesResponse() - - # get arguments that satisfy an http rule for this method - sample_request = {'parent': 'projects/sample1/agent'} - - # get truthy value for each flattened field - mock_args = dict( - parent='parent_value', - language_code='language_code_value', - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - pb_return_value = entity_type.ListEntityTypesResponse.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.list_entity_types(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v2/{parent=projects/*/agent}/entityTypes" % client.transport._host, args[1]) - - -def test_list_entity_types_rest_flattened_error(transport: str = 'rest'): - client = EntityTypesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.list_entity_types( - entity_type.ListEntityTypesRequest(), - parent='parent_value', - language_code='language_code_value', - ) - - -def test_list_entity_types_rest_pager(transport: str = 'rest'): - client = EntityTypesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # TODO(kbandes): remove this mock unless there's a good reason for it. - #with mock.patch.object(path_template, 'transcode') as transcode: - # Set the response as a series of pages - response = ( - entity_type.ListEntityTypesResponse( - entity_types=[ - entity_type.EntityType(), - entity_type.EntityType(), - entity_type.EntityType(), - ], - next_page_token='abc', - ), - entity_type.ListEntityTypesResponse( - entity_types=[], - next_page_token='def', - ), - entity_type.ListEntityTypesResponse( - entity_types=[ - entity_type.EntityType(), - ], - next_page_token='ghi', - ), - entity_type.ListEntityTypesResponse( - entity_types=[ - entity_type.EntityType(), - entity_type.EntityType(), - ], - ), - ) - # Two responses for two calls - response = response + response - - # Wrap the values into proper Response objs - response = tuple(entity_type.ListEntityTypesResponse.to_json(x) for x in response) - return_values = tuple(Response() for i in response) - for return_val, response_val in zip(return_values, response): - return_val._content = response_val.encode('UTF-8') - return_val.status_code = 200 - req.side_effect = return_values - - sample_request = {'parent': 'projects/sample1/agent'} - - pager = client.list_entity_types(request=sample_request) - - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, entity_type.EntityType) - for i in results) - - pages = list(client.list_entity_types(request=sample_request).pages) - for page_, token in zip(pages, ['abc','def','ghi', '']): - assert page_.raw_page.next_page_token == token - - -@pytest.mark.parametrize("request_type", [ - entity_type.GetEntityTypeRequest, - dict, -]) -def test_get_entity_type_rest(request_type): - client = EntityTypesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/agent/entityTypes/sample2'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = entity_type.EntityType( - name='name_value', - display_name='display_name_value', - kind=entity_type.EntityType.Kind.KIND_MAP, - auto_expansion_mode=entity_type.EntityType.AutoExpansionMode.AUTO_EXPANSION_MODE_DEFAULT, - enable_fuzzy_extraction=True, - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - pb_return_value = entity_type.EntityType.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.get_entity_type(request) - - # 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 - - -def test_get_entity_type_rest_required_fields(request_type=entity_type.GetEntityTypeRequest): - transport_class = transports.EntityTypesRestTransport - - request_init = {} - request_init["name"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - including_default_value_fields=False, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_entity_type._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["name"] = 'name_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_entity_type._get_unset_required_fields(jsonified_request) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("language_code", )) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "name" in jsonified_request - assert jsonified_request["name"] == 'name_value' - - client = EntityTypesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = entity_type.EntityType() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "get", - 'query_params': pb_request, - } - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - - pb_return_value = entity_type.EntityType.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.get_entity_type(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_get_entity_type_rest_unset_required_fields(): - transport = transports.EntityTypesRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.get_entity_type._get_unset_required_fields({}) - assert set(unset_fields) == (set(("languageCode", )) & set(("name", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_get_entity_type_rest_interceptors(null_interceptor): - transport = transports.EntityTypesRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.EntityTypesRestInterceptor(), - ) - client = EntityTypesClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.EntityTypesRestInterceptor, "post_get_entity_type") as post, \ - mock.patch.object(transports.EntityTypesRestInterceptor, "pre_get_entity_type") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = entity_type.GetEntityTypeRequest.pb(entity_type.GetEntityTypeRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = entity_type.EntityType.to_json(entity_type.EntityType()) - - request = entity_type.GetEntityTypeRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = entity_type.EntityType() - - client.get_entity_type(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_get_entity_type_rest_bad_request(transport: str = 'rest', request_type=entity_type.GetEntityTypeRequest): - client = EntityTypesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/agent/entityTypes/sample2'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.get_entity_type(request) - - -def test_get_entity_type_rest_flattened(): - client = EntityTypesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = entity_type.EntityType() - - # get arguments that satisfy an http rule for this method - sample_request = {'name': 'projects/sample1/agent/entityTypes/sample2'} - - # get truthy value for each flattened field - mock_args = dict( - name='name_value', - language_code='language_code_value', - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - pb_return_value = entity_type.EntityType.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.get_entity_type(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v2/{name=projects/*/agent/entityTypes/*}" % client.transport._host, args[1]) - - -def test_get_entity_type_rest_flattened_error(transport: str = 'rest'): - client = EntityTypesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.get_entity_type( - entity_type.GetEntityTypeRequest(), - name='name_value', - language_code='language_code_value', - ) - - -def test_get_entity_type_rest_error(): - client = EntityTypesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - gcd_entity_type.CreateEntityTypeRequest, - dict, -]) -def test_create_entity_type_rest(request_type): - client = EntityTypesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1/agent'} - request_init["entity_type"] = {'name': 'name_value', 'display_name': 'display_name_value', 'kind': 1, 'auto_expansion_mode': 1, 'entities': [{'value': 'value_value', 'synonyms': ['synonyms_value1', 'synonyms_value2']}], 'enable_fuzzy_extraction': True} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = gcd_entity_type.EntityType( - name='name_value', - display_name='display_name_value', - kind=gcd_entity_type.EntityType.Kind.KIND_MAP, - auto_expansion_mode=gcd_entity_type.EntityType.AutoExpansionMode.AUTO_EXPANSION_MODE_DEFAULT, - enable_fuzzy_extraction=True, - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - pb_return_value = gcd_entity_type.EntityType.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.create_entity_type(request) - - # 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 - - -def test_create_entity_type_rest_required_fields(request_type=gcd_entity_type.CreateEntityTypeRequest): - transport_class = transports.EntityTypesRestTransport - - request_init = {} - request_init["parent"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - including_default_value_fields=False, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_entity_type._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["parent"] = 'parent_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_entity_type._get_unset_required_fields(jsonified_request) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("language_code", )) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "parent" in jsonified_request - assert jsonified_request["parent"] == 'parent_value' - - client = EntityTypesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = gcd_entity_type.EntityType() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "post", - 'query_params': pb_request, - } - transcode_result['body'] = pb_request - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - - pb_return_value = gcd_entity_type.EntityType.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.create_entity_type(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_create_entity_type_rest_unset_required_fields(): - transport = transports.EntityTypesRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.create_entity_type._get_unset_required_fields({}) - assert set(unset_fields) == (set(("languageCode", )) & set(("parent", "entityType", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_create_entity_type_rest_interceptors(null_interceptor): - transport = transports.EntityTypesRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.EntityTypesRestInterceptor(), - ) - client = EntityTypesClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.EntityTypesRestInterceptor, "post_create_entity_type") as post, \ - mock.patch.object(transports.EntityTypesRestInterceptor, "pre_create_entity_type") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = gcd_entity_type.CreateEntityTypeRequest.pb(gcd_entity_type.CreateEntityTypeRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = gcd_entity_type.EntityType.to_json(gcd_entity_type.EntityType()) - - request = gcd_entity_type.CreateEntityTypeRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = gcd_entity_type.EntityType() - - client.create_entity_type(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_create_entity_type_rest_bad_request(transport: str = 'rest', request_type=gcd_entity_type.CreateEntityTypeRequest): - client = EntityTypesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1/agent'} - request_init["entity_type"] = {'name': 'name_value', 'display_name': 'display_name_value', 'kind': 1, 'auto_expansion_mode': 1, 'entities': [{'value': 'value_value', 'synonyms': ['synonyms_value1', 'synonyms_value2']}], 'enable_fuzzy_extraction': True} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.create_entity_type(request) - - -def test_create_entity_type_rest_flattened(): - client = EntityTypesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = gcd_entity_type.EntityType() - - # get arguments that satisfy an http rule for this method - sample_request = {'parent': 'projects/sample1/agent'} - - # get truthy value for each flattened field - mock_args = dict( - parent='parent_value', - entity_type=gcd_entity_type.EntityType(name='name_value'), - language_code='language_code_value', - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - pb_return_value = gcd_entity_type.EntityType.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.create_entity_type(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v2/{parent=projects/*/agent}/entityTypes" % client.transport._host, args[1]) - - -def test_create_entity_type_rest_flattened_error(transport: str = 'rest'): - client = EntityTypesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.create_entity_type( - gcd_entity_type.CreateEntityTypeRequest(), - parent='parent_value', - entity_type=gcd_entity_type.EntityType(name='name_value'), - language_code='language_code_value', - ) - - -def test_create_entity_type_rest_error(): - client = EntityTypesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - gcd_entity_type.UpdateEntityTypeRequest, - dict, -]) -def test_update_entity_type_rest(request_type): - client = EntityTypesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'entity_type': {'name': 'projects/sample1/agent/entityTypes/sample2'}} - request_init["entity_type"] = {'name': 'projects/sample1/agent/entityTypes/sample2', 'display_name': 'display_name_value', 'kind': 1, 'auto_expansion_mode': 1, 'entities': [{'value': 'value_value', 'synonyms': ['synonyms_value1', 'synonyms_value2']}], 'enable_fuzzy_extraction': True} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = gcd_entity_type.EntityType( - name='name_value', - display_name='display_name_value', - kind=gcd_entity_type.EntityType.Kind.KIND_MAP, - auto_expansion_mode=gcd_entity_type.EntityType.AutoExpansionMode.AUTO_EXPANSION_MODE_DEFAULT, - enable_fuzzy_extraction=True, - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - pb_return_value = gcd_entity_type.EntityType.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.update_entity_type(request) - - # 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 - - -def test_update_entity_type_rest_required_fields(request_type=gcd_entity_type.UpdateEntityTypeRequest): - transport_class = transports.EntityTypesRestTransport - - request_init = {} - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - including_default_value_fields=False, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).update_entity_type._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).update_entity_type._get_unset_required_fields(jsonified_request) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("language_code", "update_mask", )) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - - client = EntityTypesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = gcd_entity_type.EntityType() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "patch", - 'query_params': pb_request, - } - transcode_result['body'] = pb_request - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - - pb_return_value = gcd_entity_type.EntityType.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.update_entity_type(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_update_entity_type_rest_unset_required_fields(): - transport = transports.EntityTypesRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.update_entity_type._get_unset_required_fields({}) - assert set(unset_fields) == (set(("languageCode", "updateMask", )) & set(("entityType", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_update_entity_type_rest_interceptors(null_interceptor): - transport = transports.EntityTypesRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.EntityTypesRestInterceptor(), - ) - client = EntityTypesClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.EntityTypesRestInterceptor, "post_update_entity_type") as post, \ - mock.patch.object(transports.EntityTypesRestInterceptor, "pre_update_entity_type") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = gcd_entity_type.UpdateEntityTypeRequest.pb(gcd_entity_type.UpdateEntityTypeRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = gcd_entity_type.EntityType.to_json(gcd_entity_type.EntityType()) - - request = gcd_entity_type.UpdateEntityTypeRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = gcd_entity_type.EntityType() - - client.update_entity_type(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_update_entity_type_rest_bad_request(transport: str = 'rest', request_type=gcd_entity_type.UpdateEntityTypeRequest): - client = EntityTypesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'entity_type': {'name': 'projects/sample1/agent/entityTypes/sample2'}} - request_init["entity_type"] = {'name': 'projects/sample1/agent/entityTypes/sample2', 'display_name': 'display_name_value', 'kind': 1, 'auto_expansion_mode': 1, 'entities': [{'value': 'value_value', 'synonyms': ['synonyms_value1', 'synonyms_value2']}], 'enable_fuzzy_extraction': True} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.update_entity_type(request) - - -def test_update_entity_type_rest_flattened(): - client = EntityTypesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = gcd_entity_type.EntityType() - - # get arguments that satisfy an http rule for this method - sample_request = {'entity_type': {'name': 'projects/sample1/agent/entityTypes/sample2'}} - - # get truthy value for each flattened field - mock_args = dict( - entity_type=gcd_entity_type.EntityType(name='name_value'), - language_code='language_code_value', - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - pb_return_value = gcd_entity_type.EntityType.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.update_entity_type(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v2/{entity_type.name=projects/*/agent/entityTypes/*}" % client.transport._host, args[1]) - - -def test_update_entity_type_rest_flattened_error(transport: str = 'rest'): - client = EntityTypesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.update_entity_type( - gcd_entity_type.UpdateEntityTypeRequest(), - entity_type=gcd_entity_type.EntityType(name='name_value'), - language_code='language_code_value', - ) - - -def test_update_entity_type_rest_error(): - client = EntityTypesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - entity_type.DeleteEntityTypeRequest, - dict, -]) -def test_delete_entity_type_rest(request_type): - client = EntityTypesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/agent/entityTypes/sample2'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = None - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = '' - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.delete_entity_type(request) - - # Establish that the response is the type that we expect. - assert response is None - - -def test_delete_entity_type_rest_required_fields(request_type=entity_type.DeleteEntityTypeRequest): - transport_class = transports.EntityTypesRestTransport - - request_init = {} - request_init["name"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - including_default_value_fields=False, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).delete_entity_type._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["name"] = 'name_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).delete_entity_type._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "name" in jsonified_request - assert jsonified_request["name"] == 'name_value' - - client = EntityTypesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = None - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "delete", - 'query_params': pb_request, - } - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - json_return_value = '' - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.delete_entity_type(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_delete_entity_type_rest_unset_required_fields(): - transport = transports.EntityTypesRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.delete_entity_type._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_delete_entity_type_rest_interceptors(null_interceptor): - transport = transports.EntityTypesRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.EntityTypesRestInterceptor(), - ) - client = EntityTypesClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.EntityTypesRestInterceptor, "pre_delete_entity_type") as pre: - pre.assert_not_called() - pb_message = entity_type.DeleteEntityTypeRequest.pb(entity_type.DeleteEntityTypeRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - - request = entity_type.DeleteEntityTypeRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - - client.delete_entity_type(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - - -def test_delete_entity_type_rest_bad_request(transport: str = 'rest', request_type=entity_type.DeleteEntityTypeRequest): - client = EntityTypesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/agent/entityTypes/sample2'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.delete_entity_type(request) - - -def test_delete_entity_type_rest_flattened(): - client = EntityTypesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = None - - # get arguments that satisfy an http rule for this method - sample_request = {'name': 'projects/sample1/agent/entityTypes/sample2'} - - # get truthy value for each flattened field - mock_args = dict( - name='name_value', - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = '' - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.delete_entity_type(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v2/{name=projects/*/agent/entityTypes/*}" % client.transport._host, args[1]) - - -def test_delete_entity_type_rest_flattened_error(transport: str = 'rest'): - client = EntityTypesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.delete_entity_type( - entity_type.DeleteEntityTypeRequest(), - name='name_value', - ) - - -def test_delete_entity_type_rest_error(): - client = EntityTypesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - entity_type.BatchUpdateEntityTypesRequest, - dict, -]) -def test_batch_update_entity_types_rest(request_type): - client = EntityTypesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1/agent'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name='operations/spam') - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.batch_update_entity_types(request) - - # Establish that the response is the type that we expect. - assert response.operation.name == "operations/spam" - - -def test_batch_update_entity_types_rest_required_fields(request_type=entity_type.BatchUpdateEntityTypesRequest): - transport_class = transports.EntityTypesRestTransport - - request_init = {} - request_init["parent"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - including_default_value_fields=False, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).batch_update_entity_types._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["parent"] = 'parent_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).batch_update_entity_types._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "parent" in jsonified_request - assert jsonified_request["parent"] == 'parent_value' - - client = EntityTypesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name='operations/spam') - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "post", - 'query_params': pb_request, - } - transcode_result['body'] = pb_request - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.batch_update_entity_types(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_batch_update_entity_types_rest_unset_required_fields(): - transport = transports.EntityTypesRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.batch_update_entity_types._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("parent", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_batch_update_entity_types_rest_interceptors(null_interceptor): - transport = transports.EntityTypesRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.EntityTypesRestInterceptor(), - ) - client = EntityTypesClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(operation.Operation, "_set_result_from_operation"), \ - mock.patch.object(transports.EntityTypesRestInterceptor, "post_batch_update_entity_types") as post, \ - mock.patch.object(transports.EntityTypesRestInterceptor, "pre_batch_update_entity_types") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = entity_type.BatchUpdateEntityTypesRequest.pb(entity_type.BatchUpdateEntityTypesRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = json_format.MessageToJson(operations_pb2.Operation()) - - request = entity_type.BatchUpdateEntityTypesRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = operations_pb2.Operation() - - client.batch_update_entity_types(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_batch_update_entity_types_rest_bad_request(transport: str = 'rest', request_type=entity_type.BatchUpdateEntityTypesRequest): - client = EntityTypesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1/agent'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.batch_update_entity_types(request) - - -def test_batch_update_entity_types_rest_error(): - client = EntityTypesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - entity_type.BatchDeleteEntityTypesRequest, - dict, -]) -def test_batch_delete_entity_types_rest(request_type): - client = EntityTypesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1/agent'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name='operations/spam') - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.batch_delete_entity_types(request) - - # Establish that the response is the type that we expect. - assert response.operation.name == "operations/spam" - - -def test_batch_delete_entity_types_rest_required_fields(request_type=entity_type.BatchDeleteEntityTypesRequest): - transport_class = transports.EntityTypesRestTransport - - request_init = {} - request_init["parent"] = "" - request_init["entity_type_names"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - including_default_value_fields=False, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).batch_delete_entity_types._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["parent"] = 'parent_value' - jsonified_request["entityTypeNames"] = 'entity_type_names_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).batch_delete_entity_types._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "parent" in jsonified_request - assert jsonified_request["parent"] == 'parent_value' - assert "entityTypeNames" in jsonified_request - assert jsonified_request["entityTypeNames"] == 'entity_type_names_value' - - client = EntityTypesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name='operations/spam') - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "post", - 'query_params': pb_request, - } - transcode_result['body'] = pb_request - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.batch_delete_entity_types(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_batch_delete_entity_types_rest_unset_required_fields(): - transport = transports.EntityTypesRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.batch_delete_entity_types._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("parent", "entityTypeNames", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_batch_delete_entity_types_rest_interceptors(null_interceptor): - transport = transports.EntityTypesRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.EntityTypesRestInterceptor(), - ) - client = EntityTypesClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(operation.Operation, "_set_result_from_operation"), \ - mock.patch.object(transports.EntityTypesRestInterceptor, "post_batch_delete_entity_types") as post, \ - mock.patch.object(transports.EntityTypesRestInterceptor, "pre_batch_delete_entity_types") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = entity_type.BatchDeleteEntityTypesRequest.pb(entity_type.BatchDeleteEntityTypesRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = json_format.MessageToJson(operations_pb2.Operation()) - - request = entity_type.BatchDeleteEntityTypesRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = operations_pb2.Operation() - - client.batch_delete_entity_types(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_batch_delete_entity_types_rest_bad_request(transport: str = 'rest', request_type=entity_type.BatchDeleteEntityTypesRequest): - client = EntityTypesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1/agent'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.batch_delete_entity_types(request) - - -def test_batch_delete_entity_types_rest_flattened(): - client = EntityTypesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name='operations/spam') - - # get arguments that satisfy an http rule for this method - sample_request = {'parent': 'projects/sample1/agent'} - - # get truthy value for each flattened field - mock_args = dict( - parent='parent_value', - entity_type_names=['entity_type_names_value'], - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.batch_delete_entity_types(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v2/{parent=projects/*/agent}/entityTypes:batchDelete" % client.transport._host, args[1]) - - -def test_batch_delete_entity_types_rest_flattened_error(transport: str = 'rest'): - client = EntityTypesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.batch_delete_entity_types( - entity_type.BatchDeleteEntityTypesRequest(), - parent='parent_value', - entity_type_names=['entity_type_names_value'], - ) - - -def test_batch_delete_entity_types_rest_error(): - client = EntityTypesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - entity_type.BatchCreateEntitiesRequest, - dict, -]) -def test_batch_create_entities_rest(request_type): - client = EntityTypesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1/agent/entityTypes/sample2'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name='operations/spam') - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.batch_create_entities(request) - - # Establish that the response is the type that we expect. - assert response.operation.name == "operations/spam" - - -def test_batch_create_entities_rest_required_fields(request_type=entity_type.BatchCreateEntitiesRequest): - transport_class = transports.EntityTypesRestTransport - - request_init = {} - request_init["parent"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - including_default_value_fields=False, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).batch_create_entities._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["parent"] = 'parent_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).batch_create_entities._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "parent" in jsonified_request - assert jsonified_request["parent"] == 'parent_value' - - client = EntityTypesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name='operations/spam') - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "post", - 'query_params': pb_request, - } - transcode_result['body'] = pb_request - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.batch_create_entities(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_batch_create_entities_rest_unset_required_fields(): - transport = transports.EntityTypesRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.batch_create_entities._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("parent", "entities", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_batch_create_entities_rest_interceptors(null_interceptor): - transport = transports.EntityTypesRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.EntityTypesRestInterceptor(), - ) - client = EntityTypesClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(operation.Operation, "_set_result_from_operation"), \ - mock.patch.object(transports.EntityTypesRestInterceptor, "post_batch_create_entities") as post, \ - mock.patch.object(transports.EntityTypesRestInterceptor, "pre_batch_create_entities") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = entity_type.BatchCreateEntitiesRequest.pb(entity_type.BatchCreateEntitiesRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = json_format.MessageToJson(operations_pb2.Operation()) - - request = entity_type.BatchCreateEntitiesRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = operations_pb2.Operation() - - client.batch_create_entities(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_batch_create_entities_rest_bad_request(transport: str = 'rest', request_type=entity_type.BatchCreateEntitiesRequest): - client = EntityTypesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1/agent/entityTypes/sample2'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.batch_create_entities(request) - - -def test_batch_create_entities_rest_flattened(): - client = EntityTypesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name='operations/spam') - - # get arguments that satisfy an http rule for this method - sample_request = {'parent': 'projects/sample1/agent/entityTypes/sample2'} - - # get truthy value for each flattened field - mock_args = dict( - parent='parent_value', - entities=[entity_type.EntityType.Entity(value='value_value')], - language_code='language_code_value', - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.batch_create_entities(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v2/{parent=projects/*/agent/entityTypes/*}/entities:batchCreate" % client.transport._host, args[1]) - - -def test_batch_create_entities_rest_flattened_error(transport: str = 'rest'): - client = EntityTypesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.batch_create_entities( - entity_type.BatchCreateEntitiesRequest(), - parent='parent_value', - entities=[entity_type.EntityType.Entity(value='value_value')], - language_code='language_code_value', - ) - - -def test_batch_create_entities_rest_error(): - client = EntityTypesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - entity_type.BatchUpdateEntitiesRequest, - dict, -]) -def test_batch_update_entities_rest(request_type): - client = EntityTypesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1/agent/entityTypes/sample2'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name='operations/spam') - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.batch_update_entities(request) - - # Establish that the response is the type that we expect. - assert response.operation.name == "operations/spam" - - -def test_batch_update_entities_rest_required_fields(request_type=entity_type.BatchUpdateEntitiesRequest): - transport_class = transports.EntityTypesRestTransport - - request_init = {} - request_init["parent"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - including_default_value_fields=False, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).batch_update_entities._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["parent"] = 'parent_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).batch_update_entities._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "parent" in jsonified_request - assert jsonified_request["parent"] == 'parent_value' - - client = EntityTypesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name='operations/spam') - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "post", - 'query_params': pb_request, - } - transcode_result['body'] = pb_request - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.batch_update_entities(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_batch_update_entities_rest_unset_required_fields(): - transport = transports.EntityTypesRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.batch_update_entities._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("parent", "entities", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_batch_update_entities_rest_interceptors(null_interceptor): - transport = transports.EntityTypesRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.EntityTypesRestInterceptor(), - ) - client = EntityTypesClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(operation.Operation, "_set_result_from_operation"), \ - mock.patch.object(transports.EntityTypesRestInterceptor, "post_batch_update_entities") as post, \ - mock.patch.object(transports.EntityTypesRestInterceptor, "pre_batch_update_entities") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = entity_type.BatchUpdateEntitiesRequest.pb(entity_type.BatchUpdateEntitiesRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = json_format.MessageToJson(operations_pb2.Operation()) - - request = entity_type.BatchUpdateEntitiesRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = operations_pb2.Operation() - - client.batch_update_entities(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_batch_update_entities_rest_bad_request(transport: str = 'rest', request_type=entity_type.BatchUpdateEntitiesRequest): - client = EntityTypesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1/agent/entityTypes/sample2'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.batch_update_entities(request) - - -def test_batch_update_entities_rest_flattened(): - client = EntityTypesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name='operations/spam') - - # get arguments that satisfy an http rule for this method - sample_request = {'parent': 'projects/sample1/agent/entityTypes/sample2'} - - # get truthy value for each flattened field - mock_args = dict( - parent='parent_value', - entities=[entity_type.EntityType.Entity(value='value_value')], - language_code='language_code_value', - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.batch_update_entities(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v2/{parent=projects/*/agent/entityTypes/*}/entities:batchUpdate" % client.transport._host, args[1]) - - -def test_batch_update_entities_rest_flattened_error(transport: str = 'rest'): - client = EntityTypesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.batch_update_entities( - entity_type.BatchUpdateEntitiesRequest(), - parent='parent_value', - entities=[entity_type.EntityType.Entity(value='value_value')], - language_code='language_code_value', - ) - - -def test_batch_update_entities_rest_error(): - client = EntityTypesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - entity_type.BatchDeleteEntitiesRequest, - dict, -]) -def test_batch_delete_entities_rest(request_type): - client = EntityTypesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1/agent/entityTypes/sample2'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name='operations/spam') - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.batch_delete_entities(request) - - # Establish that the response is the type that we expect. - assert response.operation.name == "operations/spam" - - -def test_batch_delete_entities_rest_required_fields(request_type=entity_type.BatchDeleteEntitiesRequest): - transport_class = transports.EntityTypesRestTransport - - request_init = {} - request_init["parent"] = "" - request_init["entity_values"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - including_default_value_fields=False, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).batch_delete_entities._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["parent"] = 'parent_value' - jsonified_request["entityValues"] = 'entity_values_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).batch_delete_entities._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "parent" in jsonified_request - assert jsonified_request["parent"] == 'parent_value' - assert "entityValues" in jsonified_request - assert jsonified_request["entityValues"] == 'entity_values_value' - - client = EntityTypesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name='operations/spam') - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "post", - 'query_params': pb_request, - } - transcode_result['body'] = pb_request - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.batch_delete_entities(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_batch_delete_entities_rest_unset_required_fields(): - transport = transports.EntityTypesRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.batch_delete_entities._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("parent", "entityValues", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_batch_delete_entities_rest_interceptors(null_interceptor): - transport = transports.EntityTypesRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.EntityTypesRestInterceptor(), - ) - client = EntityTypesClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(operation.Operation, "_set_result_from_operation"), \ - mock.patch.object(transports.EntityTypesRestInterceptor, "post_batch_delete_entities") as post, \ - mock.patch.object(transports.EntityTypesRestInterceptor, "pre_batch_delete_entities") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = entity_type.BatchDeleteEntitiesRequest.pb(entity_type.BatchDeleteEntitiesRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = json_format.MessageToJson(operations_pb2.Operation()) - - request = entity_type.BatchDeleteEntitiesRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = operations_pb2.Operation() - - client.batch_delete_entities(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_batch_delete_entities_rest_bad_request(transport: str = 'rest', request_type=entity_type.BatchDeleteEntitiesRequest): - client = EntityTypesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1/agent/entityTypes/sample2'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.batch_delete_entities(request) - - -def test_batch_delete_entities_rest_flattened(): - client = EntityTypesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name='operations/spam') - - # get arguments that satisfy an http rule for this method - sample_request = {'parent': 'projects/sample1/agent/entityTypes/sample2'} - - # get truthy value for each flattened field - mock_args = dict( - parent='parent_value', - entity_values=['entity_values_value'], - language_code='language_code_value', - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.batch_delete_entities(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v2/{parent=projects/*/agent/entityTypes/*}/entities:batchDelete" % client.transport._host, args[1]) - - -def test_batch_delete_entities_rest_flattened_error(transport: str = 'rest'): - client = EntityTypesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.batch_delete_entities( - entity_type.BatchDeleteEntitiesRequest(), - parent='parent_value', - entity_values=['entity_values_value'], - language_code='language_code_value', - ) - - -def test_batch_delete_entities_rest_error(): - client = EntityTypesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -def test_credentials_transport_error(): - # It is an error to provide credentials and a transport instance. - transport = transports.EntityTypesGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = EntityTypesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # It is an error to provide a credentials file and a transport instance. - transport = transports.EntityTypesGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = EntityTypesClient( - client_options={"credentials_file": "credentials.json"}, - transport=transport, - ) - - # It is an error to provide an api_key and a transport instance. - transport = transports.EntityTypesGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - options = client_options.ClientOptions() - options.api_key = "api_key" - with pytest.raises(ValueError): - client = EntityTypesClient( - client_options=options, - transport=transport, - ) - - # It is an error to provide an api_key and a credential. - options = mock.Mock() - options.api_key = "api_key" - with pytest.raises(ValueError): - client = EntityTypesClient( - client_options=options, - credentials=ga_credentials.AnonymousCredentials() - ) - - # It is an error to provide scopes and a transport instance. - transport = transports.EntityTypesGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = EntityTypesClient( - client_options={"scopes": ["1", "2"]}, - transport=transport, - ) - - -def test_transport_instance(): - # A client may be instantiated with a custom transport instance. - transport = transports.EntityTypesGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - client = EntityTypesClient(transport=transport) - assert client.transport is transport - -def test_transport_get_channel(): - # A client may be instantiated with a custom transport instance. - transport = transports.EntityTypesGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - - transport = transports.EntityTypesGrpcAsyncIOTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - -@pytest.mark.parametrize("transport_class", [ - transports.EntityTypesGrpcTransport, - transports.EntityTypesGrpcAsyncIOTransport, - transports.EntityTypesRestTransport, -]) -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() - -@pytest.mark.parametrize("transport_name", [ - "grpc", - "rest", -]) -def test_transport_kind(transport_name): - transport = EntityTypesClient.get_transport_class(transport_name)( - credentials=ga_credentials.AnonymousCredentials(), - ) - assert transport.kind == transport_name - -def test_transport_grpc_default(): - # A client should use the gRPC transport by default. - 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(core_exceptions.DuplicateCredentialArgs): - transport = transports.EntityTypesTransport( - credentials=ga_credentials.AnonymousCredentials(), - credentials_file="credentials.json" - ) - - -def test_entity_types_base_transport(): - # Instantiate the base transport. - with mock.patch('google.cloud.dialogflow_v2.services.entity_types.transports.EntityTypesTransport.__init__') as Transport: - Transport.return_value = None - transport = transports.EntityTypesTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Every method on the transport should just blindly - # raise NotImplementedError. - methods = ( - 'list_entity_types', - 'get_entity_type', - 'create_entity_type', - 'update_entity_type', - 'delete_entity_type', - 'batch_update_entity_types', - 'batch_delete_entity_types', - 'batch_create_entities', - 'batch_update_entities', - 'batch_delete_entities', - 'get_location', - 'list_locations', - 'get_operation', - 'cancel_operation', - 'list_operations', - ) - for method in methods: - with pytest.raises(NotImplementedError): - getattr(transport, method)(request=object()) - - with pytest.raises(NotImplementedError): - transport.close() - - # Additionally, the LRO client (a property) should - # also raise NotImplementedError - with pytest.raises(NotImplementedError): - transport.operations_client - - # Catch all for all remaining methods and properties - remainder = [ - 'kind', - ] - for r in remainder: - with pytest.raises(NotImplementedError): - getattr(transport, r)() - - -def test_entity_types_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.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", - ) - - -def test_entity_types_base_transport_with_adc(): - # Test the default credentials are used if credentials and credentials_file are None. - with mock.patch.object(google.auth, 'default', autospec=True) as adc, mock.patch('google.cloud.dialogflow_v2.services.entity_types.transports.EntityTypesTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.EntityTypesTransport() - adc.assert_called_once() - - -def test_entity_types_auth_adc(): - # If no credentials are provided, we should use ADC credentials. - with mock.patch.object(google.auth, 'default', autospec=True) as adc: - 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, - ) - - -@pytest.mark.parametrize( - "transport_class", - [ - transports.EntityTypesGrpcTransport, - transports.EntityTypesGrpcAsyncIOTransport, - ], -) -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(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, - transports.EntityTypesRestTransport, - ], -) -def test_entity_types_transport_auth_gdch_credentials(transport_class): - host = 'https://language.com' - api_audience_tests = [None, 'https://language2.com'] - api_audience_expect = [host, 'https://language2.com'] - for t, e in zip(api_audience_tests, api_audience_expect): - with mock.patch.object(google.auth, 'default', autospec=True) as adc: - gdch_mock = mock.MagicMock() - type(gdch_mock).with_gdch_audience = mock.PropertyMock(return_value=gdch_mock) - adc.return_value = (gdch_mock, None) - transport_class(host=host, api_audience=t) - gdch_mock.with_gdch_audience.assert_called_once_with( - e - ) - - -@pytest.mark.parametrize( - "transport_class,grpc_helpers", - [ - (transports.EntityTypesGrpcTransport, grpc_helpers), - (transports.EntityTypesGrpcAsyncIOTransport, grpc_helpers_async) - ], -) -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", [transports.EntityTypesGrpcTransport, transports.EntityTypesGrpcAsyncIOTransport]) -def test_entity_types_grpc_transport_client_cert_source_for_mtls( - transport_class -): - cred = ga_credentials.AnonymousCredentials() - - # Check ssl_channel_credentials is used if provided. - with mock.patch.object(transport_class, "create_channel") as mock_create_channel: - mock_ssl_channel_creds = mock.Mock() - transport_class( - host="squid.clam.whelk", - credentials=cred, - ssl_channel_credentials=mock_ssl_channel_creds - ) - mock_create_channel.assert_called_once_with( - "squid.clam.whelk:443", - credentials=cred, - credentials_file=None, - scopes=None, - ssl_credentials=mock_ssl_channel_creds, - quota_project_id=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - # Check if ssl_channel_credentials is not provided, then client_cert_source_for_mtls - # is used. - with mock.patch.object(transport_class, "create_channel", return_value=mock.Mock()): - with mock.patch("grpc.ssl_channel_credentials") as mock_ssl_cred: - transport_class( - credentials=cred, - client_cert_source_for_mtls=client_cert_source_callback - ) - expected_cert, expected_key = client_cert_source_callback() - mock_ssl_cred.assert_called_once_with( - certificate_chain=expected_cert, - private_key=expected_key - ) - -def test_entity_types_http_transport_client_cert_source_for_mtls(): - cred = ga_credentials.AnonymousCredentials() - with mock.patch("google.auth.transport.requests.AuthorizedSession.configure_mtls_channel") as mock_configure_mtls_channel: - transports.EntityTypesRestTransport ( - credentials=cred, - client_cert_source_for_mtls=client_cert_source_callback - ) - mock_configure_mtls_channel.assert_called_once_with(client_cert_source_callback) - - -def test_entity_types_rest_lro_client(): - client = EntityTypesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - transport = client.transport - - # Ensure that we have a api-core operations client. - assert isinstance( - transport.operations_client, - operations_v1.AbstractOperationsClient, - ) - - # Ensure that subsequent calls to the property send the exact same object. - assert transport.operations_client is transport.operations_client - - -@pytest.mark.parametrize("transport_name", [ - "grpc", - "grpc_asyncio", - "rest", -]) -def test_entity_types_host_no_port(transport_name): - client = EntityTypesClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='dialogflow.googleapis.com'), - transport=transport_name, - ) - assert client.transport._host == ( - 'dialogflow.googleapis.com:443' - if transport_name in ['grpc', 'grpc_asyncio'] - else 'https://dialogflow.googleapis.com' - ) - -@pytest.mark.parametrize("transport_name", [ - "grpc", - "grpc_asyncio", - "rest", -]) -def test_entity_types_host_with_port(transport_name): - client = EntityTypesClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='dialogflow.googleapis.com:8000'), - transport=transport_name, - ) - assert client.transport._host == ( - 'dialogflow.googleapis.com:8000' - if transport_name in ['grpc', 'grpc_asyncio'] - else 'https://dialogflow.googleapis.com:8000' - ) - -@pytest.mark.parametrize("transport_name", [ - "rest", -]) -def test_entity_types_client_transport_session_collision(transport_name): - creds1 = ga_credentials.AnonymousCredentials() - creds2 = ga_credentials.AnonymousCredentials() - client1 = EntityTypesClient( - credentials=creds1, - transport=transport_name, - ) - client2 = EntityTypesClient( - credentials=creds2, - transport=transport_name, - ) - session1 = client1.transport.list_entity_types._session - session2 = client2.transport.list_entity_types._session - assert session1 != session2 - session1 = client1.transport.get_entity_type._session - session2 = client2.transport.get_entity_type._session - assert session1 != session2 - session1 = client1.transport.create_entity_type._session - session2 = client2.transport.create_entity_type._session - assert session1 != session2 - session1 = client1.transport.update_entity_type._session - session2 = client2.transport.update_entity_type._session - assert session1 != session2 - session1 = client1.transport.delete_entity_type._session - session2 = client2.transport.delete_entity_type._session - assert session1 != session2 - session1 = client1.transport.batch_update_entity_types._session - session2 = client2.transport.batch_update_entity_types._session - assert session1 != session2 - session1 = client1.transport.batch_delete_entity_types._session - session2 = client2.transport.batch_delete_entity_types._session - assert session1 != session2 - session1 = client1.transport.batch_create_entities._session - session2 = client2.transport.batch_create_entities._session - assert session1 != session2 - session1 = client1.transport.batch_update_entities._session - session2 = client2.transport.batch_update_entities._session - assert session1 != session2 - session1 = client1.transport.batch_delete_entities._session - session2 = client2.transport.batch_delete_entities._session - assert session1 != session2 -def test_entity_types_grpc_transport_channel(): - channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.EntityTypesGrpcTransport( - 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_entity_types_grpc_asyncio_transport_channel(): - channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.EntityTypesGrpcAsyncIOTransport( - 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.EntityTypesGrpcTransport, transports.EntityTypesGrpcAsyncIOTransport]) -def test_entity_types_transport_channel_mtls_with_client_cert_source( - transport_class -): - with mock.patch("grpc.ssl_channel_credentials", autospec=True) as grpc_ssl_channel_cred: - with mock.patch.object(transport_class, "create_channel") as grpc_create_channel: - mock_ssl_cred = mock.Mock() - grpc_ssl_channel_cred.return_value = mock_ssl_cred - - mock_grpc_channel = mock.Mock() - grpc_create_channel.return_value = mock_grpc_channel - - cred = ga_credentials.AnonymousCredentials() - with pytest.warns(DeprecationWarning): - with mock.patch.object(google.auth, 'default') as adc: - adc.return_value = (cred, None) - transport = transport_class( - host="squid.clam.whelk", - api_mtls_endpoint="mtls.squid.clam.whelk", - client_cert_source=client_cert_source_callback, - ) - adc.assert_called_once() - - grpc_ssl_channel_cred.assert_called_once_with( - certificate_chain=b"cert bytes", private_key=b"key bytes" - ) - grpc_create_channel.assert_called_once_with( - "mtls.squid.clam.whelk:443", - credentials=cred, - credentials_file=None, - scopes=None, - ssl_credentials=mock_ssl_cred, - quota_project_id=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - assert transport.grpc_channel == mock_grpc_channel - assert transport._ssl_channel_credentials == mock_ssl_cred - - -# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are -# removed from grpc/grpc_asyncio transport constructor. -@pytest.mark.parametrize("transport_class", [transports.EntityTypesGrpcTransport, transports.EntityTypesGrpcAsyncIOTransport]) -def test_entity_types_transport_channel_mtls_with_adc( - transport_class -): - mock_ssl_cred = mock.Mock() - with mock.patch.multiple( - "google.auth.transport.grpc.SslCredentials", - __init__=mock.Mock(return_value=None), - ssl_credentials=mock.PropertyMock(return_value=mock_ssl_cred), - ): - with mock.patch.object(transport_class, "create_channel") as grpc_create_channel: - mock_grpc_channel = mock.Mock() - grpc_create_channel.return_value = mock_grpc_channel - mock_cred = mock.Mock() - - with pytest.warns(DeprecationWarning): - transport = transport_class( - host="squid.clam.whelk", - credentials=mock_cred, - api_mtls_endpoint="mtls.squid.clam.whelk", - client_cert_source=None, - ) - - grpc_create_channel.assert_called_once_with( - "mtls.squid.clam.whelk:443", - credentials=mock_cred, - credentials_file=None, - scopes=None, - ssl_credentials=mock_ssl_cred, - quota_project_id=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - assert transport.grpc_channel == mock_grpc_channel - - -def test_entity_types_grpc_lro_client(): - client = EntityTypesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - transport = client.transport - - # Ensure that we have a api-core operations client. - assert isinstance( - transport.operations_client, - operations_v1.OperationsClient, - ) - - # Ensure that subsequent calls to the property send the exact same object. - assert transport.operations_client is transport.operations_client - - -def test_entity_types_grpc_lro_async_client(): - client = EntityTypesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc_asyncio', - ) - transport = client.transport - - # Ensure that we have a api-core operations client. - assert isinstance( - transport.operations_client, - operations_v1.OperationsAsyncClient, - ) - - # Ensure that subsequent calls to the property send the exact same object. - assert transport.operations_client is transport.operations_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, ) - actual = EntityTypesClient.entity_type_path(project, entity_type) - assert expected == actual - - -def test_parse_entity_type_path(): - expected = { - "project": "whelk", - "entity_type": "octopus", - } - path = EntityTypesClient.entity_type_path(**expected) - - # Check that the path construction is reversible. - actual = EntityTypesClient.parse_entity_type_path(path) - assert expected == actual - -def test_common_billing_account_path(): - billing_account = "oyster" - expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) - actual = EntityTypesClient.common_billing_account_path(billing_account) - assert expected == actual - - -def test_parse_common_billing_account_path(): - expected = { - "billing_account": "nudibranch", - } - path = EntityTypesClient.common_billing_account_path(**expected) - - # Check that the path construction is reversible. - actual = EntityTypesClient.parse_common_billing_account_path(path) - assert expected == actual - -def test_common_folder_path(): - folder = "cuttlefish" - expected = "folders/{folder}".format(folder=folder, ) - actual = EntityTypesClient.common_folder_path(folder) - assert expected == actual - - -def test_parse_common_folder_path(): - expected = { - "folder": "mussel", - } - path = EntityTypesClient.common_folder_path(**expected) - - # Check that the path construction is reversible. - actual = EntityTypesClient.parse_common_folder_path(path) - assert expected == actual - -def test_common_organization_path(): - organization = "winkle" - expected = "organizations/{organization}".format(organization=organization, ) - actual = EntityTypesClient.common_organization_path(organization) - assert expected == actual - - -def test_parse_common_organization_path(): - expected = { - "organization": "nautilus", - } - path = EntityTypesClient.common_organization_path(**expected) - - # Check that the path construction is reversible. - actual = EntityTypesClient.parse_common_organization_path(path) - assert expected == actual - -def test_common_project_path(): - project = "scallop" - expected = "projects/{project}".format(project=project, ) - actual = EntityTypesClient.common_project_path(project) - assert expected == actual - - -def test_parse_common_project_path(): - expected = { - "project": "abalone", - } - path = EntityTypesClient.common_project_path(**expected) - - # Check that the path construction is reversible. - actual = EntityTypesClient.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 = EntityTypesClient.common_location_path(project, location) - assert expected == actual - - -def test_parse_common_location_path(): - expected = { - "project": "whelk", - "location": "octopus", - } - path = EntityTypesClient.common_location_path(**expected) - - # Check that the path construction is reversible. - actual = EntityTypesClient.parse_common_location_path(path) - assert expected == actual - - -def test_client_with_default_client_info(): - client_info = gapic_v1.client_info.ClientInfo() - - with mock.patch.object(transports.EntityTypesTransport, '_prep_wrapped_messages') as prep: - client = EntityTypesClient( - credentials=ga_credentials.AnonymousCredentials(), - client_info=client_info, - ) - prep.assert_called_once_with(client_info) - - with mock.patch.object(transports.EntityTypesTransport, '_prep_wrapped_messages') as prep: - transport_class = EntityTypesClient.get_transport_class() - transport = transport_class( - credentials=ga_credentials.AnonymousCredentials(), - client_info=client_info, - ) - prep.assert_called_once_with(client_info) - -@pytest.mark.asyncio -async def test_transport_close_async(): - client = EntityTypesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - with mock.patch.object(type(getattr(client.transport, "grpc_channel")), "close") as close: - async with client: - close.assert_not_called() - close.assert_called_once() - - -def test_get_location_rest_bad_request(transport: str = 'rest', request_type=locations_pb2.GetLocationRequest): - client = EntityTypesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - request = request_type() - request = json_format.ParseDict({'name': 'projects/sample1/locations/sample2'}, request) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.get_location(request) - -@pytest.mark.parametrize("request_type", [ - locations_pb2.GetLocationRequest, - dict, -]) -def test_get_location_rest(request_type): - client = EntityTypesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request_init = {'name': 'projects/sample1/locations/sample2'} - request = request_type(**request_init) - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = locations_pb2.Location() - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.get_location(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, locations_pb2.Location) - -def test_list_locations_rest_bad_request(transport: str = 'rest', request_type=locations_pb2.ListLocationsRequest): - client = EntityTypesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - request = request_type() - request = json_format.ParseDict({'name': 'projects/sample1'}, request) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.list_locations(request) - -@pytest.mark.parametrize("request_type", [ - locations_pb2.ListLocationsRequest, - dict, -]) -def test_list_locations_rest(request_type): - client = EntityTypesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request_init = {'name': 'projects/sample1'} - request = request_type(**request_init) - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = locations_pb2.ListLocationsResponse() - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.list_locations(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, locations_pb2.ListLocationsResponse) - -def test_cancel_operation_rest_bad_request(transport: str = 'rest', request_type=operations_pb2.CancelOperationRequest): - client = EntityTypesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - request = request_type() - request = json_format.ParseDict({'name': 'projects/sample1/operations/sample2'}, request) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.cancel_operation(request) - -@pytest.mark.parametrize("request_type", [ - operations_pb2.CancelOperationRequest, - dict, -]) -def test_cancel_operation_rest(request_type): - client = EntityTypesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request_init = {'name': 'projects/sample1/operations/sample2'} - request = request_type(**request_init) - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = None - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = '{}' - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.cancel_operation(request) - - # Establish that the response is the type that we expect. - assert response is None - -def test_get_operation_rest_bad_request(transport: str = 'rest', request_type=operations_pb2.GetOperationRequest): - client = EntityTypesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - request = request_type() - request = json_format.ParseDict({'name': 'projects/sample1/operations/sample2'}, request) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.get_operation(request) - -@pytest.mark.parametrize("request_type", [ - operations_pb2.GetOperationRequest, - dict, -]) -def test_get_operation_rest(request_type): - client = EntityTypesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request_init = {'name': 'projects/sample1/operations/sample2'} - request = request_type(**request_init) - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation() - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.get_operation(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, operations_pb2.Operation) - -def test_list_operations_rest_bad_request(transport: str = 'rest', request_type=operations_pb2.ListOperationsRequest): - client = EntityTypesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - request = request_type() - request = json_format.ParseDict({'name': 'projects/sample1'}, request) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.list_operations(request) - -@pytest.mark.parametrize("request_type", [ - operations_pb2.ListOperationsRequest, - dict, -]) -def test_list_operations_rest(request_type): - client = EntityTypesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request_init = {'name': 'projects/sample1'} - request = request_type(**request_init) - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = operations_pb2.ListOperationsResponse() - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.list_operations(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, operations_pb2.ListOperationsResponse) - - -def test_cancel_operation(transport: str = "grpc"): - client = EntityTypesClient( - 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 = operations_pb2.CancelOperationRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = None - response = client.cancel_operation(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 response is the type that we expect. - assert response is None -@pytest.mark.asyncio -async def test_cancel_operation_async(transport: str = "grpc"): - client = EntityTypesAsyncClient( - 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 = operations_pb2.CancelOperationRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - None - ) - response = await client.cancel_operation(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 response is the type that we expect. - assert response is None - -def test_cancel_operation_field_headers(): - 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 = operations_pb2.CancelOperationRequest() - request.name = "locations" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call: - call.return_value = None - - client.cancel_operation(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=locations",) in kw["metadata"] -@pytest.mark.asyncio -async def test_cancel_operation_field_headers_async(): - 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 = operations_pb2.CancelOperationRequest() - request.name = "locations" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - None - ) - await client.cancel_operation(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=locations",) in kw["metadata"] - -def test_cancel_operation_from_dict(): - 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.cancel_operation), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = None - - response = client.cancel_operation( - request={ - "name": "locations", - } - ) - call.assert_called() -@pytest.mark.asyncio -async def test_cancel_operation_from_dict_async(): - 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.cancel_operation), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - None - ) - response = await client.cancel_operation( - request={ - "name": "locations", - } - ) - call.assert_called() - - -def test_get_operation(transport: str = "grpc"): - client = EntityTypesClient( - 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 = operations_pb2.GetOperationRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_operation), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation() - response = client.get_operation(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 response is the type that we expect. - assert isinstance(response, operations_pb2.Operation) -@pytest.mark.asyncio -async def test_get_operation_async(transport: str = "grpc"): - client = EntityTypesAsyncClient( - 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 = operations_pb2.GetOperationRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_operation), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation() - ) - response = await client.get_operation(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 response is the type that we expect. - assert isinstance(response, operations_pb2.Operation) - -def test_get_operation_field_headers(): - 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 = operations_pb2.GetOperationRequest() - request.name = "locations" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_operation), "__call__") as call: - call.return_value = operations_pb2.Operation() - - client.get_operation(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=locations",) in kw["metadata"] -@pytest.mark.asyncio -async def test_get_operation_field_headers_async(): - 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 = operations_pb2.GetOperationRequest() - request.name = "locations" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_operation), "__call__") as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation() - ) - await client.get_operation(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=locations",) in kw["metadata"] - -def test_get_operation_from_dict(): - 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_operation), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation() - - response = client.get_operation( - request={ - "name": "locations", - } - ) - call.assert_called() -@pytest.mark.asyncio -async def test_get_operation_from_dict_async(): - 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_operation), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation() - ) - response = await client.get_operation( - request={ - "name": "locations", - } - ) - call.assert_called() - - -def test_list_operations(transport: str = "grpc"): - client = EntityTypesClient( - 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 = operations_pb2.ListOperationsRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_operations), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.ListOperationsResponse() - response = client.list_operations(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 response is the type that we expect. - assert isinstance(response, operations_pb2.ListOperationsResponse) -@pytest.mark.asyncio -async def test_list_operations_async(transport: str = "grpc"): - client = EntityTypesAsyncClient( - 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 = operations_pb2.ListOperationsRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_operations), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.ListOperationsResponse() - ) - response = await client.list_operations(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 response is the type that we expect. - assert isinstance(response, operations_pb2.ListOperationsResponse) - -def test_list_operations_field_headers(): - 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 = operations_pb2.ListOperationsRequest() - request.name = "locations" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_operations), "__call__") as call: - call.return_value = operations_pb2.ListOperationsResponse() - - client.list_operations(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=locations",) in kw["metadata"] -@pytest.mark.asyncio -async def test_list_operations_field_headers_async(): - 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 = operations_pb2.ListOperationsRequest() - request.name = "locations" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_operations), "__call__") as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.ListOperationsResponse() - ) - await client.list_operations(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=locations",) in kw["metadata"] - -def test_list_operations_from_dict(): - 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.list_operations), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.ListOperationsResponse() - - response = client.list_operations( - request={ - "name": "locations", - } - ) - call.assert_called() -@pytest.mark.asyncio -async def test_list_operations_from_dict_async(): - 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.list_operations), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.ListOperationsResponse() - ) - response = await client.list_operations( - request={ - "name": "locations", - } - ) - call.assert_called() - - -def test_list_locations(transport: str = "grpc"): - client = EntityTypesClient( - 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 = locations_pb2.ListLocationsRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_locations), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = locations_pb2.ListLocationsResponse() - response = client.list_locations(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 response is the type that we expect. - assert isinstance(response, locations_pb2.ListLocationsResponse) -@pytest.mark.asyncio -async def test_list_locations_async(transport: str = "grpc"): - client = EntityTypesAsyncClient( - 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 = locations_pb2.ListLocationsRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_locations), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - locations_pb2.ListLocationsResponse() - ) - response = await client.list_locations(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 response is the type that we expect. - assert isinstance(response, locations_pb2.ListLocationsResponse) - -def test_list_locations_field_headers(): - 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 = locations_pb2.ListLocationsRequest() - request.name = "locations" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_locations), "__call__") as call: - call.return_value = locations_pb2.ListLocationsResponse() - - client.list_locations(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=locations",) in kw["metadata"] -@pytest.mark.asyncio -async def test_list_locations_field_headers_async(): - 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 = locations_pb2.ListLocationsRequest() - request.name = "locations" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_locations), "__call__") as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - locations_pb2.ListLocationsResponse() - ) - await client.list_locations(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=locations",) in kw["metadata"] - -def test_list_locations_from_dict(): - 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.list_locations), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = locations_pb2.ListLocationsResponse() - - response = client.list_locations( - request={ - "name": "locations", - } - ) - call.assert_called() -@pytest.mark.asyncio -async def test_list_locations_from_dict_async(): - 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.list_locations), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - locations_pb2.ListLocationsResponse() - ) - response = await client.list_locations( - request={ - "name": "locations", - } - ) - call.assert_called() - - -def test_get_location(transport: str = "grpc"): - client = EntityTypesClient( - 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 = locations_pb2.GetLocationRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_location), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = locations_pb2.Location() - response = client.get_location(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 response is the type that we expect. - assert isinstance(response, locations_pb2.Location) -@pytest.mark.asyncio -async def test_get_location_async(transport: str = "grpc_asyncio"): - client = EntityTypesAsyncClient( - 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 = locations_pb2.GetLocationRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_location), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - locations_pb2.Location() - ) - response = await client.get_location(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 response is the type that we expect. - assert isinstance(response, locations_pb2.Location) - -def test_get_location_field_headers(): - 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 = locations_pb2.GetLocationRequest() - request.name = "locations/abc" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_location), "__call__") as call: - call.return_value = locations_pb2.Location() - - client.get_location(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=locations/abc",) in kw["metadata"] -@pytest.mark.asyncio -async def test_get_location_field_headers_async(): - 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 = locations_pb2.GetLocationRequest() - request.name = "locations/abc" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_location), "__call__") as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - locations_pb2.Location() - ) - await client.get_location(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=locations/abc",) in kw["metadata"] - -def test_get_location_from_dict(): - 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.list_locations), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = locations_pb2.Location() - - response = client.get_location( - request={ - "name": "locations/abc", - } - ) - call.assert_called() -@pytest.mark.asyncio -async def test_get_location_from_dict_async(): - 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.list_locations), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - locations_pb2.Location() - ) - response = await client.get_location( - request={ - "name": "locations", - } - ) - call.assert_called() - - -def test_transport_close(): - transports = { - "rest": "_session", - "grpc": "_grpc_channel", - } - - for transport, close_name in transports.items(): - client = EntityTypesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport - ) - with mock.patch.object(type(getattr(client.transport, close_name)), "close") as close: - with client: - close.assert_not_called() - close.assert_called_once() - -def test_client_ctx(): - transports = [ - 'rest', - 'grpc', - ] - for transport in transports: - client = EntityTypesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport - ) - # Test client calls underlying transport. - with mock.patch.object(type(client.transport), "close") as close: - close.assert_not_called() - with client: - pass - close.assert_called() - -@pytest.mark.parametrize("client_class,transport_class", [ - (EntityTypesClient, transports.EntityTypesGrpcTransport), - (EntityTypesAsyncClient, transports.EntityTypesGrpcAsyncIOTransport), -]) -def test_api_key_credentials(client_class, transport_class): - with mock.patch.object( - google.auth._default, "get_api_key_credentials", create=True - ) as get_api_key_credentials: - mock_cred = mock.Mock() - get_api_key_credentials.return_value = mock_cred - options = client_options.ClientOptions() - options.api_key = "api_key" - 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=mock_cred, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) diff --git a/owl-bot-staging/v2/tests/unit/gapic/dialogflow_v2/test_environments.py b/owl-bot-staging/v2/tests/unit/gapic/dialogflow_v2/test_environments.py deleted file mode 100644 index 02773bfbd..000000000 --- a/owl-bot-staging/v2/tests/unit/gapic/dialogflow_v2/test_environments.py +++ /dev/null @@ -1,4837 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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 -# try/except added for compatibility with python < 3.8 -try: - from unittest import mock - from unittest.mock import AsyncMock # pragma: NO COVER -except ImportError: # pragma: NO COVER - import mock - -import grpc -from grpc.experimental import aio -from collections.abc import Iterable -from google.protobuf import json_format -import json -import math -import pytest -from proto.marshal.rules.dates import DurationRule, TimestampRule -from proto.marshal.rules import wrappers -from requests import Response -from requests import Request, PreparedRequest -from requests.sessions import Session -from google.protobuf import json_format - -from google.api_core import client_options -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import grpc_helpers -from google.api_core import grpc_helpers_async -from google.api_core import path_template -from google.auth import credentials as ga_credentials -from google.auth.exceptions import MutualTLSChannelError -from google.cloud.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.types import audio_config -from google.cloud.dialogflow_v2.types import environment -from google.cloud.dialogflow_v2.types import fulfillment -from google.cloud.location import locations_pb2 -from google.longrunning import operations_pb2 -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 - - -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 EnvironmentsClient._get_default_mtls_endpoint(None) is None - assert EnvironmentsClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint - assert EnvironmentsClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint - assert EnvironmentsClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint - assert EnvironmentsClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint - assert EnvironmentsClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi - - -@pytest.mark.parametrize("client_class,transport_name", [ - (EnvironmentsClient, "grpc"), - (EnvironmentsAsyncClient, "grpc_asyncio"), - (EnvironmentsClient, "rest"), -]) -def test_environments_client_from_service_account_info(client_class, transport_name): - 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, transport=transport_name) - assert client.transport._credentials == creds - assert isinstance(client, client_class) - - assert client.transport._host == ( - 'dialogflow.googleapis.com:443' - if transport_name in ['grpc', 'grpc_asyncio'] - else - 'https://dialogflow.googleapis.com' - ) - - -@pytest.mark.parametrize("transport_class,transport_name", [ - (transports.EnvironmentsGrpcTransport, "grpc"), - (transports.EnvironmentsGrpcAsyncIOTransport, "grpc_asyncio"), - (transports.EnvironmentsRestTransport, "rest"), -]) -def test_environments_client_service_account_always_use_jwt(transport_class, transport_name): - with mock.patch.object(service_account.Credentials, 'with_always_use_jwt_access', create=True) as use_jwt: - creds = service_account.Credentials(None, None, None) - transport = transport_class(credentials=creds, always_use_jwt_access=True) - use_jwt.assert_called_once_with(True) - - with mock.patch.object(service_account.Credentials, 'with_always_use_jwt_access', create=True) as use_jwt: - creds = service_account.Credentials(None, None, None) - transport = transport_class(credentials=creds, always_use_jwt_access=False) - use_jwt.assert_not_called() - - -@pytest.mark.parametrize("client_class,transport_name", [ - (EnvironmentsClient, "grpc"), - (EnvironmentsAsyncClient, "grpc_asyncio"), - (EnvironmentsClient, "rest"), -]) -def test_environments_client_from_service_account_file(client_class, transport_name): - 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", transport=transport_name) - assert client.transport._credentials == creds - assert isinstance(client, client_class) - - client = client_class.from_service_account_json("dummy/file/path.json", transport=transport_name) - assert client.transport._credentials == creds - assert isinstance(client, client_class) - - assert client.transport._host == ( - 'dialogflow.googleapis.com:443' - if transport_name in ['grpc', 'grpc_asyncio'] - else - 'https://dialogflow.googleapis.com' - ) - - -def test_environments_client_get_transport_class(): - transport = EnvironmentsClient.get_transport_class() - available_transports = [ - transports.EnvironmentsGrpcTransport, - transports.EnvironmentsRestTransport, - ] - assert transport in available_transports - - transport = EnvironmentsClient.get_transport_class("grpc") - assert transport == transports.EnvironmentsGrpcTransport - - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (EnvironmentsClient, transports.EnvironmentsGrpcTransport, "grpc"), - (EnvironmentsAsyncClient, transports.EnvironmentsGrpcAsyncIOTransport, "grpc_asyncio"), - (EnvironmentsClient, transports.EnvironmentsRestTransport, "rest"), -]) -@mock.patch.object(EnvironmentsClient, "DEFAULT_ENDPOINT", modify_default_endpoint(EnvironmentsClient)) -@mock.patch.object(EnvironmentsAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(EnvironmentsAsyncClient)) -def test_environments_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(EnvironmentsClient, '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(EnvironmentsClient, 'get_transport_class') as gtc: - client = client_class(transport=transport_name) - gtc.assert_called() - - # Check the case api_endpoint is provided. - options = client_options.ClientOptions(api_endpoint="squid.clam.whelk") - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(transport=transport_name, client_options=options) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host="squid.clam.whelk", - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is - # "never". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is - # "always". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_MTLS_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # 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(transport=transport_name) - - # 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(transport=transport_name) - - # 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, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id="octopus", - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - # Check the case api_endpoint is provided - options = client_options.ClientOptions(api_audience="https://language.googleapis.com") - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience="https://language.googleapis.com" - ) - -@pytest.mark.parametrize("client_class,transport_class,transport_name,use_client_cert_env", [ - (EnvironmentsClient, transports.EnvironmentsGrpcTransport, "grpc", "true"), - (EnvironmentsAsyncClient, transports.EnvironmentsGrpcAsyncIOTransport, "grpc_asyncio", "true"), - (EnvironmentsClient, transports.EnvironmentsGrpcTransport, "grpc", "false"), - (EnvironmentsAsyncClient, transports.EnvironmentsGrpcAsyncIOTransport, "grpc_asyncio", "false"), - (EnvironmentsClient, transports.EnvironmentsRestTransport, "rest", "true"), - (EnvironmentsClient, transports.EnvironmentsRestTransport, "rest", "false"), -]) -@mock.patch.object(EnvironmentsClient, "DEFAULT_ENDPOINT", modify_default_endpoint(EnvironmentsClient)) -@mock.patch.object(EnvironmentsAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(EnvironmentsAsyncClient)) -@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) -def test_environments_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, transport=transport_name) - - if use_client_cert_env == "false": - expected_client_cert_source = None - expected_host = client.DEFAULT_ENDPOINT - else: - expected_client_cert_source = client_cert_source_callback - expected_host = client.DEFAULT_MTLS_ENDPOINT - - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=expected_host, - scopes=None, - client_cert_source_for_mtls=expected_client_cert_source, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case ADC client cert is provided. Whether client cert is used depends on - # GOOGLE_API_USE_CLIENT_CERTIFICATE value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): - with mock.patch.object(transport_class, '__init__') as patched: - with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): - with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=client_cert_source_callback): - if use_client_cert_env == "false": - expected_host = client.DEFAULT_ENDPOINT - expected_client_cert_source = None - else: - expected_host = client.DEFAULT_MTLS_ENDPOINT - expected_client_cert_source = client_cert_source_callback - - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=expected_host, - scopes=None, - client_cert_source_for_mtls=expected_client_cert_source, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case client_cert_source and ADC client cert are not provided. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): - with mock.patch.object(transport_class, '__init__') as patched: - with mock.patch("google.auth.transport.mtls.has_default_client_cert_source", return_value=False): - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - -@pytest.mark.parametrize("client_class", [ - EnvironmentsClient, EnvironmentsAsyncClient -]) -@mock.patch.object(EnvironmentsClient, "DEFAULT_ENDPOINT", modify_default_endpoint(EnvironmentsClient)) -@mock.patch.object(EnvironmentsAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(EnvironmentsAsyncClient)) -def test_environments_client_get_mtls_endpoint_and_cert_source(client_class): - mock_client_cert_source = mock.Mock() - - # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "true". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - mock_api_endpoint = "foo" - options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) - assert api_endpoint == mock_api_endpoint - assert cert_source == mock_client_cert_source - - # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "false". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): - mock_client_cert_source = mock.Mock() - mock_api_endpoint = "foo" - options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) - assert api_endpoint == mock_api_endpoint - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "never". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_ENDPOINT - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "always". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert doesn't exist. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=False): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_ENDPOINT - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert exists. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - 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=mock_client_cert_source): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT - assert cert_source == mock_client_cert_source - - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (EnvironmentsClient, transports.EnvironmentsGrpcTransport, "grpc"), - (EnvironmentsAsyncClient, transports.EnvironmentsGrpcAsyncIOTransport, "grpc_asyncio"), - (EnvironmentsClient, transports.EnvironmentsRestTransport, "rest"), -]) -def test_environments_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, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=["1", "2"], - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - -@pytest.mark.parametrize("client_class,transport_class,transport_name,grpc_helpers", [ - (EnvironmentsClient, transports.EnvironmentsGrpcTransport, "grpc", grpc_helpers), - (EnvironmentsAsyncClient, transports.EnvironmentsGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), - (EnvironmentsClient, transports.EnvironmentsRestTransport, "rest", None), -]) -def test_environments_client_client_options_credentials_file(client_class, transport_class, transport_name, grpc_helpers): - # 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, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file="credentials.json", - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - -def test_environments_client_client_options_from_dict(): - with mock.patch('google.cloud.dialogflow_v2.services.environments.transports.EnvironmentsGrpcTransport.__init__') as grpc_transport: - grpc_transport.return_value = None - client = EnvironmentsClient( - client_options={'api_endpoint': 'squid.clam.whelk'} - ) - grpc_transport.assert_called_once_with( - credentials=None, - credentials_file=None, - host="squid.clam.whelk", - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - -@pytest.mark.parametrize("client_class,transport_class,transport_name,grpc_helpers", [ - (EnvironmentsClient, transports.EnvironmentsGrpcTransport, "grpc", grpc_helpers), - (EnvironmentsAsyncClient, transports.EnvironmentsGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), -]) -def test_environments_client_create_channel_credentials_file(client_class, transport_class, transport_name, grpc_helpers): - # 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, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file="credentials.json", - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # test that the credentials from file are saved and used as the credentials. - with mock.patch.object( - google.auth, "load_credentials_from_file", autospec=True - ) as load_creds, mock.patch.object( - google.auth, "default", autospec=True - ) as adc, mock.patch.object( - grpc_helpers, "create_channel" - ) as create_channel: - creds = ga_credentials.AnonymousCredentials() - file_creds = ga_credentials.AnonymousCredentials() - load_creds.return_value = (file_creds, None) - adc.return_value = (creds, None) - client = client_class(client_options=options, transport=transport_name) - create_channel.assert_called_with( - "dialogflow.googleapis.com:443", - credentials=file_creds, - credentials_file=None, - quota_project_id=None, - default_scopes=( - 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/dialogflow', -), - scopes=None, - default_host="dialogflow.googleapis.com", - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - -@pytest.mark.parametrize("request_type", [ - environment.ListEnvironmentsRequest, - dict, -]) -def test_list_environments(request_type, transport: str = 'grpc'): - 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.list_environments), - '__call__') as call: - # Designate an appropriate return value for the call. - 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' - - -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=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_environments), - '__call__') as call: - client.list_environments() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == environment.ListEnvironmentsRequest() - -@pytest.mark.asyncio -async def test_list_environments_async(transport: str = 'grpc_asyncio', request_type=environment.ListEnvironmentsRequest): - 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.list_environments), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(environment.ListEnvironmentsResponse( - 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' - - -@pytest.mark.asyncio -async def test_list_environments_async_from_dict(): - await test_list_environments_async(request_type=dict) - - -def test_list_environments_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.ListEnvironmentsRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - 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. - 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_environments_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.ListEnvironmentsRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_environments), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(environment.ListEnvironmentsResponse()) - 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] == 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_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] - arg = args[0].parent - mock_val = 'parent_value' - assert arg == mock_val - - -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] - arg = args[0].parent - mock_val = 'parent_value' - assert arg == mock_val - -@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(transport_name: str = "grpc"): - client = EnvironmentsClient( - credentials=ga_credentials.AnonymousCredentials, - transport=transport_name, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_environments), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - environment.ListEnvironmentsResponse( - environments=[ - environment.Environment(), - environment.Environment(), - environment.Environment(), - ], - next_page_token='abc', - ), - environment.ListEnvironmentsResponse( - environments=[], - next_page_token='def', - ), - environment.ListEnvironmentsResponse( - environments=[ - environment.Environment(), - ], - next_page_token='ghi', - ), - environment.ListEnvironmentsResponse( - environments=[ - environment.Environment(), - environment.Environment(), - ], - ), - RuntimeError, - ) - - metadata = () - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ('parent', ''), - )), - ) - pager = client.list_environments(request={}) - - assert pager._metadata == metadata - - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, environment.Environment) - for i in results) -def test_list_environments_pages(transport_name: str = "grpc"): - client = EnvironmentsClient( - credentials=ga_credentials.AnonymousCredentials, - transport=transport_name, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_environments), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - environment.ListEnvironmentsResponse( - environments=[ - environment.Environment(), - environment.Environment(), - environment.Environment(), - ], - next_page_token='abc', - ), - environment.ListEnvironmentsResponse( - environments=[], - next_page_token='def', - ), - environment.ListEnvironmentsResponse( - environments=[ - environment.Environment(), - ], - next_page_token='ghi', - ), - environment.ListEnvironmentsResponse( - environments=[ - environment.Environment(), - environment.Environment(), - ], - ), - RuntimeError, - ) - pages = list(client.list_environments(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_environments_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.list_environments), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - environment.ListEnvironmentsResponse( - environments=[ - environment.Environment(), - environment.Environment(), - environment.Environment(), - ], - next_page_token='abc', - ), - environment.ListEnvironmentsResponse( - environments=[], - next_page_token='def', - ), - environment.ListEnvironmentsResponse( - environments=[ - environment.Environment(), - ], - next_page_token='ghi', - ), - environment.ListEnvironmentsResponse( - environments=[ - environment.Environment(), - environment.Environment(), - ], - ), - RuntimeError, - ) - async_pager = await client.list_environments(request={},) - assert async_pager.next_page_token == 'abc' - responses = [] - async for response in async_pager: # pragma: no branch - responses.append(response) - - assert len(responses) == 6 - assert all(isinstance(i, environment.Environment) - for i in responses) - - -@pytest.mark.asyncio -async def test_list_environments_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.list_environments), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - environment.ListEnvironmentsResponse( - environments=[ - environment.Environment(), - environment.Environment(), - environment.Environment(), - ], - next_page_token='abc', - ), - environment.ListEnvironmentsResponse( - environments=[], - next_page_token='def', - ), - environment.ListEnvironmentsResponse( - environments=[ - environment.Environment(), - ], - next_page_token='ghi', - ), - environment.ListEnvironmentsResponse( - environments=[ - environment.Environment(), - environment.Environment(), - ], - ), - RuntimeError, - ) - pages = [] - async for page_ in (await client.list_environments(request={})).pages: # pragma: no branch - pages.append(page_) - for page_, token in zip(pages, ['abc','def','ghi', '']): - assert page_.raw_page.next_page_token == token - -@pytest.mark.parametrize("request_type", [ - environment.GetEnvironmentRequest, - dict, -]) -def test_get_environment(request_type, transport: str = 'grpc'): - 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), - '__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() - - # 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_empty_call(): - # 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), - '__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, - ) - - # 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() - - # 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_get_environment_async_from_dict(): - await test_get_environment_async(request_type=dict) - - -def test_get_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.GetEnvironmentRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_environment), - '__call__') as call: - call.return_value = environment.Environment() - client.get_environment(request) - - # Establish that the underlying gRPC stub method was called. - 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_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.GetEnvironmentRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_environment), - '__call__') as call: - call.return_value = 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 - - # 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("request_type", [ - environment.CreateEnvironmentRequest, - dict, -]) -def test_create_environment(request_type, transport: str = 'grpc'): - 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.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_empty_call(): - # 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'] - - -@pytest.mark.parametrize("request_type", [ - environment.UpdateEnvironmentRequest, - dict, -]) -def test_update_environment(request_type, transport: str = 'grpc'): - 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_empty_call(): - # 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 = '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=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 = '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=name_value', - ) in kw['metadata'] - - -@pytest.mark.parametrize("request_type", [ - environment.DeleteEnvironmentRequest, - dict, -]) -def test_delete_environment(request_type, transport: str = 'grpc'): - 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_empty_call(): - # 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'] - - -@pytest.mark.parametrize("request_type", [ - environment.GetEnvironmentHistoryRequest, - dict, -]) -def test_get_environment_history(request_type, transport: str = 'grpc'): - 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_empty_call(): - # 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(transport_name: str = "grpc"): - client = EnvironmentsClient( - credentials=ga_credentials.AnonymousCredentials, - transport=transport_name, - ) - - # 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 = list(pager) - assert len(results) == 6 - assert all(isinstance(i, environment.EnvironmentHistory.Entry) - for i in results) -def test_get_environment_history_pages(transport_name: str = "grpc"): - client = EnvironmentsClient( - credentials=ga_credentials.AnonymousCredentials, - transport=transport_name, - ) - - # 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: # pragma: no branch - 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: # pragma: no branch - pages.append(page_) - for page_, token in zip(pages, ['abc','def','ghi', '']): - assert page_.raw_page.next_page_token == token - - -@pytest.mark.parametrize("request_type", [ - environment.ListEnvironmentsRequest, - dict, -]) -def test_list_environments_rest(request_type): - client = EnvironmentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1/agent'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = environment.ListEnvironmentsResponse( - next_page_token='next_page_token_value', - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - pb_return_value = environment.ListEnvironmentsResponse.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.list_environments(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListEnvironmentsPager) - assert response.next_page_token == 'next_page_token_value' - - -def test_list_environments_rest_required_fields(request_type=environment.ListEnvironmentsRequest): - transport_class = transports.EnvironmentsRestTransport - - request_init = {} - request_init["parent"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - including_default_value_fields=False, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).list_environments._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["parent"] = 'parent_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).list_environments._get_unset_required_fields(jsonified_request) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("page_size", "page_token", )) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "parent" in jsonified_request - assert jsonified_request["parent"] == 'parent_value' - - client = EnvironmentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = environment.ListEnvironmentsResponse() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "get", - 'query_params': pb_request, - } - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - - pb_return_value = environment.ListEnvironmentsResponse.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.list_environments(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_list_environments_rest_unset_required_fields(): - transport = transports.EnvironmentsRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.list_environments._get_unset_required_fields({}) - assert set(unset_fields) == (set(("pageSize", "pageToken", )) & set(("parent", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_list_environments_rest_interceptors(null_interceptor): - transport = transports.EnvironmentsRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.EnvironmentsRestInterceptor(), - ) - client = EnvironmentsClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.EnvironmentsRestInterceptor, "post_list_environments") as post, \ - mock.patch.object(transports.EnvironmentsRestInterceptor, "pre_list_environments") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = environment.ListEnvironmentsRequest.pb(environment.ListEnvironmentsRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = environment.ListEnvironmentsResponse.to_json(environment.ListEnvironmentsResponse()) - - request = environment.ListEnvironmentsRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = environment.ListEnvironmentsResponse() - - client.list_environments(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_list_environments_rest_bad_request(transport: str = 'rest', request_type=environment.ListEnvironmentsRequest): - client = EnvironmentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1/agent'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.list_environments(request) - - -def test_list_environments_rest_flattened(): - client = EnvironmentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = environment.ListEnvironmentsResponse() - - # get arguments that satisfy an http rule for this method - sample_request = {'parent': 'projects/sample1/agent'} - - # get truthy value for each flattened field - mock_args = dict( - parent='parent_value', - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - pb_return_value = environment.ListEnvironmentsResponse.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.list_environments(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v2/{parent=projects/*/agent}/environments" % client.transport._host, args[1]) - - -def test_list_environments_rest_flattened_error(transport: str = 'rest'): - client = EnvironmentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # 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', - ) - - -def test_list_environments_rest_pager(transport: str = 'rest'): - client = EnvironmentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # TODO(kbandes): remove this mock unless there's a good reason for it. - #with mock.patch.object(path_template, 'transcode') as transcode: - # Set the response as a series of pages - response = ( - environment.ListEnvironmentsResponse( - environments=[ - environment.Environment(), - environment.Environment(), - environment.Environment(), - ], - next_page_token='abc', - ), - environment.ListEnvironmentsResponse( - environments=[], - next_page_token='def', - ), - environment.ListEnvironmentsResponse( - environments=[ - environment.Environment(), - ], - next_page_token='ghi', - ), - environment.ListEnvironmentsResponse( - environments=[ - environment.Environment(), - environment.Environment(), - ], - ), - ) - # Two responses for two calls - response = response + response - - # Wrap the values into proper Response objs - response = tuple(environment.ListEnvironmentsResponse.to_json(x) for x in response) - return_values = tuple(Response() for i in response) - for return_val, response_val in zip(return_values, response): - return_val._content = response_val.encode('UTF-8') - return_val.status_code = 200 - req.side_effect = return_values - - sample_request = {'parent': 'projects/sample1/agent'} - - pager = client.list_environments(request=sample_request) - - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, environment.Environment) - for i in results) - - pages = list(client.list_environments(request=sample_request).pages) - for page_, token in zip(pages, ['abc','def','ghi', '']): - assert page_.raw_page.next_page_token == token - - -@pytest.mark.parametrize("request_type", [ - environment.GetEnvironmentRequest, - dict, -]) -def test_get_environment_rest(request_type): - client = EnvironmentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/agent/environments/sample2'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = environment.Environment( - name='name_value', - description='description_value', - agent_version='agent_version_value', - state=environment.Environment.State.STOPPED, - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - pb_return_value = environment.Environment.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.get_environment(request) - - # 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_rest_required_fields(request_type=environment.GetEnvironmentRequest): - transport_class = transports.EnvironmentsRestTransport - - request_init = {} - request_init["name"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - including_default_value_fields=False, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_environment._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["name"] = 'name_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_environment._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "name" in jsonified_request - assert jsonified_request["name"] == 'name_value' - - client = EnvironmentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = environment.Environment() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "get", - 'query_params': pb_request, - } - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - - pb_return_value = environment.Environment.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.get_environment(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_get_environment_rest_unset_required_fields(): - transport = transports.EnvironmentsRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.get_environment._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_get_environment_rest_interceptors(null_interceptor): - transport = transports.EnvironmentsRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.EnvironmentsRestInterceptor(), - ) - client = EnvironmentsClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.EnvironmentsRestInterceptor, "post_get_environment") as post, \ - mock.patch.object(transports.EnvironmentsRestInterceptor, "pre_get_environment") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = environment.GetEnvironmentRequest.pb(environment.GetEnvironmentRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = environment.Environment.to_json(environment.Environment()) - - request = environment.GetEnvironmentRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = environment.Environment() - - client.get_environment(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_get_environment_rest_bad_request(transport: str = 'rest', request_type=environment.GetEnvironmentRequest): - client = EnvironmentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/agent/environments/sample2'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.get_environment(request) - - -def test_get_environment_rest_error(): - client = EnvironmentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - environment.CreateEnvironmentRequest, - dict, -]) -def test_create_environment_rest(request_type): - client = EnvironmentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1/agent'} - request_init["environment"] = {'name': 'name_value', 'description': 'description_value', 'agent_version': 'agent_version_value', 'state': 1, 'update_time': {'seconds': 751, 'nanos': 543}, 'text_to_speech_settings': {'enable_text_to_speech': True, 'output_audio_encoding': 1, 'sample_rate_hertz': 1817, 'synthesize_speech_configs': {}}, 'fulfillment': {'name': 'name_value', 'display_name': 'display_name_value', 'generic_web_service': {'uri': 'uri_value', 'username': 'username_value', 'password': 'password_value', 'request_headers': {}, 'is_cloud_function': True}, 'enabled': True, 'features': [{'type_': 1}]}} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = environment.Environment( - name='name_value', - description='description_value', - agent_version='agent_version_value', - state=environment.Environment.State.STOPPED, - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - pb_return_value = environment.Environment.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.create_environment(request) - - # 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_rest_required_fields(request_type=environment.CreateEnvironmentRequest): - transport_class = transports.EnvironmentsRestTransport - - request_init = {} - request_init["parent"] = "" - request_init["environment_id"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - including_default_value_fields=False, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - assert "environmentId" not in jsonified_request - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_environment._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - assert "environmentId" in jsonified_request - assert jsonified_request["environmentId"] == request_init["environment_id"] - - jsonified_request["parent"] = 'parent_value' - jsonified_request["environmentId"] = 'environment_id_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_environment._get_unset_required_fields(jsonified_request) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("environment_id", )) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "parent" in jsonified_request - assert jsonified_request["parent"] == 'parent_value' - assert "environmentId" in jsonified_request - assert jsonified_request["environmentId"] == 'environment_id_value' - - client = EnvironmentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = environment.Environment() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "post", - 'query_params': pb_request, - } - transcode_result['body'] = pb_request - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - - pb_return_value = environment.Environment.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.create_environment(request) - - expected_params = [ - ( - "environmentId", - "", - ), - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_create_environment_rest_unset_required_fields(): - transport = transports.EnvironmentsRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.create_environment._get_unset_required_fields({}) - assert set(unset_fields) == (set(("environmentId", )) & set(("parent", "environment", "environmentId", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_create_environment_rest_interceptors(null_interceptor): - transport = transports.EnvironmentsRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.EnvironmentsRestInterceptor(), - ) - client = EnvironmentsClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.EnvironmentsRestInterceptor, "post_create_environment") as post, \ - mock.patch.object(transports.EnvironmentsRestInterceptor, "pre_create_environment") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = environment.CreateEnvironmentRequest.pb(environment.CreateEnvironmentRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = environment.Environment.to_json(environment.Environment()) - - request = environment.CreateEnvironmentRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = environment.Environment() - - client.create_environment(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_create_environment_rest_bad_request(transport: str = 'rest', request_type=environment.CreateEnvironmentRequest): - client = EnvironmentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1/agent'} - request_init["environment"] = {'name': 'name_value', 'description': 'description_value', 'agent_version': 'agent_version_value', 'state': 1, 'update_time': {'seconds': 751, 'nanos': 543}, 'text_to_speech_settings': {'enable_text_to_speech': True, 'output_audio_encoding': 1, 'sample_rate_hertz': 1817, 'synthesize_speech_configs': {}}, 'fulfillment': {'name': 'name_value', 'display_name': 'display_name_value', 'generic_web_service': {'uri': 'uri_value', 'username': 'username_value', 'password': 'password_value', 'request_headers': {}, 'is_cloud_function': True}, 'enabled': True, 'features': [{'type_': 1}]}} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.create_environment(request) - - -def test_create_environment_rest_error(): - client = EnvironmentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - environment.UpdateEnvironmentRequest, - dict, -]) -def test_update_environment_rest(request_type): - client = EnvironmentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'environment': {'name': 'projects/sample1/agent/environments/sample2'}} - request_init["environment"] = {'name': 'projects/sample1/agent/environments/sample2', 'description': 'description_value', 'agent_version': 'agent_version_value', 'state': 1, 'update_time': {'seconds': 751, 'nanos': 543}, 'text_to_speech_settings': {'enable_text_to_speech': True, 'output_audio_encoding': 1, 'sample_rate_hertz': 1817, 'synthesize_speech_configs': {}}, 'fulfillment': {'name': 'name_value', 'display_name': 'display_name_value', 'generic_web_service': {'uri': 'uri_value', 'username': 'username_value', 'password': 'password_value', 'request_headers': {}, 'is_cloud_function': True}, 'enabled': True, 'features': [{'type_': 1}]}} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = environment.Environment( - name='name_value', - description='description_value', - agent_version='agent_version_value', - state=environment.Environment.State.STOPPED, - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - pb_return_value = environment.Environment.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.update_environment(request) - - # 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_rest_required_fields(request_type=environment.UpdateEnvironmentRequest): - transport_class = transports.EnvironmentsRestTransport - - request_init = {} - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - including_default_value_fields=False, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).update_environment._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).update_environment._get_unset_required_fields(jsonified_request) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("allow_load_to_draft_and_discard_changes", "update_mask", )) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - - client = EnvironmentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = environment.Environment() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "patch", - 'query_params': pb_request, - } - transcode_result['body'] = pb_request - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - - pb_return_value = environment.Environment.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.update_environment(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_update_environment_rest_unset_required_fields(): - transport = transports.EnvironmentsRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.update_environment._get_unset_required_fields({}) - assert set(unset_fields) == (set(("allowLoadToDraftAndDiscardChanges", "updateMask", )) & set(("environment", "updateMask", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_update_environment_rest_interceptors(null_interceptor): - transport = transports.EnvironmentsRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.EnvironmentsRestInterceptor(), - ) - client = EnvironmentsClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.EnvironmentsRestInterceptor, "post_update_environment") as post, \ - mock.patch.object(transports.EnvironmentsRestInterceptor, "pre_update_environment") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = environment.UpdateEnvironmentRequest.pb(environment.UpdateEnvironmentRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = environment.Environment.to_json(environment.Environment()) - - request = environment.UpdateEnvironmentRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = environment.Environment() - - client.update_environment(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_update_environment_rest_bad_request(transport: str = 'rest', request_type=environment.UpdateEnvironmentRequest): - client = EnvironmentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'environment': {'name': 'projects/sample1/agent/environments/sample2'}} - request_init["environment"] = {'name': 'projects/sample1/agent/environments/sample2', 'description': 'description_value', 'agent_version': 'agent_version_value', 'state': 1, 'update_time': {'seconds': 751, 'nanos': 543}, 'text_to_speech_settings': {'enable_text_to_speech': True, 'output_audio_encoding': 1, 'sample_rate_hertz': 1817, 'synthesize_speech_configs': {}}, 'fulfillment': {'name': 'name_value', 'display_name': 'display_name_value', 'generic_web_service': {'uri': 'uri_value', 'username': 'username_value', 'password': 'password_value', 'request_headers': {}, 'is_cloud_function': True}, 'enabled': True, 'features': [{'type_': 1}]}} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.update_environment(request) - - -def test_update_environment_rest_error(): - client = EnvironmentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - environment.DeleteEnvironmentRequest, - dict, -]) -def test_delete_environment_rest(request_type): - client = EnvironmentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/agent/environments/sample2'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = None - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = '' - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.delete_environment(request) - - # Establish that the response is the type that we expect. - assert response is None - - -def test_delete_environment_rest_required_fields(request_type=environment.DeleteEnvironmentRequest): - transport_class = transports.EnvironmentsRestTransport - - request_init = {} - request_init["name"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - including_default_value_fields=False, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).delete_environment._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["name"] = 'name_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).delete_environment._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "name" in jsonified_request - assert jsonified_request["name"] == 'name_value' - - client = EnvironmentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = None - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "delete", - 'query_params': pb_request, - } - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - json_return_value = '' - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.delete_environment(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_delete_environment_rest_unset_required_fields(): - transport = transports.EnvironmentsRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.delete_environment._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_delete_environment_rest_interceptors(null_interceptor): - transport = transports.EnvironmentsRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.EnvironmentsRestInterceptor(), - ) - client = EnvironmentsClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.EnvironmentsRestInterceptor, "pre_delete_environment") as pre: - pre.assert_not_called() - pb_message = environment.DeleteEnvironmentRequest.pb(environment.DeleteEnvironmentRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - - request = environment.DeleteEnvironmentRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - - client.delete_environment(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - - -def test_delete_environment_rest_bad_request(transport: str = 'rest', request_type=environment.DeleteEnvironmentRequest): - client = EnvironmentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/agent/environments/sample2'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.delete_environment(request) - - -def test_delete_environment_rest_error(): - client = EnvironmentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - environment.GetEnvironmentHistoryRequest, - dict, -]) -def test_get_environment_history_rest(request_type): - client = EnvironmentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1/agent/environments/sample2'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = environment.EnvironmentHistory( - parent='parent_value', - next_page_token='next_page_token_value', - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - pb_return_value = environment.EnvironmentHistory.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.get_environment_history(request) - - # 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_rest_required_fields(request_type=environment.GetEnvironmentHistoryRequest): - transport_class = transports.EnvironmentsRestTransport - - request_init = {} - request_init["parent"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - including_default_value_fields=False, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_environment_history._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["parent"] = 'parent_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_environment_history._get_unset_required_fields(jsonified_request) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("page_size", "page_token", )) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "parent" in jsonified_request - assert jsonified_request["parent"] == 'parent_value' - - client = EnvironmentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = environment.EnvironmentHistory() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "get", - 'query_params': pb_request, - } - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - - pb_return_value = environment.EnvironmentHistory.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.get_environment_history(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_get_environment_history_rest_unset_required_fields(): - transport = transports.EnvironmentsRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.get_environment_history._get_unset_required_fields({}) - assert set(unset_fields) == (set(("pageSize", "pageToken", )) & set(("parent", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_get_environment_history_rest_interceptors(null_interceptor): - transport = transports.EnvironmentsRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.EnvironmentsRestInterceptor(), - ) - client = EnvironmentsClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.EnvironmentsRestInterceptor, "post_get_environment_history") as post, \ - mock.patch.object(transports.EnvironmentsRestInterceptor, "pre_get_environment_history") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = environment.GetEnvironmentHistoryRequest.pb(environment.GetEnvironmentHistoryRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = environment.EnvironmentHistory.to_json(environment.EnvironmentHistory()) - - request = environment.GetEnvironmentHistoryRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = environment.EnvironmentHistory() - - client.get_environment_history(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_get_environment_history_rest_bad_request(transport: str = 'rest', request_type=environment.GetEnvironmentHistoryRequest): - client = EnvironmentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1/agent/environments/sample2'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.get_environment_history(request) - - -def test_get_environment_history_rest_pager(transport: str = 'rest'): - client = EnvironmentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # TODO(kbandes): remove this mock unless there's a good reason for it. - #with mock.patch.object(path_template, 'transcode') as transcode: - # Set the response as a series of pages - response = ( - 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(), - ], - ), - ) - # Two responses for two calls - response = response + response - - # Wrap the values into proper Response objs - response = tuple(environment.EnvironmentHistory.to_json(x) for x in response) - return_values = tuple(Response() for i in response) - for return_val, response_val in zip(return_values, response): - return_val._content = response_val.encode('UTF-8') - return_val.status_code = 200 - req.side_effect = return_values - - sample_request = {'parent': 'projects/sample1/agent/environments/sample2'} - - pager = client.get_environment_history(request=sample_request) - - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, environment.EnvironmentHistory.Entry) - for i in results) - - pages = list(client.get_environment_history(request=sample_request).pages) - 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 an api_key and a transport instance. - transport = transports.EnvironmentsGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - options = client_options.ClientOptions() - options.api_key = "api_key" - with pytest.raises(ValueError): - client = EnvironmentsClient( - client_options=options, - transport=transport, - ) - - # It is an error to provide an api_key and a credential. - options = mock.Mock() - options.api_key = "api_key" - with pytest.raises(ValueError): - client = EnvironmentsClient( - client_options=options, - credentials=ga_credentials.AnonymousCredentials() - ) - - # 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, - transports.EnvironmentsRestTransport, -]) -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() - -@pytest.mark.parametrize("transport_name", [ - "grpc", - "rest", -]) -def test_transport_kind(transport_name): - transport = EnvironmentsClient.get_transport_class(transport_name)( - credentials=ga_credentials.AnonymousCredentials(), - ) - assert transport.kind == transport_name - -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', - 'get_location', - 'list_locations', - 'get_operation', - 'cancel_operation', - 'list_operations', - ) - for method in methods: - with pytest.raises(NotImplementedError): - getattr(transport, method)(request=object()) - - with pytest.raises(NotImplementedError): - transport.close() - - # Catch all for all remaining methods and properties - remainder = [ - 'kind', - ] - for r in remainder: - with pytest.raises(NotImplementedError): - getattr(transport, r)() - - -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", - ) - - -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() - - -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, - ) - - -@pytest.mark.parametrize( - "transport_class", - [ - transports.EnvironmentsGrpcTransport, - transports.EnvironmentsGrpcAsyncIOTransport, - ], -) -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, - transports.EnvironmentsRestTransport, - ], -) -def test_environments_transport_auth_gdch_credentials(transport_class): - host = 'https://language.com' - api_audience_tests = [None, 'https://language2.com'] - api_audience_expect = [host, 'https://language2.com'] - for t, e in zip(api_audience_tests, api_audience_expect): - with mock.patch.object(google.auth, 'default', autospec=True) as adc: - gdch_mock = mock.MagicMock() - type(gdch_mock).with_gdch_audience = mock.PropertyMock(return_value=gdch_mock) - adc.return_value = (gdch_mock, None) - transport_class(host=host, api_audience=t) - gdch_mock.with_gdch_audience.assert_called_once_with( - e - ) - - -@pytest.mark.parametrize( - "transport_class,grpc_helpers", - [ - (transports.EnvironmentsGrpcTransport, grpc_helpers), - (transports.EnvironmentsGrpcAsyncIOTransport, grpc_helpers_async) - ], -) -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", [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=None, - ssl_credentials=mock_ssl_channel_creds, - quota_project_id=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - # Check if ssl_channel_credentials is not provided, then client_cert_source_for_mtls - # is used. - with mock.patch.object(transport_class, "create_channel", return_value=mock.Mock()): - with mock.patch("grpc.ssl_channel_credentials") as mock_ssl_cred: - transport_class( - credentials=cred, - client_cert_source_for_mtls=client_cert_source_callback - ) - expected_cert, expected_key = client_cert_source_callback() - mock_ssl_cred.assert_called_once_with( - certificate_chain=expected_cert, - private_key=expected_key - ) - -def test_environments_http_transport_client_cert_source_for_mtls(): - cred = ga_credentials.AnonymousCredentials() - with mock.patch("google.auth.transport.requests.AuthorizedSession.configure_mtls_channel") as mock_configure_mtls_channel: - transports.EnvironmentsRestTransport ( - credentials=cred, - client_cert_source_for_mtls=client_cert_source_callback - ) - mock_configure_mtls_channel.assert_called_once_with(client_cert_source_callback) - - -@pytest.mark.parametrize("transport_name", [ - "grpc", - "grpc_asyncio", - "rest", -]) -def test_environments_host_no_port(transport_name): - client = EnvironmentsClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='dialogflow.googleapis.com'), - transport=transport_name, - ) - assert client.transport._host == ( - 'dialogflow.googleapis.com:443' - if transport_name in ['grpc', 'grpc_asyncio'] - else 'https://dialogflow.googleapis.com' - ) - -@pytest.mark.parametrize("transport_name", [ - "grpc", - "grpc_asyncio", - "rest", -]) -def test_environments_host_with_port(transport_name): - client = EnvironmentsClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='dialogflow.googleapis.com:8000'), - transport=transport_name, - ) - assert client.transport._host == ( - 'dialogflow.googleapis.com:8000' - if transport_name in ['grpc', 'grpc_asyncio'] - else 'https://dialogflow.googleapis.com:8000' - ) - -@pytest.mark.parametrize("transport_name", [ - "rest", -]) -def test_environments_client_transport_session_collision(transport_name): - creds1 = ga_credentials.AnonymousCredentials() - creds2 = ga_credentials.AnonymousCredentials() - client1 = EnvironmentsClient( - credentials=creds1, - transport=transport_name, - ) - client2 = EnvironmentsClient( - credentials=creds2, - transport=transport_name, - ) - session1 = client1.transport.list_environments._session - session2 = client2.transport.list_environments._session - assert session1 != session2 - session1 = client1.transport.get_environment._session - session2 = client2.transport.get_environment._session - assert session1 != session2 - session1 = client1.transport.create_environment._session - session2 = client2.transport.create_environment._session - assert session1 != session2 - session1 = client1.transport.update_environment._session - session2 = client2.transport.update_environment._session - assert session1 != session2 - session1 = client1.transport.delete_environment._session - session2 = client2.transport.delete_environment._session - assert session1 != session2 - session1 = client1.transport.get_environment_history._session - session2 = client2.transport.get_environment_history._session - assert session1 != session2 -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, - ) - assert transport.grpc_channel == channel - assert transport._host == "squid.clam.whelk:443" - assert transport._ssl_channel_credentials == None - - -def test_environments_grpc_asyncio_transport_channel(): - channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.EnvironmentsGrpcAsyncIOTransport( - 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.EnvironmentsGrpcTransport, transports.EnvironmentsGrpcAsyncIOTransport]) -def test_environments_transport_channel_mtls_with_client_cert_source( - transport_class -): - with mock.patch("grpc.ssl_channel_credentials", autospec=True) as grpc_ssl_channel_cred: - with mock.patch.object(transport_class, "create_channel") as grpc_create_channel: - mock_ssl_cred = mock.Mock() - grpc_ssl_channel_cred.return_value = mock_ssl_cred - - mock_grpc_channel = mock.Mock() - grpc_create_channel.return_value = mock_grpc_channel - - cred = ga_credentials.AnonymousCredentials() - with pytest.warns(DeprecationWarning): - with mock.patch.object(google.auth, 'default') as adc: - adc.return_value = (cred, None) - transport = transport_class( - host="squid.clam.whelk", - api_mtls_endpoint="mtls.squid.clam.whelk", - client_cert_source=client_cert_source_callback, - ) - adc.assert_called_once() - - grpc_ssl_channel_cred.assert_called_once_with( - certificate_chain=b"cert bytes", private_key=b"key bytes" - ) - grpc_create_channel.assert_called_once_with( - "mtls.squid.clam.whelk:443", - credentials=cred, - credentials_file=None, - scopes=None, - ssl_credentials=mock_ssl_cred, - quota_project_id=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - assert transport.grpc_channel == mock_grpc_channel - assert transport._ssl_channel_credentials == mock_ssl_cred - - -# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are -# removed from grpc/grpc_asyncio transport constructor. -@pytest.mark.parametrize("transport_class", [transports.EnvironmentsGrpcTransport, transports.EnvironmentsGrpcAsyncIOTransport]) -def test_environments_transport_channel_mtls_with_adc( - transport_class -): - mock_ssl_cred = mock.Mock() - with mock.patch.multiple( - "google.auth.transport.grpc.SslCredentials", - __init__=mock.Mock(return_value=None), - ssl_credentials=mock.PropertyMock(return_value=mock_ssl_cred), - ): - with mock.patch.object(transport_class, "create_channel") as grpc_create_channel: - mock_grpc_channel = mock.Mock() - grpc_create_channel.return_value = mock_grpc_channel - mock_cred = mock.Mock() - - with pytest.warns(DeprecationWarning): - transport = transport_class( - host="squid.clam.whelk", - credentials=mock_cred, - api_mtls_endpoint="mtls.squid.clam.whelk", - client_cert_source=None, - ) - - grpc_create_channel.assert_called_once_with( - "mtls.squid.clam.whelk:443", - credentials=mock_cred, - credentials_file=None, - scopes=None, - ssl_credentials=mock_ssl_cred, - quota_project_id=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - assert transport.grpc_channel == mock_grpc_channel - - -def test_environment_path(): - project = "squid" - environment = "clam" - expected = "projects/{project}/agent/environments/{environment}".format(project=project, environment=environment, ) - actual = EnvironmentsClient.environment_path(project, environment) - assert expected == actual - - -def test_parse_environment_path(): - expected = { - "project": "whelk", - "environment": "octopus", - } - path = EnvironmentsClient.environment_path(**expected) - - # Check that the path construction is reversible. - actual = EnvironmentsClient.parse_environment_path(path) - assert expected == actual - -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_version_path(): - project = "cuttlefish" - version = "mussel" - expected = "projects/{project}/agent/versions/{version}".format(project=project, version=version, ) - actual = EnvironmentsClient.version_path(project, version) - assert expected == actual - - -def test_parse_version_path(): - expected = { - "project": "winkle", - "version": "nautilus", - } - path = EnvironmentsClient.version_path(**expected) - - # Check that the path construction is reversible. - actual = EnvironmentsClient.parse_version_path(path) - assert expected == actual - -def test_common_billing_account_path(): - billing_account = "scallop" - expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) - actual = EnvironmentsClient.common_billing_account_path(billing_account) - assert expected == actual - - -def test_parse_common_billing_account_path(): - expected = { - "billing_account": "abalone", - } - path = EnvironmentsClient.common_billing_account_path(**expected) - - # Check that the path construction is reversible. - actual = EnvironmentsClient.parse_common_billing_account_path(path) - assert expected == actual - -def test_common_folder_path(): - folder = "squid" - expected = "folders/{folder}".format(folder=folder, ) - actual = EnvironmentsClient.common_folder_path(folder) - assert expected == actual - - -def test_parse_common_folder_path(): - expected = { - "folder": "clam", - } - path = EnvironmentsClient.common_folder_path(**expected) - - # Check that the path construction is reversible. - actual = EnvironmentsClient.parse_common_folder_path(path) - assert expected == actual - -def test_common_organization_path(): - organization = "whelk" - expected = "organizations/{organization}".format(organization=organization, ) - actual = EnvironmentsClient.common_organization_path(organization) - assert expected == actual - - -def test_parse_common_organization_path(): - expected = { - "organization": "octopus", - } - path = EnvironmentsClient.common_organization_path(**expected) - - # Check that the path construction is reversible. - actual = EnvironmentsClient.parse_common_organization_path(path) - assert expected == actual - -def test_common_project_path(): - project = "oyster" - expected = "projects/{project}".format(project=project, ) - actual = EnvironmentsClient.common_project_path(project) - assert expected == actual - - -def test_parse_common_project_path(): - expected = { - "project": "nudibranch", - } - path = EnvironmentsClient.common_project_path(**expected) - - # Check that the path construction is reversible. - actual = EnvironmentsClient.parse_common_project_path(path) - assert expected == actual - -def test_common_location_path(): - project = "cuttlefish" - location = "mussel" - expected = "projects/{project}/locations/{location}".format(project=project, location=location, ) - actual = EnvironmentsClient.common_location_path(project, location) - assert expected == actual - - -def test_parse_common_location_path(): - expected = { - "project": "winkle", - "location": "nautilus", - } - path = EnvironmentsClient.common_location_path(**expected) - - # Check that the path construction is reversible. - actual = EnvironmentsClient.parse_common_location_path(path) - assert expected == actual - - -def test_client_with_default_client_info(): - client_info = gapic_v1.client_info.ClientInfo() - - with mock.patch.object(transports.EnvironmentsTransport, '_prep_wrapped_messages') as prep: - client = EnvironmentsClient( - credentials=ga_credentials.AnonymousCredentials(), - client_info=client_info, - ) - prep.assert_called_once_with(client_info) - - with mock.patch.object(transports.EnvironmentsTransport, '_prep_wrapped_messages') as prep: - transport_class = EnvironmentsClient.get_transport_class() - transport = transport_class( - credentials=ga_credentials.AnonymousCredentials(), - client_info=client_info, - ) - prep.assert_called_once_with(client_info) - -@pytest.mark.asyncio -async def test_transport_close_async(): - client = EnvironmentsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - with mock.patch.object(type(getattr(client.transport, "grpc_channel")), "close") as close: - async with client: - close.assert_not_called() - close.assert_called_once() - - -def test_get_location_rest_bad_request(transport: str = 'rest', request_type=locations_pb2.GetLocationRequest): - client = EnvironmentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - request = request_type() - request = json_format.ParseDict({'name': 'projects/sample1/locations/sample2'}, request) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.get_location(request) - -@pytest.mark.parametrize("request_type", [ - locations_pb2.GetLocationRequest, - dict, -]) -def test_get_location_rest(request_type): - client = EnvironmentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request_init = {'name': 'projects/sample1/locations/sample2'} - request = request_type(**request_init) - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = locations_pb2.Location() - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.get_location(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, locations_pb2.Location) - -def test_list_locations_rest_bad_request(transport: str = 'rest', request_type=locations_pb2.ListLocationsRequest): - client = EnvironmentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - request = request_type() - request = json_format.ParseDict({'name': 'projects/sample1'}, request) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.list_locations(request) - -@pytest.mark.parametrize("request_type", [ - locations_pb2.ListLocationsRequest, - dict, -]) -def test_list_locations_rest(request_type): - client = EnvironmentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request_init = {'name': 'projects/sample1'} - request = request_type(**request_init) - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = locations_pb2.ListLocationsResponse() - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.list_locations(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, locations_pb2.ListLocationsResponse) - -def test_cancel_operation_rest_bad_request(transport: str = 'rest', request_type=operations_pb2.CancelOperationRequest): - client = EnvironmentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - request = request_type() - request = json_format.ParseDict({'name': 'projects/sample1/operations/sample2'}, request) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.cancel_operation(request) - -@pytest.mark.parametrize("request_type", [ - operations_pb2.CancelOperationRequest, - dict, -]) -def test_cancel_operation_rest(request_type): - client = EnvironmentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request_init = {'name': 'projects/sample1/operations/sample2'} - request = request_type(**request_init) - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = None - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = '{}' - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.cancel_operation(request) - - # Establish that the response is the type that we expect. - assert response is None - -def test_get_operation_rest_bad_request(transport: str = 'rest', request_type=operations_pb2.GetOperationRequest): - client = EnvironmentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - request = request_type() - request = json_format.ParseDict({'name': 'projects/sample1/operations/sample2'}, request) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.get_operation(request) - -@pytest.mark.parametrize("request_type", [ - operations_pb2.GetOperationRequest, - dict, -]) -def test_get_operation_rest(request_type): - client = EnvironmentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request_init = {'name': 'projects/sample1/operations/sample2'} - request = request_type(**request_init) - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation() - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.get_operation(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, operations_pb2.Operation) - -def test_list_operations_rest_bad_request(transport: str = 'rest', request_type=operations_pb2.ListOperationsRequest): - client = EnvironmentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - request = request_type() - request = json_format.ParseDict({'name': 'projects/sample1'}, request) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.list_operations(request) - -@pytest.mark.parametrize("request_type", [ - operations_pb2.ListOperationsRequest, - dict, -]) -def test_list_operations_rest(request_type): - client = EnvironmentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request_init = {'name': 'projects/sample1'} - request = request_type(**request_init) - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = operations_pb2.ListOperationsResponse() - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.list_operations(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, operations_pb2.ListOperationsResponse) - - -def test_cancel_operation(transport: str = "grpc"): - 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 = operations_pb2.CancelOperationRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = None - response = client.cancel_operation(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 response is the type that we expect. - assert response is None -@pytest.mark.asyncio -async def test_cancel_operation_async(transport: str = "grpc"): - 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 = operations_pb2.CancelOperationRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - None - ) - response = await client.cancel_operation(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 response is the type that we expect. - assert response is None - -def test_cancel_operation_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 = operations_pb2.CancelOperationRequest() - request.name = "locations" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call: - call.return_value = None - - client.cancel_operation(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=locations",) in kw["metadata"] -@pytest.mark.asyncio -async def test_cancel_operation_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 = operations_pb2.CancelOperationRequest() - request.name = "locations" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - None - ) - await client.cancel_operation(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=locations",) in kw["metadata"] - -def test_cancel_operation_from_dict(): - 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.cancel_operation), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = None - - response = client.cancel_operation( - request={ - "name": "locations", - } - ) - call.assert_called() -@pytest.mark.asyncio -async def test_cancel_operation_from_dict_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.cancel_operation), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - None - ) - response = await client.cancel_operation( - request={ - "name": "locations", - } - ) - call.assert_called() - - -def test_get_operation(transport: str = "grpc"): - 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 = operations_pb2.GetOperationRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_operation), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation() - response = client.get_operation(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 response is the type that we expect. - assert isinstance(response, operations_pb2.Operation) -@pytest.mark.asyncio -async def test_get_operation_async(transport: str = "grpc"): - 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 = operations_pb2.GetOperationRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_operation), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation() - ) - response = await client.get_operation(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 response is the type that we expect. - assert isinstance(response, operations_pb2.Operation) - -def test_get_operation_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 = operations_pb2.GetOperationRequest() - request.name = "locations" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_operation), "__call__") as call: - call.return_value = operations_pb2.Operation() - - client.get_operation(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=locations",) in kw["metadata"] -@pytest.mark.asyncio -async def test_get_operation_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 = operations_pb2.GetOperationRequest() - request.name = "locations" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_operation), "__call__") as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation() - ) - await client.get_operation(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=locations",) in kw["metadata"] - -def test_get_operation_from_dict(): - 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_operation), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation() - - response = client.get_operation( - request={ - "name": "locations", - } - ) - call.assert_called() -@pytest.mark.asyncio -async def test_get_operation_from_dict_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.get_operation), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation() - ) - response = await client.get_operation( - request={ - "name": "locations", - } - ) - call.assert_called() - - -def test_list_operations(transport: str = "grpc"): - 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 = operations_pb2.ListOperationsRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_operations), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.ListOperationsResponse() - response = client.list_operations(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 response is the type that we expect. - assert isinstance(response, operations_pb2.ListOperationsResponse) -@pytest.mark.asyncio -async def test_list_operations_async(transport: str = "grpc"): - 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 = operations_pb2.ListOperationsRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_operations), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.ListOperationsResponse() - ) - response = await client.list_operations(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 response is the type that we expect. - assert isinstance(response, operations_pb2.ListOperationsResponse) - -def test_list_operations_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 = operations_pb2.ListOperationsRequest() - request.name = "locations" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_operations), "__call__") as call: - call.return_value = operations_pb2.ListOperationsResponse() - - client.list_operations(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=locations",) in kw["metadata"] -@pytest.mark.asyncio -async def test_list_operations_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 = operations_pb2.ListOperationsRequest() - request.name = "locations" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_operations), "__call__") as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.ListOperationsResponse() - ) - await client.list_operations(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=locations",) in kw["metadata"] - -def test_list_operations_from_dict(): - 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_operations), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.ListOperationsResponse() - - response = client.list_operations( - request={ - "name": "locations", - } - ) - call.assert_called() -@pytest.mark.asyncio -async def test_list_operations_from_dict_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_operations), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.ListOperationsResponse() - ) - response = await client.list_operations( - request={ - "name": "locations", - } - ) - call.assert_called() - - -def test_list_locations(transport: str = "grpc"): - 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 = locations_pb2.ListLocationsRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_locations), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = locations_pb2.ListLocationsResponse() - response = client.list_locations(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 response is the type that we expect. - assert isinstance(response, locations_pb2.ListLocationsResponse) -@pytest.mark.asyncio -async def test_list_locations_async(transport: str = "grpc"): - 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 = locations_pb2.ListLocationsRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_locations), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - locations_pb2.ListLocationsResponse() - ) - response = await client.list_locations(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 response is the type that we expect. - assert isinstance(response, locations_pb2.ListLocationsResponse) - -def test_list_locations_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 = locations_pb2.ListLocationsRequest() - request.name = "locations" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_locations), "__call__") as call: - call.return_value = locations_pb2.ListLocationsResponse() - - client.list_locations(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=locations",) in kw["metadata"] -@pytest.mark.asyncio -async def test_list_locations_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 = locations_pb2.ListLocationsRequest() - request.name = "locations" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_locations), "__call__") as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - locations_pb2.ListLocationsResponse() - ) - await client.list_locations(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=locations",) in kw["metadata"] - -def test_list_locations_from_dict(): - 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_locations), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = locations_pb2.ListLocationsResponse() - - response = client.list_locations( - request={ - "name": "locations", - } - ) - call.assert_called() -@pytest.mark.asyncio -async def test_list_locations_from_dict_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_locations), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - locations_pb2.ListLocationsResponse() - ) - response = await client.list_locations( - request={ - "name": "locations", - } - ) - call.assert_called() - - -def test_get_location(transport: str = "grpc"): - 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 = locations_pb2.GetLocationRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_location), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = locations_pb2.Location() - response = client.get_location(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 response is the type that we expect. - assert isinstance(response, locations_pb2.Location) -@pytest.mark.asyncio -async def test_get_location_async(transport: str = "grpc_asyncio"): - 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 = locations_pb2.GetLocationRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_location), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - locations_pb2.Location() - ) - response = await client.get_location(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 response is the type that we expect. - assert isinstance(response, locations_pb2.Location) - -def test_get_location_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 = locations_pb2.GetLocationRequest() - request.name = "locations/abc" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_location), "__call__") as call: - call.return_value = locations_pb2.Location() - - client.get_location(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=locations/abc",) in kw["metadata"] -@pytest.mark.asyncio -async def test_get_location_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 = locations_pb2.GetLocationRequest() - request.name = "locations/abc" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_location), "__call__") as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - locations_pb2.Location() - ) - await client.get_location(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=locations/abc",) in kw["metadata"] - -def test_get_location_from_dict(): - 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_locations), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = locations_pb2.Location() - - response = client.get_location( - request={ - "name": "locations/abc", - } - ) - call.assert_called() -@pytest.mark.asyncio -async def test_get_location_from_dict_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_locations), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - locations_pb2.Location() - ) - response = await client.get_location( - request={ - "name": "locations", - } - ) - call.assert_called() - - -def test_transport_close(): - transports = { - "rest": "_session", - "grpc": "_grpc_channel", - } - - for transport, close_name in transports.items(): - client = EnvironmentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport - ) - with mock.patch.object(type(getattr(client.transport, close_name)), "close") as close: - with client: - close.assert_not_called() - close.assert_called_once() - -def test_client_ctx(): - transports = [ - 'rest', - 'grpc', - ] - for transport in transports: - client = EnvironmentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport - ) - # Test client calls underlying transport. - with mock.patch.object(type(client.transport), "close") as close: - close.assert_not_called() - with client: - pass - close.assert_called() - -@pytest.mark.parametrize("client_class,transport_class", [ - (EnvironmentsClient, transports.EnvironmentsGrpcTransport), - (EnvironmentsAsyncClient, transports.EnvironmentsGrpcAsyncIOTransport), -]) -def test_api_key_credentials(client_class, transport_class): - with mock.patch.object( - google.auth._default, "get_api_key_credentials", create=True - ) as get_api_key_credentials: - mock_cred = mock.Mock() - get_api_key_credentials.return_value = mock_cred - options = client_options.ClientOptions() - options.api_key = "api_key" - 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=mock_cred, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) diff --git a/owl-bot-staging/v2/tests/unit/gapic/dialogflow_v2/test_fulfillments.py b/owl-bot-staging/v2/tests/unit/gapic/dialogflow_v2/test_fulfillments.py deleted file mode 100644 index 46895dda3..000000000 --- a/owl-bot-staging/v2/tests/unit/gapic/dialogflow_v2/test_fulfillments.py +++ /dev/null @@ -1,3080 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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 -# try/except added for compatibility with python < 3.8 -try: - from unittest import mock - from unittest.mock import AsyncMock # pragma: NO COVER -except ImportError: # pragma: NO COVER - import mock - -import grpc -from grpc.experimental import aio -from collections.abc import Iterable -from google.protobuf import json_format -import json -import math -import pytest -from proto.marshal.rules.dates import DurationRule, TimestampRule -from proto.marshal.rules import wrappers -from requests import Response -from requests import Request, PreparedRequest -from requests.sessions import Session -from google.protobuf import json_format - -from google.api_core import client_options -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import grpc_helpers -from google.api_core import grpc_helpers_async -from google.api_core import path_template -from google.auth import credentials as ga_credentials -from google.auth.exceptions import MutualTLSChannelError -from google.cloud.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.types import fulfillment -from google.cloud.dialogflow_v2.types import fulfillment as gcd_fulfillment -from google.cloud.location import locations_pb2 -from google.longrunning import operations_pb2 -from google.oauth2 import service_account -from google.protobuf import field_mask_pb2 # type: ignore -import google.auth - - -def client_cert_source_callback(): - return b"cert bytes", b"key bytes" - - -# If default endpoint is localhost, then default mtls endpoint will be the same. -# This method modifies the default endpoint so the client can produce a different -# mtls endpoint for endpoint testing purposes. -def modify_default_endpoint(client): - return "foo.googleapis.com" if ("localhost" in client.DEFAULT_ENDPOINT) else client.DEFAULT_ENDPOINT - - -def test__get_default_mtls_endpoint(): - api_endpoint = "example.googleapis.com" - api_mtls_endpoint = "example.mtls.googleapis.com" - sandbox_endpoint = "example.sandbox.googleapis.com" - sandbox_mtls_endpoint = "example.mtls.sandbox.googleapis.com" - non_googleapi = "api.example.com" - - assert 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,transport_name", [ - (FulfillmentsClient, "grpc"), - (FulfillmentsAsyncClient, "grpc_asyncio"), - (FulfillmentsClient, "rest"), -]) -def test_fulfillments_client_from_service_account_info(client_class, transport_name): - 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, transport=transport_name) - assert client.transport._credentials == creds - assert isinstance(client, client_class) - - assert client.transport._host == ( - 'dialogflow.googleapis.com:443' - if transport_name in ['grpc', 'grpc_asyncio'] - else - 'https://dialogflow.googleapis.com' - ) - - -@pytest.mark.parametrize("transport_class,transport_name", [ - (transports.FulfillmentsGrpcTransport, "grpc"), - (transports.FulfillmentsGrpcAsyncIOTransport, "grpc_asyncio"), - (transports.FulfillmentsRestTransport, "rest"), -]) -def test_fulfillments_client_service_account_always_use_jwt(transport_class, transport_name): - with mock.patch.object(service_account.Credentials, 'with_always_use_jwt_access', create=True) as use_jwt: - creds = service_account.Credentials(None, None, None) - transport = transport_class(credentials=creds, always_use_jwt_access=True) - use_jwt.assert_called_once_with(True) - - with mock.patch.object(service_account.Credentials, 'with_always_use_jwt_access', create=True) as use_jwt: - creds = service_account.Credentials(None, None, None) - transport = transport_class(credentials=creds, always_use_jwt_access=False) - use_jwt.assert_not_called() - - -@pytest.mark.parametrize("client_class,transport_name", [ - (FulfillmentsClient, "grpc"), - (FulfillmentsAsyncClient, "grpc_asyncio"), - (FulfillmentsClient, "rest"), -]) -def test_fulfillments_client_from_service_account_file(client_class, transport_name): - 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", transport=transport_name) - assert client.transport._credentials == creds - assert isinstance(client, client_class) - - client = client_class.from_service_account_json("dummy/file/path.json", transport=transport_name) - assert client.transport._credentials == creds - assert isinstance(client, client_class) - - assert client.transport._host == ( - 'dialogflow.googleapis.com:443' - if transport_name in ['grpc', 'grpc_asyncio'] - else - 'https://dialogflow.googleapis.com' - ) - - -def test_fulfillments_client_get_transport_class(): - transport = FulfillmentsClient.get_transport_class() - available_transports = [ - transports.FulfillmentsGrpcTransport, - transports.FulfillmentsRestTransport, - ] - 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"), - (FulfillmentsClient, transports.FulfillmentsRestTransport, "rest"), -]) -@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(transport=transport_name, client_options=options) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host="squid.clam.whelk", - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is - # "never". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is - # "always". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_MTLS_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # 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(transport=transport_name) - - # 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(transport=transport_name) - - # 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, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id="octopus", - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - # Check the case api_endpoint is provided - options = client_options.ClientOptions(api_audience="https://language.googleapis.com") - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience="https://language.googleapis.com" - ) - -@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"), - (FulfillmentsClient, transports.FulfillmentsRestTransport, "rest", "true"), - (FulfillmentsClient, transports.FulfillmentsRestTransport, "rest", "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, transport=transport_name) - - if use_client_cert_env == "false": - expected_client_cert_source = None - expected_host = client.DEFAULT_ENDPOINT - else: - expected_client_cert_source = client_cert_source_callback - expected_host = client.DEFAULT_MTLS_ENDPOINT - - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=expected_host, - scopes=None, - client_cert_source_for_mtls=expected_client_cert_source, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case ADC client cert is provided. Whether client cert is used depends on - # GOOGLE_API_USE_CLIENT_CERTIFICATE value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): - with mock.patch.object(transport_class, '__init__') as patched: - with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): - with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=client_cert_source_callback): - if use_client_cert_env == "false": - expected_host = client.DEFAULT_ENDPOINT - expected_client_cert_source = None - else: - expected_host = client.DEFAULT_MTLS_ENDPOINT - expected_client_cert_source = client_cert_source_callback - - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=expected_host, - scopes=None, - client_cert_source_for_mtls=expected_client_cert_source, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case client_cert_source and ADC client cert are not provided. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): - with mock.patch.object(transport_class, '__init__') as patched: - with mock.patch("google.auth.transport.mtls.has_default_client_cert_source", return_value=False): - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - -@pytest.mark.parametrize("client_class", [ - FulfillmentsClient, FulfillmentsAsyncClient -]) -@mock.patch.object(FulfillmentsClient, "DEFAULT_ENDPOINT", modify_default_endpoint(FulfillmentsClient)) -@mock.patch.object(FulfillmentsAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(FulfillmentsAsyncClient)) -def test_fulfillments_client_get_mtls_endpoint_and_cert_source(client_class): - mock_client_cert_source = mock.Mock() - - # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "true". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - mock_api_endpoint = "foo" - options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) - assert api_endpoint == mock_api_endpoint - assert cert_source == mock_client_cert_source - - # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "false". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): - mock_client_cert_source = mock.Mock() - mock_api_endpoint = "foo" - options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) - assert api_endpoint == mock_api_endpoint - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "never". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_ENDPOINT - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "always". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert doesn't exist. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=False): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_ENDPOINT - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert exists. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - 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=mock_client_cert_source): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT - assert cert_source == mock_client_cert_source - - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (FulfillmentsClient, transports.FulfillmentsGrpcTransport, "grpc"), - (FulfillmentsAsyncClient, transports.FulfillmentsGrpcAsyncIOTransport, "grpc_asyncio"), - (FulfillmentsClient, transports.FulfillmentsRestTransport, "rest"), -]) -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, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=["1", "2"], - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - -@pytest.mark.parametrize("client_class,transport_class,transport_name,grpc_helpers", [ - (FulfillmentsClient, transports.FulfillmentsGrpcTransport, "grpc", grpc_helpers), - (FulfillmentsAsyncClient, transports.FulfillmentsGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), - (FulfillmentsClient, transports.FulfillmentsRestTransport, "rest", None), -]) -def test_fulfillments_client_client_options_credentials_file(client_class, transport_class, transport_name, grpc_helpers): - # 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, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file="credentials.json", - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - -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, - always_use_jwt_access=True, - api_audience=None, - ) - - -@pytest.mark.parametrize("client_class,transport_class,transport_name,grpc_helpers", [ - (FulfillmentsClient, transports.FulfillmentsGrpcTransport, "grpc", grpc_helpers), - (FulfillmentsAsyncClient, transports.FulfillmentsGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), -]) -def test_fulfillments_client_create_channel_credentials_file(client_class, transport_class, transport_name, grpc_helpers): - # 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, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file="credentials.json", - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # test that the credentials from file are saved and used as the credentials. - with mock.patch.object( - google.auth, "load_credentials_from_file", autospec=True - ) as load_creds, mock.patch.object( - google.auth, "default", autospec=True - ) as adc, mock.patch.object( - grpc_helpers, "create_channel" - ) as create_channel: - creds = ga_credentials.AnonymousCredentials() - file_creds = ga_credentials.AnonymousCredentials() - load_creds.return_value = (file_creds, None) - adc.return_value = (creds, None) - client = client_class(client_options=options, transport=transport_name) - create_channel.assert_called_with( - "dialogflow.googleapis.com:443", - credentials=file_creds, - credentials_file=None, - quota_project_id=None, - default_scopes=( - 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/dialogflow', -), - scopes=None, - default_host="dialogflow.googleapis.com", - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - -@pytest.mark.parametrize("request_type", [ - fulfillment.GetFulfillmentRequest, - dict, -]) -def test_get_fulfillment(request_type, transport: str = 'grpc'): - 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_empty_call(): - # 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] - arg = args[0].name - mock_val = 'name_value' - assert arg == mock_val - - -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] - arg = args[0].name - mock_val = 'name_value' - assert arg == mock_val - -@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', - ) - - -@pytest.mark.parametrize("request_type", [ - gcd_fulfillment.UpdateFulfillmentRequest, - dict, -]) -def test_update_fulfillment(request_type, transport: str = 'grpc'): - 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_empty_call(): - # 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 = '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=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 = '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=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] - arg = args[0].fulfillment - mock_val = gcd_fulfillment.Fulfillment(name='name_value') - assert arg == mock_val - arg = args[0].update_mask - mock_val = field_mask_pb2.FieldMask(paths=['paths_value']) - assert arg == mock_val - - -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] - arg = args[0].fulfillment - mock_val = gcd_fulfillment.Fulfillment(name='name_value') - assert arg == mock_val - arg = args[0].update_mask - mock_val = field_mask_pb2.FieldMask(paths=['paths_value']) - assert arg == mock_val - -@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']), - ) - - -@pytest.mark.parametrize("request_type", [ - fulfillment.GetFulfillmentRequest, - dict, -]) -def test_get_fulfillment_rest(request_type): - client = FulfillmentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/agent/fulfillment'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = fulfillment.Fulfillment( - name='name_value', - display_name='display_name_value', - enabled=True, - generic_web_service=fulfillment.Fulfillment.GenericWebService(uri='uri_value'), - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - pb_return_value = fulfillment.Fulfillment.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.get_fulfillment(request) - - # 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_rest_required_fields(request_type=fulfillment.GetFulfillmentRequest): - transport_class = transports.FulfillmentsRestTransport - - request_init = {} - request_init["name"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - including_default_value_fields=False, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_fulfillment._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["name"] = 'name_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_fulfillment._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "name" in jsonified_request - assert jsonified_request["name"] == 'name_value' - - client = FulfillmentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = fulfillment.Fulfillment() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "get", - 'query_params': pb_request, - } - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - - pb_return_value = fulfillment.Fulfillment.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.get_fulfillment(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_get_fulfillment_rest_unset_required_fields(): - transport = transports.FulfillmentsRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.get_fulfillment._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_get_fulfillment_rest_interceptors(null_interceptor): - transport = transports.FulfillmentsRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.FulfillmentsRestInterceptor(), - ) - client = FulfillmentsClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.FulfillmentsRestInterceptor, "post_get_fulfillment") as post, \ - mock.patch.object(transports.FulfillmentsRestInterceptor, "pre_get_fulfillment") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = fulfillment.GetFulfillmentRequest.pb(fulfillment.GetFulfillmentRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = fulfillment.Fulfillment.to_json(fulfillment.Fulfillment()) - - request = fulfillment.GetFulfillmentRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = fulfillment.Fulfillment() - - client.get_fulfillment(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_get_fulfillment_rest_bad_request(transport: str = 'rest', request_type=fulfillment.GetFulfillmentRequest): - client = FulfillmentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/agent/fulfillment'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.get_fulfillment(request) - - -def test_get_fulfillment_rest_flattened(): - client = FulfillmentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = fulfillment.Fulfillment() - - # get arguments that satisfy an http rule for this method - sample_request = {'name': 'projects/sample1/agent/fulfillment'} - - # get truthy value for each flattened field - mock_args = dict( - name='name_value', - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - pb_return_value = fulfillment.Fulfillment.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.get_fulfillment(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v2/{name=projects/*/agent/fulfillment}" % client.transport._host, args[1]) - - -def test_get_fulfillment_rest_flattened_error(transport: str = 'rest'): - client = FulfillmentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # 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', - ) - - -def test_get_fulfillment_rest_error(): - client = FulfillmentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - gcd_fulfillment.UpdateFulfillmentRequest, - dict, -]) -def test_update_fulfillment_rest(request_type): - client = FulfillmentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'fulfillment': {'name': 'projects/sample1/agent/fulfillment'}} - request_init["fulfillment"] = {'name': 'projects/sample1/agent/fulfillment', 'display_name': 'display_name_value', 'generic_web_service': {'uri': 'uri_value', 'username': 'username_value', 'password': 'password_value', 'request_headers': {}, 'is_cloud_function': True}, 'enabled': True, 'features': [{'type_': 1}]} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - 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'), - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - pb_return_value = gcd_fulfillment.Fulfillment.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.update_fulfillment(request) - - # 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_rest_required_fields(request_type=gcd_fulfillment.UpdateFulfillmentRequest): - transport_class = transports.FulfillmentsRestTransport - - request_init = {} - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - including_default_value_fields=False, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).update_fulfillment._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).update_fulfillment._get_unset_required_fields(jsonified_request) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("update_mask", )) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - - client = FulfillmentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = gcd_fulfillment.Fulfillment() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "patch", - 'query_params': pb_request, - } - transcode_result['body'] = pb_request - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - - pb_return_value = gcd_fulfillment.Fulfillment.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.update_fulfillment(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_update_fulfillment_rest_unset_required_fields(): - transport = transports.FulfillmentsRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.update_fulfillment._get_unset_required_fields({}) - assert set(unset_fields) == (set(("updateMask", )) & set(("fulfillment", "updateMask", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_update_fulfillment_rest_interceptors(null_interceptor): - transport = transports.FulfillmentsRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.FulfillmentsRestInterceptor(), - ) - client = FulfillmentsClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.FulfillmentsRestInterceptor, "post_update_fulfillment") as post, \ - mock.patch.object(transports.FulfillmentsRestInterceptor, "pre_update_fulfillment") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = gcd_fulfillment.UpdateFulfillmentRequest.pb(gcd_fulfillment.UpdateFulfillmentRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = gcd_fulfillment.Fulfillment.to_json(gcd_fulfillment.Fulfillment()) - - request = gcd_fulfillment.UpdateFulfillmentRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = gcd_fulfillment.Fulfillment() - - client.update_fulfillment(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_update_fulfillment_rest_bad_request(transport: str = 'rest', request_type=gcd_fulfillment.UpdateFulfillmentRequest): - client = FulfillmentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'fulfillment': {'name': 'projects/sample1/agent/fulfillment'}} - request_init["fulfillment"] = {'name': 'projects/sample1/agent/fulfillment', 'display_name': 'display_name_value', 'generic_web_service': {'uri': 'uri_value', 'username': 'username_value', 'password': 'password_value', 'request_headers': {}, 'is_cloud_function': True}, 'enabled': True, 'features': [{'type_': 1}]} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.update_fulfillment(request) - - -def test_update_fulfillment_rest_flattened(): - client = FulfillmentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = gcd_fulfillment.Fulfillment() - - # get arguments that satisfy an http rule for this method - sample_request = {'fulfillment': {'name': 'projects/sample1/agent/fulfillment'}} - - # get truthy value for each flattened field - mock_args = dict( - fulfillment=gcd_fulfillment.Fulfillment(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - pb_return_value = gcd_fulfillment.Fulfillment.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.update_fulfillment(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v2/{fulfillment.name=projects/*/agent/fulfillment}" % client.transport._host, args[1]) - - -def test_update_fulfillment_rest_flattened_error(transport: str = 'rest'): - client = FulfillmentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # 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']), - ) - - -def test_update_fulfillment_rest_error(): - client = FulfillmentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -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 an api_key and a transport instance. - transport = transports.FulfillmentsGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - options = client_options.ClientOptions() - options.api_key = "api_key" - with pytest.raises(ValueError): - client = FulfillmentsClient( - client_options=options, - transport=transport, - ) - - # It is an error to provide an api_key and a credential. - options = mock.Mock() - options.api_key = "api_key" - with pytest.raises(ValueError): - client = FulfillmentsClient( - client_options=options, - credentials=ga_credentials.AnonymousCredentials() - ) - - # 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, - transports.FulfillmentsRestTransport, -]) -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() - -@pytest.mark.parametrize("transport_name", [ - "grpc", - "rest", -]) -def test_transport_kind(transport_name): - transport = FulfillmentsClient.get_transport_class(transport_name)( - credentials=ga_credentials.AnonymousCredentials(), - ) - assert transport.kind == transport_name - -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', - 'get_location', - 'list_locations', - 'get_operation', - 'cancel_operation', - 'list_operations', - ) - for method in methods: - with pytest.raises(NotImplementedError): - getattr(transport, method)(request=object()) - - with pytest.raises(NotImplementedError): - transport.close() - - # Catch all for all remaining methods and properties - remainder = [ - 'kind', - ] - for r in remainder: - with pytest.raises(NotImplementedError): - getattr(transport, r)() - - -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", - ) - - -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() - - -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, - ) - - -@pytest.mark.parametrize( - "transport_class", - [ - transports.FulfillmentsGrpcTransport, - transports.FulfillmentsGrpcAsyncIOTransport, - ], -) -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, - transports.FulfillmentsRestTransport, - ], -) -def test_fulfillments_transport_auth_gdch_credentials(transport_class): - host = 'https://language.com' - api_audience_tests = [None, 'https://language2.com'] - api_audience_expect = [host, 'https://language2.com'] - for t, e in zip(api_audience_tests, api_audience_expect): - with mock.patch.object(google.auth, 'default', autospec=True) as adc: - gdch_mock = mock.MagicMock() - type(gdch_mock).with_gdch_audience = mock.PropertyMock(return_value=gdch_mock) - adc.return_value = (gdch_mock, None) - transport_class(host=host, api_audience=t) - gdch_mock.with_gdch_audience.assert_called_once_with( - e - ) - - -@pytest.mark.parametrize( - "transport_class,grpc_helpers", - [ - (transports.FulfillmentsGrpcTransport, grpc_helpers), - (transports.FulfillmentsGrpcAsyncIOTransport, grpc_helpers_async) - ], -) -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", [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=None, - ssl_credentials=mock_ssl_channel_creds, - quota_project_id=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - # Check if ssl_channel_credentials is not provided, then client_cert_source_for_mtls - # is used. - with mock.patch.object(transport_class, "create_channel", return_value=mock.Mock()): - with mock.patch("grpc.ssl_channel_credentials") as mock_ssl_cred: - transport_class( - credentials=cred, - client_cert_source_for_mtls=client_cert_source_callback - ) - expected_cert, expected_key = client_cert_source_callback() - mock_ssl_cred.assert_called_once_with( - certificate_chain=expected_cert, - private_key=expected_key - ) - -def test_fulfillments_http_transport_client_cert_source_for_mtls(): - cred = ga_credentials.AnonymousCredentials() - with mock.patch("google.auth.transport.requests.AuthorizedSession.configure_mtls_channel") as mock_configure_mtls_channel: - transports.FulfillmentsRestTransport ( - credentials=cred, - client_cert_source_for_mtls=client_cert_source_callback - ) - mock_configure_mtls_channel.assert_called_once_with(client_cert_source_callback) - - -@pytest.mark.parametrize("transport_name", [ - "grpc", - "grpc_asyncio", - "rest", -]) -def test_fulfillments_host_no_port(transport_name): - client = FulfillmentsClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='dialogflow.googleapis.com'), - transport=transport_name, - ) - assert client.transport._host == ( - 'dialogflow.googleapis.com:443' - if transport_name in ['grpc', 'grpc_asyncio'] - else 'https://dialogflow.googleapis.com' - ) - -@pytest.mark.parametrize("transport_name", [ - "grpc", - "grpc_asyncio", - "rest", -]) -def test_fulfillments_host_with_port(transport_name): - client = FulfillmentsClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='dialogflow.googleapis.com:8000'), - transport=transport_name, - ) - assert client.transport._host == ( - 'dialogflow.googleapis.com:8000' - if transport_name in ['grpc', 'grpc_asyncio'] - else 'https://dialogflow.googleapis.com:8000' - ) - -@pytest.mark.parametrize("transport_name", [ - "rest", -]) -def test_fulfillments_client_transport_session_collision(transport_name): - creds1 = ga_credentials.AnonymousCredentials() - creds2 = ga_credentials.AnonymousCredentials() - client1 = FulfillmentsClient( - credentials=creds1, - transport=transport_name, - ) - client2 = FulfillmentsClient( - credentials=creds2, - transport=transport_name, - ) - session1 = client1.transport.get_fulfillment._session - session2 = client2.transport.get_fulfillment._session - assert session1 != session2 - session1 = client1.transport.update_fulfillment._session - session2 = client2.transport.update_fulfillment._session - assert session1 != session2 -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=None, - ssl_credentials=mock_ssl_cred, - quota_project_id=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - assert transport.grpc_channel == mock_grpc_channel - assert transport._ssl_channel_credentials == mock_ssl_cred - - -# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are -# removed from grpc/grpc_asyncio transport constructor. -@pytest.mark.parametrize("transport_class", [transports.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=None, - ssl_credentials=mock_ssl_cred, - quota_project_id=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - assert transport.grpc_channel == mock_grpc_channel - - -def test_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_with_default_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) - -@pytest.mark.asyncio -async def test_transport_close_async(): - client = FulfillmentsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - with mock.patch.object(type(getattr(client.transport, "grpc_channel")), "close") as close: - async with client: - close.assert_not_called() - close.assert_called_once() - - -def test_get_location_rest_bad_request(transport: str = 'rest', request_type=locations_pb2.GetLocationRequest): - client = FulfillmentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - request = request_type() - request = json_format.ParseDict({'name': 'projects/sample1/locations/sample2'}, request) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.get_location(request) - -@pytest.mark.parametrize("request_type", [ - locations_pb2.GetLocationRequest, - dict, -]) -def test_get_location_rest(request_type): - client = FulfillmentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request_init = {'name': 'projects/sample1/locations/sample2'} - request = request_type(**request_init) - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = locations_pb2.Location() - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.get_location(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, locations_pb2.Location) - -def test_list_locations_rest_bad_request(transport: str = 'rest', request_type=locations_pb2.ListLocationsRequest): - client = FulfillmentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - request = request_type() - request = json_format.ParseDict({'name': 'projects/sample1'}, request) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.list_locations(request) - -@pytest.mark.parametrize("request_type", [ - locations_pb2.ListLocationsRequest, - dict, -]) -def test_list_locations_rest(request_type): - client = FulfillmentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request_init = {'name': 'projects/sample1'} - request = request_type(**request_init) - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = locations_pb2.ListLocationsResponse() - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.list_locations(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, locations_pb2.ListLocationsResponse) - -def test_cancel_operation_rest_bad_request(transport: str = 'rest', request_type=operations_pb2.CancelOperationRequest): - client = FulfillmentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - request = request_type() - request = json_format.ParseDict({'name': 'projects/sample1/operations/sample2'}, request) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.cancel_operation(request) - -@pytest.mark.parametrize("request_type", [ - operations_pb2.CancelOperationRequest, - dict, -]) -def test_cancel_operation_rest(request_type): - client = FulfillmentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request_init = {'name': 'projects/sample1/operations/sample2'} - request = request_type(**request_init) - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = None - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = '{}' - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.cancel_operation(request) - - # Establish that the response is the type that we expect. - assert response is None - -def test_get_operation_rest_bad_request(transport: str = 'rest', request_type=operations_pb2.GetOperationRequest): - client = FulfillmentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - request = request_type() - request = json_format.ParseDict({'name': 'projects/sample1/operations/sample2'}, request) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.get_operation(request) - -@pytest.mark.parametrize("request_type", [ - operations_pb2.GetOperationRequest, - dict, -]) -def test_get_operation_rest(request_type): - client = FulfillmentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request_init = {'name': 'projects/sample1/operations/sample2'} - request = request_type(**request_init) - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation() - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.get_operation(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, operations_pb2.Operation) - -def test_list_operations_rest_bad_request(transport: str = 'rest', request_type=operations_pb2.ListOperationsRequest): - client = FulfillmentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - request = request_type() - request = json_format.ParseDict({'name': 'projects/sample1'}, request) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.list_operations(request) - -@pytest.mark.parametrize("request_type", [ - operations_pb2.ListOperationsRequest, - dict, -]) -def test_list_operations_rest(request_type): - client = FulfillmentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request_init = {'name': 'projects/sample1'} - request = request_type(**request_init) - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = operations_pb2.ListOperationsResponse() - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.list_operations(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, operations_pb2.ListOperationsResponse) - - -def test_cancel_operation(transport: str = "grpc"): - 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 = operations_pb2.CancelOperationRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = None - response = client.cancel_operation(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 response is the type that we expect. - assert response is None -@pytest.mark.asyncio -async def test_cancel_operation_async(transport: str = "grpc"): - 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 = operations_pb2.CancelOperationRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - None - ) - response = await client.cancel_operation(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 response is the type that we expect. - assert response is None - -def test_cancel_operation_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 = operations_pb2.CancelOperationRequest() - request.name = "locations" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call: - call.return_value = None - - client.cancel_operation(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=locations",) in kw["metadata"] -@pytest.mark.asyncio -async def test_cancel_operation_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 = operations_pb2.CancelOperationRequest() - request.name = "locations" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - None - ) - await client.cancel_operation(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=locations",) in kw["metadata"] - -def test_cancel_operation_from_dict(): - 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.cancel_operation), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = None - - response = client.cancel_operation( - request={ - "name": "locations", - } - ) - call.assert_called() -@pytest.mark.asyncio -async def test_cancel_operation_from_dict_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.cancel_operation), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - None - ) - response = await client.cancel_operation( - request={ - "name": "locations", - } - ) - call.assert_called() - - -def test_get_operation(transport: str = "grpc"): - 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 = operations_pb2.GetOperationRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_operation), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation() - response = client.get_operation(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 response is the type that we expect. - assert isinstance(response, operations_pb2.Operation) -@pytest.mark.asyncio -async def test_get_operation_async(transport: str = "grpc"): - 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 = operations_pb2.GetOperationRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_operation), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation() - ) - response = await client.get_operation(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 response is the type that we expect. - assert isinstance(response, operations_pb2.Operation) - -def test_get_operation_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 = operations_pb2.GetOperationRequest() - request.name = "locations" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_operation), "__call__") as call: - call.return_value = operations_pb2.Operation() - - client.get_operation(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=locations",) in kw["metadata"] -@pytest.mark.asyncio -async def test_get_operation_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 = operations_pb2.GetOperationRequest() - request.name = "locations" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_operation), "__call__") as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation() - ) - await client.get_operation(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=locations",) in kw["metadata"] - -def test_get_operation_from_dict(): - 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_operation), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation() - - response = client.get_operation( - request={ - "name": "locations", - } - ) - call.assert_called() -@pytest.mark.asyncio -async def test_get_operation_from_dict_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_operation), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation() - ) - response = await client.get_operation( - request={ - "name": "locations", - } - ) - call.assert_called() - - -def test_list_operations(transport: str = "grpc"): - 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 = operations_pb2.ListOperationsRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_operations), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.ListOperationsResponse() - response = client.list_operations(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 response is the type that we expect. - assert isinstance(response, operations_pb2.ListOperationsResponse) -@pytest.mark.asyncio -async def test_list_operations_async(transport: str = "grpc"): - 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 = operations_pb2.ListOperationsRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_operations), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.ListOperationsResponse() - ) - response = await client.list_operations(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 response is the type that we expect. - assert isinstance(response, operations_pb2.ListOperationsResponse) - -def test_list_operations_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 = operations_pb2.ListOperationsRequest() - request.name = "locations" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_operations), "__call__") as call: - call.return_value = operations_pb2.ListOperationsResponse() - - client.list_operations(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=locations",) in kw["metadata"] -@pytest.mark.asyncio -async def test_list_operations_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 = operations_pb2.ListOperationsRequest() - request.name = "locations" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_operations), "__call__") as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.ListOperationsResponse() - ) - await client.list_operations(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=locations",) in kw["metadata"] - -def test_list_operations_from_dict(): - 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.list_operations), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.ListOperationsResponse() - - response = client.list_operations( - request={ - "name": "locations", - } - ) - call.assert_called() -@pytest.mark.asyncio -async def test_list_operations_from_dict_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.list_operations), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.ListOperationsResponse() - ) - response = await client.list_operations( - request={ - "name": "locations", - } - ) - call.assert_called() - - -def test_list_locations(transport: str = "grpc"): - 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 = locations_pb2.ListLocationsRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_locations), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = locations_pb2.ListLocationsResponse() - response = client.list_locations(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 response is the type that we expect. - assert isinstance(response, locations_pb2.ListLocationsResponse) -@pytest.mark.asyncio -async def test_list_locations_async(transport: str = "grpc"): - 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 = locations_pb2.ListLocationsRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_locations), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - locations_pb2.ListLocationsResponse() - ) - response = await client.list_locations(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 response is the type that we expect. - assert isinstance(response, locations_pb2.ListLocationsResponse) - -def test_list_locations_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 = locations_pb2.ListLocationsRequest() - request.name = "locations" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_locations), "__call__") as call: - call.return_value = locations_pb2.ListLocationsResponse() - - client.list_locations(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=locations",) in kw["metadata"] -@pytest.mark.asyncio -async def test_list_locations_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 = locations_pb2.ListLocationsRequest() - request.name = "locations" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_locations), "__call__") as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - locations_pb2.ListLocationsResponse() - ) - await client.list_locations(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=locations",) in kw["metadata"] - -def test_list_locations_from_dict(): - 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.list_locations), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = locations_pb2.ListLocationsResponse() - - response = client.list_locations( - request={ - "name": "locations", - } - ) - call.assert_called() -@pytest.mark.asyncio -async def test_list_locations_from_dict_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.list_locations), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - locations_pb2.ListLocationsResponse() - ) - response = await client.list_locations( - request={ - "name": "locations", - } - ) - call.assert_called() - - -def test_get_location(transport: str = "grpc"): - 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 = locations_pb2.GetLocationRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_location), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = locations_pb2.Location() - response = client.get_location(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 response is the type that we expect. - assert isinstance(response, locations_pb2.Location) -@pytest.mark.asyncio -async def test_get_location_async(transport: str = "grpc_asyncio"): - 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 = locations_pb2.GetLocationRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_location), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - locations_pb2.Location() - ) - response = await client.get_location(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 response is the type that we expect. - assert isinstance(response, locations_pb2.Location) - -def test_get_location_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 = locations_pb2.GetLocationRequest() - request.name = "locations/abc" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_location), "__call__") as call: - call.return_value = locations_pb2.Location() - - client.get_location(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=locations/abc",) in kw["metadata"] -@pytest.mark.asyncio -async def test_get_location_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 = locations_pb2.GetLocationRequest() - request.name = "locations/abc" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_location), "__call__") as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - locations_pb2.Location() - ) - await client.get_location(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=locations/abc",) in kw["metadata"] - -def test_get_location_from_dict(): - 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.list_locations), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = locations_pb2.Location() - - response = client.get_location( - request={ - "name": "locations/abc", - } - ) - call.assert_called() -@pytest.mark.asyncio -async def test_get_location_from_dict_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.list_locations), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - locations_pb2.Location() - ) - response = await client.get_location( - request={ - "name": "locations", - } - ) - call.assert_called() - - -def test_transport_close(): - transports = { - "rest": "_session", - "grpc": "_grpc_channel", - } - - for transport, close_name in transports.items(): - client = FulfillmentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport - ) - with mock.patch.object(type(getattr(client.transport, close_name)), "close") as close: - with client: - close.assert_not_called() - close.assert_called_once() - -def test_client_ctx(): - transports = [ - 'rest', - 'grpc', - ] - for transport in transports: - client = FulfillmentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport - ) - # Test client calls underlying transport. - with mock.patch.object(type(client.transport), "close") as close: - close.assert_not_called() - with client: - pass - close.assert_called() - -@pytest.mark.parametrize("client_class,transport_class", [ - (FulfillmentsClient, transports.FulfillmentsGrpcTransport), - (FulfillmentsAsyncClient, transports.FulfillmentsGrpcAsyncIOTransport), -]) -def test_api_key_credentials(client_class, transport_class): - with mock.patch.object( - google.auth._default, "get_api_key_credentials", create=True - ) as get_api_key_credentials: - mock_cred = mock.Mock() - get_api_key_credentials.return_value = mock_cred - options = client_options.ClientOptions() - options.api_key = "api_key" - 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=mock_cred, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) diff --git a/owl-bot-staging/v2/tests/unit/gapic/dialogflow_v2/test_intents.py b/owl-bot-staging/v2/tests/unit/gapic/dialogflow_v2/test_intents.py deleted file mode 100644 index c2c6cff2e..000000000 --- a/owl-bot-staging/v2/tests/unit/gapic/dialogflow_v2/test_intents.py +++ /dev/null @@ -1,6040 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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 -# try/except added for compatibility with python < 3.8 -try: - from unittest import mock - from unittest.mock import AsyncMock # pragma: NO COVER -except ImportError: # pragma: NO COVER - import mock - -import grpc -from grpc.experimental import aio -from collections.abc import Iterable -from google.protobuf import json_format -import json -import math -import pytest -from proto.marshal.rules.dates import DurationRule, TimestampRule -from proto.marshal.rules import wrappers -from requests import Response -from requests import Request, PreparedRequest -from requests.sessions import Session -from google.protobuf import json_format - -from google.api_core import client_options -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 -from google.api_core import operation_async # type: ignore -from google.api_core import operations_v1 -from google.api_core import path_template -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.types import context -from google.cloud.dialogflow_v2.types import intent -from google.cloud.dialogflow_v2.types import intent as gcd_intent -from google.cloud.location import locations_pb2 -from google.longrunning import operations_pb2 -from google.oauth2 import service_account -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 -import google.auth - - -def client_cert_source_callback(): - return b"cert bytes", b"key bytes" - - -# If default endpoint is localhost, then default mtls endpoint will be the same. -# This method modifies the default endpoint so the client can produce a different -# mtls endpoint for endpoint testing purposes. -def modify_default_endpoint(client): - return "foo.googleapis.com" if ("localhost" in client.DEFAULT_ENDPOINT) else client.DEFAULT_ENDPOINT - - -def test__get_default_mtls_endpoint(): - api_endpoint = "example.googleapis.com" - api_mtls_endpoint = "example.mtls.googleapis.com" - sandbox_endpoint = "example.sandbox.googleapis.com" - sandbox_mtls_endpoint = "example.mtls.sandbox.googleapis.com" - non_googleapi = "api.example.com" - - assert IntentsClient._get_default_mtls_endpoint(None) is None - assert IntentsClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint - assert IntentsClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint - assert IntentsClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint - assert IntentsClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint - assert IntentsClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi - - -@pytest.mark.parametrize("client_class,transport_name", [ - (IntentsClient, "grpc"), - (IntentsAsyncClient, "grpc_asyncio"), - (IntentsClient, "rest"), -]) -def test_intents_client_from_service_account_info(client_class, transport_name): - 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, transport=transport_name) - assert client.transport._credentials == creds - assert isinstance(client, client_class) - - assert client.transport._host == ( - 'dialogflow.googleapis.com:443' - if transport_name in ['grpc', 'grpc_asyncio'] - else - 'https://dialogflow.googleapis.com' - ) - - -@pytest.mark.parametrize("transport_class,transport_name", [ - (transports.IntentsGrpcTransport, "grpc"), - (transports.IntentsGrpcAsyncIOTransport, "grpc_asyncio"), - (transports.IntentsRestTransport, "rest"), -]) -def test_intents_client_service_account_always_use_jwt(transport_class, transport_name): - with mock.patch.object(service_account.Credentials, 'with_always_use_jwt_access', create=True) as use_jwt: - creds = service_account.Credentials(None, None, None) - transport = transport_class(credentials=creds, always_use_jwt_access=True) - use_jwt.assert_called_once_with(True) - - with mock.patch.object(service_account.Credentials, 'with_always_use_jwt_access', create=True) as use_jwt: - creds = service_account.Credentials(None, None, None) - transport = transport_class(credentials=creds, always_use_jwt_access=False) - use_jwt.assert_not_called() - - -@pytest.mark.parametrize("client_class,transport_name", [ - (IntentsClient, "grpc"), - (IntentsAsyncClient, "grpc_asyncio"), - (IntentsClient, "rest"), -]) -def test_intents_client_from_service_account_file(client_class, transport_name): - 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", transport=transport_name) - assert client.transport._credentials == creds - assert isinstance(client, client_class) - - client = client_class.from_service_account_json("dummy/file/path.json", transport=transport_name) - assert client.transport._credentials == creds - assert isinstance(client, client_class) - - assert client.transport._host == ( - 'dialogflow.googleapis.com:443' - if transport_name in ['grpc', 'grpc_asyncio'] - else - 'https://dialogflow.googleapis.com' - ) - - -def test_intents_client_get_transport_class(): - transport = IntentsClient.get_transport_class() - available_transports = [ - transports.IntentsGrpcTransport, - transports.IntentsRestTransport, - ] - assert transport in available_transports - - transport = IntentsClient.get_transport_class("grpc") - assert transport == transports.IntentsGrpcTransport - - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (IntentsClient, transports.IntentsGrpcTransport, "grpc"), - (IntentsAsyncClient, transports.IntentsGrpcAsyncIOTransport, "grpc_asyncio"), - (IntentsClient, transports.IntentsRestTransport, "rest"), -]) -@mock.patch.object(IntentsClient, "DEFAULT_ENDPOINT", modify_default_endpoint(IntentsClient)) -@mock.patch.object(IntentsAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(IntentsAsyncClient)) -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=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(IntentsClient, 'get_transport_class') as gtc: - client = client_class(transport=transport_name) - gtc.assert_called() - - # Check the case api_endpoint is provided. - options = client_options.ClientOptions(api_endpoint="squid.clam.whelk") - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(transport=transport_name, client_options=options) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host="squid.clam.whelk", - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is - # "never". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is - # "always". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_MTLS_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # 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(transport=transport_name) - - # 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(transport=transport_name) - - # 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, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id="octopus", - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - # Check the case api_endpoint is provided - options = client_options.ClientOptions(api_audience="https://language.googleapis.com") - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience="https://language.googleapis.com" - ) - -@pytest.mark.parametrize("client_class,transport_class,transport_name,use_client_cert_env", [ - (IntentsClient, transports.IntentsGrpcTransport, "grpc", "true"), - (IntentsAsyncClient, transports.IntentsGrpcAsyncIOTransport, "grpc_asyncio", "true"), - (IntentsClient, transports.IntentsGrpcTransport, "grpc", "false"), - (IntentsAsyncClient, transports.IntentsGrpcAsyncIOTransport, "grpc_asyncio", "false"), - (IntentsClient, transports.IntentsRestTransport, "rest", "true"), - (IntentsClient, transports.IntentsRestTransport, "rest", "false"), -]) -@mock.patch.object(IntentsClient, "DEFAULT_ENDPOINT", modify_default_endpoint(IntentsClient)) -@mock.patch.object(IntentsAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(IntentsAsyncClient)) -@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) -def test_intents_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, transport=transport_name) - - if use_client_cert_env == "false": - expected_client_cert_source = None - expected_host = client.DEFAULT_ENDPOINT - else: - expected_client_cert_source = client_cert_source_callback - expected_host = client.DEFAULT_MTLS_ENDPOINT - - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=expected_host, - scopes=None, - client_cert_source_for_mtls=expected_client_cert_source, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case ADC client cert is provided. Whether client cert is used depends on - # GOOGLE_API_USE_CLIENT_CERTIFICATE value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): - with mock.patch.object(transport_class, '__init__') as patched: - with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): - with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=client_cert_source_callback): - if use_client_cert_env == "false": - expected_host = client.DEFAULT_ENDPOINT - expected_client_cert_source = None - else: - expected_host = client.DEFAULT_MTLS_ENDPOINT - expected_client_cert_source = client_cert_source_callback - - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=expected_host, - scopes=None, - client_cert_source_for_mtls=expected_client_cert_source, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case client_cert_source and ADC client cert are not provided. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): - with mock.patch.object(transport_class, '__init__') as patched: - with mock.patch("google.auth.transport.mtls.has_default_client_cert_source", return_value=False): - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - -@pytest.mark.parametrize("client_class", [ - IntentsClient, IntentsAsyncClient -]) -@mock.patch.object(IntentsClient, "DEFAULT_ENDPOINT", modify_default_endpoint(IntentsClient)) -@mock.patch.object(IntentsAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(IntentsAsyncClient)) -def test_intents_client_get_mtls_endpoint_and_cert_source(client_class): - mock_client_cert_source = mock.Mock() - - # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "true". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - mock_api_endpoint = "foo" - options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) - assert api_endpoint == mock_api_endpoint - assert cert_source == mock_client_cert_source - - # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "false". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): - mock_client_cert_source = mock.Mock() - mock_api_endpoint = "foo" - options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) - assert api_endpoint == mock_api_endpoint - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "never". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_ENDPOINT - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "always". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert doesn't exist. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=False): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_ENDPOINT - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert exists. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - 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=mock_client_cert_source): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT - assert cert_source == mock_client_cert_source - - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (IntentsClient, transports.IntentsGrpcTransport, "grpc"), - (IntentsAsyncClient, transports.IntentsGrpcAsyncIOTransport, "grpc_asyncio"), - (IntentsClient, transports.IntentsRestTransport, "rest"), -]) -def test_intents_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, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=["1", "2"], - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - -@pytest.mark.parametrize("client_class,transport_class,transport_name,grpc_helpers", [ - (IntentsClient, transports.IntentsGrpcTransport, "grpc", grpc_helpers), - (IntentsAsyncClient, transports.IntentsGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), - (IntentsClient, transports.IntentsRestTransport, "rest", None), -]) -def test_intents_client_client_options_credentials_file(client_class, transport_class, transport_name, grpc_helpers): - # 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, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file="credentials.json", - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - -def test_intents_client_client_options_from_dict(): - with mock.patch('google.cloud.dialogflow_v2.services.intents.transports.IntentsGrpcTransport.__init__') as grpc_transport: - grpc_transport.return_value = None - client = IntentsClient( - client_options={'api_endpoint': 'squid.clam.whelk'} - ) - grpc_transport.assert_called_once_with( - credentials=None, - credentials_file=None, - host="squid.clam.whelk", - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - -@pytest.mark.parametrize("client_class,transport_class,transport_name,grpc_helpers", [ - (IntentsClient, transports.IntentsGrpcTransport, "grpc", grpc_helpers), - (IntentsAsyncClient, transports.IntentsGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), -]) -def test_intents_client_create_channel_credentials_file(client_class, transport_class, transport_name, grpc_helpers): - # 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, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file="credentials.json", - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # test that the credentials from file are saved and used as the credentials. - with mock.patch.object( - google.auth, "load_credentials_from_file", autospec=True - ) as load_creds, mock.patch.object( - google.auth, "default", autospec=True - ) as adc, mock.patch.object( - grpc_helpers, "create_channel" - ) as create_channel: - creds = ga_credentials.AnonymousCredentials() - file_creds = ga_credentials.AnonymousCredentials() - load_creds.return_value = (file_creds, None) - adc.return_value = (creds, None) - client = client_class(client_options=options, transport=transport_name) - create_channel.assert_called_with( - "dialogflow.googleapis.com:443", - credentials=file_creds, - credentials_file=None, - quota_project_id=None, - default_scopes=( - 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/dialogflow', -), - scopes=None, - default_host="dialogflow.googleapis.com", - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - -@pytest.mark.parametrize("request_type", [ - intent.ListIntentsRequest, - dict, -]) -def test_list_intents(request_type, transport: str = 'grpc'): - client = IntentsClient( - 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_intents), - '__call__') as call: - # Designate an appropriate return value for the call. - 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' - - -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=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_intents), - '__call__') as call: - client.list_intents() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == intent.ListIntentsRequest() - -@pytest.mark.asyncio -async def test_list_intents_async(transport: str = 'grpc_asyncio', request_type=intent.ListIntentsRequest): - client = IntentsAsyncClient( - 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_intents), - '__call__') as call: - # Designate an appropriate return value for the call. - 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' - - -@pytest.mark.asyncio -async def test_list_intents_async_from_dict(): - await test_list_intents_async(request_type=dict) - - -def test_list_intents_field_headers(): - 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. - 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_intents_field_headers_async(): - 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. - with mock.patch.object( - type(client.transport.list_intents), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(intent.ListIntentsResponse()) - 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] == 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_intents_flattened(): - client = IntentsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_intents), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = intent.ListIntentsResponse() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.list_intents( - parent='parent_value', - language_code='language_code_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] - arg = args[0].parent - mock_val = 'parent_value' - assert arg == mock_val - arg = args[0].language_code - mock_val = 'language_code_value' - assert arg == mock_val - - -def test_list_intents_flattened_error(): - client = IntentsClient( - 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_intents( - intent.ListIntentsRequest(), - parent='parent_value', - language_code='language_code_value', - ) - -@pytest.mark.asyncio -async def test_list_intents_flattened_async(): - 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: - # Designate an appropriate return value for the call. - call.return_value = intent.ListIntentsResponse() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(intent.ListIntentsResponse()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.list_intents( - parent='parent_value', - language_code='language_code_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - arg = args[0].parent - mock_val = 'parent_value' - assert arg == mock_val - arg = args[0].language_code - mock_val = 'language_code_value' - assert arg == mock_val - -@pytest.mark.asyncio -async def test_list_intents_flattened_error_async(): - client = IntentsAsyncClient( - 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_intents( - intent.ListIntentsRequest(), - parent='parent_value', - language_code='language_code_value', - ) - - -def test_list_intents_pager(transport_name: str = "grpc"): - client = IntentsClient( - credentials=ga_credentials.AnonymousCredentials, - transport=transport_name, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_intents), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - intent.ListIntentsResponse( - intents=[ - intent.Intent(), - intent.Intent(), - intent.Intent(), - ], - next_page_token='abc', - ), - intent.ListIntentsResponse( - intents=[], - next_page_token='def', - ), - intent.ListIntentsResponse( - intents=[ - intent.Intent(), - ], - next_page_token='ghi', - ), - intent.ListIntentsResponse( - intents=[ - intent.Intent(), - intent.Intent(), - ], - ), - RuntimeError, - ) - - metadata = () - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ('parent', ''), - )), - ) - pager = client.list_intents(request={}) - - assert pager._metadata == metadata - - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, intent.Intent) - for i in results) -def test_list_intents_pages(transport_name: str = "grpc"): - client = IntentsClient( - credentials=ga_credentials.AnonymousCredentials, - transport=transport_name, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_intents), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - intent.ListIntentsResponse( - intents=[ - intent.Intent(), - intent.Intent(), - intent.Intent(), - ], - next_page_token='abc', - ), - intent.ListIntentsResponse( - intents=[], - next_page_token='def', - ), - intent.ListIntentsResponse( - intents=[ - intent.Intent(), - ], - next_page_token='ghi', - ), - intent.ListIntentsResponse( - intents=[ - intent.Intent(), - intent.Intent(), - ], - ), - RuntimeError, - ) - pages = list(client.list_intents(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_intents_async_pager(): - 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__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - intent.ListIntentsResponse( - intents=[ - intent.Intent(), - intent.Intent(), - intent.Intent(), - ], - next_page_token='abc', - ), - intent.ListIntentsResponse( - intents=[], - next_page_token='def', - ), - intent.ListIntentsResponse( - intents=[ - intent.Intent(), - ], - next_page_token='ghi', - ), - intent.ListIntentsResponse( - intents=[ - intent.Intent(), - intent.Intent(), - ], - ), - RuntimeError, - ) - async_pager = await client.list_intents(request={},) - assert async_pager.next_page_token == 'abc' - responses = [] - async for response in async_pager: # pragma: no branch - responses.append(response) - - assert len(responses) == 6 - assert all(isinstance(i, intent.Intent) - for i in responses) - - -@pytest.mark.asyncio -async def test_list_intents_async_pages(): - 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__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - intent.ListIntentsResponse( - intents=[ - intent.Intent(), - intent.Intent(), - intent.Intent(), - ], - next_page_token='abc', - ), - intent.ListIntentsResponse( - intents=[], - next_page_token='def', - ), - intent.ListIntentsResponse( - intents=[ - intent.Intent(), - ], - next_page_token='ghi', - ), - intent.ListIntentsResponse( - intents=[ - intent.Intent(), - intent.Intent(), - ], - ), - RuntimeError, - ) - pages = [] - async for page_ in (await client.list_intents(request={})).pages: # pragma: no branch - pages.append(page_) - for page_, token in zip(pages, ['abc','def','ghi', '']): - assert page_.raw_page.next_page_token == token - -@pytest.mark.parametrize("request_type", [ - intent.GetIntentRequest, - dict, -]) -def test_get_intent(request_type, transport: str = 'grpc'): - client = IntentsClient( - 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_intent), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = intent.Intent( - name='name_value', - display_name='display_name_value', - webhook_state=intent.Intent.WebhookState.WEBHOOK_STATE_ENABLED, - priority=898, - is_fallback=True, - ml_disabled=True, - live_agent_handoff=True, - end_interaction=True, - input_context_names=['input_context_names_value'], - events=['events_value'], - action='action_value', - reset_contexts=True, - default_response_platforms=[intent.Intent.Message.Platform.FACEBOOK], - 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' - - -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=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_intent), - '__call__') as call: - client.get_intent() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == intent.GetIntentRequest() - -@pytest.mark.asyncio -async def test_get_intent_async(transport: str = 'grpc_asyncio', request_type=intent.GetIntentRequest): - client = IntentsAsyncClient( - 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_intent), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(intent.Intent( - name='name_value', - display_name='display_name_value', - webhook_state=intent.Intent.WebhookState.WEBHOOK_STATE_ENABLED, - priority=898, - is_fallback=True, - ml_disabled=True, - live_agent_handoff=True, - end_interaction=True, - input_context_names=['input_context_names_value'], - events=['events_value'], - action='action_value', - reset_contexts=True, - default_response_platforms=[intent.Intent.Message.Platform.FACEBOOK], - root_followup_intent_name='root_followup_intent_name_value', - 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' - - -@pytest.mark.asyncio -async def test_get_intent_async_from_dict(): - await test_get_intent_async(request_type=dict) - - -def test_get_intent_field_headers(): - 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. - 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_intent_field_headers_async(): - 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. - 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_intent_flattened(): - client = IntentsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_intent), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = intent.Intent() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.get_intent( - name='name_value', - language_code='language_code_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] - arg = args[0].name - mock_val = 'name_value' - assert arg == mock_val - arg = args[0].language_code - mock_val = 'language_code_value' - assert arg == mock_val - - -def test_get_intent_flattened_error(): - client = IntentsClient( - 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_intent( - intent.GetIntentRequest(), - name='name_value', - language_code='language_code_value', - ) - -@pytest.mark.asyncio -async def test_get_intent_flattened_async(): - 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: - # Designate an appropriate return value for the call. - call.return_value = intent.Intent() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(intent.Intent()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.get_intent( - name='name_value', - language_code='language_code_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - arg = args[0].name - mock_val = 'name_value' - assert arg == mock_val - arg = args[0].language_code - mock_val = 'language_code_value' - assert arg == mock_val - -@pytest.mark.asyncio -async def test_get_intent_flattened_error_async(): - client = IntentsAsyncClient( - 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_intent( - intent.GetIntentRequest(), - name='name_value', - language_code='language_code_value', - ) - - -@pytest.mark.parametrize("request_type", [ - gcd_intent.CreateIntentRequest, - dict, -]) -def test_create_intent(request_type, transport: str = 'grpc'): - client = IntentsClient( - 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_intent), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcd_intent.Intent( - name='name_value', - display_name='display_name_value', - webhook_state=gcd_intent.Intent.WebhookState.WEBHOOK_STATE_ENABLED, - priority=898, - is_fallback=True, - ml_disabled=True, - live_agent_handoff=True, - end_interaction=True, - input_context_names=['input_context_names_value'], - events=['events_value'], - action='action_value', - reset_contexts=True, - default_response_platforms=[gcd_intent.Intent.Message.Platform.FACEBOOK], - 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' - - -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=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_intent), - '__call__') as call: - client.create_intent() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == gcd_intent.CreateIntentRequest() - -@pytest.mark.asyncio -async def test_create_intent_async(transport: str = 'grpc_asyncio', request_type=gcd_intent.CreateIntentRequest): - client = IntentsAsyncClient( - 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_intent), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gcd_intent.Intent( - name='name_value', - display_name='display_name_value', - webhook_state=gcd_intent.Intent.WebhookState.WEBHOOK_STATE_ENABLED, - priority=898, - is_fallback=True, - ml_disabled=True, - live_agent_handoff=True, - end_interaction=True, - input_context_names=['input_context_names_value'], - events=['events_value'], - action='action_value', - reset_contexts=True, - default_response_platforms=[gcd_intent.Intent.Message.Platform.FACEBOOK], - root_followup_intent_name='root_followup_intent_name_value', - 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' - - -@pytest.mark.asyncio -async def test_create_intent_async_from_dict(): - await test_create_intent_async(request_type=dict) - - -def test_create_intent_field_headers(): - 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. - 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_intent_field_headers_async(): - 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. - 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_intent_flattened(): - 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( - parent='parent_value', - intent=gcd_intent.Intent(name='name_value'), - language_code='language_code_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] - arg = args[0].parent - mock_val = 'parent_value' - assert arg == mock_val - arg = args[0].intent - mock_val = gcd_intent.Intent(name='name_value') - assert arg == mock_val - arg = args[0].language_code - mock_val = 'language_code_value' - assert arg == mock_val - - -def test_create_intent_flattened_error(): - client = IntentsClient( - 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_intent( - gcd_intent.CreateIntentRequest(), - parent='parent_value', - intent=gcd_intent.Intent(name='name_value'), - language_code='language_code_value', - ) - -@pytest.mark.asyncio -async def test_create_intent_flattened_async(): - 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: - # Designate an appropriate return value for the call. - call.return_value = gcd_intent.Intent() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcd_intent.Intent()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.create_intent( - parent='parent_value', - intent=gcd_intent.Intent(name='name_value'), - language_code='language_code_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - arg = args[0].parent - mock_val = 'parent_value' - assert arg == mock_val - arg = args[0].intent - mock_val = gcd_intent.Intent(name='name_value') - assert arg == mock_val - arg = args[0].language_code - mock_val = 'language_code_value' - assert arg == mock_val - -@pytest.mark.asyncio -async def test_create_intent_flattened_error_async(): - client = IntentsAsyncClient( - 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_intent( - gcd_intent.CreateIntentRequest(), - parent='parent_value', - intent=gcd_intent.Intent(name='name_value'), - language_code='language_code_value', - ) - - -@pytest.mark.parametrize("request_type", [ - gcd_intent.UpdateIntentRequest, - dict, -]) -def test_update_intent(request_type, transport: str = 'grpc'): - client = IntentsClient( - 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_intent), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcd_intent.Intent( - name='name_value', - display_name='display_name_value', - webhook_state=gcd_intent.Intent.WebhookState.WEBHOOK_STATE_ENABLED, - priority=898, - is_fallback=True, - ml_disabled=True, - live_agent_handoff=True, - end_interaction=True, - input_context_names=['input_context_names_value'], - events=['events_value'], - action='action_value', - reset_contexts=True, - default_response_platforms=[gcd_intent.Intent.Message.Platform.FACEBOOK], - 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' - - -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=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_intent), - '__call__') as call: - client.update_intent() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == gcd_intent.UpdateIntentRequest() - -@pytest.mark.asyncio -async def test_update_intent_async(transport: str = 'grpc_asyncio', request_type=gcd_intent.UpdateIntentRequest): - client = IntentsAsyncClient( - 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_intent), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gcd_intent.Intent( - name='name_value', - display_name='display_name_value', - webhook_state=gcd_intent.Intent.WebhookState.WEBHOOK_STATE_ENABLED, - priority=898, - is_fallback=True, - ml_disabled=True, - live_agent_handoff=True, - end_interaction=True, - input_context_names=['input_context_names_value'], - events=['events_value'], - action='action_value', - reset_contexts=True, - default_response_platforms=[gcd_intent.Intent.Message.Platform.FACEBOOK], - root_followup_intent_name='root_followup_intent_name_value', - 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' - - -@pytest.mark.asyncio -async def test_update_intent_async_from_dict(): - await test_update_intent_async(request_type=dict) - - -def test_update_intent_field_headers(): - 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 = '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. - 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', - 'intent.name=name_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_update_intent_field_headers_async(): - 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 = '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. - 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', - 'intent.name=name_value', - ) in kw['metadata'] - - -def test_update_intent_flattened(): - 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_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] - arg = args[0].intent - mock_val = gcd_intent.Intent(name='name_value') - assert arg == mock_val - arg = args[0].language_code - mock_val = 'language_code_value' - assert arg == mock_val - arg = args[0].update_mask - mock_val = field_mask_pb2.FieldMask(paths=['paths_value']) - assert arg == mock_val - - -def test_update_intent_flattened_error(): - client = IntentsClient( - 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_intent( - gcd_intent.UpdateIntentRequest(), - intent=gcd_intent.Intent(name='name_value'), - language_code='language_code_value', - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - -@pytest.mark.asyncio -async def test_update_intent_flattened_async(): - 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: - # Designate an appropriate return value for the call. - call.return_value = gcd_intent.Intent() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcd_intent.Intent()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.update_intent( - intent=gcd_intent.Intent(name='name_value'), - language_code='language_code_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] - arg = args[0].intent - mock_val = gcd_intent.Intent(name='name_value') - assert arg == mock_val - arg = args[0].language_code - mock_val = 'language_code_value' - assert arg == mock_val - arg = args[0].update_mask - mock_val = field_mask_pb2.FieldMask(paths=['paths_value']) - assert arg == mock_val - -@pytest.mark.asyncio -async def test_update_intent_flattened_error_async(): - client = IntentsAsyncClient( - 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_intent( - gcd_intent.UpdateIntentRequest(), - intent=gcd_intent.Intent(name='name_value'), - language_code='language_code_value', - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - - -@pytest.mark.parametrize("request_type", [ - intent.DeleteIntentRequest, - dict, -]) -def test_delete_intent(request_type, transport: str = 'grpc'): - client = IntentsClient( - 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_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. - assert response is None - - -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=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_intent), - '__call__') as call: - client.delete_intent() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == intent.DeleteIntentRequest() - -@pytest.mark.asyncio -async def test_delete_intent_async(transport: str = 'grpc_asyncio', request_type=intent.DeleteIntentRequest): - client = IntentsAsyncClient( - 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_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. - assert response is None - - -@pytest.mark.asyncio -async def test_delete_intent_async_from_dict(): - await test_delete_intent_async(request_type=dict) - - -def test_delete_intent_field_headers(): - 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. - 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_intent_field_headers_async(): - 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. - 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_intent_flattened(): - 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', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - arg = args[0].name - mock_val = 'name_value' - assert arg == mock_val - - -def test_delete_intent_flattened_error(): - client = IntentsClient( - 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_intent( - intent.DeleteIntentRequest(), - name='name_value', - ) - -@pytest.mark.asyncio -async def test_delete_intent_flattened_async(): - 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: - # 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_intent( - 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] - arg = args[0].name - mock_val = 'name_value' - assert arg == mock_val - -@pytest.mark.asyncio -async def test_delete_intent_flattened_error_async(): - client = IntentsAsyncClient( - 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_intent( - intent.DeleteIntentRequest(), - name='name_value', - ) - - -@pytest.mark.parametrize("request_type", [ - intent.BatchUpdateIntentsRequest, - dict, -]) -def test_batch_update_intents(request_type, transport: str = 'grpc'): - client = IntentsClient( - 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.batch_update_intents), - '__call__') 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. - assert isinstance(response, future.Future) - - -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=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.batch_update_intents), - '__call__') as call: - client.batch_update_intents() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == intent.BatchUpdateIntentsRequest() - -@pytest.mark.asyncio -async def test_batch_update_intents_async(transport: str = 'grpc_asyncio', request_type=intent.BatchUpdateIntentsRequest): - client = IntentsAsyncClient( - 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.batch_update_intents), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name='operations/spam') - ) - response = await client.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. - assert isinstance(response, future.Future) - - -@pytest.mark.asyncio -async def test_batch_update_intents_async_from_dict(): - await test_batch_update_intents_async(request_type=dict) - - -def test_batch_update_intents_field_headers(): - 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. - with mock.patch.object( - 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. - 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_batch_update_intents_field_headers_async(): - 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. - with mock.patch.object( - type(client.transport.batch_update_intents), - '__call__') as call: - 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. - 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_batch_update_intents_flattened(): - 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.batch_update_intents), - '__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.batch_update_intents( - parent='parent_value', - intent_batch_uri='intent_batch_uri_value', - intent_batch_inline=intent.IntentBatch(intents=[intent.Intent(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] - arg = args[0].parent - mock_val = 'parent_value' - assert arg == mock_val - assert args[0].intent_batch_inline == intent.IntentBatch(intents=[intent.Intent(name='name_value')]) - - -def test_batch_update_intents_flattened_error(): - client = IntentsClient( - 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.batch_update_intents( - intent.BatchUpdateIntentsRequest(), - parent='parent_value', - intent_batch_uri='intent_batch_uri_value', - intent_batch_inline=intent.IntentBatch(intents=[intent.Intent(name='name_value')]), - ) - -@pytest.mark.asyncio -async def test_batch_update_intents_flattened_async(): - 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.batch_update_intents), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/op') - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name='operations/spam') - ) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.batch_update_intents( - parent='parent_value', - intent_batch_uri='intent_batch_uri_value', - intent_batch_inline=intent.IntentBatch(intents=[intent.Intent(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] - arg = args[0].parent - mock_val = 'parent_value' - assert arg == mock_val - assert args[0].intent_batch_inline == intent.IntentBatch(intents=[intent.Intent(name='name_value')]) - -@pytest.mark.asyncio -async def test_batch_update_intents_flattened_error_async(): - client = IntentsAsyncClient( - 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.batch_update_intents( - intent.BatchUpdateIntentsRequest(), - parent='parent_value', - intent_batch_uri='intent_batch_uri_value', - intent_batch_inline=intent.IntentBatch(intents=[intent.Intent(name='name_value')]), - ) - - -@pytest.mark.parametrize("request_type", [ - intent.BatchDeleteIntentsRequest, - dict, -]) -def test_batch_delete_intents(request_type, transport: str = 'grpc'): - client = IntentsClient( - 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.batch_delete_intents), - '__call__') 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. - assert isinstance(response, future.Future) - - -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=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.batch_delete_intents), - '__call__') as call: - client.batch_delete_intents() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == intent.BatchDeleteIntentsRequest() - -@pytest.mark.asyncio -async def test_batch_delete_intents_async(transport: str = 'grpc_asyncio', request_type=intent.BatchDeleteIntentsRequest): - client = IntentsAsyncClient( - 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.batch_delete_intents), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name='operations/spam') - ) - response = await client.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. - assert isinstance(response, future.Future) - - -@pytest.mark.asyncio -async def test_batch_delete_intents_async_from_dict(): - await test_batch_delete_intents_async(request_type=dict) - - -def test_batch_delete_intents_field_headers(): - 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. - with mock.patch.object( - 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. - 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_batch_delete_intents_field_headers_async(): - 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. - with mock.patch.object( - type(client.transport.batch_delete_intents), - '__call__') as call: - 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. - 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_batch_delete_intents_flattened(): - 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.batch_delete_intents), - '__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.batch_delete_intents( - parent='parent_value', - intents=[intent.Intent(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] - arg = args[0].parent - mock_val = 'parent_value' - assert arg == mock_val - arg = args[0].intents - mock_val = [intent.Intent(name='name_value')] - assert arg == mock_val - - -def test_batch_delete_intents_flattened_error(): - client = IntentsClient( - 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.batch_delete_intents( - intent.BatchDeleteIntentsRequest(), - parent='parent_value', - intents=[intent.Intent(name='name_value')], - ) - -@pytest.mark.asyncio -async def test_batch_delete_intents_flattened_async(): - 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.batch_delete_intents), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/op') - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name='operations/spam') - ) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.batch_delete_intents( - parent='parent_value', - intents=[intent.Intent(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] - arg = args[0].parent - mock_val = 'parent_value' - assert arg == mock_val - arg = args[0].intents - mock_val = [intent.Intent(name='name_value')] - assert arg == mock_val - -@pytest.mark.asyncio -async def test_batch_delete_intents_flattened_error_async(): - client = IntentsAsyncClient( - 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.batch_delete_intents( - intent.BatchDeleteIntentsRequest(), - parent='parent_value', - intents=[intent.Intent(name='name_value')], - ) - - -@pytest.mark.parametrize("request_type", [ - intent.ListIntentsRequest, - dict, -]) -def test_list_intents_rest(request_type): - client = IntentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1/agent'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = intent.ListIntentsResponse( - next_page_token='next_page_token_value', - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - pb_return_value = intent.ListIntentsResponse.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.list_intents(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListIntentsPager) - assert response.next_page_token == 'next_page_token_value' - - -def test_list_intents_rest_required_fields(request_type=intent.ListIntentsRequest): - transport_class = transports.IntentsRestTransport - - request_init = {} - request_init["parent"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - including_default_value_fields=False, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).list_intents._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["parent"] = 'parent_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).list_intents._get_unset_required_fields(jsonified_request) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("intent_view", "language_code", "page_size", "page_token", )) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "parent" in jsonified_request - assert jsonified_request["parent"] == 'parent_value' - - client = IntentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = intent.ListIntentsResponse() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "get", - 'query_params': pb_request, - } - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - - pb_return_value = intent.ListIntentsResponse.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.list_intents(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_list_intents_rest_unset_required_fields(): - transport = transports.IntentsRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.list_intents._get_unset_required_fields({}) - assert set(unset_fields) == (set(("intentView", "languageCode", "pageSize", "pageToken", )) & set(("parent", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_list_intents_rest_interceptors(null_interceptor): - transport = transports.IntentsRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.IntentsRestInterceptor(), - ) - client = IntentsClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.IntentsRestInterceptor, "post_list_intents") as post, \ - mock.patch.object(transports.IntentsRestInterceptor, "pre_list_intents") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = intent.ListIntentsRequest.pb(intent.ListIntentsRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = intent.ListIntentsResponse.to_json(intent.ListIntentsResponse()) - - request = intent.ListIntentsRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = intent.ListIntentsResponse() - - client.list_intents(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_list_intents_rest_bad_request(transport: str = 'rest', request_type=intent.ListIntentsRequest): - client = IntentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1/agent'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.list_intents(request) - - -def test_list_intents_rest_flattened(): - client = IntentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = intent.ListIntentsResponse() - - # get arguments that satisfy an http rule for this method - sample_request = {'parent': 'projects/sample1/agent'} - - # get truthy value for each flattened field - mock_args = dict( - parent='parent_value', - language_code='language_code_value', - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - pb_return_value = intent.ListIntentsResponse.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.list_intents(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v2/{parent=projects/*/agent}/intents" % client.transport._host, args[1]) - - -def test_list_intents_rest_flattened_error(transport: str = 'rest'): - client = IntentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.list_intents( - intent.ListIntentsRequest(), - parent='parent_value', - language_code='language_code_value', - ) - - -def test_list_intents_rest_pager(transport: str = 'rest'): - client = IntentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # TODO(kbandes): remove this mock unless there's a good reason for it. - #with mock.patch.object(path_template, 'transcode') as transcode: - # Set the response as a series of pages - response = ( - intent.ListIntentsResponse( - intents=[ - intent.Intent(), - intent.Intent(), - intent.Intent(), - ], - next_page_token='abc', - ), - intent.ListIntentsResponse( - intents=[], - next_page_token='def', - ), - intent.ListIntentsResponse( - intents=[ - intent.Intent(), - ], - next_page_token='ghi', - ), - intent.ListIntentsResponse( - intents=[ - intent.Intent(), - intent.Intent(), - ], - ), - ) - # Two responses for two calls - response = response + response - - # Wrap the values into proper Response objs - response = tuple(intent.ListIntentsResponse.to_json(x) for x in response) - return_values = tuple(Response() for i in response) - for return_val, response_val in zip(return_values, response): - return_val._content = response_val.encode('UTF-8') - return_val.status_code = 200 - req.side_effect = return_values - - sample_request = {'parent': 'projects/sample1/agent'} - - pager = client.list_intents(request=sample_request) - - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, intent.Intent) - for i in results) - - pages = list(client.list_intents(request=sample_request).pages) - for page_, token in zip(pages, ['abc','def','ghi', '']): - assert page_.raw_page.next_page_token == token - - -@pytest.mark.parametrize("request_type", [ - intent.GetIntentRequest, - dict, -]) -def test_get_intent_rest(request_type): - client = IntentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/agent/intents/sample2'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = intent.Intent( - name='name_value', - display_name='display_name_value', - webhook_state=intent.Intent.WebhookState.WEBHOOK_STATE_ENABLED, - priority=898, - is_fallback=True, - ml_disabled=True, - live_agent_handoff=True, - end_interaction=True, - input_context_names=['input_context_names_value'], - events=['events_value'], - action='action_value', - reset_contexts=True, - default_response_platforms=[intent.Intent.Message.Platform.FACEBOOK], - root_followup_intent_name='root_followup_intent_name_value', - parent_followup_intent_name='parent_followup_intent_name_value', - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - pb_return_value = intent.Intent.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.get_intent(request) - - # 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' - - -def test_get_intent_rest_required_fields(request_type=intent.GetIntentRequest): - transport_class = transports.IntentsRestTransport - - request_init = {} - request_init["name"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - including_default_value_fields=False, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_intent._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["name"] = 'name_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_intent._get_unset_required_fields(jsonified_request) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("intent_view", "language_code", )) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "name" in jsonified_request - assert jsonified_request["name"] == 'name_value' - - client = IntentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = intent.Intent() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "get", - 'query_params': pb_request, - } - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - - pb_return_value = intent.Intent.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.get_intent(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_get_intent_rest_unset_required_fields(): - transport = transports.IntentsRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.get_intent._get_unset_required_fields({}) - assert set(unset_fields) == (set(("intentView", "languageCode", )) & set(("name", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_get_intent_rest_interceptors(null_interceptor): - transport = transports.IntentsRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.IntentsRestInterceptor(), - ) - client = IntentsClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.IntentsRestInterceptor, "post_get_intent") as post, \ - mock.patch.object(transports.IntentsRestInterceptor, "pre_get_intent") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = intent.GetIntentRequest.pb(intent.GetIntentRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = intent.Intent.to_json(intent.Intent()) - - request = intent.GetIntentRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = intent.Intent() - - client.get_intent(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_get_intent_rest_bad_request(transport: str = 'rest', request_type=intent.GetIntentRequest): - client = IntentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/agent/intents/sample2'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.get_intent(request) - - -def test_get_intent_rest_flattened(): - client = IntentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = intent.Intent() - - # get arguments that satisfy an http rule for this method - sample_request = {'name': 'projects/sample1/agent/intents/sample2'} - - # get truthy value for each flattened field - mock_args = dict( - name='name_value', - language_code='language_code_value', - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - pb_return_value = intent.Intent.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.get_intent(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v2/{name=projects/*/agent/intents/*}" % client.transport._host, args[1]) - - -def test_get_intent_rest_flattened_error(transport: str = 'rest'): - client = IntentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.get_intent( - intent.GetIntentRequest(), - name='name_value', - language_code='language_code_value', - ) - - -def test_get_intent_rest_error(): - client = IntentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - gcd_intent.CreateIntentRequest, - dict, -]) -def test_create_intent_rest(request_type): - client = IntentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1/agent'} - request_init["intent"] = {'name': 'name_value', 'display_name': 'display_name_value', 'webhook_state': 1, 'priority': 898, 'is_fallback': True, 'ml_disabled': True, 'live_agent_handoff': True, 'end_interaction': True, 'input_context_names': ['input_context_names_value1', 'input_context_names_value2'], 'events': ['events_value1', 'events_value2'], 'training_phrases': [{'name': 'name_value', 'type_': 1, 'parts': [{'text': 'text_value', 'entity_type': 'entity_type_value', 'alias': 'alias_value', 'user_defined': True}], 'times_added_count': 1787}], 'action': 'action_value', 'output_contexts': [{'name': 'name_value', 'lifespan_count': 1498, 'parameters': {'fields': {}}}], 'reset_contexts': True, 'parameters': [{'name': 'name_value', 'display_name': 'display_name_value', 'value': 'value_value', 'default_value': 'default_value_value', 'entity_type_display_name': 'entity_type_display_name_value', 'mandatory': True, 'prompts': ['prompts_value1', 'prompts_value2'], 'is_list': True}], 'messages': [{'text': {'text': ['text_value1', 'text_value2']}, 'image': {'image_uri': 'image_uri_value', 'accessibility_text': 'accessibility_text_value'}, 'quick_replies': {'title': 'title_value', 'quick_replies': ['quick_replies_value1', 'quick_replies_value2']}, 'card': {'title': 'title_value', 'subtitle': 'subtitle_value', 'image_uri': 'image_uri_value', 'buttons': [{'text': 'text_value', 'postback': 'postback_value'}]}, 'payload': {}, 'simple_responses': {'simple_responses': [{'text_to_speech': 'text_to_speech_value', 'ssml': 'ssml_value', 'display_text': 'display_text_value'}]}, 'basic_card': {'title': 'title_value', 'subtitle': 'subtitle_value', 'formatted_text': 'formatted_text_value', 'image': {}, 'buttons': [{'title': 'title_value', 'open_uri_action': {'uri': 'uri_value'}}]}, 'suggestions': {'suggestions': [{'title': 'title_value'}]}, 'link_out_suggestion': {'destination_name': 'destination_name_value', 'uri': 'uri_value'}, 'list_select': {'title': 'title_value', 'items': [{'info': {'key': 'key_value', 'synonyms': ['synonyms_value1', 'synonyms_value2']}, 'title': 'title_value', 'description': 'description_value', 'image': {}}], 'subtitle': 'subtitle_value'}, 'carousel_select': {'items': [{'info': {}, 'title': 'title_value', 'description': 'description_value', 'image': {}}]}, 'browse_carousel_card': {'items': [{'open_uri_action': {'url': 'url_value', 'url_type_hint': 1}, 'title': 'title_value', 'description': 'description_value', 'image': {}, 'footer': 'footer_value'}], 'image_display_options': 1}, 'table_card': {'title': 'title_value', 'subtitle': 'subtitle_value', 'image': {}, 'column_properties': [{'header': 'header_value', 'horizontal_alignment': 1}], 'rows': [{'cells': [{'text': 'text_value'}], 'divider_after': True}], 'buttons': {}}, 'media_content': {'media_type': 1, 'media_objects': [{'name': 'name_value', 'description': 'description_value', 'large_image': {}, 'icon': {}, 'content_url': 'content_url_value'}]}, 'platform': 1}], 'default_response_platforms': [1], 'root_followup_intent_name': 'root_followup_intent_name_value', 'parent_followup_intent_name': 'parent_followup_intent_name_value', 'followup_intent_info': [{'followup_intent_name': 'followup_intent_name_value', 'parent_followup_intent_name': 'parent_followup_intent_name_value'}]} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = gcd_intent.Intent( - name='name_value', - display_name='display_name_value', - webhook_state=gcd_intent.Intent.WebhookState.WEBHOOK_STATE_ENABLED, - priority=898, - is_fallback=True, - ml_disabled=True, - live_agent_handoff=True, - end_interaction=True, - input_context_names=['input_context_names_value'], - events=['events_value'], - action='action_value', - reset_contexts=True, - default_response_platforms=[gcd_intent.Intent.Message.Platform.FACEBOOK], - root_followup_intent_name='root_followup_intent_name_value', - parent_followup_intent_name='parent_followup_intent_name_value', - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - pb_return_value = gcd_intent.Intent.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.create_intent(request) - - # 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' - - -def test_create_intent_rest_required_fields(request_type=gcd_intent.CreateIntentRequest): - transport_class = transports.IntentsRestTransport - - request_init = {} - request_init["parent"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - including_default_value_fields=False, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_intent._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["parent"] = 'parent_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_intent._get_unset_required_fields(jsonified_request) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("intent_view", "language_code", )) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "parent" in jsonified_request - assert jsonified_request["parent"] == 'parent_value' - - client = IntentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = gcd_intent.Intent() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "post", - 'query_params': pb_request, - } - transcode_result['body'] = pb_request - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - - pb_return_value = gcd_intent.Intent.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.create_intent(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_create_intent_rest_unset_required_fields(): - transport = transports.IntentsRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.create_intent._get_unset_required_fields({}) - assert set(unset_fields) == (set(("intentView", "languageCode", )) & set(("parent", "intent", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_create_intent_rest_interceptors(null_interceptor): - transport = transports.IntentsRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.IntentsRestInterceptor(), - ) - client = IntentsClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.IntentsRestInterceptor, "post_create_intent") as post, \ - mock.patch.object(transports.IntentsRestInterceptor, "pre_create_intent") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = gcd_intent.CreateIntentRequest.pb(gcd_intent.CreateIntentRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = gcd_intent.Intent.to_json(gcd_intent.Intent()) - - request = gcd_intent.CreateIntentRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = gcd_intent.Intent() - - client.create_intent(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_create_intent_rest_bad_request(transport: str = 'rest', request_type=gcd_intent.CreateIntentRequest): - client = IntentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1/agent'} - request_init["intent"] = {'name': 'name_value', 'display_name': 'display_name_value', 'webhook_state': 1, 'priority': 898, 'is_fallback': True, 'ml_disabled': True, 'live_agent_handoff': True, 'end_interaction': True, 'input_context_names': ['input_context_names_value1', 'input_context_names_value2'], 'events': ['events_value1', 'events_value2'], 'training_phrases': [{'name': 'name_value', 'type_': 1, 'parts': [{'text': 'text_value', 'entity_type': 'entity_type_value', 'alias': 'alias_value', 'user_defined': True}], 'times_added_count': 1787}], 'action': 'action_value', 'output_contexts': [{'name': 'name_value', 'lifespan_count': 1498, 'parameters': {'fields': {}}}], 'reset_contexts': True, 'parameters': [{'name': 'name_value', 'display_name': 'display_name_value', 'value': 'value_value', 'default_value': 'default_value_value', 'entity_type_display_name': 'entity_type_display_name_value', 'mandatory': True, 'prompts': ['prompts_value1', 'prompts_value2'], 'is_list': True}], 'messages': [{'text': {'text': ['text_value1', 'text_value2']}, 'image': {'image_uri': 'image_uri_value', 'accessibility_text': 'accessibility_text_value'}, 'quick_replies': {'title': 'title_value', 'quick_replies': ['quick_replies_value1', 'quick_replies_value2']}, 'card': {'title': 'title_value', 'subtitle': 'subtitle_value', 'image_uri': 'image_uri_value', 'buttons': [{'text': 'text_value', 'postback': 'postback_value'}]}, 'payload': {}, 'simple_responses': {'simple_responses': [{'text_to_speech': 'text_to_speech_value', 'ssml': 'ssml_value', 'display_text': 'display_text_value'}]}, 'basic_card': {'title': 'title_value', 'subtitle': 'subtitle_value', 'formatted_text': 'formatted_text_value', 'image': {}, 'buttons': [{'title': 'title_value', 'open_uri_action': {'uri': 'uri_value'}}]}, 'suggestions': {'suggestions': [{'title': 'title_value'}]}, 'link_out_suggestion': {'destination_name': 'destination_name_value', 'uri': 'uri_value'}, 'list_select': {'title': 'title_value', 'items': [{'info': {'key': 'key_value', 'synonyms': ['synonyms_value1', 'synonyms_value2']}, 'title': 'title_value', 'description': 'description_value', 'image': {}}], 'subtitle': 'subtitle_value'}, 'carousel_select': {'items': [{'info': {}, 'title': 'title_value', 'description': 'description_value', 'image': {}}]}, 'browse_carousel_card': {'items': [{'open_uri_action': {'url': 'url_value', 'url_type_hint': 1}, 'title': 'title_value', 'description': 'description_value', 'image': {}, 'footer': 'footer_value'}], 'image_display_options': 1}, 'table_card': {'title': 'title_value', 'subtitle': 'subtitle_value', 'image': {}, 'column_properties': [{'header': 'header_value', 'horizontal_alignment': 1}], 'rows': [{'cells': [{'text': 'text_value'}], 'divider_after': True}], 'buttons': {}}, 'media_content': {'media_type': 1, 'media_objects': [{'name': 'name_value', 'description': 'description_value', 'large_image': {}, 'icon': {}, 'content_url': 'content_url_value'}]}, 'platform': 1}], 'default_response_platforms': [1], 'root_followup_intent_name': 'root_followup_intent_name_value', 'parent_followup_intent_name': 'parent_followup_intent_name_value', 'followup_intent_info': [{'followup_intent_name': 'followup_intent_name_value', 'parent_followup_intent_name': 'parent_followup_intent_name_value'}]} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.create_intent(request) - - -def test_create_intent_rest_flattened(): - client = IntentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = gcd_intent.Intent() - - # get arguments that satisfy an http rule for this method - sample_request = {'parent': 'projects/sample1/agent'} - - # get truthy value for each flattened field - mock_args = dict( - parent='parent_value', - intent=gcd_intent.Intent(name='name_value'), - language_code='language_code_value', - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - pb_return_value = gcd_intent.Intent.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.create_intent(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v2/{parent=projects/*/agent}/intents" % client.transport._host, args[1]) - - -def test_create_intent_rest_flattened_error(transport: str = 'rest'): - client = IntentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.create_intent( - gcd_intent.CreateIntentRequest(), - parent='parent_value', - intent=gcd_intent.Intent(name='name_value'), - language_code='language_code_value', - ) - - -def test_create_intent_rest_error(): - client = IntentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - gcd_intent.UpdateIntentRequest, - dict, -]) -def test_update_intent_rest(request_type): - client = IntentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'intent': {'name': 'projects/sample1/agent/intents/sample2'}} - request_init["intent"] = {'name': 'projects/sample1/agent/intents/sample2', 'display_name': 'display_name_value', 'webhook_state': 1, 'priority': 898, 'is_fallback': True, 'ml_disabled': True, 'live_agent_handoff': True, 'end_interaction': True, 'input_context_names': ['input_context_names_value1', 'input_context_names_value2'], 'events': ['events_value1', 'events_value2'], 'training_phrases': [{'name': 'name_value', 'type_': 1, 'parts': [{'text': 'text_value', 'entity_type': 'entity_type_value', 'alias': 'alias_value', 'user_defined': True}], 'times_added_count': 1787}], 'action': 'action_value', 'output_contexts': [{'name': 'name_value', 'lifespan_count': 1498, 'parameters': {'fields': {}}}], 'reset_contexts': True, 'parameters': [{'name': 'name_value', 'display_name': 'display_name_value', 'value': 'value_value', 'default_value': 'default_value_value', 'entity_type_display_name': 'entity_type_display_name_value', 'mandatory': True, 'prompts': ['prompts_value1', 'prompts_value2'], 'is_list': True}], 'messages': [{'text': {'text': ['text_value1', 'text_value2']}, 'image': {'image_uri': 'image_uri_value', 'accessibility_text': 'accessibility_text_value'}, 'quick_replies': {'title': 'title_value', 'quick_replies': ['quick_replies_value1', 'quick_replies_value2']}, 'card': {'title': 'title_value', 'subtitle': 'subtitle_value', 'image_uri': 'image_uri_value', 'buttons': [{'text': 'text_value', 'postback': 'postback_value'}]}, 'payload': {}, 'simple_responses': {'simple_responses': [{'text_to_speech': 'text_to_speech_value', 'ssml': 'ssml_value', 'display_text': 'display_text_value'}]}, 'basic_card': {'title': 'title_value', 'subtitle': 'subtitle_value', 'formatted_text': 'formatted_text_value', 'image': {}, 'buttons': [{'title': 'title_value', 'open_uri_action': {'uri': 'uri_value'}}]}, 'suggestions': {'suggestions': [{'title': 'title_value'}]}, 'link_out_suggestion': {'destination_name': 'destination_name_value', 'uri': 'uri_value'}, 'list_select': {'title': 'title_value', 'items': [{'info': {'key': 'key_value', 'synonyms': ['synonyms_value1', 'synonyms_value2']}, 'title': 'title_value', 'description': 'description_value', 'image': {}}], 'subtitle': 'subtitle_value'}, 'carousel_select': {'items': [{'info': {}, 'title': 'title_value', 'description': 'description_value', 'image': {}}]}, 'browse_carousel_card': {'items': [{'open_uri_action': {'url': 'url_value', 'url_type_hint': 1}, 'title': 'title_value', 'description': 'description_value', 'image': {}, 'footer': 'footer_value'}], 'image_display_options': 1}, 'table_card': {'title': 'title_value', 'subtitle': 'subtitle_value', 'image': {}, 'column_properties': [{'header': 'header_value', 'horizontal_alignment': 1}], 'rows': [{'cells': [{'text': 'text_value'}], 'divider_after': True}], 'buttons': {}}, 'media_content': {'media_type': 1, 'media_objects': [{'name': 'name_value', 'description': 'description_value', 'large_image': {}, 'icon': {}, 'content_url': 'content_url_value'}]}, 'platform': 1}], 'default_response_platforms': [1], 'root_followup_intent_name': 'root_followup_intent_name_value', 'parent_followup_intent_name': 'parent_followup_intent_name_value', 'followup_intent_info': [{'followup_intent_name': 'followup_intent_name_value', 'parent_followup_intent_name': 'parent_followup_intent_name_value'}]} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = gcd_intent.Intent( - name='name_value', - display_name='display_name_value', - webhook_state=gcd_intent.Intent.WebhookState.WEBHOOK_STATE_ENABLED, - priority=898, - is_fallback=True, - ml_disabled=True, - live_agent_handoff=True, - end_interaction=True, - input_context_names=['input_context_names_value'], - events=['events_value'], - action='action_value', - reset_contexts=True, - default_response_platforms=[gcd_intent.Intent.Message.Platform.FACEBOOK], - root_followup_intent_name='root_followup_intent_name_value', - parent_followup_intent_name='parent_followup_intent_name_value', - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - pb_return_value = gcd_intent.Intent.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.update_intent(request) - - # 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' - - -def test_update_intent_rest_required_fields(request_type=gcd_intent.UpdateIntentRequest): - transport_class = transports.IntentsRestTransport - - request_init = {} - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - including_default_value_fields=False, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).update_intent._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).update_intent._get_unset_required_fields(jsonified_request) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("intent_view", "language_code", "update_mask", )) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - - client = IntentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = gcd_intent.Intent() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "patch", - 'query_params': pb_request, - } - transcode_result['body'] = pb_request - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - - pb_return_value = gcd_intent.Intent.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.update_intent(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_update_intent_rest_unset_required_fields(): - transport = transports.IntentsRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.update_intent._get_unset_required_fields({}) - assert set(unset_fields) == (set(("intentView", "languageCode", "updateMask", )) & set(("intent", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_update_intent_rest_interceptors(null_interceptor): - transport = transports.IntentsRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.IntentsRestInterceptor(), - ) - client = IntentsClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.IntentsRestInterceptor, "post_update_intent") as post, \ - mock.patch.object(transports.IntentsRestInterceptor, "pre_update_intent") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = gcd_intent.UpdateIntentRequest.pb(gcd_intent.UpdateIntentRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = gcd_intent.Intent.to_json(gcd_intent.Intent()) - - request = gcd_intent.UpdateIntentRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = gcd_intent.Intent() - - client.update_intent(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_update_intent_rest_bad_request(transport: str = 'rest', request_type=gcd_intent.UpdateIntentRequest): - client = IntentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'intent': {'name': 'projects/sample1/agent/intents/sample2'}} - request_init["intent"] = {'name': 'projects/sample1/agent/intents/sample2', 'display_name': 'display_name_value', 'webhook_state': 1, 'priority': 898, 'is_fallback': True, 'ml_disabled': True, 'live_agent_handoff': True, 'end_interaction': True, 'input_context_names': ['input_context_names_value1', 'input_context_names_value2'], 'events': ['events_value1', 'events_value2'], 'training_phrases': [{'name': 'name_value', 'type_': 1, 'parts': [{'text': 'text_value', 'entity_type': 'entity_type_value', 'alias': 'alias_value', 'user_defined': True}], 'times_added_count': 1787}], 'action': 'action_value', 'output_contexts': [{'name': 'name_value', 'lifespan_count': 1498, 'parameters': {'fields': {}}}], 'reset_contexts': True, 'parameters': [{'name': 'name_value', 'display_name': 'display_name_value', 'value': 'value_value', 'default_value': 'default_value_value', 'entity_type_display_name': 'entity_type_display_name_value', 'mandatory': True, 'prompts': ['prompts_value1', 'prompts_value2'], 'is_list': True}], 'messages': [{'text': {'text': ['text_value1', 'text_value2']}, 'image': {'image_uri': 'image_uri_value', 'accessibility_text': 'accessibility_text_value'}, 'quick_replies': {'title': 'title_value', 'quick_replies': ['quick_replies_value1', 'quick_replies_value2']}, 'card': {'title': 'title_value', 'subtitle': 'subtitle_value', 'image_uri': 'image_uri_value', 'buttons': [{'text': 'text_value', 'postback': 'postback_value'}]}, 'payload': {}, 'simple_responses': {'simple_responses': [{'text_to_speech': 'text_to_speech_value', 'ssml': 'ssml_value', 'display_text': 'display_text_value'}]}, 'basic_card': {'title': 'title_value', 'subtitle': 'subtitle_value', 'formatted_text': 'formatted_text_value', 'image': {}, 'buttons': [{'title': 'title_value', 'open_uri_action': {'uri': 'uri_value'}}]}, 'suggestions': {'suggestions': [{'title': 'title_value'}]}, 'link_out_suggestion': {'destination_name': 'destination_name_value', 'uri': 'uri_value'}, 'list_select': {'title': 'title_value', 'items': [{'info': {'key': 'key_value', 'synonyms': ['synonyms_value1', 'synonyms_value2']}, 'title': 'title_value', 'description': 'description_value', 'image': {}}], 'subtitle': 'subtitle_value'}, 'carousel_select': {'items': [{'info': {}, 'title': 'title_value', 'description': 'description_value', 'image': {}}]}, 'browse_carousel_card': {'items': [{'open_uri_action': {'url': 'url_value', 'url_type_hint': 1}, 'title': 'title_value', 'description': 'description_value', 'image': {}, 'footer': 'footer_value'}], 'image_display_options': 1}, 'table_card': {'title': 'title_value', 'subtitle': 'subtitle_value', 'image': {}, 'column_properties': [{'header': 'header_value', 'horizontal_alignment': 1}], 'rows': [{'cells': [{'text': 'text_value'}], 'divider_after': True}], 'buttons': {}}, 'media_content': {'media_type': 1, 'media_objects': [{'name': 'name_value', 'description': 'description_value', 'large_image': {}, 'icon': {}, 'content_url': 'content_url_value'}]}, 'platform': 1}], 'default_response_platforms': [1], 'root_followup_intent_name': 'root_followup_intent_name_value', 'parent_followup_intent_name': 'parent_followup_intent_name_value', 'followup_intent_info': [{'followup_intent_name': 'followup_intent_name_value', 'parent_followup_intent_name': 'parent_followup_intent_name_value'}]} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.update_intent(request) - - -def test_update_intent_rest_flattened(): - client = IntentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = gcd_intent.Intent() - - # get arguments that satisfy an http rule for this method - sample_request = {'intent': {'name': 'projects/sample1/agent/intents/sample2'}} - - # get truthy value for each flattened field - mock_args = dict( - intent=gcd_intent.Intent(name='name_value'), - language_code='language_code_value', - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - pb_return_value = gcd_intent.Intent.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.update_intent(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v2/{intent.name=projects/*/agent/intents/*}" % client.transport._host, args[1]) - - -def test_update_intent_rest_flattened_error(transport: str = 'rest'): - client = IntentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.update_intent( - gcd_intent.UpdateIntentRequest(), - intent=gcd_intent.Intent(name='name_value'), - language_code='language_code_value', - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - - -def test_update_intent_rest_error(): - client = IntentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - intent.DeleteIntentRequest, - dict, -]) -def test_delete_intent_rest(request_type): - client = IntentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/agent/intents/sample2'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = None - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = '' - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.delete_intent(request) - - # Establish that the response is the type that we expect. - assert response is None - - -def test_delete_intent_rest_required_fields(request_type=intent.DeleteIntentRequest): - transport_class = transports.IntentsRestTransport - - request_init = {} - request_init["name"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - including_default_value_fields=False, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).delete_intent._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["name"] = 'name_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).delete_intent._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "name" in jsonified_request - assert jsonified_request["name"] == 'name_value' - - client = IntentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = None - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "delete", - 'query_params': pb_request, - } - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - json_return_value = '' - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.delete_intent(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_delete_intent_rest_unset_required_fields(): - transport = transports.IntentsRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.delete_intent._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_delete_intent_rest_interceptors(null_interceptor): - transport = transports.IntentsRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.IntentsRestInterceptor(), - ) - client = IntentsClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.IntentsRestInterceptor, "pre_delete_intent") as pre: - pre.assert_not_called() - pb_message = intent.DeleteIntentRequest.pb(intent.DeleteIntentRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - - request = intent.DeleteIntentRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - - client.delete_intent(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - - -def test_delete_intent_rest_bad_request(transport: str = 'rest', request_type=intent.DeleteIntentRequest): - client = IntentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/agent/intents/sample2'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.delete_intent(request) - - -def test_delete_intent_rest_flattened(): - client = IntentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = None - - # get arguments that satisfy an http rule for this method - sample_request = {'name': 'projects/sample1/agent/intents/sample2'} - - # get truthy value for each flattened field - mock_args = dict( - name='name_value', - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = '' - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.delete_intent(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v2/{name=projects/*/agent/intents/*}" % client.transport._host, args[1]) - - -def test_delete_intent_rest_flattened_error(transport: str = 'rest'): - client = IntentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.delete_intent( - intent.DeleteIntentRequest(), - name='name_value', - ) - - -def test_delete_intent_rest_error(): - client = IntentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - intent.BatchUpdateIntentsRequest, - dict, -]) -def test_batch_update_intents_rest(request_type): - client = IntentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1/agent'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name='operations/spam') - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.batch_update_intents(request) - - # Establish that the response is the type that we expect. - assert response.operation.name == "operations/spam" - - -def test_batch_update_intents_rest_required_fields(request_type=intent.BatchUpdateIntentsRequest): - transport_class = transports.IntentsRestTransport - - request_init = {} - request_init["parent"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - including_default_value_fields=False, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).batch_update_intents._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["parent"] = 'parent_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).batch_update_intents._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "parent" in jsonified_request - assert jsonified_request["parent"] == 'parent_value' - - client = IntentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name='operations/spam') - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "post", - 'query_params': pb_request, - } - transcode_result['body'] = pb_request - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.batch_update_intents(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_batch_update_intents_rest_unset_required_fields(): - transport = transports.IntentsRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.batch_update_intents._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("parent", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_batch_update_intents_rest_interceptors(null_interceptor): - transport = transports.IntentsRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.IntentsRestInterceptor(), - ) - client = IntentsClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(operation.Operation, "_set_result_from_operation"), \ - mock.patch.object(transports.IntentsRestInterceptor, "post_batch_update_intents") as post, \ - mock.patch.object(transports.IntentsRestInterceptor, "pre_batch_update_intents") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = intent.BatchUpdateIntentsRequest.pb(intent.BatchUpdateIntentsRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = json_format.MessageToJson(operations_pb2.Operation()) - - request = intent.BatchUpdateIntentsRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = operations_pb2.Operation() - - client.batch_update_intents(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_batch_update_intents_rest_bad_request(transport: str = 'rest', request_type=intent.BatchUpdateIntentsRequest): - client = IntentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1/agent'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.batch_update_intents(request) - - -def test_batch_update_intents_rest_flattened(): - client = IntentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name='operations/spam') - - # get arguments that satisfy an http rule for this method - sample_request = {'parent': 'projects/sample1/agent'} - - # get truthy value for each flattened field - mock_args = dict( - parent='parent_value', - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.batch_update_intents(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v2/{parent=projects/*/agent}/intents:batchUpdate" % client.transport._host, args[1]) - - -def test_batch_update_intents_rest_flattened_error(transport: str = 'rest'): - client = IntentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.batch_update_intents( - intent.BatchUpdateIntentsRequest(), - parent='parent_value', - intent_batch_uri='intent_batch_uri_value', - intent_batch_inline=intent.IntentBatch(intents=[intent.Intent(name='name_value')]), - ) - - -def test_batch_update_intents_rest_error(): - client = IntentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - intent.BatchDeleteIntentsRequest, - dict, -]) -def test_batch_delete_intents_rest(request_type): - client = IntentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1/agent'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name='operations/spam') - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.batch_delete_intents(request) - - # Establish that the response is the type that we expect. - assert response.operation.name == "operations/spam" - - -def test_batch_delete_intents_rest_required_fields(request_type=intent.BatchDeleteIntentsRequest): - transport_class = transports.IntentsRestTransport - - request_init = {} - request_init["parent"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - including_default_value_fields=False, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).batch_delete_intents._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["parent"] = 'parent_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).batch_delete_intents._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "parent" in jsonified_request - assert jsonified_request["parent"] == 'parent_value' - - client = IntentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name='operations/spam') - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "post", - 'query_params': pb_request, - } - transcode_result['body'] = pb_request - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.batch_delete_intents(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_batch_delete_intents_rest_unset_required_fields(): - transport = transports.IntentsRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.batch_delete_intents._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("parent", "intents", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_batch_delete_intents_rest_interceptors(null_interceptor): - transport = transports.IntentsRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.IntentsRestInterceptor(), - ) - client = IntentsClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(operation.Operation, "_set_result_from_operation"), \ - mock.patch.object(transports.IntentsRestInterceptor, "post_batch_delete_intents") as post, \ - mock.patch.object(transports.IntentsRestInterceptor, "pre_batch_delete_intents") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = intent.BatchDeleteIntentsRequest.pb(intent.BatchDeleteIntentsRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = json_format.MessageToJson(operations_pb2.Operation()) - - request = intent.BatchDeleteIntentsRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = operations_pb2.Operation() - - client.batch_delete_intents(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_batch_delete_intents_rest_bad_request(transport: str = 'rest', request_type=intent.BatchDeleteIntentsRequest): - client = IntentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1/agent'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.batch_delete_intents(request) - - -def test_batch_delete_intents_rest_flattened(): - client = IntentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name='operations/spam') - - # get arguments that satisfy an http rule for this method - sample_request = {'parent': 'projects/sample1/agent'} - - # get truthy value for each flattened field - mock_args = dict( - parent='parent_value', - intents=[intent.Intent(name='name_value')], - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.batch_delete_intents(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v2/{parent=projects/*/agent}/intents:batchDelete" % client.transport._host, args[1]) - - -def test_batch_delete_intents_rest_flattened_error(transport: str = 'rest'): - client = IntentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.batch_delete_intents( - intent.BatchDeleteIntentsRequest(), - parent='parent_value', - intents=[intent.Intent(name='name_value')], - ) - - -def test_batch_delete_intents_rest_error(): - client = IntentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -def test_credentials_transport_error(): - # It is an error to provide credentials and a transport instance. - transport = transports.IntentsGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = IntentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # It is an error to provide a credentials file and a transport instance. - transport = transports.IntentsGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = IntentsClient( - client_options={"credentials_file": "credentials.json"}, - transport=transport, - ) - - # It is an error to provide an api_key and a transport instance. - transport = transports.IntentsGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - options = client_options.ClientOptions() - options.api_key = "api_key" - with pytest.raises(ValueError): - client = IntentsClient( - client_options=options, - transport=transport, - ) - - # It is an error to provide an api_key and a credential. - options = mock.Mock() - options.api_key = "api_key" - with pytest.raises(ValueError): - client = IntentsClient( - client_options=options, - credentials=ga_credentials.AnonymousCredentials() - ) - - # It is an error to provide scopes and a transport instance. - transport = transports.IntentsGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = IntentsClient( - client_options={"scopes": ["1", "2"]}, - transport=transport, - ) - - -def test_transport_instance(): - # A client may be instantiated with a custom transport instance. - transport = transports.IntentsGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - client = IntentsClient(transport=transport) - assert client.transport is transport - -def test_transport_get_channel(): - # A client may be instantiated with a custom transport instance. - transport = transports.IntentsGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - - transport = transports.IntentsGrpcAsyncIOTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - -@pytest.mark.parametrize("transport_class", [ - transports.IntentsGrpcTransport, - transports.IntentsGrpcAsyncIOTransport, - transports.IntentsRestTransport, -]) -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() - -@pytest.mark.parametrize("transport_name", [ - "grpc", - "rest", -]) -def test_transport_kind(transport_name): - transport = IntentsClient.get_transport_class(transport_name)( - credentials=ga_credentials.AnonymousCredentials(), - ) - assert transport.kind == transport_name - -def test_transport_grpc_default(): - # A client should use the gRPC transport by default. - 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(core_exceptions.DuplicateCredentialArgs): - transport = transports.IntentsTransport( - credentials=ga_credentials.AnonymousCredentials(), - credentials_file="credentials.json" - ) - - -def test_intents_base_transport(): - # Instantiate the base transport. - with mock.patch('google.cloud.dialogflow_v2.services.intents.transports.IntentsTransport.__init__') as Transport: - Transport.return_value = None - transport = transports.IntentsTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Every method on the transport should just blindly - # raise NotImplementedError. - methods = ( - 'list_intents', - 'get_intent', - 'create_intent', - 'update_intent', - 'delete_intent', - 'batch_update_intents', - 'batch_delete_intents', - 'get_location', - 'list_locations', - 'get_operation', - 'cancel_operation', - 'list_operations', - ) - for method in methods: - with pytest.raises(NotImplementedError): - getattr(transport, method)(request=object()) - - with pytest.raises(NotImplementedError): - transport.close() - - # Additionally, the LRO client (a property) should - # also raise NotImplementedError - with pytest.raises(NotImplementedError): - transport.operations_client - - # Catch all for all remaining methods and properties - remainder = [ - 'kind', - ] - for r in remainder: - with pytest.raises(NotImplementedError): - getattr(transport, r)() - - -def test_intents_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.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", - ) - - -def test_intents_base_transport_with_adc(): - # Test the default credentials are used if credentials and credentials_file are None. - with mock.patch.object(google.auth, 'default', autospec=True) as adc, mock.patch('google.cloud.dialogflow_v2.services.intents.transports.IntentsTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.IntentsTransport() - adc.assert_called_once() - - -def test_intents_auth_adc(): - # If no credentials are provided, we should use ADC credentials. - with mock.patch.object(google.auth, 'default', autospec=True) as adc: - 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, - ) - - -@pytest.mark.parametrize( - "transport_class", - [ - transports.IntentsGrpcTransport, - transports.IntentsGrpcAsyncIOTransport, - ], -) -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(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, - transports.IntentsRestTransport, - ], -) -def test_intents_transport_auth_gdch_credentials(transport_class): - host = 'https://language.com' - api_audience_tests = [None, 'https://language2.com'] - api_audience_expect = [host, 'https://language2.com'] - for t, e in zip(api_audience_tests, api_audience_expect): - with mock.patch.object(google.auth, 'default', autospec=True) as adc: - gdch_mock = mock.MagicMock() - type(gdch_mock).with_gdch_audience = mock.PropertyMock(return_value=gdch_mock) - adc.return_value = (gdch_mock, None) - transport_class(host=host, api_audience=t) - gdch_mock.with_gdch_audience.assert_called_once_with( - e - ) - - -@pytest.mark.parametrize( - "transport_class,grpc_helpers", - [ - (transports.IntentsGrpcTransport, grpc_helpers), - (transports.IntentsGrpcAsyncIOTransport, grpc_helpers_async) - ], -) -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", [transports.IntentsGrpcTransport, transports.IntentsGrpcAsyncIOTransport]) -def test_intents_grpc_transport_client_cert_source_for_mtls( - transport_class -): - cred = ga_credentials.AnonymousCredentials() - - # Check ssl_channel_credentials is used if provided. - with mock.patch.object(transport_class, "create_channel") as mock_create_channel: - mock_ssl_channel_creds = mock.Mock() - transport_class( - host="squid.clam.whelk", - credentials=cred, - ssl_channel_credentials=mock_ssl_channel_creds - ) - mock_create_channel.assert_called_once_with( - "squid.clam.whelk:443", - credentials=cred, - credentials_file=None, - scopes=None, - ssl_credentials=mock_ssl_channel_creds, - quota_project_id=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - # Check if ssl_channel_credentials is not provided, then client_cert_source_for_mtls - # is used. - with mock.patch.object(transport_class, "create_channel", return_value=mock.Mock()): - with mock.patch("grpc.ssl_channel_credentials") as mock_ssl_cred: - transport_class( - credentials=cred, - client_cert_source_for_mtls=client_cert_source_callback - ) - expected_cert, expected_key = client_cert_source_callback() - mock_ssl_cred.assert_called_once_with( - certificate_chain=expected_cert, - private_key=expected_key - ) - -def test_intents_http_transport_client_cert_source_for_mtls(): - cred = ga_credentials.AnonymousCredentials() - with mock.patch("google.auth.transport.requests.AuthorizedSession.configure_mtls_channel") as mock_configure_mtls_channel: - transports.IntentsRestTransport ( - credentials=cred, - client_cert_source_for_mtls=client_cert_source_callback - ) - mock_configure_mtls_channel.assert_called_once_with(client_cert_source_callback) - - -def test_intents_rest_lro_client(): - client = IntentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - transport = client.transport - - # Ensure that we have a api-core operations client. - assert isinstance( - transport.operations_client, - operations_v1.AbstractOperationsClient, - ) - - # Ensure that subsequent calls to the property send the exact same object. - assert transport.operations_client is transport.operations_client - - -@pytest.mark.parametrize("transport_name", [ - "grpc", - "grpc_asyncio", - "rest", -]) -def test_intents_host_no_port(transport_name): - client = IntentsClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='dialogflow.googleapis.com'), - transport=transport_name, - ) - assert client.transport._host == ( - 'dialogflow.googleapis.com:443' - if transport_name in ['grpc', 'grpc_asyncio'] - else 'https://dialogflow.googleapis.com' - ) - -@pytest.mark.parametrize("transport_name", [ - "grpc", - "grpc_asyncio", - "rest", -]) -def test_intents_host_with_port(transport_name): - client = IntentsClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='dialogflow.googleapis.com:8000'), - transport=transport_name, - ) - assert client.transport._host == ( - 'dialogflow.googleapis.com:8000' - if transport_name in ['grpc', 'grpc_asyncio'] - else 'https://dialogflow.googleapis.com:8000' - ) - -@pytest.mark.parametrize("transport_name", [ - "rest", -]) -def test_intents_client_transport_session_collision(transport_name): - creds1 = ga_credentials.AnonymousCredentials() - creds2 = ga_credentials.AnonymousCredentials() - client1 = IntentsClient( - credentials=creds1, - transport=transport_name, - ) - client2 = IntentsClient( - credentials=creds2, - transport=transport_name, - ) - session1 = client1.transport.list_intents._session - session2 = client2.transport.list_intents._session - assert session1 != session2 - session1 = client1.transport.get_intent._session - session2 = client2.transport.get_intent._session - assert session1 != session2 - session1 = client1.transport.create_intent._session - session2 = client2.transport.create_intent._session - assert session1 != session2 - session1 = client1.transport.update_intent._session - session2 = client2.transport.update_intent._session - assert session1 != session2 - session1 = client1.transport.delete_intent._session - session2 = client2.transport.delete_intent._session - assert session1 != session2 - session1 = client1.transport.batch_update_intents._session - session2 = client2.transport.batch_update_intents._session - assert session1 != session2 - session1 = client1.transport.batch_delete_intents._session - session2 = client2.transport.batch_delete_intents._session - assert session1 != session2 -def test_intents_grpc_transport_channel(): - channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.IntentsGrpcTransport( - 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_intents_grpc_asyncio_transport_channel(): - channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.IntentsGrpcAsyncIOTransport( - 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.IntentsGrpcTransport, transports.IntentsGrpcAsyncIOTransport]) -def test_intents_transport_channel_mtls_with_client_cert_source( - transport_class -): - with mock.patch("grpc.ssl_channel_credentials", autospec=True) as grpc_ssl_channel_cred: - with mock.patch.object(transport_class, "create_channel") as grpc_create_channel: - mock_ssl_cred = mock.Mock() - grpc_ssl_channel_cred.return_value = mock_ssl_cred - - mock_grpc_channel = mock.Mock() - grpc_create_channel.return_value = mock_grpc_channel - - cred = ga_credentials.AnonymousCredentials() - with pytest.warns(DeprecationWarning): - with mock.patch.object(google.auth, 'default') as adc: - adc.return_value = (cred, None) - transport = transport_class( - host="squid.clam.whelk", - api_mtls_endpoint="mtls.squid.clam.whelk", - client_cert_source=client_cert_source_callback, - ) - adc.assert_called_once() - - grpc_ssl_channel_cred.assert_called_once_with( - certificate_chain=b"cert bytes", private_key=b"key bytes" - ) - grpc_create_channel.assert_called_once_with( - "mtls.squid.clam.whelk:443", - credentials=cred, - credentials_file=None, - scopes=None, - ssl_credentials=mock_ssl_cred, - quota_project_id=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - assert transport.grpc_channel == mock_grpc_channel - assert transport._ssl_channel_credentials == mock_ssl_cred - - -# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are -# removed from grpc/grpc_asyncio transport constructor. -@pytest.mark.parametrize("transport_class", [transports.IntentsGrpcTransport, transports.IntentsGrpcAsyncIOTransport]) -def test_intents_transport_channel_mtls_with_adc( - transport_class -): - mock_ssl_cred = mock.Mock() - with mock.patch.multiple( - "google.auth.transport.grpc.SslCredentials", - __init__=mock.Mock(return_value=None), - ssl_credentials=mock.PropertyMock(return_value=mock_ssl_cred), - ): - with mock.patch.object(transport_class, "create_channel") as grpc_create_channel: - mock_grpc_channel = mock.Mock() - grpc_create_channel.return_value = mock_grpc_channel - mock_cred = mock.Mock() - - with pytest.warns(DeprecationWarning): - transport = transport_class( - host="squid.clam.whelk", - credentials=mock_cred, - api_mtls_endpoint="mtls.squid.clam.whelk", - client_cert_source=None, - ) - - grpc_create_channel.assert_called_once_with( - "mtls.squid.clam.whelk:443", - credentials=mock_cred, - credentials_file=None, - scopes=None, - ssl_credentials=mock_ssl_cred, - quota_project_id=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - assert transport.grpc_channel == mock_grpc_channel - - -def test_intents_grpc_lro_client(): - client = IntentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - transport = client.transport - - # Ensure that we have a api-core operations client. - assert isinstance( - transport.operations_client, - operations_v1.OperationsClient, - ) - - # Ensure that subsequent calls to the property send the exact same object. - assert transport.operations_client is transport.operations_client - - -def test_intents_grpc_lro_async_client(): - client = IntentsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc_asyncio', - ) - transport = client.transport - - # Ensure that we have a api-core operations client. - assert isinstance( - transport.operations_client, - operations_v1.OperationsAsyncClient, - ) - - # Ensure that subsequent calls to the property send the exact same object. - assert transport.operations_client is transport.operations_client - - -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, ) - actual = IntentsClient.context_path(project, session, context) - assert expected == actual - - -def test_parse_context_path(): - expected = { - "project": "octopus", - "session": "oyster", - "context": "nudibranch", - } - path = IntentsClient.context_path(**expected) - - # Check that the path construction is reversible. - actual = IntentsClient.parse_context_path(path) - assert expected == actual - -def test_intent_path(): - project = "cuttlefish" - intent = "mussel" - expected = "projects/{project}/agent/intents/{intent}".format(project=project, intent=intent, ) - actual = IntentsClient.intent_path(project, intent) - assert expected == actual - - -def test_parse_intent_path(): - expected = { - "project": "winkle", - "intent": "nautilus", - } - path = IntentsClient.intent_path(**expected) - - # Check that the path construction is reversible. - actual = IntentsClient.parse_intent_path(path) - assert expected == actual - -def test_common_billing_account_path(): - billing_account = "scallop" - expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) - actual = IntentsClient.common_billing_account_path(billing_account) - assert expected == actual - - -def test_parse_common_billing_account_path(): - expected = { - "billing_account": "abalone", - } - path = IntentsClient.common_billing_account_path(**expected) - - # Check that the path construction is reversible. - actual = IntentsClient.parse_common_billing_account_path(path) - assert expected == actual - -def test_common_folder_path(): - folder = "squid" - expected = "folders/{folder}".format(folder=folder, ) - actual = IntentsClient.common_folder_path(folder) - assert expected == actual - - -def test_parse_common_folder_path(): - expected = { - "folder": "clam", - } - path = IntentsClient.common_folder_path(**expected) - - # Check that the path construction is reversible. - actual = IntentsClient.parse_common_folder_path(path) - assert expected == actual - -def test_common_organization_path(): - organization = "whelk" - expected = "organizations/{organization}".format(organization=organization, ) - actual = IntentsClient.common_organization_path(organization) - assert expected == actual - - -def test_parse_common_organization_path(): - expected = { - "organization": "octopus", - } - path = IntentsClient.common_organization_path(**expected) - - # Check that the path construction is reversible. - actual = IntentsClient.parse_common_organization_path(path) - assert expected == actual - -def test_common_project_path(): - project = "oyster" - expected = "projects/{project}".format(project=project, ) - actual = IntentsClient.common_project_path(project) - assert expected == actual - - -def test_parse_common_project_path(): - expected = { - "project": "nudibranch", - } - path = IntentsClient.common_project_path(**expected) - - # Check that the path construction is reversible. - actual = IntentsClient.parse_common_project_path(path) - assert expected == actual - -def test_common_location_path(): - project = "cuttlefish" - location = "mussel" - expected = "projects/{project}/locations/{location}".format(project=project, location=location, ) - actual = IntentsClient.common_location_path(project, location) - assert expected == actual - - -def test_parse_common_location_path(): - expected = { - "project": "winkle", - "location": "nautilus", - } - path = IntentsClient.common_location_path(**expected) - - # Check that the path construction is reversible. - actual = IntentsClient.parse_common_location_path(path) - assert expected == actual - - -def test_client_with_default_client_info(): - client_info = gapic_v1.client_info.ClientInfo() - - with mock.patch.object(transports.IntentsTransport, '_prep_wrapped_messages') as prep: - client = IntentsClient( - credentials=ga_credentials.AnonymousCredentials(), - client_info=client_info, - ) - prep.assert_called_once_with(client_info) - - with mock.patch.object(transports.IntentsTransport, '_prep_wrapped_messages') as prep: - transport_class = IntentsClient.get_transport_class() - transport = transport_class( - credentials=ga_credentials.AnonymousCredentials(), - client_info=client_info, - ) - prep.assert_called_once_with(client_info) - -@pytest.mark.asyncio -async def test_transport_close_async(): - client = IntentsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - with mock.patch.object(type(getattr(client.transport, "grpc_channel")), "close") as close: - async with client: - close.assert_not_called() - close.assert_called_once() - - -def test_get_location_rest_bad_request(transport: str = 'rest', request_type=locations_pb2.GetLocationRequest): - client = IntentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - request = request_type() - request = json_format.ParseDict({'name': 'projects/sample1/locations/sample2'}, request) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.get_location(request) - -@pytest.mark.parametrize("request_type", [ - locations_pb2.GetLocationRequest, - dict, -]) -def test_get_location_rest(request_type): - client = IntentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request_init = {'name': 'projects/sample1/locations/sample2'} - request = request_type(**request_init) - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = locations_pb2.Location() - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.get_location(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, locations_pb2.Location) - -def test_list_locations_rest_bad_request(transport: str = 'rest', request_type=locations_pb2.ListLocationsRequest): - client = IntentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - request = request_type() - request = json_format.ParseDict({'name': 'projects/sample1'}, request) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.list_locations(request) - -@pytest.mark.parametrize("request_type", [ - locations_pb2.ListLocationsRequest, - dict, -]) -def test_list_locations_rest(request_type): - client = IntentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request_init = {'name': 'projects/sample1'} - request = request_type(**request_init) - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = locations_pb2.ListLocationsResponse() - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.list_locations(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, locations_pb2.ListLocationsResponse) - -def test_cancel_operation_rest_bad_request(transport: str = 'rest', request_type=operations_pb2.CancelOperationRequest): - client = IntentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - request = request_type() - request = json_format.ParseDict({'name': 'projects/sample1/operations/sample2'}, request) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.cancel_operation(request) - -@pytest.mark.parametrize("request_type", [ - operations_pb2.CancelOperationRequest, - dict, -]) -def test_cancel_operation_rest(request_type): - client = IntentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request_init = {'name': 'projects/sample1/operations/sample2'} - request = request_type(**request_init) - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = None - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = '{}' - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.cancel_operation(request) - - # Establish that the response is the type that we expect. - assert response is None - -def test_get_operation_rest_bad_request(transport: str = 'rest', request_type=operations_pb2.GetOperationRequest): - client = IntentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - request = request_type() - request = json_format.ParseDict({'name': 'projects/sample1/operations/sample2'}, request) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.get_operation(request) - -@pytest.mark.parametrize("request_type", [ - operations_pb2.GetOperationRequest, - dict, -]) -def test_get_operation_rest(request_type): - client = IntentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request_init = {'name': 'projects/sample1/operations/sample2'} - request = request_type(**request_init) - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation() - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.get_operation(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, operations_pb2.Operation) - -def test_list_operations_rest_bad_request(transport: str = 'rest', request_type=operations_pb2.ListOperationsRequest): - client = IntentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - request = request_type() - request = json_format.ParseDict({'name': 'projects/sample1'}, request) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.list_operations(request) - -@pytest.mark.parametrize("request_type", [ - operations_pb2.ListOperationsRequest, - dict, -]) -def test_list_operations_rest(request_type): - client = IntentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request_init = {'name': 'projects/sample1'} - request = request_type(**request_init) - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = operations_pb2.ListOperationsResponse() - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.list_operations(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, operations_pb2.ListOperationsResponse) - - -def test_cancel_operation(transport: str = "grpc"): - client = IntentsClient( - 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 = operations_pb2.CancelOperationRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = None - response = client.cancel_operation(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 response is the type that we expect. - assert response is None -@pytest.mark.asyncio -async def test_cancel_operation_async(transport: str = "grpc"): - client = IntentsAsyncClient( - 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 = operations_pb2.CancelOperationRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - None - ) - response = await client.cancel_operation(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 response is the type that we expect. - assert response is None - -def test_cancel_operation_field_headers(): - 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 = operations_pb2.CancelOperationRequest() - request.name = "locations" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call: - call.return_value = None - - client.cancel_operation(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=locations",) in kw["metadata"] -@pytest.mark.asyncio -async def test_cancel_operation_field_headers_async(): - 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 = operations_pb2.CancelOperationRequest() - request.name = "locations" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - None - ) - await client.cancel_operation(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=locations",) in kw["metadata"] - -def test_cancel_operation_from_dict(): - 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.cancel_operation), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = None - - response = client.cancel_operation( - request={ - "name": "locations", - } - ) - call.assert_called() -@pytest.mark.asyncio -async def test_cancel_operation_from_dict_async(): - 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.cancel_operation), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - None - ) - response = await client.cancel_operation( - request={ - "name": "locations", - } - ) - call.assert_called() - - -def test_get_operation(transport: str = "grpc"): - client = IntentsClient( - 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 = operations_pb2.GetOperationRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_operation), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation() - response = client.get_operation(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 response is the type that we expect. - assert isinstance(response, operations_pb2.Operation) -@pytest.mark.asyncio -async def test_get_operation_async(transport: str = "grpc"): - client = IntentsAsyncClient( - 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 = operations_pb2.GetOperationRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_operation), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation() - ) - response = await client.get_operation(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 response is the type that we expect. - assert isinstance(response, operations_pb2.Operation) - -def test_get_operation_field_headers(): - 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 = operations_pb2.GetOperationRequest() - request.name = "locations" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_operation), "__call__") as call: - call.return_value = operations_pb2.Operation() - - client.get_operation(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=locations",) in kw["metadata"] -@pytest.mark.asyncio -async def test_get_operation_field_headers_async(): - 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 = operations_pb2.GetOperationRequest() - request.name = "locations" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_operation), "__call__") as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation() - ) - await client.get_operation(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=locations",) in kw["metadata"] - -def test_get_operation_from_dict(): - 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_operation), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation() - - response = client.get_operation( - request={ - "name": "locations", - } - ) - call.assert_called() -@pytest.mark.asyncio -async def test_get_operation_from_dict_async(): - 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_operation), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation() - ) - response = await client.get_operation( - request={ - "name": "locations", - } - ) - call.assert_called() - - -def test_list_operations(transport: str = "grpc"): - client = IntentsClient( - 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 = operations_pb2.ListOperationsRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_operations), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.ListOperationsResponse() - response = client.list_operations(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 response is the type that we expect. - assert isinstance(response, operations_pb2.ListOperationsResponse) -@pytest.mark.asyncio -async def test_list_operations_async(transport: str = "grpc"): - client = IntentsAsyncClient( - 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 = operations_pb2.ListOperationsRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_operations), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.ListOperationsResponse() - ) - response = await client.list_operations(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 response is the type that we expect. - assert isinstance(response, operations_pb2.ListOperationsResponse) - -def test_list_operations_field_headers(): - 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 = operations_pb2.ListOperationsRequest() - request.name = "locations" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_operations), "__call__") as call: - call.return_value = operations_pb2.ListOperationsResponse() - - client.list_operations(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=locations",) in kw["metadata"] -@pytest.mark.asyncio -async def test_list_operations_field_headers_async(): - 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 = operations_pb2.ListOperationsRequest() - request.name = "locations" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_operations), "__call__") as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.ListOperationsResponse() - ) - await client.list_operations(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=locations",) in kw["metadata"] - -def test_list_operations_from_dict(): - 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_operations), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.ListOperationsResponse() - - response = client.list_operations( - request={ - "name": "locations", - } - ) - call.assert_called() -@pytest.mark.asyncio -async def test_list_operations_from_dict_async(): - 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_operations), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.ListOperationsResponse() - ) - response = await client.list_operations( - request={ - "name": "locations", - } - ) - call.assert_called() - - -def test_list_locations(transport: str = "grpc"): - client = IntentsClient( - 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 = locations_pb2.ListLocationsRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_locations), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = locations_pb2.ListLocationsResponse() - response = client.list_locations(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 response is the type that we expect. - assert isinstance(response, locations_pb2.ListLocationsResponse) -@pytest.mark.asyncio -async def test_list_locations_async(transport: str = "grpc"): - client = IntentsAsyncClient( - 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 = locations_pb2.ListLocationsRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_locations), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - locations_pb2.ListLocationsResponse() - ) - response = await client.list_locations(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 response is the type that we expect. - assert isinstance(response, locations_pb2.ListLocationsResponse) - -def test_list_locations_field_headers(): - 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 = locations_pb2.ListLocationsRequest() - request.name = "locations" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_locations), "__call__") as call: - call.return_value = locations_pb2.ListLocationsResponse() - - client.list_locations(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=locations",) in kw["metadata"] -@pytest.mark.asyncio -async def test_list_locations_field_headers_async(): - 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 = locations_pb2.ListLocationsRequest() - request.name = "locations" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_locations), "__call__") as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - locations_pb2.ListLocationsResponse() - ) - await client.list_locations(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=locations",) in kw["metadata"] - -def test_list_locations_from_dict(): - 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_locations), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = locations_pb2.ListLocationsResponse() - - response = client.list_locations( - request={ - "name": "locations", - } - ) - call.assert_called() -@pytest.mark.asyncio -async def test_list_locations_from_dict_async(): - 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_locations), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - locations_pb2.ListLocationsResponse() - ) - response = await client.list_locations( - request={ - "name": "locations", - } - ) - call.assert_called() - - -def test_get_location(transport: str = "grpc"): - client = IntentsClient( - 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 = locations_pb2.GetLocationRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_location), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = locations_pb2.Location() - response = client.get_location(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 response is the type that we expect. - assert isinstance(response, locations_pb2.Location) -@pytest.mark.asyncio -async def test_get_location_async(transport: str = "grpc_asyncio"): - client = IntentsAsyncClient( - 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 = locations_pb2.GetLocationRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_location), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - locations_pb2.Location() - ) - response = await client.get_location(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 response is the type that we expect. - assert isinstance(response, locations_pb2.Location) - -def test_get_location_field_headers(): - 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 = locations_pb2.GetLocationRequest() - request.name = "locations/abc" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_location), "__call__") as call: - call.return_value = locations_pb2.Location() - - client.get_location(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=locations/abc",) in kw["metadata"] -@pytest.mark.asyncio -async def test_get_location_field_headers_async(): - 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 = locations_pb2.GetLocationRequest() - request.name = "locations/abc" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_location), "__call__") as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - locations_pb2.Location() - ) - await client.get_location(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=locations/abc",) in kw["metadata"] - -def test_get_location_from_dict(): - 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_locations), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = locations_pb2.Location() - - response = client.get_location( - request={ - "name": "locations/abc", - } - ) - call.assert_called() -@pytest.mark.asyncio -async def test_get_location_from_dict_async(): - 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_locations), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - locations_pb2.Location() - ) - response = await client.get_location( - request={ - "name": "locations", - } - ) - call.assert_called() - - -def test_transport_close(): - transports = { - "rest": "_session", - "grpc": "_grpc_channel", - } - - for transport, close_name in transports.items(): - client = IntentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport - ) - with mock.patch.object(type(getattr(client.transport, close_name)), "close") as close: - with client: - close.assert_not_called() - close.assert_called_once() - -def test_client_ctx(): - transports = [ - 'rest', - 'grpc', - ] - for transport in transports: - client = IntentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport - ) - # Test client calls underlying transport. - with mock.patch.object(type(client.transport), "close") as close: - close.assert_not_called() - with client: - pass - close.assert_called() - -@pytest.mark.parametrize("client_class,transport_class", [ - (IntentsClient, transports.IntentsGrpcTransport), - (IntentsAsyncClient, transports.IntentsGrpcAsyncIOTransport), -]) -def test_api_key_credentials(client_class, transport_class): - with mock.patch.object( - google.auth._default, "get_api_key_credentials", create=True - ) as get_api_key_credentials: - mock_cred = mock.Mock() - get_api_key_credentials.return_value = mock_cred - options = client_options.ClientOptions() - options.api_key = "api_key" - 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=mock_cred, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) diff --git a/owl-bot-staging/v2/tests/unit/gapic/dialogflow_v2/test_knowledge_bases.py b/owl-bot-staging/v2/tests/unit/gapic/dialogflow_v2/test_knowledge_bases.py deleted file mode 100644 index 3bb16fc8a..000000000 --- a/owl-bot-staging/v2/tests/unit/gapic/dialogflow_v2/test_knowledge_bases.py +++ /dev/null @@ -1,4742 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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 -# try/except added for compatibility with python < 3.8 -try: - from unittest import mock - from unittest.mock import AsyncMock # pragma: NO COVER -except ImportError: # pragma: NO COVER - import mock - -import grpc -from grpc.experimental import aio -from collections.abc import Iterable -from google.protobuf import json_format -import json -import math -import pytest -from proto.marshal.rules.dates import DurationRule, TimestampRule -from proto.marshal.rules import wrappers -from requests import Response -from requests import Request, PreparedRequest -from requests.sessions import Session -from google.protobuf import json_format - -from google.api_core import client_options -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import grpc_helpers -from google.api_core import grpc_helpers_async -from google.api_core import path_template -from google.auth import credentials as ga_credentials -from google.auth.exceptions import MutualTLSChannelError -from google.cloud.dialogflow_v2.services.knowledge_bases import KnowledgeBasesAsyncClient -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.types import knowledge_base -from google.cloud.dialogflow_v2.types import knowledge_base as gcd_knowledge_base -from google.cloud.location import locations_pb2 -from google.longrunning import operations_pb2 -from google.oauth2 import service_account -from google.protobuf import field_mask_pb2 # type: ignore -import google.auth - - -def client_cert_source_callback(): - return b"cert bytes", b"key bytes" - - -# If default endpoint is localhost, then default mtls endpoint will be the same. -# This method modifies the default endpoint so the client can produce a different -# mtls endpoint for endpoint testing purposes. -def modify_default_endpoint(client): - return "foo.googleapis.com" if ("localhost" in client.DEFAULT_ENDPOINT) else client.DEFAULT_ENDPOINT - - -def test__get_default_mtls_endpoint(): - api_endpoint = "example.googleapis.com" - api_mtls_endpoint = "example.mtls.googleapis.com" - sandbox_endpoint = "example.sandbox.googleapis.com" - sandbox_mtls_endpoint = "example.mtls.sandbox.googleapis.com" - non_googleapi = "api.example.com" - - assert KnowledgeBasesClient._get_default_mtls_endpoint(None) is None - assert KnowledgeBasesClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint - assert KnowledgeBasesClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint - assert KnowledgeBasesClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint - assert KnowledgeBasesClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint - assert KnowledgeBasesClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi - - -@pytest.mark.parametrize("client_class,transport_name", [ - (KnowledgeBasesClient, "grpc"), - (KnowledgeBasesAsyncClient, "grpc_asyncio"), - (KnowledgeBasesClient, "rest"), -]) -def test_knowledge_bases_client_from_service_account_info(client_class, transport_name): - 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, transport=transport_name) - assert client.transport._credentials == creds - assert isinstance(client, client_class) - - assert client.transport._host == ( - 'dialogflow.googleapis.com:443' - if transport_name in ['grpc', 'grpc_asyncio'] - else - 'https://dialogflow.googleapis.com' - ) - - -@pytest.mark.parametrize("transport_class,transport_name", [ - (transports.KnowledgeBasesGrpcTransport, "grpc"), - (transports.KnowledgeBasesGrpcAsyncIOTransport, "grpc_asyncio"), - (transports.KnowledgeBasesRestTransport, "rest"), -]) -def test_knowledge_bases_client_service_account_always_use_jwt(transport_class, transport_name): - with mock.patch.object(service_account.Credentials, 'with_always_use_jwt_access', create=True) as use_jwt: - creds = service_account.Credentials(None, None, None) - transport = transport_class(credentials=creds, always_use_jwt_access=True) - use_jwt.assert_called_once_with(True) - - with mock.patch.object(service_account.Credentials, 'with_always_use_jwt_access', create=True) as use_jwt: - creds = service_account.Credentials(None, None, None) - transport = transport_class(credentials=creds, always_use_jwt_access=False) - use_jwt.assert_not_called() - - -@pytest.mark.parametrize("client_class,transport_name", [ - (KnowledgeBasesClient, "grpc"), - (KnowledgeBasesAsyncClient, "grpc_asyncio"), - (KnowledgeBasesClient, "rest"), -]) -def test_knowledge_bases_client_from_service_account_file(client_class, transport_name): - 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", transport=transport_name) - assert client.transport._credentials == creds - assert isinstance(client, client_class) - - client = client_class.from_service_account_json("dummy/file/path.json", transport=transport_name) - assert client.transport._credentials == creds - assert isinstance(client, client_class) - - assert client.transport._host == ( - 'dialogflow.googleapis.com:443' - if transport_name in ['grpc', 'grpc_asyncio'] - else - 'https://dialogflow.googleapis.com' - ) - - -def test_knowledge_bases_client_get_transport_class(): - transport = KnowledgeBasesClient.get_transport_class() - available_transports = [ - transports.KnowledgeBasesGrpcTransport, - transports.KnowledgeBasesRestTransport, - ] - assert transport in available_transports - - transport = KnowledgeBasesClient.get_transport_class("grpc") - assert transport == transports.KnowledgeBasesGrpcTransport - - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (KnowledgeBasesClient, transports.KnowledgeBasesGrpcTransport, "grpc"), - (KnowledgeBasesAsyncClient, transports.KnowledgeBasesGrpcAsyncIOTransport, "grpc_asyncio"), - (KnowledgeBasesClient, transports.KnowledgeBasesRestTransport, "rest"), -]) -@mock.patch.object(KnowledgeBasesClient, "DEFAULT_ENDPOINT", modify_default_endpoint(KnowledgeBasesClient)) -@mock.patch.object(KnowledgeBasesAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(KnowledgeBasesAsyncClient)) -def test_knowledge_bases_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(KnowledgeBasesClient, '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(KnowledgeBasesClient, 'get_transport_class') as gtc: - client = client_class(transport=transport_name) - gtc.assert_called() - - # Check the case api_endpoint is provided. - options = client_options.ClientOptions(api_endpoint="squid.clam.whelk") - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(transport=transport_name, client_options=options) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host="squid.clam.whelk", - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is - # "never". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is - # "always". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_MTLS_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # 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(transport=transport_name) - - # 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(transport=transport_name) - - # 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, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id="octopus", - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - # Check the case api_endpoint is provided - options = client_options.ClientOptions(api_audience="https://language.googleapis.com") - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience="https://language.googleapis.com" - ) - -@pytest.mark.parametrize("client_class,transport_class,transport_name,use_client_cert_env", [ - (KnowledgeBasesClient, transports.KnowledgeBasesGrpcTransport, "grpc", "true"), - (KnowledgeBasesAsyncClient, transports.KnowledgeBasesGrpcAsyncIOTransport, "grpc_asyncio", "true"), - (KnowledgeBasesClient, transports.KnowledgeBasesGrpcTransport, "grpc", "false"), - (KnowledgeBasesAsyncClient, transports.KnowledgeBasesGrpcAsyncIOTransport, "grpc_asyncio", "false"), - (KnowledgeBasesClient, transports.KnowledgeBasesRestTransport, "rest", "true"), - (KnowledgeBasesClient, transports.KnowledgeBasesRestTransport, "rest", "false"), -]) -@mock.patch.object(KnowledgeBasesClient, "DEFAULT_ENDPOINT", modify_default_endpoint(KnowledgeBasesClient)) -@mock.patch.object(KnowledgeBasesAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(KnowledgeBasesAsyncClient)) -@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) -def test_knowledge_bases_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, transport=transport_name) - - if use_client_cert_env == "false": - expected_client_cert_source = None - expected_host = client.DEFAULT_ENDPOINT - else: - expected_client_cert_source = client_cert_source_callback - expected_host = client.DEFAULT_MTLS_ENDPOINT - - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=expected_host, - scopes=None, - client_cert_source_for_mtls=expected_client_cert_source, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case ADC client cert is provided. Whether client cert is used depends on - # GOOGLE_API_USE_CLIENT_CERTIFICATE value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): - with mock.patch.object(transport_class, '__init__') as patched: - with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): - with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=client_cert_source_callback): - if use_client_cert_env == "false": - expected_host = client.DEFAULT_ENDPOINT - expected_client_cert_source = None - else: - expected_host = client.DEFAULT_MTLS_ENDPOINT - expected_client_cert_source = client_cert_source_callback - - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=expected_host, - scopes=None, - client_cert_source_for_mtls=expected_client_cert_source, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case client_cert_source and ADC client cert are not provided. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): - with mock.patch.object(transport_class, '__init__') as patched: - with mock.patch("google.auth.transport.mtls.has_default_client_cert_source", return_value=False): - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - -@pytest.mark.parametrize("client_class", [ - KnowledgeBasesClient, KnowledgeBasesAsyncClient -]) -@mock.patch.object(KnowledgeBasesClient, "DEFAULT_ENDPOINT", modify_default_endpoint(KnowledgeBasesClient)) -@mock.patch.object(KnowledgeBasesAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(KnowledgeBasesAsyncClient)) -def test_knowledge_bases_client_get_mtls_endpoint_and_cert_source(client_class): - mock_client_cert_source = mock.Mock() - - # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "true". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - mock_api_endpoint = "foo" - options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) - assert api_endpoint == mock_api_endpoint - assert cert_source == mock_client_cert_source - - # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "false". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): - mock_client_cert_source = mock.Mock() - mock_api_endpoint = "foo" - options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) - assert api_endpoint == mock_api_endpoint - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "never". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_ENDPOINT - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "always". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert doesn't exist. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=False): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_ENDPOINT - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert exists. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - 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=mock_client_cert_source): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT - assert cert_source == mock_client_cert_source - - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (KnowledgeBasesClient, transports.KnowledgeBasesGrpcTransport, "grpc"), - (KnowledgeBasesAsyncClient, transports.KnowledgeBasesGrpcAsyncIOTransport, "grpc_asyncio"), - (KnowledgeBasesClient, transports.KnowledgeBasesRestTransport, "rest"), -]) -def test_knowledge_bases_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, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=["1", "2"], - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - -@pytest.mark.parametrize("client_class,transport_class,transport_name,grpc_helpers", [ - (KnowledgeBasesClient, transports.KnowledgeBasesGrpcTransport, "grpc", grpc_helpers), - (KnowledgeBasesAsyncClient, transports.KnowledgeBasesGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), - (KnowledgeBasesClient, transports.KnowledgeBasesRestTransport, "rest", None), -]) -def test_knowledge_bases_client_client_options_credentials_file(client_class, transport_class, transport_name, grpc_helpers): - # 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, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file="credentials.json", - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - -def test_knowledge_bases_client_client_options_from_dict(): - with mock.patch('google.cloud.dialogflow_v2.services.knowledge_bases.transports.KnowledgeBasesGrpcTransport.__init__') as grpc_transport: - grpc_transport.return_value = None - client = KnowledgeBasesClient( - client_options={'api_endpoint': 'squid.clam.whelk'} - ) - grpc_transport.assert_called_once_with( - credentials=None, - credentials_file=None, - host="squid.clam.whelk", - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - -@pytest.mark.parametrize("client_class,transport_class,transport_name,grpc_helpers", [ - (KnowledgeBasesClient, transports.KnowledgeBasesGrpcTransport, "grpc", grpc_helpers), - (KnowledgeBasesAsyncClient, transports.KnowledgeBasesGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), -]) -def test_knowledge_bases_client_create_channel_credentials_file(client_class, transport_class, transport_name, grpc_helpers): - # 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, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file="credentials.json", - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # test that the credentials from file are saved and used as the credentials. - with mock.patch.object( - google.auth, "load_credentials_from_file", autospec=True - ) as load_creds, mock.patch.object( - google.auth, "default", autospec=True - ) as adc, mock.patch.object( - grpc_helpers, "create_channel" - ) as create_channel: - creds = ga_credentials.AnonymousCredentials() - file_creds = ga_credentials.AnonymousCredentials() - load_creds.return_value = (file_creds, None) - adc.return_value = (creds, None) - client = client_class(client_options=options, transport=transport_name) - create_channel.assert_called_with( - "dialogflow.googleapis.com:443", - credentials=file_creds, - credentials_file=None, - quota_project_id=None, - default_scopes=( - 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/dialogflow', -), - scopes=None, - default_host="dialogflow.googleapis.com", - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - -@pytest.mark.parametrize("request_type", [ - knowledge_base.ListKnowledgeBasesRequest, - dict, -]) -def test_list_knowledge_bases(request_type, transport: str = 'grpc'): - client = KnowledgeBasesClient( - 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_knowledge_bases), - '__call__') as call: - # Designate an appropriate return value for the call. - 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' - - -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=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_knowledge_bases), - '__call__') as call: - client.list_knowledge_bases() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == knowledge_base.ListKnowledgeBasesRequest() - -@pytest.mark.asyncio -async def test_list_knowledge_bases_async(transport: str = 'grpc_asyncio', request_type=knowledge_base.ListKnowledgeBasesRequest): - client = KnowledgeBasesAsyncClient( - 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_knowledge_bases), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(knowledge_base.ListKnowledgeBasesResponse( - 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' - - -@pytest.mark.asyncio -async def test_list_knowledge_bases_async_from_dict(): - await test_list_knowledge_bases_async(request_type=dict) - - -def test_list_knowledge_bases_field_headers(): - 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. - with mock.patch.object( - 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. - 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_knowledge_bases_field_headers_async(): - 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. - with mock.patch.object( - type(client.transport.list_knowledge_bases), - '__call__') as call: - 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. - 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_knowledge_bases_flattened(): - client = KnowledgeBasesClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_knowledge_bases), - '__call__') 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', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - arg = args[0].parent - mock_val = 'parent_value' - assert arg == mock_val - - -def test_list_knowledge_bases_flattened_error(): - client = KnowledgeBasesClient( - 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_knowledge_bases( - knowledge_base.ListKnowledgeBasesRequest(), - parent='parent_value', - ) - -@pytest.mark.asyncio -async def test_list_knowledge_bases_flattened_async(): - client = KnowledgeBasesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_knowledge_bases), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = knowledge_base.ListKnowledgeBasesResponse() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(knowledge_base.ListKnowledgeBasesResponse()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.list_knowledge_bases( - 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] - arg = args[0].parent - mock_val = 'parent_value' - assert arg == mock_val - -@pytest.mark.asyncio -async def test_list_knowledge_bases_flattened_error_async(): - client = KnowledgeBasesAsyncClient( - 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_knowledge_bases( - knowledge_base.ListKnowledgeBasesRequest(), - parent='parent_value', - ) - - -def test_list_knowledge_bases_pager(transport_name: str = "grpc"): - client = KnowledgeBasesClient( - credentials=ga_credentials.AnonymousCredentials, - transport=transport_name, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_knowledge_bases), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - knowledge_base.ListKnowledgeBasesResponse( - knowledge_bases=[ - knowledge_base.KnowledgeBase(), - knowledge_base.KnowledgeBase(), - knowledge_base.KnowledgeBase(), - ], - next_page_token='abc', - ), - knowledge_base.ListKnowledgeBasesResponse( - knowledge_bases=[], - next_page_token='def', - ), - knowledge_base.ListKnowledgeBasesResponse( - knowledge_bases=[ - knowledge_base.KnowledgeBase(), - ], - next_page_token='ghi', - ), - knowledge_base.ListKnowledgeBasesResponse( - knowledge_bases=[ - knowledge_base.KnowledgeBase(), - knowledge_base.KnowledgeBase(), - ], - ), - RuntimeError, - ) - - metadata = () - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ('parent', ''), - )), - ) - pager = client.list_knowledge_bases(request={}) - - assert pager._metadata == metadata - - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, knowledge_base.KnowledgeBase) - for i in results) -def test_list_knowledge_bases_pages(transport_name: str = "grpc"): - client = KnowledgeBasesClient( - credentials=ga_credentials.AnonymousCredentials, - transport=transport_name, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_knowledge_bases), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - knowledge_base.ListKnowledgeBasesResponse( - knowledge_bases=[ - knowledge_base.KnowledgeBase(), - knowledge_base.KnowledgeBase(), - knowledge_base.KnowledgeBase(), - ], - next_page_token='abc', - ), - knowledge_base.ListKnowledgeBasesResponse( - knowledge_bases=[], - next_page_token='def', - ), - knowledge_base.ListKnowledgeBasesResponse( - knowledge_bases=[ - knowledge_base.KnowledgeBase(), - ], - next_page_token='ghi', - ), - knowledge_base.ListKnowledgeBasesResponse( - knowledge_bases=[ - knowledge_base.KnowledgeBase(), - knowledge_base.KnowledgeBase(), - ], - ), - RuntimeError, - ) - pages = list(client.list_knowledge_bases(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_knowledge_bases_async_pager(): - client = KnowledgeBasesAsyncClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_knowledge_bases), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - knowledge_base.ListKnowledgeBasesResponse( - knowledge_bases=[ - knowledge_base.KnowledgeBase(), - knowledge_base.KnowledgeBase(), - knowledge_base.KnowledgeBase(), - ], - next_page_token='abc', - ), - knowledge_base.ListKnowledgeBasesResponse( - knowledge_bases=[], - next_page_token='def', - ), - knowledge_base.ListKnowledgeBasesResponse( - knowledge_bases=[ - knowledge_base.KnowledgeBase(), - ], - next_page_token='ghi', - ), - knowledge_base.ListKnowledgeBasesResponse( - knowledge_bases=[ - knowledge_base.KnowledgeBase(), - knowledge_base.KnowledgeBase(), - ], - ), - RuntimeError, - ) - async_pager = await client.list_knowledge_bases(request={},) - assert async_pager.next_page_token == 'abc' - responses = [] - async for response in async_pager: # pragma: no branch - responses.append(response) - - assert len(responses) == 6 - assert all(isinstance(i, knowledge_base.KnowledgeBase) - for i in responses) - - -@pytest.mark.asyncio -async def test_list_knowledge_bases_async_pages(): - client = KnowledgeBasesAsyncClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_knowledge_bases), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - knowledge_base.ListKnowledgeBasesResponse( - knowledge_bases=[ - knowledge_base.KnowledgeBase(), - knowledge_base.KnowledgeBase(), - knowledge_base.KnowledgeBase(), - ], - next_page_token='abc', - ), - knowledge_base.ListKnowledgeBasesResponse( - knowledge_bases=[], - next_page_token='def', - ), - knowledge_base.ListKnowledgeBasesResponse( - knowledge_bases=[ - knowledge_base.KnowledgeBase(), - ], - next_page_token='ghi', - ), - knowledge_base.ListKnowledgeBasesResponse( - knowledge_bases=[ - knowledge_base.KnowledgeBase(), - knowledge_base.KnowledgeBase(), - ], - ), - RuntimeError, - ) - pages = [] - async for page_ in (await client.list_knowledge_bases(request={})).pages: # pragma: no branch - pages.append(page_) - for page_, token in zip(pages, ['abc','def','ghi', '']): - assert page_.raw_page.next_page_token == token - -@pytest.mark.parametrize("request_type", [ - knowledge_base.GetKnowledgeBaseRequest, - dict, -]) -def test_get_knowledge_base(request_type, transport: str = 'grpc'): - client = KnowledgeBasesClient( - 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_knowledge_base), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = knowledge_base.KnowledgeBase( - name='name_value', - 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' - - -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=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_knowledge_base), - '__call__') as call: - client.get_knowledge_base() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == knowledge_base.GetKnowledgeBaseRequest() - -@pytest.mark.asyncio -async def test_get_knowledge_base_async(transport: str = 'grpc_asyncio', request_type=knowledge_base.GetKnowledgeBaseRequest): - client = KnowledgeBasesAsyncClient( - 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_knowledge_base), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(knowledge_base.KnowledgeBase( - name='name_value', - display_name='display_name_value', - 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' - - -@pytest.mark.asyncio -async def test_get_knowledge_base_async_from_dict(): - await test_get_knowledge_base_async(request_type=dict) - - -def test_get_knowledge_base_field_headers(): - 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. - with mock.patch.object( - 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. - 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_knowledge_base_field_headers_async(): - 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. - with mock.patch.object( - type(client.transport.get_knowledge_base), - '__call__') as call: - 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. - 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_knowledge_base_flattened(): - client = KnowledgeBasesClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_knowledge_base), - '__call__') 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', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - arg = args[0].name - mock_val = 'name_value' - assert arg == mock_val - - -def test_get_knowledge_base_flattened_error(): - client = KnowledgeBasesClient( - 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_knowledge_base( - knowledge_base.GetKnowledgeBaseRequest(), - name='name_value', - ) - -@pytest.mark.asyncio -async def test_get_knowledge_base_flattened_async(): - client = KnowledgeBasesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_knowledge_base), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = knowledge_base.KnowledgeBase() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(knowledge_base.KnowledgeBase()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.get_knowledge_base( - 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] - arg = args[0].name - mock_val = 'name_value' - assert arg == mock_val - -@pytest.mark.asyncio -async def test_get_knowledge_base_flattened_error_async(): - client = KnowledgeBasesAsyncClient( - 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_knowledge_base( - knowledge_base.GetKnowledgeBaseRequest(), - name='name_value', - ) - - -@pytest.mark.parametrize("request_type", [ - gcd_knowledge_base.CreateKnowledgeBaseRequest, - dict, -]) -def test_create_knowledge_base(request_type, transport: str = 'grpc'): - client = KnowledgeBasesClient( - 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_knowledge_base), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcd_knowledge_base.KnowledgeBase( - name='name_value', - 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' - - -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=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_knowledge_base), - '__call__') as call: - client.create_knowledge_base() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == gcd_knowledge_base.CreateKnowledgeBaseRequest() - -@pytest.mark.asyncio -async def test_create_knowledge_base_async(transport: str = 'grpc_asyncio', request_type=gcd_knowledge_base.CreateKnowledgeBaseRequest): - client = KnowledgeBasesAsyncClient( - 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_knowledge_base), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gcd_knowledge_base.KnowledgeBase( - name='name_value', - display_name='display_name_value', - 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' - - -@pytest.mark.asyncio -async def test_create_knowledge_base_async_from_dict(): - await test_create_knowledge_base_async(request_type=dict) - - -def test_create_knowledge_base_field_headers(): - 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. - with mock.patch.object( - 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. - 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_knowledge_base_field_headers_async(): - 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. - with mock.patch.object( - type(client.transport.create_knowledge_base), - '__call__') as call: - 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. - 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_knowledge_base_flattened(): - client = KnowledgeBasesClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_knowledge_base), - '__call__') 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( - parent='parent_value', - knowledge_base=gcd_knowledge_base.KnowledgeBase(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] - arg = args[0].parent - mock_val = 'parent_value' - assert arg == mock_val - arg = args[0].knowledge_base - mock_val = gcd_knowledge_base.KnowledgeBase(name='name_value') - assert arg == mock_val - - -def test_create_knowledge_base_flattened_error(): - client = KnowledgeBasesClient( - 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_knowledge_base( - gcd_knowledge_base.CreateKnowledgeBaseRequest(), - parent='parent_value', - knowledge_base=gcd_knowledge_base.KnowledgeBase(name='name_value'), - ) - -@pytest.mark.asyncio -async def test_create_knowledge_base_flattened_async(): - client = KnowledgeBasesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_knowledge_base), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcd_knowledge_base.KnowledgeBase() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcd_knowledge_base.KnowledgeBase()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.create_knowledge_base( - parent='parent_value', - knowledge_base=gcd_knowledge_base.KnowledgeBase(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] - arg = args[0].parent - mock_val = 'parent_value' - assert arg == mock_val - arg = args[0].knowledge_base - mock_val = gcd_knowledge_base.KnowledgeBase(name='name_value') - assert arg == mock_val - -@pytest.mark.asyncio -async def test_create_knowledge_base_flattened_error_async(): - client = KnowledgeBasesAsyncClient( - 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_knowledge_base( - gcd_knowledge_base.CreateKnowledgeBaseRequest(), - parent='parent_value', - knowledge_base=gcd_knowledge_base.KnowledgeBase(name='name_value'), - ) - - -@pytest.mark.parametrize("request_type", [ - knowledge_base.DeleteKnowledgeBaseRequest, - dict, -]) -def test_delete_knowledge_base(request_type, transport: str = 'grpc'): - client = KnowledgeBasesClient( - 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_knowledge_base), - '__call__') 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. - assert response is None - - -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=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_knowledge_base), - '__call__') as call: - client.delete_knowledge_base() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == knowledge_base.DeleteKnowledgeBaseRequest() - -@pytest.mark.asyncio -async def test_delete_knowledge_base_async(transport: str = 'grpc_asyncio', request_type=knowledge_base.DeleteKnowledgeBaseRequest): - client = KnowledgeBasesAsyncClient( - 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_knowledge_base), - '__call__') 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. - assert response is None - - -@pytest.mark.asyncio -async def test_delete_knowledge_base_async_from_dict(): - await test_delete_knowledge_base_async(request_type=dict) - - -def test_delete_knowledge_base_field_headers(): - 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. - with mock.patch.object( - 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. - 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_knowledge_base_field_headers_async(): - 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. - with mock.patch.object( - 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. - 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_knowledge_base_flattened(): - client = KnowledgeBasesClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_knowledge_base), - '__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_knowledge_base( - 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] - arg = args[0].name - mock_val = 'name_value' - assert arg == mock_val - - -def test_delete_knowledge_base_flattened_error(): - client = KnowledgeBasesClient( - 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_knowledge_base( - knowledge_base.DeleteKnowledgeBaseRequest(), - name='name_value', - ) - -@pytest.mark.asyncio -async def test_delete_knowledge_base_flattened_async(): - client = KnowledgeBasesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_knowledge_base), - '__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_knowledge_base( - 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] - arg = args[0].name - mock_val = 'name_value' - assert arg == mock_val - -@pytest.mark.asyncio -async def test_delete_knowledge_base_flattened_error_async(): - client = KnowledgeBasesAsyncClient( - 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_knowledge_base( - knowledge_base.DeleteKnowledgeBaseRequest(), - name='name_value', - ) - - -@pytest.mark.parametrize("request_type", [ - gcd_knowledge_base.UpdateKnowledgeBaseRequest, - dict, -]) -def test_update_knowledge_base(request_type, transport: str = 'grpc'): - client = KnowledgeBasesClient( - 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_knowledge_base), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcd_knowledge_base.KnowledgeBase( - name='name_value', - 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' - - -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=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_knowledge_base), - '__call__') as call: - client.update_knowledge_base() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == gcd_knowledge_base.UpdateKnowledgeBaseRequest() - -@pytest.mark.asyncio -async def test_update_knowledge_base_async(transport: str = 'grpc_asyncio', request_type=gcd_knowledge_base.UpdateKnowledgeBaseRequest): - client = KnowledgeBasesAsyncClient( - 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_knowledge_base), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gcd_knowledge_base.KnowledgeBase( - name='name_value', - display_name='display_name_value', - 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' - - -@pytest.mark.asyncio -async def test_update_knowledge_base_async_from_dict(): - await test_update_knowledge_base_async(request_type=dict) - - -def test_update_knowledge_base_field_headers(): - 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 = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - 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. - 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', - 'knowledge_base.name=name_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_update_knowledge_base_field_headers_async(): - 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 = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_knowledge_base), - '__call__') as call: - 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. - 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', - 'knowledge_base.name=name_value', - ) in kw['metadata'] - - -def test_update_knowledge_base_flattened(): - client = KnowledgeBasesClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_knowledge_base), - '__call__') 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_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] - arg = args[0].knowledge_base - mock_val = gcd_knowledge_base.KnowledgeBase(name='name_value') - assert arg == mock_val - arg = args[0].update_mask - mock_val = field_mask_pb2.FieldMask(paths=['paths_value']) - assert arg == mock_val - - -def test_update_knowledge_base_flattened_error(): - client = KnowledgeBasesClient( - 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_knowledge_base( - gcd_knowledge_base.UpdateKnowledgeBaseRequest(), - knowledge_base=gcd_knowledge_base.KnowledgeBase(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - -@pytest.mark.asyncio -async def test_update_knowledge_base_flattened_async(): - client = KnowledgeBasesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_knowledge_base), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcd_knowledge_base.KnowledgeBase() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcd_knowledge_base.KnowledgeBase()) - # Call the method with a truthy value for each flattened field, - # 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_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] - arg = args[0].knowledge_base - mock_val = gcd_knowledge_base.KnowledgeBase(name='name_value') - assert arg == mock_val - arg = args[0].update_mask - mock_val = field_mask_pb2.FieldMask(paths=['paths_value']) - assert arg == mock_val - -@pytest.mark.asyncio -async def test_update_knowledge_base_flattened_error_async(): - client = KnowledgeBasesAsyncClient( - 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_knowledge_base( - gcd_knowledge_base.UpdateKnowledgeBaseRequest(), - knowledge_base=gcd_knowledge_base.KnowledgeBase(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - - -@pytest.mark.parametrize("request_type", [ - knowledge_base.ListKnowledgeBasesRequest, - dict, -]) -def test_list_knowledge_bases_rest(request_type): - client = KnowledgeBasesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = knowledge_base.ListKnowledgeBasesResponse( - next_page_token='next_page_token_value', - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - pb_return_value = knowledge_base.ListKnowledgeBasesResponse.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.list_knowledge_bases(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListKnowledgeBasesPager) - assert response.next_page_token == 'next_page_token_value' - - -def test_list_knowledge_bases_rest_required_fields(request_type=knowledge_base.ListKnowledgeBasesRequest): - transport_class = transports.KnowledgeBasesRestTransport - - request_init = {} - request_init["parent"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - including_default_value_fields=False, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).list_knowledge_bases._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["parent"] = 'parent_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).list_knowledge_bases._get_unset_required_fields(jsonified_request) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("filter", "page_size", "page_token", )) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "parent" in jsonified_request - assert jsonified_request["parent"] == 'parent_value' - - client = KnowledgeBasesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = knowledge_base.ListKnowledgeBasesResponse() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "get", - 'query_params': pb_request, - } - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - - pb_return_value = knowledge_base.ListKnowledgeBasesResponse.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.list_knowledge_bases(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_list_knowledge_bases_rest_unset_required_fields(): - transport = transports.KnowledgeBasesRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.list_knowledge_bases._get_unset_required_fields({}) - assert set(unset_fields) == (set(("filter", "pageSize", "pageToken", )) & set(("parent", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_list_knowledge_bases_rest_interceptors(null_interceptor): - transport = transports.KnowledgeBasesRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.KnowledgeBasesRestInterceptor(), - ) - client = KnowledgeBasesClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.KnowledgeBasesRestInterceptor, "post_list_knowledge_bases") as post, \ - mock.patch.object(transports.KnowledgeBasesRestInterceptor, "pre_list_knowledge_bases") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = knowledge_base.ListKnowledgeBasesRequest.pb(knowledge_base.ListKnowledgeBasesRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = knowledge_base.ListKnowledgeBasesResponse.to_json(knowledge_base.ListKnowledgeBasesResponse()) - - request = knowledge_base.ListKnowledgeBasesRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = knowledge_base.ListKnowledgeBasesResponse() - - client.list_knowledge_bases(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_list_knowledge_bases_rest_bad_request(transport: str = 'rest', request_type=knowledge_base.ListKnowledgeBasesRequest): - client = KnowledgeBasesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.list_knowledge_bases(request) - - -def test_list_knowledge_bases_rest_flattened(): - client = KnowledgeBasesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = knowledge_base.ListKnowledgeBasesResponse() - - # get arguments that satisfy an http rule for this method - sample_request = {'parent': 'projects/sample1'} - - # get truthy value for each flattened field - mock_args = dict( - parent='parent_value', - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - pb_return_value = knowledge_base.ListKnowledgeBasesResponse.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.list_knowledge_bases(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v2/{parent=projects/*}/knowledgeBases" % client.transport._host, args[1]) - - -def test_list_knowledge_bases_rest_flattened_error(transport: str = 'rest'): - client = KnowledgeBasesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.list_knowledge_bases( - knowledge_base.ListKnowledgeBasesRequest(), - parent='parent_value', - ) - - -def test_list_knowledge_bases_rest_pager(transport: str = 'rest'): - client = KnowledgeBasesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # TODO(kbandes): remove this mock unless there's a good reason for it. - #with mock.patch.object(path_template, 'transcode') as transcode: - # Set the response as a series of pages - response = ( - knowledge_base.ListKnowledgeBasesResponse( - knowledge_bases=[ - knowledge_base.KnowledgeBase(), - knowledge_base.KnowledgeBase(), - knowledge_base.KnowledgeBase(), - ], - next_page_token='abc', - ), - knowledge_base.ListKnowledgeBasesResponse( - knowledge_bases=[], - next_page_token='def', - ), - knowledge_base.ListKnowledgeBasesResponse( - knowledge_bases=[ - knowledge_base.KnowledgeBase(), - ], - next_page_token='ghi', - ), - knowledge_base.ListKnowledgeBasesResponse( - knowledge_bases=[ - knowledge_base.KnowledgeBase(), - knowledge_base.KnowledgeBase(), - ], - ), - ) - # Two responses for two calls - response = response + response - - # Wrap the values into proper Response objs - response = tuple(knowledge_base.ListKnowledgeBasesResponse.to_json(x) for x in response) - return_values = tuple(Response() for i in response) - for return_val, response_val in zip(return_values, response): - return_val._content = response_val.encode('UTF-8') - return_val.status_code = 200 - req.side_effect = return_values - - sample_request = {'parent': 'projects/sample1'} - - pager = client.list_knowledge_bases(request=sample_request) - - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, knowledge_base.KnowledgeBase) - for i in results) - - pages = list(client.list_knowledge_bases(request=sample_request).pages) - for page_, token in zip(pages, ['abc','def','ghi', '']): - assert page_.raw_page.next_page_token == token - - -@pytest.mark.parametrize("request_type", [ - knowledge_base.GetKnowledgeBaseRequest, - dict, -]) -def test_get_knowledge_base_rest(request_type): - client = KnowledgeBasesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/knowledgeBases/sample2'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = knowledge_base.KnowledgeBase( - name='name_value', - display_name='display_name_value', - language_code='language_code_value', - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - pb_return_value = knowledge_base.KnowledgeBase.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.get_knowledge_base(request) - - # 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' - - -def test_get_knowledge_base_rest_required_fields(request_type=knowledge_base.GetKnowledgeBaseRequest): - transport_class = transports.KnowledgeBasesRestTransport - - request_init = {} - request_init["name"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - including_default_value_fields=False, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_knowledge_base._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["name"] = 'name_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_knowledge_base._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "name" in jsonified_request - assert jsonified_request["name"] == 'name_value' - - client = KnowledgeBasesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = knowledge_base.KnowledgeBase() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "get", - 'query_params': pb_request, - } - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - - pb_return_value = knowledge_base.KnowledgeBase.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.get_knowledge_base(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_get_knowledge_base_rest_unset_required_fields(): - transport = transports.KnowledgeBasesRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.get_knowledge_base._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_get_knowledge_base_rest_interceptors(null_interceptor): - transport = transports.KnowledgeBasesRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.KnowledgeBasesRestInterceptor(), - ) - client = KnowledgeBasesClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.KnowledgeBasesRestInterceptor, "post_get_knowledge_base") as post, \ - mock.patch.object(transports.KnowledgeBasesRestInterceptor, "pre_get_knowledge_base") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = knowledge_base.GetKnowledgeBaseRequest.pb(knowledge_base.GetKnowledgeBaseRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = knowledge_base.KnowledgeBase.to_json(knowledge_base.KnowledgeBase()) - - request = knowledge_base.GetKnowledgeBaseRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = knowledge_base.KnowledgeBase() - - client.get_knowledge_base(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_get_knowledge_base_rest_bad_request(transport: str = 'rest', request_type=knowledge_base.GetKnowledgeBaseRequest): - client = KnowledgeBasesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/knowledgeBases/sample2'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.get_knowledge_base(request) - - -def test_get_knowledge_base_rest_flattened(): - client = KnowledgeBasesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = knowledge_base.KnowledgeBase() - - # get arguments that satisfy an http rule for this method - sample_request = {'name': 'projects/sample1/knowledgeBases/sample2'} - - # get truthy value for each flattened field - mock_args = dict( - name='name_value', - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - pb_return_value = knowledge_base.KnowledgeBase.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.get_knowledge_base(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v2/{name=projects/*/knowledgeBases/*}" % client.transport._host, args[1]) - - -def test_get_knowledge_base_rest_flattened_error(transport: str = 'rest'): - client = KnowledgeBasesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.get_knowledge_base( - knowledge_base.GetKnowledgeBaseRequest(), - name='name_value', - ) - - -def test_get_knowledge_base_rest_error(): - client = KnowledgeBasesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - gcd_knowledge_base.CreateKnowledgeBaseRequest, - dict, -]) -def test_create_knowledge_base_rest(request_type): - client = KnowledgeBasesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1'} - request_init["knowledge_base"] = {'name': 'name_value', 'display_name': 'display_name_value', 'language_code': 'language_code_value'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = gcd_knowledge_base.KnowledgeBase( - name='name_value', - display_name='display_name_value', - language_code='language_code_value', - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - pb_return_value = gcd_knowledge_base.KnowledgeBase.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.create_knowledge_base(request) - - # 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' - - -def test_create_knowledge_base_rest_required_fields(request_type=gcd_knowledge_base.CreateKnowledgeBaseRequest): - transport_class = transports.KnowledgeBasesRestTransport - - request_init = {} - request_init["parent"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - including_default_value_fields=False, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_knowledge_base._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["parent"] = 'parent_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_knowledge_base._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "parent" in jsonified_request - assert jsonified_request["parent"] == 'parent_value' - - client = KnowledgeBasesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = gcd_knowledge_base.KnowledgeBase() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "post", - 'query_params': pb_request, - } - transcode_result['body'] = pb_request - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - - pb_return_value = gcd_knowledge_base.KnowledgeBase.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.create_knowledge_base(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_create_knowledge_base_rest_unset_required_fields(): - transport = transports.KnowledgeBasesRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.create_knowledge_base._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("parent", "knowledgeBase", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_create_knowledge_base_rest_interceptors(null_interceptor): - transport = transports.KnowledgeBasesRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.KnowledgeBasesRestInterceptor(), - ) - client = KnowledgeBasesClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.KnowledgeBasesRestInterceptor, "post_create_knowledge_base") as post, \ - mock.patch.object(transports.KnowledgeBasesRestInterceptor, "pre_create_knowledge_base") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = gcd_knowledge_base.CreateKnowledgeBaseRequest.pb(gcd_knowledge_base.CreateKnowledgeBaseRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = gcd_knowledge_base.KnowledgeBase.to_json(gcd_knowledge_base.KnowledgeBase()) - - request = gcd_knowledge_base.CreateKnowledgeBaseRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = gcd_knowledge_base.KnowledgeBase() - - client.create_knowledge_base(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_create_knowledge_base_rest_bad_request(transport: str = 'rest', request_type=gcd_knowledge_base.CreateKnowledgeBaseRequest): - client = KnowledgeBasesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1'} - request_init["knowledge_base"] = {'name': 'name_value', 'display_name': 'display_name_value', 'language_code': 'language_code_value'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.create_knowledge_base(request) - - -def test_create_knowledge_base_rest_flattened(): - client = KnowledgeBasesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = gcd_knowledge_base.KnowledgeBase() - - # get arguments that satisfy an http rule for this method - sample_request = {'parent': 'projects/sample1'} - - # get truthy value for each flattened field - mock_args = dict( - parent='parent_value', - knowledge_base=gcd_knowledge_base.KnowledgeBase(name='name_value'), - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - pb_return_value = gcd_knowledge_base.KnowledgeBase.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.create_knowledge_base(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v2/{parent=projects/*}/knowledgeBases" % client.transport._host, args[1]) - - -def test_create_knowledge_base_rest_flattened_error(transport: str = 'rest'): - client = KnowledgeBasesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.create_knowledge_base( - gcd_knowledge_base.CreateKnowledgeBaseRequest(), - parent='parent_value', - knowledge_base=gcd_knowledge_base.KnowledgeBase(name='name_value'), - ) - - -def test_create_knowledge_base_rest_error(): - client = KnowledgeBasesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - knowledge_base.DeleteKnowledgeBaseRequest, - dict, -]) -def test_delete_knowledge_base_rest(request_type): - client = KnowledgeBasesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/knowledgeBases/sample2'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = None - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = '' - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.delete_knowledge_base(request) - - # Establish that the response is the type that we expect. - assert response is None - - -def test_delete_knowledge_base_rest_required_fields(request_type=knowledge_base.DeleteKnowledgeBaseRequest): - transport_class = transports.KnowledgeBasesRestTransport - - request_init = {} - request_init["name"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - including_default_value_fields=False, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).delete_knowledge_base._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["name"] = 'name_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).delete_knowledge_base._get_unset_required_fields(jsonified_request) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("force", )) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "name" in jsonified_request - assert jsonified_request["name"] == 'name_value' - - client = KnowledgeBasesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = None - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "delete", - 'query_params': pb_request, - } - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - json_return_value = '' - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.delete_knowledge_base(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_delete_knowledge_base_rest_unset_required_fields(): - transport = transports.KnowledgeBasesRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.delete_knowledge_base._get_unset_required_fields({}) - assert set(unset_fields) == (set(("force", )) & set(("name", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_delete_knowledge_base_rest_interceptors(null_interceptor): - transport = transports.KnowledgeBasesRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.KnowledgeBasesRestInterceptor(), - ) - client = KnowledgeBasesClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.KnowledgeBasesRestInterceptor, "pre_delete_knowledge_base") as pre: - pre.assert_not_called() - pb_message = knowledge_base.DeleteKnowledgeBaseRequest.pb(knowledge_base.DeleteKnowledgeBaseRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - - request = knowledge_base.DeleteKnowledgeBaseRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - - client.delete_knowledge_base(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - - -def test_delete_knowledge_base_rest_bad_request(transport: str = 'rest', request_type=knowledge_base.DeleteKnowledgeBaseRequest): - client = KnowledgeBasesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/knowledgeBases/sample2'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.delete_knowledge_base(request) - - -def test_delete_knowledge_base_rest_flattened(): - client = KnowledgeBasesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = None - - # get arguments that satisfy an http rule for this method - sample_request = {'name': 'projects/sample1/knowledgeBases/sample2'} - - # get truthy value for each flattened field - mock_args = dict( - name='name_value', - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = '' - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.delete_knowledge_base(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v2/{name=projects/*/knowledgeBases/*}" % client.transport._host, args[1]) - - -def test_delete_knowledge_base_rest_flattened_error(transport: str = 'rest'): - client = KnowledgeBasesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.delete_knowledge_base( - knowledge_base.DeleteKnowledgeBaseRequest(), - name='name_value', - ) - - -def test_delete_knowledge_base_rest_error(): - client = KnowledgeBasesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - gcd_knowledge_base.UpdateKnowledgeBaseRequest, - dict, -]) -def test_update_knowledge_base_rest(request_type): - client = KnowledgeBasesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'knowledge_base': {'name': 'projects/sample1/knowledgeBases/sample2'}} - request_init["knowledge_base"] = {'name': 'projects/sample1/knowledgeBases/sample2', 'display_name': 'display_name_value', 'language_code': 'language_code_value'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = gcd_knowledge_base.KnowledgeBase( - name='name_value', - display_name='display_name_value', - language_code='language_code_value', - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - pb_return_value = gcd_knowledge_base.KnowledgeBase.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.update_knowledge_base(request) - - # 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' - - -def test_update_knowledge_base_rest_required_fields(request_type=gcd_knowledge_base.UpdateKnowledgeBaseRequest): - transport_class = transports.KnowledgeBasesRestTransport - - request_init = {} - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - including_default_value_fields=False, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).update_knowledge_base._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).update_knowledge_base._get_unset_required_fields(jsonified_request) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("update_mask", )) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - - client = KnowledgeBasesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = gcd_knowledge_base.KnowledgeBase() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "patch", - 'query_params': pb_request, - } - transcode_result['body'] = pb_request - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - - pb_return_value = gcd_knowledge_base.KnowledgeBase.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.update_knowledge_base(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_update_knowledge_base_rest_unset_required_fields(): - transport = transports.KnowledgeBasesRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.update_knowledge_base._get_unset_required_fields({}) - assert set(unset_fields) == (set(("updateMask", )) & set(("knowledgeBase", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_update_knowledge_base_rest_interceptors(null_interceptor): - transport = transports.KnowledgeBasesRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.KnowledgeBasesRestInterceptor(), - ) - client = KnowledgeBasesClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.KnowledgeBasesRestInterceptor, "post_update_knowledge_base") as post, \ - mock.patch.object(transports.KnowledgeBasesRestInterceptor, "pre_update_knowledge_base") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = gcd_knowledge_base.UpdateKnowledgeBaseRequest.pb(gcd_knowledge_base.UpdateKnowledgeBaseRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = gcd_knowledge_base.KnowledgeBase.to_json(gcd_knowledge_base.KnowledgeBase()) - - request = gcd_knowledge_base.UpdateKnowledgeBaseRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = gcd_knowledge_base.KnowledgeBase() - - client.update_knowledge_base(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_update_knowledge_base_rest_bad_request(transport: str = 'rest', request_type=gcd_knowledge_base.UpdateKnowledgeBaseRequest): - client = KnowledgeBasesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'knowledge_base': {'name': 'projects/sample1/knowledgeBases/sample2'}} - request_init["knowledge_base"] = {'name': 'projects/sample1/knowledgeBases/sample2', 'display_name': 'display_name_value', 'language_code': 'language_code_value'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.update_knowledge_base(request) - - -def test_update_knowledge_base_rest_flattened(): - client = KnowledgeBasesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = gcd_knowledge_base.KnowledgeBase() - - # get arguments that satisfy an http rule for this method - sample_request = {'knowledge_base': {'name': 'projects/sample1/knowledgeBases/sample2'}} - - # get truthy value for each flattened field - mock_args = dict( - knowledge_base=gcd_knowledge_base.KnowledgeBase(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - pb_return_value = gcd_knowledge_base.KnowledgeBase.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.update_knowledge_base(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v2/{knowledge_base.name=projects/*/knowledgeBases/*}" % client.transport._host, args[1]) - - -def test_update_knowledge_base_rest_flattened_error(transport: str = 'rest'): - client = KnowledgeBasesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.update_knowledge_base( - gcd_knowledge_base.UpdateKnowledgeBaseRequest(), - knowledge_base=gcd_knowledge_base.KnowledgeBase(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - - -def test_update_knowledge_base_rest_error(): - client = KnowledgeBasesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -def test_credentials_transport_error(): - # It is an error to provide credentials and a transport instance. - transport = transports.KnowledgeBasesGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = KnowledgeBasesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # It is an error to provide a credentials file and a transport instance. - transport = transports.KnowledgeBasesGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = KnowledgeBasesClient( - client_options={"credentials_file": "credentials.json"}, - transport=transport, - ) - - # It is an error to provide an api_key and a transport instance. - transport = transports.KnowledgeBasesGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - options = client_options.ClientOptions() - options.api_key = "api_key" - with pytest.raises(ValueError): - client = KnowledgeBasesClient( - client_options=options, - transport=transport, - ) - - # It is an error to provide an api_key and a credential. - options = mock.Mock() - options.api_key = "api_key" - with pytest.raises(ValueError): - client = KnowledgeBasesClient( - client_options=options, - credentials=ga_credentials.AnonymousCredentials() - ) - - # It is an error to provide scopes and a transport instance. - transport = transports.KnowledgeBasesGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = KnowledgeBasesClient( - client_options={"scopes": ["1", "2"]}, - transport=transport, - ) - - -def test_transport_instance(): - # A client may be instantiated with a custom transport instance. - transport = transports.KnowledgeBasesGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - client = KnowledgeBasesClient(transport=transport) - assert client.transport is transport - -def test_transport_get_channel(): - # A client may be instantiated with a custom transport instance. - transport = transports.KnowledgeBasesGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - - transport = transports.KnowledgeBasesGrpcAsyncIOTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - -@pytest.mark.parametrize("transport_class", [ - transports.KnowledgeBasesGrpcTransport, - transports.KnowledgeBasesGrpcAsyncIOTransport, - transports.KnowledgeBasesRestTransport, -]) -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() - -@pytest.mark.parametrize("transport_name", [ - "grpc", - "rest", -]) -def test_transport_kind(transport_name): - transport = KnowledgeBasesClient.get_transport_class(transport_name)( - credentials=ga_credentials.AnonymousCredentials(), - ) - assert transport.kind == transport_name - -def test_transport_grpc_default(): - # A client should use the gRPC transport by default. - 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(core_exceptions.DuplicateCredentialArgs): - transport = transports.KnowledgeBasesTransport( - credentials=ga_credentials.AnonymousCredentials(), - credentials_file="credentials.json" - ) - - -def test_knowledge_bases_base_transport(): - # Instantiate the base transport. - with mock.patch('google.cloud.dialogflow_v2.services.knowledge_bases.transports.KnowledgeBasesTransport.__init__') as Transport: - Transport.return_value = None - transport = transports.KnowledgeBasesTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Every method on the transport should just blindly - # raise NotImplementedError. - methods = ( - 'list_knowledge_bases', - 'get_knowledge_base', - 'create_knowledge_base', - 'delete_knowledge_base', - 'update_knowledge_base', - 'get_location', - 'list_locations', - 'get_operation', - 'cancel_operation', - 'list_operations', - ) - for method in methods: - with pytest.raises(NotImplementedError): - getattr(transport, method)(request=object()) - - with pytest.raises(NotImplementedError): - transport.close() - - # Catch all for all remaining methods and properties - remainder = [ - 'kind', - ] - for r in remainder: - with pytest.raises(NotImplementedError): - getattr(transport, r)() - - -def test_knowledge_bases_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.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", - ) - - -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(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 = (ga_credentials.AnonymousCredentials(), None) - transport = transports.KnowledgeBasesTransport() - adc.assert_called_once() - - -def test_knowledge_bases_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) - 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, - ) - - -@pytest.mark.parametrize( - "transport_class", - [ - transports.KnowledgeBasesGrpcTransport, - transports.KnowledgeBasesGrpcAsyncIOTransport, - ], -) -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(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, - transports.KnowledgeBasesRestTransport, - ], -) -def test_knowledge_bases_transport_auth_gdch_credentials(transport_class): - host = 'https://language.com' - api_audience_tests = [None, 'https://language2.com'] - api_audience_expect = [host, 'https://language2.com'] - for t, e in zip(api_audience_tests, api_audience_expect): - with mock.patch.object(google.auth, 'default', autospec=True) as adc: - gdch_mock = mock.MagicMock() - type(gdch_mock).with_gdch_audience = mock.PropertyMock(return_value=gdch_mock) - adc.return_value = (gdch_mock, None) - transport_class(host=host, api_audience=t) - gdch_mock.with_gdch_audience.assert_called_once_with( - e - ) - - -@pytest.mark.parametrize( - "transport_class,grpc_helpers", - [ - (transports.KnowledgeBasesGrpcTransport, grpc_helpers), - (transports.KnowledgeBasesGrpcAsyncIOTransport, grpc_helpers_async) - ], -) -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", [transports.KnowledgeBasesGrpcTransport, transports.KnowledgeBasesGrpcAsyncIOTransport]) -def test_knowledge_bases_grpc_transport_client_cert_source_for_mtls( - transport_class -): - cred = ga_credentials.AnonymousCredentials() - - # Check ssl_channel_credentials is used if provided. - with mock.patch.object(transport_class, "create_channel") as mock_create_channel: - mock_ssl_channel_creds = mock.Mock() - transport_class( - host="squid.clam.whelk", - credentials=cred, - ssl_channel_credentials=mock_ssl_channel_creds - ) - mock_create_channel.assert_called_once_with( - "squid.clam.whelk:443", - credentials=cred, - credentials_file=None, - scopes=None, - ssl_credentials=mock_ssl_channel_creds, - quota_project_id=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - # Check if ssl_channel_credentials is not provided, then client_cert_source_for_mtls - # is used. - with mock.patch.object(transport_class, "create_channel", return_value=mock.Mock()): - with mock.patch("grpc.ssl_channel_credentials") as mock_ssl_cred: - transport_class( - credentials=cred, - client_cert_source_for_mtls=client_cert_source_callback - ) - expected_cert, expected_key = client_cert_source_callback() - mock_ssl_cred.assert_called_once_with( - certificate_chain=expected_cert, - private_key=expected_key - ) - -def test_knowledge_bases_http_transport_client_cert_source_for_mtls(): - cred = ga_credentials.AnonymousCredentials() - with mock.patch("google.auth.transport.requests.AuthorizedSession.configure_mtls_channel") as mock_configure_mtls_channel: - transports.KnowledgeBasesRestTransport ( - credentials=cred, - client_cert_source_for_mtls=client_cert_source_callback - ) - mock_configure_mtls_channel.assert_called_once_with(client_cert_source_callback) - - -@pytest.mark.parametrize("transport_name", [ - "grpc", - "grpc_asyncio", - "rest", -]) -def test_knowledge_bases_host_no_port(transport_name): - client = KnowledgeBasesClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='dialogflow.googleapis.com'), - transport=transport_name, - ) - assert client.transport._host == ( - 'dialogflow.googleapis.com:443' - if transport_name in ['grpc', 'grpc_asyncio'] - else 'https://dialogflow.googleapis.com' - ) - -@pytest.mark.parametrize("transport_name", [ - "grpc", - "grpc_asyncio", - "rest", -]) -def test_knowledge_bases_host_with_port(transport_name): - client = KnowledgeBasesClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='dialogflow.googleapis.com:8000'), - transport=transport_name, - ) - assert client.transport._host == ( - 'dialogflow.googleapis.com:8000' - if transport_name in ['grpc', 'grpc_asyncio'] - else 'https://dialogflow.googleapis.com:8000' - ) - -@pytest.mark.parametrize("transport_name", [ - "rest", -]) -def test_knowledge_bases_client_transport_session_collision(transport_name): - creds1 = ga_credentials.AnonymousCredentials() - creds2 = ga_credentials.AnonymousCredentials() - client1 = KnowledgeBasesClient( - credentials=creds1, - transport=transport_name, - ) - client2 = KnowledgeBasesClient( - credentials=creds2, - transport=transport_name, - ) - session1 = client1.transport.list_knowledge_bases._session - session2 = client2.transport.list_knowledge_bases._session - assert session1 != session2 - session1 = client1.transport.get_knowledge_base._session - session2 = client2.transport.get_knowledge_base._session - assert session1 != session2 - session1 = client1.transport.create_knowledge_base._session - session2 = client2.transport.create_knowledge_base._session - assert session1 != session2 - session1 = client1.transport.delete_knowledge_base._session - session2 = client2.transport.delete_knowledge_base._session - assert session1 != session2 - session1 = client1.transport.update_knowledge_base._session - session2 = client2.transport.update_knowledge_base._session - assert session1 != session2 -def test_knowledge_bases_grpc_transport_channel(): - channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.KnowledgeBasesGrpcTransport( - 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_knowledge_bases_grpc_asyncio_transport_channel(): - channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.KnowledgeBasesGrpcAsyncIOTransport( - 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.KnowledgeBasesGrpcTransport, transports.KnowledgeBasesGrpcAsyncIOTransport]) -def test_knowledge_bases_transport_channel_mtls_with_client_cert_source( - transport_class -): - with mock.patch("grpc.ssl_channel_credentials", autospec=True) as grpc_ssl_channel_cred: - with mock.patch.object(transport_class, "create_channel") as grpc_create_channel: - mock_ssl_cred = mock.Mock() - grpc_ssl_channel_cred.return_value = mock_ssl_cred - - mock_grpc_channel = mock.Mock() - grpc_create_channel.return_value = mock_grpc_channel - - cred = ga_credentials.AnonymousCredentials() - with pytest.warns(DeprecationWarning): - with mock.patch.object(google.auth, 'default') as adc: - adc.return_value = (cred, None) - transport = transport_class( - host="squid.clam.whelk", - api_mtls_endpoint="mtls.squid.clam.whelk", - client_cert_source=client_cert_source_callback, - ) - adc.assert_called_once() - - grpc_ssl_channel_cred.assert_called_once_with( - certificate_chain=b"cert bytes", private_key=b"key bytes" - ) - grpc_create_channel.assert_called_once_with( - "mtls.squid.clam.whelk:443", - credentials=cred, - credentials_file=None, - scopes=None, - ssl_credentials=mock_ssl_cred, - quota_project_id=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - assert transport.grpc_channel == mock_grpc_channel - assert transport._ssl_channel_credentials == mock_ssl_cred - - -# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are -# removed from grpc/grpc_asyncio transport constructor. -@pytest.mark.parametrize("transport_class", [transports.KnowledgeBasesGrpcTransport, transports.KnowledgeBasesGrpcAsyncIOTransport]) -def test_knowledge_bases_transport_channel_mtls_with_adc( - transport_class -): - mock_ssl_cred = mock.Mock() - with mock.patch.multiple( - "google.auth.transport.grpc.SslCredentials", - __init__=mock.Mock(return_value=None), - ssl_credentials=mock.PropertyMock(return_value=mock_ssl_cred), - ): - with mock.patch.object(transport_class, "create_channel") as grpc_create_channel: - mock_grpc_channel = mock.Mock() - grpc_create_channel.return_value = mock_grpc_channel - mock_cred = mock.Mock() - - with pytest.warns(DeprecationWarning): - transport = transport_class( - host="squid.clam.whelk", - credentials=mock_cred, - api_mtls_endpoint="mtls.squid.clam.whelk", - client_cert_source=None, - ) - - grpc_create_channel.assert_called_once_with( - "mtls.squid.clam.whelk:443", - credentials=mock_cred, - credentials_file=None, - scopes=None, - ssl_credentials=mock_ssl_cred, - quota_project_id=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - assert transport.grpc_channel == mock_grpc_channel - - -def test_knowledge_base_path(): - project = "squid" - knowledge_base = "clam" - expected = "projects/{project}/knowledgeBases/{knowledge_base}".format(project=project, knowledge_base=knowledge_base, ) - actual = KnowledgeBasesClient.knowledge_base_path(project, knowledge_base) - assert expected == actual - - -def test_parse_knowledge_base_path(): - expected = { - "project": "whelk", - "knowledge_base": "octopus", - } - path = KnowledgeBasesClient.knowledge_base_path(**expected) - - # Check that the path construction is reversible. - actual = KnowledgeBasesClient.parse_knowledge_base_path(path) - assert expected == actual - -def test_common_billing_account_path(): - billing_account = "oyster" - expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) - actual = KnowledgeBasesClient.common_billing_account_path(billing_account) - assert expected == actual - - -def test_parse_common_billing_account_path(): - expected = { - "billing_account": "nudibranch", - } - path = KnowledgeBasesClient.common_billing_account_path(**expected) - - # Check that the path construction is reversible. - actual = KnowledgeBasesClient.parse_common_billing_account_path(path) - assert expected == actual - -def test_common_folder_path(): - folder = "cuttlefish" - expected = "folders/{folder}".format(folder=folder, ) - actual = KnowledgeBasesClient.common_folder_path(folder) - assert expected == actual - - -def test_parse_common_folder_path(): - expected = { - "folder": "mussel", - } - path = KnowledgeBasesClient.common_folder_path(**expected) - - # Check that the path construction is reversible. - actual = KnowledgeBasesClient.parse_common_folder_path(path) - assert expected == actual - -def test_common_organization_path(): - organization = "winkle" - expected = "organizations/{organization}".format(organization=organization, ) - actual = KnowledgeBasesClient.common_organization_path(organization) - assert expected == actual - - -def test_parse_common_organization_path(): - expected = { - "organization": "nautilus", - } - path = KnowledgeBasesClient.common_organization_path(**expected) - - # Check that the path construction is reversible. - actual = KnowledgeBasesClient.parse_common_organization_path(path) - assert expected == actual - -def test_common_project_path(): - project = "scallop" - expected = "projects/{project}".format(project=project, ) - actual = KnowledgeBasesClient.common_project_path(project) - assert expected == actual - - -def test_parse_common_project_path(): - expected = { - "project": "abalone", - } - path = KnowledgeBasesClient.common_project_path(**expected) - - # Check that the path construction is reversible. - actual = KnowledgeBasesClient.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 = KnowledgeBasesClient.common_location_path(project, location) - assert expected == actual - - -def test_parse_common_location_path(): - expected = { - "project": "whelk", - "location": "octopus", - } - path = KnowledgeBasesClient.common_location_path(**expected) - - # Check that the path construction is reversible. - actual = KnowledgeBasesClient.parse_common_location_path(path) - assert expected == actual - - -def test_client_with_default_client_info(): - client_info = gapic_v1.client_info.ClientInfo() - - with mock.patch.object(transports.KnowledgeBasesTransport, '_prep_wrapped_messages') as prep: - client = KnowledgeBasesClient( - credentials=ga_credentials.AnonymousCredentials(), - client_info=client_info, - ) - prep.assert_called_once_with(client_info) - - with mock.patch.object(transports.KnowledgeBasesTransport, '_prep_wrapped_messages') as prep: - transport_class = KnowledgeBasesClient.get_transport_class() - transport = transport_class( - credentials=ga_credentials.AnonymousCredentials(), - client_info=client_info, - ) - prep.assert_called_once_with(client_info) - -@pytest.mark.asyncio -async def test_transport_close_async(): - client = KnowledgeBasesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - with mock.patch.object(type(getattr(client.transport, "grpc_channel")), "close") as close: - async with client: - close.assert_not_called() - close.assert_called_once() - - -def test_get_location_rest_bad_request(transport: str = 'rest', request_type=locations_pb2.GetLocationRequest): - client = KnowledgeBasesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - request = request_type() - request = json_format.ParseDict({'name': 'projects/sample1/locations/sample2'}, request) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.get_location(request) - -@pytest.mark.parametrize("request_type", [ - locations_pb2.GetLocationRequest, - dict, -]) -def test_get_location_rest(request_type): - client = KnowledgeBasesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request_init = {'name': 'projects/sample1/locations/sample2'} - request = request_type(**request_init) - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = locations_pb2.Location() - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.get_location(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, locations_pb2.Location) - -def test_list_locations_rest_bad_request(transport: str = 'rest', request_type=locations_pb2.ListLocationsRequest): - client = KnowledgeBasesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - request = request_type() - request = json_format.ParseDict({'name': 'projects/sample1'}, request) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.list_locations(request) - -@pytest.mark.parametrize("request_type", [ - locations_pb2.ListLocationsRequest, - dict, -]) -def test_list_locations_rest(request_type): - client = KnowledgeBasesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request_init = {'name': 'projects/sample1'} - request = request_type(**request_init) - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = locations_pb2.ListLocationsResponse() - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.list_locations(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, locations_pb2.ListLocationsResponse) - -def test_cancel_operation_rest_bad_request(transport: str = 'rest', request_type=operations_pb2.CancelOperationRequest): - client = KnowledgeBasesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - request = request_type() - request = json_format.ParseDict({'name': 'projects/sample1/operations/sample2'}, request) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.cancel_operation(request) - -@pytest.mark.parametrize("request_type", [ - operations_pb2.CancelOperationRequest, - dict, -]) -def test_cancel_operation_rest(request_type): - client = KnowledgeBasesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request_init = {'name': 'projects/sample1/operations/sample2'} - request = request_type(**request_init) - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = None - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = '{}' - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.cancel_operation(request) - - # Establish that the response is the type that we expect. - assert response is None - -def test_get_operation_rest_bad_request(transport: str = 'rest', request_type=operations_pb2.GetOperationRequest): - client = KnowledgeBasesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - request = request_type() - request = json_format.ParseDict({'name': 'projects/sample1/operations/sample2'}, request) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.get_operation(request) - -@pytest.mark.parametrize("request_type", [ - operations_pb2.GetOperationRequest, - dict, -]) -def test_get_operation_rest(request_type): - client = KnowledgeBasesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request_init = {'name': 'projects/sample1/operations/sample2'} - request = request_type(**request_init) - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation() - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.get_operation(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, operations_pb2.Operation) - -def test_list_operations_rest_bad_request(transport: str = 'rest', request_type=operations_pb2.ListOperationsRequest): - client = KnowledgeBasesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - request = request_type() - request = json_format.ParseDict({'name': 'projects/sample1'}, request) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.list_operations(request) - -@pytest.mark.parametrize("request_type", [ - operations_pb2.ListOperationsRequest, - dict, -]) -def test_list_operations_rest(request_type): - client = KnowledgeBasesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request_init = {'name': 'projects/sample1'} - request = request_type(**request_init) - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = operations_pb2.ListOperationsResponse() - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.list_operations(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, operations_pb2.ListOperationsResponse) - - -def test_cancel_operation(transport: str = "grpc"): - client = KnowledgeBasesClient( - 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 = operations_pb2.CancelOperationRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = None - response = client.cancel_operation(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 response is the type that we expect. - assert response is None -@pytest.mark.asyncio -async def test_cancel_operation_async(transport: str = "grpc"): - client = KnowledgeBasesAsyncClient( - 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 = operations_pb2.CancelOperationRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - None - ) - response = await client.cancel_operation(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 response is the type that we expect. - assert response is None - -def test_cancel_operation_field_headers(): - 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 = operations_pb2.CancelOperationRequest() - request.name = "locations" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call: - call.return_value = None - - client.cancel_operation(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=locations",) in kw["metadata"] -@pytest.mark.asyncio -async def test_cancel_operation_field_headers_async(): - 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 = operations_pb2.CancelOperationRequest() - request.name = "locations" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - None - ) - await client.cancel_operation(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=locations",) in kw["metadata"] - -def test_cancel_operation_from_dict(): - client = KnowledgeBasesClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = None - - response = client.cancel_operation( - request={ - "name": "locations", - } - ) - call.assert_called() -@pytest.mark.asyncio -async def test_cancel_operation_from_dict_async(): - client = KnowledgeBasesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - None - ) - response = await client.cancel_operation( - request={ - "name": "locations", - } - ) - call.assert_called() - - -def test_get_operation(transport: str = "grpc"): - client = KnowledgeBasesClient( - 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 = operations_pb2.GetOperationRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_operation), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation() - response = client.get_operation(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 response is the type that we expect. - assert isinstance(response, operations_pb2.Operation) -@pytest.mark.asyncio -async def test_get_operation_async(transport: str = "grpc"): - client = KnowledgeBasesAsyncClient( - 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 = operations_pb2.GetOperationRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_operation), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation() - ) - response = await client.get_operation(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 response is the type that we expect. - assert isinstance(response, operations_pb2.Operation) - -def test_get_operation_field_headers(): - 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 = operations_pb2.GetOperationRequest() - request.name = "locations" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_operation), "__call__") as call: - call.return_value = operations_pb2.Operation() - - client.get_operation(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=locations",) in kw["metadata"] -@pytest.mark.asyncio -async def test_get_operation_field_headers_async(): - 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 = operations_pb2.GetOperationRequest() - request.name = "locations" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_operation), "__call__") as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation() - ) - await client.get_operation(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=locations",) in kw["metadata"] - -def test_get_operation_from_dict(): - client = KnowledgeBasesClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_operation), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation() - - response = client.get_operation( - request={ - "name": "locations", - } - ) - call.assert_called() -@pytest.mark.asyncio -async def test_get_operation_from_dict_async(): - client = KnowledgeBasesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_operation), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation() - ) - response = await client.get_operation( - request={ - "name": "locations", - } - ) - call.assert_called() - - -def test_list_operations(transport: str = "grpc"): - client = KnowledgeBasesClient( - 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 = operations_pb2.ListOperationsRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_operations), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.ListOperationsResponse() - response = client.list_operations(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 response is the type that we expect. - assert isinstance(response, operations_pb2.ListOperationsResponse) -@pytest.mark.asyncio -async def test_list_operations_async(transport: str = "grpc"): - client = KnowledgeBasesAsyncClient( - 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 = operations_pb2.ListOperationsRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_operations), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.ListOperationsResponse() - ) - response = await client.list_operations(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 response is the type that we expect. - assert isinstance(response, operations_pb2.ListOperationsResponse) - -def test_list_operations_field_headers(): - 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 = operations_pb2.ListOperationsRequest() - request.name = "locations" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_operations), "__call__") as call: - call.return_value = operations_pb2.ListOperationsResponse() - - client.list_operations(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=locations",) in kw["metadata"] -@pytest.mark.asyncio -async def test_list_operations_field_headers_async(): - 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 = operations_pb2.ListOperationsRequest() - request.name = "locations" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_operations), "__call__") as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.ListOperationsResponse() - ) - await client.list_operations(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=locations",) in kw["metadata"] - -def test_list_operations_from_dict(): - client = KnowledgeBasesClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_operations), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.ListOperationsResponse() - - response = client.list_operations( - request={ - "name": "locations", - } - ) - call.assert_called() -@pytest.mark.asyncio -async def test_list_operations_from_dict_async(): - client = KnowledgeBasesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_operations), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.ListOperationsResponse() - ) - response = await client.list_operations( - request={ - "name": "locations", - } - ) - call.assert_called() - - -def test_list_locations(transport: str = "grpc"): - client = KnowledgeBasesClient( - 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 = locations_pb2.ListLocationsRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_locations), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = locations_pb2.ListLocationsResponse() - response = client.list_locations(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 response is the type that we expect. - assert isinstance(response, locations_pb2.ListLocationsResponse) -@pytest.mark.asyncio -async def test_list_locations_async(transport: str = "grpc"): - client = KnowledgeBasesAsyncClient( - 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 = locations_pb2.ListLocationsRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_locations), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - locations_pb2.ListLocationsResponse() - ) - response = await client.list_locations(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 response is the type that we expect. - assert isinstance(response, locations_pb2.ListLocationsResponse) - -def test_list_locations_field_headers(): - 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 = locations_pb2.ListLocationsRequest() - request.name = "locations" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_locations), "__call__") as call: - call.return_value = locations_pb2.ListLocationsResponse() - - client.list_locations(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=locations",) in kw["metadata"] -@pytest.mark.asyncio -async def test_list_locations_field_headers_async(): - 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 = locations_pb2.ListLocationsRequest() - request.name = "locations" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_locations), "__call__") as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - locations_pb2.ListLocationsResponse() - ) - await client.list_locations(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=locations",) in kw["metadata"] - -def test_list_locations_from_dict(): - client = KnowledgeBasesClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_locations), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = locations_pb2.ListLocationsResponse() - - response = client.list_locations( - request={ - "name": "locations", - } - ) - call.assert_called() -@pytest.mark.asyncio -async def test_list_locations_from_dict_async(): - client = KnowledgeBasesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_locations), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - locations_pb2.ListLocationsResponse() - ) - response = await client.list_locations( - request={ - "name": "locations", - } - ) - call.assert_called() - - -def test_get_location(transport: str = "grpc"): - client = KnowledgeBasesClient( - 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 = locations_pb2.GetLocationRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_location), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = locations_pb2.Location() - response = client.get_location(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 response is the type that we expect. - assert isinstance(response, locations_pb2.Location) -@pytest.mark.asyncio -async def test_get_location_async(transport: str = "grpc_asyncio"): - client = KnowledgeBasesAsyncClient( - 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 = locations_pb2.GetLocationRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_location), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - locations_pb2.Location() - ) - response = await client.get_location(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 response is the type that we expect. - assert isinstance(response, locations_pb2.Location) - -def test_get_location_field_headers(): - 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 = locations_pb2.GetLocationRequest() - request.name = "locations/abc" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_location), "__call__") as call: - call.return_value = locations_pb2.Location() - - client.get_location(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=locations/abc",) in kw["metadata"] -@pytest.mark.asyncio -async def test_get_location_field_headers_async(): - 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 = locations_pb2.GetLocationRequest() - request.name = "locations/abc" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_location), "__call__") as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - locations_pb2.Location() - ) - await client.get_location(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=locations/abc",) in kw["metadata"] - -def test_get_location_from_dict(): - client = KnowledgeBasesClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_locations), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = locations_pb2.Location() - - response = client.get_location( - request={ - "name": "locations/abc", - } - ) - call.assert_called() -@pytest.mark.asyncio -async def test_get_location_from_dict_async(): - client = KnowledgeBasesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_locations), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - locations_pb2.Location() - ) - response = await client.get_location( - request={ - "name": "locations", - } - ) - call.assert_called() - - -def test_transport_close(): - transports = { - "rest": "_session", - "grpc": "_grpc_channel", - } - - for transport, close_name in transports.items(): - client = KnowledgeBasesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport - ) - with mock.patch.object(type(getattr(client.transport, close_name)), "close") as close: - with client: - close.assert_not_called() - close.assert_called_once() - -def test_client_ctx(): - transports = [ - 'rest', - 'grpc', - ] - for transport in transports: - client = KnowledgeBasesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport - ) - # Test client calls underlying transport. - with mock.patch.object(type(client.transport), "close") as close: - close.assert_not_called() - with client: - pass - close.assert_called() - -@pytest.mark.parametrize("client_class,transport_class", [ - (KnowledgeBasesClient, transports.KnowledgeBasesGrpcTransport), - (KnowledgeBasesAsyncClient, transports.KnowledgeBasesGrpcAsyncIOTransport), -]) -def test_api_key_credentials(client_class, transport_class): - with mock.patch.object( - google.auth._default, "get_api_key_credentials", create=True - ) as get_api_key_credentials: - mock_cred = mock.Mock() - get_api_key_credentials.return_value = mock_cred - options = client_options.ClientOptions() - options.api_key = "api_key" - 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=mock_cred, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) diff --git a/owl-bot-staging/v2/tests/unit/gapic/dialogflow_v2/test_participants.py b/owl-bot-staging/v2/tests/unit/gapic/dialogflow_v2/test_participants.py deleted file mode 100644 index f54624ed9..000000000 --- a/owl-bot-staging/v2/tests/unit/gapic/dialogflow_v2/test_participants.py +++ /dev/null @@ -1,6426 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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 -# try/except added for compatibility with python < 3.8 -try: - from unittest import mock - from unittest.mock import AsyncMock # pragma: NO COVER -except ImportError: # pragma: NO COVER - import mock - -import grpc -from grpc.experimental import aio -from collections.abc import Iterable -from google.protobuf import json_format -import json -import math -import pytest -from proto.marshal.rules.dates import DurationRule, TimestampRule -from proto.marshal.rules import wrappers -from requests import Response -from requests import Request, PreparedRequest -from requests.sessions import Session -from google.protobuf import json_format - -from google.api_core import client_options -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import grpc_helpers -from google.api_core import grpc_helpers_async -from google.api_core import path_template -from google.auth import credentials as ga_credentials -from google.auth.exceptions import MutualTLSChannelError -from google.cloud.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.types import audio_config -from google.cloud.dialogflow_v2.types import context -from google.cloud.dialogflow_v2.types import entity_type -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.cloud.dialogflow_v2.types import session_entity_type -from google.cloud.location import locations_pb2 -from google.longrunning import operations_pb2 -from google.oauth2 import service_account -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 - - -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 ParticipantsClient._get_default_mtls_endpoint(None) is None - assert ParticipantsClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint - assert ParticipantsClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint - assert ParticipantsClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint - assert ParticipantsClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint - assert ParticipantsClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi - - -@pytest.mark.parametrize("client_class,transport_name", [ - (ParticipantsClient, "grpc"), - (ParticipantsAsyncClient, "grpc_asyncio"), - (ParticipantsClient, "rest"), -]) -def test_participants_client_from_service_account_info(client_class, transport_name): - 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, transport=transport_name) - assert client.transport._credentials == creds - assert isinstance(client, client_class) - - assert client.transport._host == ( - 'dialogflow.googleapis.com:443' - if transport_name in ['grpc', 'grpc_asyncio'] - else - 'https://dialogflow.googleapis.com' - ) - - -@pytest.mark.parametrize("transport_class,transport_name", [ - (transports.ParticipantsGrpcTransport, "grpc"), - (transports.ParticipantsGrpcAsyncIOTransport, "grpc_asyncio"), - (transports.ParticipantsRestTransport, "rest"), -]) -def test_participants_client_service_account_always_use_jwt(transport_class, transport_name): - with mock.patch.object(service_account.Credentials, 'with_always_use_jwt_access', create=True) as use_jwt: - creds = service_account.Credentials(None, None, None) - transport = transport_class(credentials=creds, always_use_jwt_access=True) - use_jwt.assert_called_once_with(True) - - with mock.patch.object(service_account.Credentials, 'with_always_use_jwt_access', create=True) as use_jwt: - creds = service_account.Credentials(None, None, None) - transport = transport_class(credentials=creds, always_use_jwt_access=False) - use_jwt.assert_not_called() - - -@pytest.mark.parametrize("client_class,transport_name", [ - (ParticipantsClient, "grpc"), - (ParticipantsAsyncClient, "grpc_asyncio"), - (ParticipantsClient, "rest"), -]) -def test_participants_client_from_service_account_file(client_class, transport_name): - 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", transport=transport_name) - assert client.transport._credentials == creds - assert isinstance(client, client_class) - - client = client_class.from_service_account_json("dummy/file/path.json", transport=transport_name) - assert client.transport._credentials == creds - assert isinstance(client, client_class) - - assert client.transport._host == ( - 'dialogflow.googleapis.com:443' - if transport_name in ['grpc', 'grpc_asyncio'] - else - 'https://dialogflow.googleapis.com' - ) - - -def test_participants_client_get_transport_class(): - transport = ParticipantsClient.get_transport_class() - available_transports = [ - transports.ParticipantsGrpcTransport, - transports.ParticipantsRestTransport, - ] - assert transport in available_transports - - transport = ParticipantsClient.get_transport_class("grpc") - assert transport == transports.ParticipantsGrpcTransport - - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (ParticipantsClient, transports.ParticipantsGrpcTransport, "grpc"), - (ParticipantsAsyncClient, transports.ParticipantsGrpcAsyncIOTransport, "grpc_asyncio"), - (ParticipantsClient, transports.ParticipantsRestTransport, "rest"), -]) -@mock.patch.object(ParticipantsClient, "DEFAULT_ENDPOINT", modify_default_endpoint(ParticipantsClient)) -@mock.patch.object(ParticipantsAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(ParticipantsAsyncClient)) -def test_participants_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(ParticipantsClient, '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(ParticipantsClient, 'get_transport_class') as gtc: - client = client_class(transport=transport_name) - gtc.assert_called() - - # Check the case api_endpoint is provided. - options = client_options.ClientOptions(api_endpoint="squid.clam.whelk") - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(transport=transport_name, client_options=options) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host="squid.clam.whelk", - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is - # "never". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is - # "always". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_MTLS_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # 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(transport=transport_name) - - # 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(transport=transport_name) - - # 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, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id="octopus", - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - # Check the case api_endpoint is provided - options = client_options.ClientOptions(api_audience="https://language.googleapis.com") - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience="https://language.googleapis.com" - ) - -@pytest.mark.parametrize("client_class,transport_class,transport_name,use_client_cert_env", [ - (ParticipantsClient, transports.ParticipantsGrpcTransport, "grpc", "true"), - (ParticipantsAsyncClient, transports.ParticipantsGrpcAsyncIOTransport, "grpc_asyncio", "true"), - (ParticipantsClient, transports.ParticipantsGrpcTransport, "grpc", "false"), - (ParticipantsAsyncClient, transports.ParticipantsGrpcAsyncIOTransport, "grpc_asyncio", "false"), - (ParticipantsClient, transports.ParticipantsRestTransport, "rest", "true"), - (ParticipantsClient, transports.ParticipantsRestTransport, "rest", "false"), -]) -@mock.patch.object(ParticipantsClient, "DEFAULT_ENDPOINT", modify_default_endpoint(ParticipantsClient)) -@mock.patch.object(ParticipantsAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(ParticipantsAsyncClient)) -@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) -def test_participants_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, transport=transport_name) - - if use_client_cert_env == "false": - expected_client_cert_source = None - expected_host = client.DEFAULT_ENDPOINT - else: - expected_client_cert_source = client_cert_source_callback - expected_host = client.DEFAULT_MTLS_ENDPOINT - - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=expected_host, - scopes=None, - client_cert_source_for_mtls=expected_client_cert_source, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case ADC client cert is provided. Whether client cert is used depends on - # GOOGLE_API_USE_CLIENT_CERTIFICATE value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): - with mock.patch.object(transport_class, '__init__') as patched: - with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): - with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=client_cert_source_callback): - if use_client_cert_env == "false": - expected_host = client.DEFAULT_ENDPOINT - expected_client_cert_source = None - else: - expected_host = client.DEFAULT_MTLS_ENDPOINT - expected_client_cert_source = client_cert_source_callback - - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=expected_host, - scopes=None, - client_cert_source_for_mtls=expected_client_cert_source, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case client_cert_source and ADC client cert are not provided. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): - with mock.patch.object(transport_class, '__init__') as patched: - with mock.patch("google.auth.transport.mtls.has_default_client_cert_source", return_value=False): - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - -@pytest.mark.parametrize("client_class", [ - ParticipantsClient, ParticipantsAsyncClient -]) -@mock.patch.object(ParticipantsClient, "DEFAULT_ENDPOINT", modify_default_endpoint(ParticipantsClient)) -@mock.patch.object(ParticipantsAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(ParticipantsAsyncClient)) -def test_participants_client_get_mtls_endpoint_and_cert_source(client_class): - mock_client_cert_source = mock.Mock() - - # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "true". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - mock_api_endpoint = "foo" - options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) - assert api_endpoint == mock_api_endpoint - assert cert_source == mock_client_cert_source - - # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "false". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): - mock_client_cert_source = mock.Mock() - mock_api_endpoint = "foo" - options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) - assert api_endpoint == mock_api_endpoint - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "never". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_ENDPOINT - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "always". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert doesn't exist. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=False): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_ENDPOINT - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert exists. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - 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=mock_client_cert_source): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT - assert cert_source == mock_client_cert_source - - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (ParticipantsClient, transports.ParticipantsGrpcTransport, "grpc"), - (ParticipantsAsyncClient, transports.ParticipantsGrpcAsyncIOTransport, "grpc_asyncio"), - (ParticipantsClient, transports.ParticipantsRestTransport, "rest"), -]) -def test_participants_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, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=["1", "2"], - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - -@pytest.mark.parametrize("client_class,transport_class,transport_name,grpc_helpers", [ - (ParticipantsClient, transports.ParticipantsGrpcTransport, "grpc", grpc_helpers), - (ParticipantsAsyncClient, transports.ParticipantsGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), - (ParticipantsClient, transports.ParticipantsRestTransport, "rest", None), -]) -def test_participants_client_client_options_credentials_file(client_class, transport_class, transport_name, grpc_helpers): - # 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, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file="credentials.json", - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - -def test_participants_client_client_options_from_dict(): - with mock.patch('google.cloud.dialogflow_v2.services.participants.transports.ParticipantsGrpcTransport.__init__') as grpc_transport: - grpc_transport.return_value = None - client = ParticipantsClient( - client_options={'api_endpoint': 'squid.clam.whelk'} - ) - grpc_transport.assert_called_once_with( - credentials=None, - credentials_file=None, - host="squid.clam.whelk", - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - -@pytest.mark.parametrize("client_class,transport_class,transport_name,grpc_helpers", [ - (ParticipantsClient, transports.ParticipantsGrpcTransport, "grpc", grpc_helpers), - (ParticipantsAsyncClient, transports.ParticipantsGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), -]) -def test_participants_client_create_channel_credentials_file(client_class, transport_class, transport_name, grpc_helpers): - # 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, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file="credentials.json", - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # test that the credentials from file are saved and used as the credentials. - with mock.patch.object( - google.auth, "load_credentials_from_file", autospec=True - ) as load_creds, mock.patch.object( - google.auth, "default", autospec=True - ) as adc, mock.patch.object( - grpc_helpers, "create_channel" - ) as create_channel: - creds = ga_credentials.AnonymousCredentials() - file_creds = ga_credentials.AnonymousCredentials() - load_creds.return_value = (file_creds, None) - adc.return_value = (creds, None) - client = client_class(client_options=options, transport=transport_name) - create_channel.assert_called_with( - "dialogflow.googleapis.com:443", - credentials=file_creds, - credentials_file=None, - quota_project_id=None, - default_scopes=( - 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/dialogflow', -), - scopes=None, - default_host="dialogflow.googleapis.com", - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - -@pytest.mark.parametrize("request_type", [ - gcd_participant.CreateParticipantRequest, - dict, -]) -def test_create_participant(request_type, transport: str = 'grpc'): - client = ParticipantsClient( - 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_participant), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcd_participant.Participant( - name='name_value', - role=gcd_participant.Participant.Role.HUMAN_AGENT, - sip_recording_media_label='sip_recording_media_label_value', - 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.sip_recording_media_label == 'sip_recording_media_label_value' - assert response.obfuscated_external_user_id == 'obfuscated_external_user_id_value' - - -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=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_participant), - '__call__') as call: - client.create_participant() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == gcd_participant.CreateParticipantRequest() - -@pytest.mark.asyncio -async def test_create_participant_async(transport: str = 'grpc_asyncio', request_type=gcd_participant.CreateParticipantRequest): - client = ParticipantsAsyncClient( - 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_participant), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gcd_participant.Participant( - name='name_value', - role=gcd_participant.Participant.Role.HUMAN_AGENT, - sip_recording_media_label='sip_recording_media_label_value', - 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.sip_recording_media_label == 'sip_recording_media_label_value' - assert response.obfuscated_external_user_id == 'obfuscated_external_user_id_value' - - -@pytest.mark.asyncio -async def test_create_participant_async_from_dict(): - await test_create_participant_async(request_type=dict) - - -def test_create_participant_field_headers(): - 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. - with mock.patch.object( - 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. - 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_participant_field_headers_async(): - 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. - with mock.patch.object( - type(client.transport.create_participant), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcd_participant.Participant()) - 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] == 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_participant_flattened(): - 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.create_participant), - '__call__') 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( - parent='parent_value', - participant=gcd_participant.Participant(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] - arg = args[0].parent - mock_val = 'parent_value' - assert arg == mock_val - arg = args[0].participant - mock_val = gcd_participant.Participant(name='name_value') - assert arg == mock_val - - -def test_create_participant_flattened_error(): - client = ParticipantsClient( - 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_participant( - gcd_participant.CreateParticipantRequest(), - parent='parent_value', - participant=gcd_participant.Participant(name='name_value'), - ) - -@pytest.mark.asyncio -async def test_create_participant_flattened_async(): - 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.create_participant), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcd_participant.Participant() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcd_participant.Participant()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.create_participant( - parent='parent_value', - participant=gcd_participant.Participant(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] - arg = args[0].parent - mock_val = 'parent_value' - assert arg == mock_val - arg = args[0].participant - mock_val = gcd_participant.Participant(name='name_value') - assert arg == mock_val - -@pytest.mark.asyncio -async def test_create_participant_flattened_error_async(): - client = ParticipantsAsyncClient( - 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_participant( - gcd_participant.CreateParticipantRequest(), - parent='parent_value', - participant=gcd_participant.Participant(name='name_value'), - ) - - -@pytest.mark.parametrize("request_type", [ - participant.GetParticipantRequest, - dict, -]) -def test_get_participant(request_type, transport: str = 'grpc'): - client = ParticipantsClient( - 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_participant), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = participant.Participant( - name='name_value', - role=participant.Participant.Role.HUMAN_AGENT, - sip_recording_media_label='sip_recording_media_label_value', - 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.sip_recording_media_label == 'sip_recording_media_label_value' - assert response.obfuscated_external_user_id == 'obfuscated_external_user_id_value' - - -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=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_participant), - '__call__') as call: - client.get_participant() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == participant.GetParticipantRequest() - -@pytest.mark.asyncio -async def test_get_participant_async(transport: str = 'grpc_asyncio', request_type=participant.GetParticipantRequest): - client = ParticipantsAsyncClient( - 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_participant), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(participant.Participant( - name='name_value', - role=participant.Participant.Role.HUMAN_AGENT, - sip_recording_media_label='sip_recording_media_label_value', - 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.sip_recording_media_label == 'sip_recording_media_label_value' - assert response.obfuscated_external_user_id == 'obfuscated_external_user_id_value' - - -@pytest.mark.asyncio -async def test_get_participant_async_from_dict(): - await test_get_participant_async(request_type=dict) - - -def test_get_participant_field_headers(): - 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. - 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_participant_field_headers_async(): - 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. - with mock.patch.object( - type(client.transport.get_participant), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(participant.Participant()) - 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] == 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_participant_flattened(): - 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', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - arg = args[0].name - mock_val = 'name_value' - assert arg == mock_val - - -def test_get_participant_flattened_error(): - client = ParticipantsClient( - 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_participant( - participant.GetParticipantRequest(), - name='name_value', - ) - -@pytest.mark.asyncio -async def test_get_participant_flattened_async(): - 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: - # Designate an appropriate return value for the call. - call.return_value = participant.Participant() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(participant.Participant()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.get_participant( - 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] - arg = args[0].name - mock_val = 'name_value' - assert arg == mock_val - -@pytest.mark.asyncio -async def test_get_participant_flattened_error_async(): - client = ParticipantsAsyncClient( - 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_participant( - participant.GetParticipantRequest(), - name='name_value', - ) - - -@pytest.mark.parametrize("request_type", [ - participant.ListParticipantsRequest, - dict, -]) -def test_list_participants(request_type, transport: str = 'grpc'): - client = ParticipantsClient( - 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_participants), - '__call__') as call: - # Designate an appropriate return value for the call. - 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' - - -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=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_participants), - '__call__') as call: - client.list_participants() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == participant.ListParticipantsRequest() - -@pytest.mark.asyncio -async def test_list_participants_async(transport: str = 'grpc_asyncio', request_type=participant.ListParticipantsRequest): - client = ParticipantsAsyncClient( - 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_participants), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(participant.ListParticipantsResponse( - 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' - - -@pytest.mark.asyncio -async def test_list_participants_async_from_dict(): - await test_list_participants_async(request_type=dict) - - -def test_list_participants_field_headers(): - 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. - with mock.patch.object( - 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. - 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_participants_field_headers_async(): - 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. - with mock.patch.object( - type(client.transport.list_participants), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(participant.ListParticipantsResponse()) - 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] == 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_participants_flattened(): - 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_participants), - '__call__') 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', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - arg = args[0].parent - mock_val = 'parent_value' - assert arg == mock_val - - -def test_list_participants_flattened_error(): - client = ParticipantsClient( - 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_participants( - participant.ListParticipantsRequest(), - parent='parent_value', - ) - -@pytest.mark.asyncio -async def test_list_participants_flattened_async(): - 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.list_participants), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = participant.ListParticipantsResponse() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(participant.ListParticipantsResponse()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.list_participants( - 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] - arg = args[0].parent - mock_val = 'parent_value' - assert arg == mock_val - -@pytest.mark.asyncio -async def test_list_participants_flattened_error_async(): - client = ParticipantsAsyncClient( - 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_participants( - participant.ListParticipantsRequest(), - parent='parent_value', - ) - - -def test_list_participants_pager(transport_name: str = "grpc"): - client = ParticipantsClient( - credentials=ga_credentials.AnonymousCredentials, - transport=transport_name, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_participants), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - participant.ListParticipantsResponse( - participants=[ - participant.Participant(), - participant.Participant(), - participant.Participant(), - ], - next_page_token='abc', - ), - participant.ListParticipantsResponse( - participants=[], - next_page_token='def', - ), - participant.ListParticipantsResponse( - participants=[ - participant.Participant(), - ], - next_page_token='ghi', - ), - participant.ListParticipantsResponse( - participants=[ - participant.Participant(), - participant.Participant(), - ], - ), - RuntimeError, - ) - - metadata = () - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ('parent', ''), - )), - ) - pager = client.list_participants(request={}) - - assert pager._metadata == metadata - - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, participant.Participant) - for i in results) -def test_list_participants_pages(transport_name: str = "grpc"): - client = ParticipantsClient( - credentials=ga_credentials.AnonymousCredentials, - transport=transport_name, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_participants), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - participant.ListParticipantsResponse( - participants=[ - participant.Participant(), - participant.Participant(), - participant.Participant(), - ], - next_page_token='abc', - ), - participant.ListParticipantsResponse( - participants=[], - next_page_token='def', - ), - participant.ListParticipantsResponse( - participants=[ - participant.Participant(), - ], - next_page_token='ghi', - ), - participant.ListParticipantsResponse( - participants=[ - participant.Participant(), - participant.Participant(), - ], - ), - RuntimeError, - ) - pages = list(client.list_participants(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_participants_async_pager(): - 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.list_participants), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - participant.ListParticipantsResponse( - participants=[ - participant.Participant(), - participant.Participant(), - participant.Participant(), - ], - next_page_token='abc', - ), - participant.ListParticipantsResponse( - participants=[], - next_page_token='def', - ), - participant.ListParticipantsResponse( - participants=[ - participant.Participant(), - ], - next_page_token='ghi', - ), - participant.ListParticipantsResponse( - participants=[ - participant.Participant(), - participant.Participant(), - ], - ), - RuntimeError, - ) - async_pager = await client.list_participants(request={},) - assert async_pager.next_page_token == 'abc' - responses = [] - async for response in async_pager: # pragma: no branch - responses.append(response) - - assert len(responses) == 6 - assert all(isinstance(i, participant.Participant) - for i in responses) - - -@pytest.mark.asyncio -async def test_list_participants_async_pages(): - 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.list_participants), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - participant.ListParticipantsResponse( - participants=[ - participant.Participant(), - participant.Participant(), - participant.Participant(), - ], - next_page_token='abc', - ), - participant.ListParticipantsResponse( - participants=[], - next_page_token='def', - ), - participant.ListParticipantsResponse( - participants=[ - participant.Participant(), - ], - next_page_token='ghi', - ), - participant.ListParticipantsResponse( - participants=[ - participant.Participant(), - participant.Participant(), - ], - ), - RuntimeError, - ) - pages = [] - async for page_ in (await client.list_participants(request={})).pages: # pragma: no branch - pages.append(page_) - for page_, token in zip(pages, ['abc','def','ghi', '']): - assert page_.raw_page.next_page_token == token - -@pytest.mark.parametrize("request_type", [ - gcd_participant.UpdateParticipantRequest, - dict, -]) -def test_update_participant(request_type, transport: str = 'grpc'): - client = ParticipantsClient( - 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_participant), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcd_participant.Participant( - name='name_value', - role=gcd_participant.Participant.Role.HUMAN_AGENT, - sip_recording_media_label='sip_recording_media_label_value', - 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.sip_recording_media_label == 'sip_recording_media_label_value' - assert response.obfuscated_external_user_id == 'obfuscated_external_user_id_value' - - -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=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_participant), - '__call__') as call: - client.update_participant() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == gcd_participant.UpdateParticipantRequest() - -@pytest.mark.asyncio -async def test_update_participant_async(transport: str = 'grpc_asyncio', request_type=gcd_participant.UpdateParticipantRequest): - client = ParticipantsAsyncClient( - 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_participant), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gcd_participant.Participant( - name='name_value', - role=gcd_participant.Participant.Role.HUMAN_AGENT, - sip_recording_media_label='sip_recording_media_label_value', - 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.sip_recording_media_label == 'sip_recording_media_label_value' - assert response.obfuscated_external_user_id == 'obfuscated_external_user_id_value' - - -@pytest.mark.asyncio -async def test_update_participant_async_from_dict(): - await test_update_participant_async(request_type=dict) - - -def test_update_participant_field_headers(): - 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 = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - 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. - 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', - 'participant.name=name_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_update_participant_field_headers_async(): - 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 = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_participant), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcd_participant.Participant()) - 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] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'participant.name=name_value', - ) in kw['metadata'] - - -def test_update_participant_flattened(): - 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.update_participant), - '__call__') 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_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] - arg = args[0].participant - mock_val = gcd_participant.Participant(name='name_value') - assert arg == mock_val - arg = args[0].update_mask - mock_val = field_mask_pb2.FieldMask(paths=['paths_value']) - assert arg == mock_val - - -def test_update_participant_flattened_error(): - client = ParticipantsClient( - 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_participant( - gcd_participant.UpdateParticipantRequest(), - participant=gcd_participant.Participant(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - -@pytest.mark.asyncio -async def test_update_participant_flattened_async(): - 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.update_participant), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcd_participant.Participant() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcd_participant.Participant()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.update_participant( - participant=gcd_participant.Participant(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] - arg = args[0].participant - mock_val = gcd_participant.Participant(name='name_value') - assert arg == mock_val - arg = args[0].update_mask - mock_val = field_mask_pb2.FieldMask(paths=['paths_value']) - assert arg == mock_val - -@pytest.mark.asyncio -async def test_update_participant_flattened_error_async(): - client = ParticipantsAsyncClient( - 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_participant( - gcd_participant.UpdateParticipantRequest(), - participant=gcd_participant.Participant(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - - -@pytest.mark.parametrize("request_type", [ - gcd_participant.AnalyzeContentRequest, - dict, -]) -def test_analyze_content(request_type, transport: str = 'grpc'): - client = ParticipantsClient( - 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.analyze_content), - '__call__') as call: - # Designate an appropriate return value for the call. - 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' - - -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=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.analyze_content), - '__call__') as call: - client.analyze_content() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == gcd_participant.AnalyzeContentRequest() - -@pytest.mark.asyncio -async def test_analyze_content_async(transport: str = 'grpc_asyncio', request_type=gcd_participant.AnalyzeContentRequest): - client = ParticipantsAsyncClient( - 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.analyze_content), - '__call__') as call: - # Designate an appropriate return value for the call. - 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' - - -@pytest.mark.asyncio -async def test_analyze_content_async_from_dict(): - await test_analyze_content_async(request_type=dict) - - -def test_analyze_content_field_headers(): - 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. - 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', - 'participant=participant_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_analyze_content_field_headers_async(): - 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. - with mock.patch.object( - type(client.transport.analyze_content), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcd_participant.AnalyzeContentResponse()) - 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] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'participant=participant_value', - ) in kw['metadata'] - - -def test_analyze_content_flattened(): - 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( - participant='participant_value', - text_input=session.TextInput(text='text_value'), - event_input=session.EventInput(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] - arg = args[0].participant - mock_val = 'participant_value' - assert arg == mock_val - assert args[0].event_input == session.EventInput(name='name_value') - - -def test_analyze_content_flattened_error(): - client = ParticipantsClient( - 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.analyze_content( - gcd_participant.AnalyzeContentRequest(), - participant='participant_value', - text_input=session.TextInput(text='text_value'), - event_input=session.EventInput(name='name_value'), - ) - -@pytest.mark.asyncio -async def test_analyze_content_flattened_async(): - 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: - # Designate an appropriate return value for the call. - call.return_value = gcd_participant.AnalyzeContentResponse() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcd_participant.AnalyzeContentResponse()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.analyze_content( - participant='participant_value', - text_input=session.TextInput(text='text_value'), - event_input=session.EventInput(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] - arg = args[0].participant - mock_val = 'participant_value' - assert arg == mock_val - assert args[0].event_input == session.EventInput(name='name_value') - -@pytest.mark.asyncio -async def test_analyze_content_flattened_error_async(): - client = ParticipantsAsyncClient( - 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.analyze_content( - gcd_participant.AnalyzeContentRequest(), - participant='participant_value', - text_input=session.TextInput(text='text_value'), - event_input=session.EventInput(name='name_value'), - ) - - -@pytest.mark.parametrize("request_type", [ - participant.StreamingAnalyzeContentRequest, - dict, -]) -def test_streaming_analyze_content(request_type, transport: str = 'grpc'): - client = ParticipantsClient( - 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. - with mock.patch.object( - type(client.transport.streaming_analyze_content), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = iter([participant.StreamingAnalyzeContentResponse()]) - response = client.streaming_analyze_content(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. - for message in response: - assert isinstance(message, participant.StreamingAnalyzeContentResponse) - - -@pytest.mark.asyncio -async def test_streaming_analyze_content_async(transport: str = 'grpc_asyncio', request_type=participant.StreamingAnalyzeContentRequest): - client = ParticipantsAsyncClient( - 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. - with mock.patch.object( - type(client.transport.streaming_analyze_content), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = mock.Mock(aio.StreamStreamCall, autospec=True) - call.return_value.read = mock.AsyncMock(side_effect=[participant.StreamingAnalyzeContentResponse()]) - response = await client.streaming_analyze_content(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. - message = await response.read() - assert isinstance(message, participant.StreamingAnalyzeContentResponse) - - -@pytest.mark.asyncio -async def test_streaming_analyze_content_async_from_dict(): - await test_streaming_analyze_content_async(request_type=dict) - - -@pytest.mark.parametrize("request_type", [ - participant.SuggestArticlesRequest, - dict, -]) -def test_suggest_articles(request_type, transport: str = 'grpc'): - client = ParticipantsClient( - 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.suggest_articles), - '__call__') as call: - # Designate an appropriate return value for the call. - 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 - - -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=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.suggest_articles), - '__call__') as call: - client.suggest_articles() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == participant.SuggestArticlesRequest() - -@pytest.mark.asyncio -async def test_suggest_articles_async(transport: str = 'grpc_asyncio', request_type=participant.SuggestArticlesRequest): - client = ParticipantsAsyncClient( - 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.suggest_articles), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(participant.SuggestArticlesResponse( - 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 - - -@pytest.mark.asyncio -async def test_suggest_articles_async_from_dict(): - await test_suggest_articles_async(request_type=dict) - - -def test_suggest_articles_field_headers(): - 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. - 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_suggest_articles_field_headers_async(): - 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. - with mock.patch.object( - type(client.transport.suggest_articles), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(participant.SuggestArticlesResponse()) - 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] == 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_suggest_articles_flattened(): - 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', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - arg = args[0].parent - mock_val = 'parent_value' - assert arg == mock_val - - -def test_suggest_articles_flattened_error(): - client = ParticipantsClient( - 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.suggest_articles( - participant.SuggestArticlesRequest(), - parent='parent_value', - ) - -@pytest.mark.asyncio -async def test_suggest_articles_flattened_async(): - 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: - # Designate an appropriate return value for the call. - call.return_value = participant.SuggestArticlesResponse() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(participant.SuggestArticlesResponse()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.suggest_articles( - 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] - arg = args[0].parent - mock_val = 'parent_value' - assert arg == mock_val - -@pytest.mark.asyncio -async def test_suggest_articles_flattened_error_async(): - client = ParticipantsAsyncClient( - 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.suggest_articles( - participant.SuggestArticlesRequest(), - parent='parent_value', - ) - - -@pytest.mark.parametrize("request_type", [ - participant.SuggestFaqAnswersRequest, - dict, -]) -def test_suggest_faq_answers(request_type, transport: str = 'grpc'): - client = ParticipantsClient( - 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.suggest_faq_answers), - '__call__') as call: - # Designate an appropriate return value for the call. - 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 - - -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=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.suggest_faq_answers), - '__call__') as call: - client.suggest_faq_answers() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == participant.SuggestFaqAnswersRequest() - -@pytest.mark.asyncio -async def test_suggest_faq_answers_async(transport: str = 'grpc_asyncio', request_type=participant.SuggestFaqAnswersRequest): - client = ParticipantsAsyncClient( - 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.suggest_faq_answers), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(participant.SuggestFaqAnswersResponse( - 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 - - -@pytest.mark.asyncio -async def test_suggest_faq_answers_async_from_dict(): - await test_suggest_faq_answers_async(request_type=dict) - - -def test_suggest_faq_answers_field_headers(): - 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. - with mock.patch.object( - 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. - 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_suggest_faq_answers_field_headers_async(): - 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. - with mock.patch.object( - type(client.transport.suggest_faq_answers), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(participant.SuggestFaqAnswersResponse()) - 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] == 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_suggest_faq_answers_flattened(): - 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_faq_answers), - '__call__') 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', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - arg = args[0].parent - mock_val = 'parent_value' - assert arg == mock_val - - -def test_suggest_faq_answers_flattened_error(): - client = ParticipantsClient( - 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.suggest_faq_answers( - participant.SuggestFaqAnswersRequest(), - parent='parent_value', - ) - -@pytest.mark.asyncio -async def test_suggest_faq_answers_flattened_async(): - 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_faq_answers), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = participant.SuggestFaqAnswersResponse() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(participant.SuggestFaqAnswersResponse()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.suggest_faq_answers( - 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] - arg = args[0].parent - mock_val = 'parent_value' - assert arg == mock_val - -@pytest.mark.asyncio -async def test_suggest_faq_answers_flattened_error_async(): - client = ParticipantsAsyncClient( - 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.suggest_faq_answers( - participant.SuggestFaqAnswersRequest(), - parent='parent_value', - ) - - -@pytest.mark.parametrize("request_type", [ - participant.SuggestSmartRepliesRequest, - dict, -]) -def test_suggest_smart_replies(request_type, transport: str = 'grpc'): - client = ParticipantsClient( - 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.suggest_smart_replies), - '__call__') as call: - # Designate an appropriate return value for the call. - 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 - - -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=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.suggest_smart_replies), - '__call__') as call: - client.suggest_smart_replies() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == participant.SuggestSmartRepliesRequest() - -@pytest.mark.asyncio -async def test_suggest_smart_replies_async(transport: str = 'grpc_asyncio', request_type=participant.SuggestSmartRepliesRequest): - client = ParticipantsAsyncClient( - 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.suggest_smart_replies), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(participant.SuggestSmartRepliesResponse( - 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 - - -@pytest.mark.asyncio -async def test_suggest_smart_replies_async_from_dict(): - await test_suggest_smart_replies_async(request_type=dict) - - -def test_suggest_smart_replies_field_headers(): - 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. - with mock.patch.object( - 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. - 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_suggest_smart_replies_field_headers_async(): - 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. - with mock.patch.object( - type(client.transport.suggest_smart_replies), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(participant.SuggestSmartRepliesResponse()) - 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] == 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_suggest_smart_replies_flattened(): - 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_smart_replies), - '__call__') 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', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - arg = args[0].parent - mock_val = 'parent_value' - assert arg == mock_val - - -def test_suggest_smart_replies_flattened_error(): - client = ParticipantsClient( - 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.suggest_smart_replies( - participant.SuggestSmartRepliesRequest(), - parent='parent_value', - ) - -@pytest.mark.asyncio -async def test_suggest_smart_replies_flattened_async(): - 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_smart_replies), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = participant.SuggestSmartRepliesResponse() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(participant.SuggestSmartRepliesResponse()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.suggest_smart_replies( - 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] - arg = args[0].parent - mock_val = 'parent_value' - assert arg == mock_val - -@pytest.mark.asyncio -async def test_suggest_smart_replies_flattened_error_async(): - client = ParticipantsAsyncClient( - 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.suggest_smart_replies( - participant.SuggestSmartRepliesRequest(), - parent='parent_value', - ) - - -@pytest.mark.parametrize("request_type", [ - gcd_participant.CreateParticipantRequest, - dict, -]) -def test_create_participant_rest(request_type): - client = ParticipantsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1/conversations/sample2'} - request_init["participant"] = {'name': 'name_value', 'role': 1, 'sip_recording_media_label': 'sip_recording_media_label_value', 'obfuscated_external_user_id': 'obfuscated_external_user_id_value', 'documents_metadata_filters': {}} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = gcd_participant.Participant( - name='name_value', - role=gcd_participant.Participant.Role.HUMAN_AGENT, - sip_recording_media_label='sip_recording_media_label_value', - obfuscated_external_user_id='obfuscated_external_user_id_value', - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - pb_return_value = gcd_participant.Participant.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.create_participant(request) - - # 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' - assert response.obfuscated_external_user_id == 'obfuscated_external_user_id_value' - - -def test_create_participant_rest_required_fields(request_type=gcd_participant.CreateParticipantRequest): - transport_class = transports.ParticipantsRestTransport - - request_init = {} - request_init["parent"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - including_default_value_fields=False, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_participant._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["parent"] = 'parent_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_participant._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "parent" in jsonified_request - assert jsonified_request["parent"] == 'parent_value' - - client = ParticipantsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = gcd_participant.Participant() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "post", - 'query_params': pb_request, - } - transcode_result['body'] = pb_request - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - - pb_return_value = gcd_participant.Participant.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.create_participant(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_create_participant_rest_unset_required_fields(): - transport = transports.ParticipantsRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.create_participant._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("parent", "participant", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_create_participant_rest_interceptors(null_interceptor): - transport = transports.ParticipantsRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.ParticipantsRestInterceptor(), - ) - client = ParticipantsClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.ParticipantsRestInterceptor, "post_create_participant") as post, \ - mock.patch.object(transports.ParticipantsRestInterceptor, "pre_create_participant") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = gcd_participant.CreateParticipantRequest.pb(gcd_participant.CreateParticipantRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = gcd_participant.Participant.to_json(gcd_participant.Participant()) - - request = gcd_participant.CreateParticipantRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = gcd_participant.Participant() - - client.create_participant(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_create_participant_rest_bad_request(transport: str = 'rest', request_type=gcd_participant.CreateParticipantRequest): - client = ParticipantsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1/conversations/sample2'} - request_init["participant"] = {'name': 'name_value', 'role': 1, 'sip_recording_media_label': 'sip_recording_media_label_value', 'obfuscated_external_user_id': 'obfuscated_external_user_id_value', 'documents_metadata_filters': {}} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.create_participant(request) - - -def test_create_participant_rest_flattened(): - client = ParticipantsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = gcd_participant.Participant() - - # get arguments that satisfy an http rule for this method - sample_request = {'parent': 'projects/sample1/conversations/sample2'} - - # get truthy value for each flattened field - mock_args = dict( - parent='parent_value', - participant=gcd_participant.Participant(name='name_value'), - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - pb_return_value = gcd_participant.Participant.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.create_participant(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v2/{parent=projects/*/conversations/*}/participants" % client.transport._host, args[1]) - - -def test_create_participant_rest_flattened_error(transport: str = 'rest'): - client = ParticipantsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.create_participant( - gcd_participant.CreateParticipantRequest(), - parent='parent_value', - participant=gcd_participant.Participant(name='name_value'), - ) - - -def test_create_participant_rest_error(): - client = ParticipantsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - participant.GetParticipantRequest, - dict, -]) -def test_get_participant_rest(request_type): - client = ParticipantsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/conversations/sample2/participants/sample3'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = participant.Participant( - name='name_value', - role=participant.Participant.Role.HUMAN_AGENT, - sip_recording_media_label='sip_recording_media_label_value', - obfuscated_external_user_id='obfuscated_external_user_id_value', - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - pb_return_value = participant.Participant.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.get_participant(request) - - # 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' - assert response.obfuscated_external_user_id == 'obfuscated_external_user_id_value' - - -def test_get_participant_rest_required_fields(request_type=participant.GetParticipantRequest): - transport_class = transports.ParticipantsRestTransport - - request_init = {} - request_init["name"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - including_default_value_fields=False, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_participant._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["name"] = 'name_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_participant._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "name" in jsonified_request - assert jsonified_request["name"] == 'name_value' - - client = ParticipantsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = participant.Participant() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "get", - 'query_params': pb_request, - } - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - - pb_return_value = participant.Participant.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.get_participant(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_get_participant_rest_unset_required_fields(): - transport = transports.ParticipantsRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.get_participant._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_get_participant_rest_interceptors(null_interceptor): - transport = transports.ParticipantsRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.ParticipantsRestInterceptor(), - ) - client = ParticipantsClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.ParticipantsRestInterceptor, "post_get_participant") as post, \ - mock.patch.object(transports.ParticipantsRestInterceptor, "pre_get_participant") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = participant.GetParticipantRequest.pb(participant.GetParticipantRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = participant.Participant.to_json(participant.Participant()) - - request = participant.GetParticipantRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = participant.Participant() - - client.get_participant(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_get_participant_rest_bad_request(transport: str = 'rest', request_type=participant.GetParticipantRequest): - client = ParticipantsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/conversations/sample2/participants/sample3'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.get_participant(request) - - -def test_get_participant_rest_flattened(): - client = ParticipantsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = participant.Participant() - - # get arguments that satisfy an http rule for this method - sample_request = {'name': 'projects/sample1/conversations/sample2/participants/sample3'} - - # get truthy value for each flattened field - mock_args = dict( - name='name_value', - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - pb_return_value = participant.Participant.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.get_participant(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v2/{name=projects/*/conversations/*/participants/*}" % client.transport._host, args[1]) - - -def test_get_participant_rest_flattened_error(transport: str = 'rest'): - client = ParticipantsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.get_participant( - participant.GetParticipantRequest(), - name='name_value', - ) - - -def test_get_participant_rest_error(): - client = ParticipantsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - participant.ListParticipantsRequest, - dict, -]) -def test_list_participants_rest(request_type): - client = ParticipantsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1/conversations/sample2'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = participant.ListParticipantsResponse( - next_page_token='next_page_token_value', - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - pb_return_value = participant.ListParticipantsResponse.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.list_participants(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListParticipantsPager) - assert response.next_page_token == 'next_page_token_value' - - -def test_list_participants_rest_required_fields(request_type=participant.ListParticipantsRequest): - transport_class = transports.ParticipantsRestTransport - - request_init = {} - request_init["parent"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - including_default_value_fields=False, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).list_participants._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["parent"] = 'parent_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).list_participants._get_unset_required_fields(jsonified_request) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("page_size", "page_token", )) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "parent" in jsonified_request - assert jsonified_request["parent"] == 'parent_value' - - client = ParticipantsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = participant.ListParticipantsResponse() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "get", - 'query_params': pb_request, - } - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - - pb_return_value = participant.ListParticipantsResponse.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.list_participants(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_list_participants_rest_unset_required_fields(): - transport = transports.ParticipantsRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.list_participants._get_unset_required_fields({}) - assert set(unset_fields) == (set(("pageSize", "pageToken", )) & set(("parent", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_list_participants_rest_interceptors(null_interceptor): - transport = transports.ParticipantsRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.ParticipantsRestInterceptor(), - ) - client = ParticipantsClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.ParticipantsRestInterceptor, "post_list_participants") as post, \ - mock.patch.object(transports.ParticipantsRestInterceptor, "pre_list_participants") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = participant.ListParticipantsRequest.pb(participant.ListParticipantsRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = participant.ListParticipantsResponse.to_json(participant.ListParticipantsResponse()) - - request = participant.ListParticipantsRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = participant.ListParticipantsResponse() - - client.list_participants(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_list_participants_rest_bad_request(transport: str = 'rest', request_type=participant.ListParticipantsRequest): - client = ParticipantsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1/conversations/sample2'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.list_participants(request) - - -def test_list_participants_rest_flattened(): - client = ParticipantsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = participant.ListParticipantsResponse() - - # get arguments that satisfy an http rule for this method - sample_request = {'parent': 'projects/sample1/conversations/sample2'} - - # get truthy value for each flattened field - mock_args = dict( - parent='parent_value', - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - pb_return_value = participant.ListParticipantsResponse.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.list_participants(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v2/{parent=projects/*/conversations/*}/participants" % client.transport._host, args[1]) - - -def test_list_participants_rest_flattened_error(transport: str = 'rest'): - client = ParticipantsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.list_participants( - participant.ListParticipantsRequest(), - parent='parent_value', - ) - - -def test_list_participants_rest_pager(transport: str = 'rest'): - client = ParticipantsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # TODO(kbandes): remove this mock unless there's a good reason for it. - #with mock.patch.object(path_template, 'transcode') as transcode: - # Set the response as a series of pages - response = ( - participant.ListParticipantsResponse( - participants=[ - participant.Participant(), - participant.Participant(), - participant.Participant(), - ], - next_page_token='abc', - ), - participant.ListParticipantsResponse( - participants=[], - next_page_token='def', - ), - participant.ListParticipantsResponse( - participants=[ - participant.Participant(), - ], - next_page_token='ghi', - ), - participant.ListParticipantsResponse( - participants=[ - participant.Participant(), - participant.Participant(), - ], - ), - ) - # Two responses for two calls - response = response + response - - # Wrap the values into proper Response objs - response = tuple(participant.ListParticipantsResponse.to_json(x) for x in response) - return_values = tuple(Response() for i in response) - for return_val, response_val in zip(return_values, response): - return_val._content = response_val.encode('UTF-8') - return_val.status_code = 200 - req.side_effect = return_values - - sample_request = {'parent': 'projects/sample1/conversations/sample2'} - - pager = client.list_participants(request=sample_request) - - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, participant.Participant) - for i in results) - - pages = list(client.list_participants(request=sample_request).pages) - for page_, token in zip(pages, ['abc','def','ghi', '']): - assert page_.raw_page.next_page_token == token - - -@pytest.mark.parametrize("request_type", [ - gcd_participant.UpdateParticipantRequest, - dict, -]) -def test_update_participant_rest(request_type): - client = ParticipantsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'participant': {'name': 'projects/sample1/conversations/sample2/participants/sample3'}} - request_init["participant"] = {'name': 'projects/sample1/conversations/sample2/participants/sample3', 'role': 1, 'sip_recording_media_label': 'sip_recording_media_label_value', 'obfuscated_external_user_id': 'obfuscated_external_user_id_value', 'documents_metadata_filters': {}} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = gcd_participant.Participant( - name='name_value', - role=gcd_participant.Participant.Role.HUMAN_AGENT, - sip_recording_media_label='sip_recording_media_label_value', - obfuscated_external_user_id='obfuscated_external_user_id_value', - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - pb_return_value = gcd_participant.Participant.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.update_participant(request) - - # 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' - assert response.obfuscated_external_user_id == 'obfuscated_external_user_id_value' - - -def test_update_participant_rest_required_fields(request_type=gcd_participant.UpdateParticipantRequest): - transport_class = transports.ParticipantsRestTransport - - request_init = {} - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - including_default_value_fields=False, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).update_participant._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).update_participant._get_unset_required_fields(jsonified_request) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("update_mask", )) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - - client = ParticipantsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = gcd_participant.Participant() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "patch", - 'query_params': pb_request, - } - transcode_result['body'] = pb_request - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - - pb_return_value = gcd_participant.Participant.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.update_participant(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_update_participant_rest_unset_required_fields(): - transport = transports.ParticipantsRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.update_participant._get_unset_required_fields({}) - assert set(unset_fields) == (set(("updateMask", )) & set(("participant", "updateMask", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_update_participant_rest_interceptors(null_interceptor): - transport = transports.ParticipantsRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.ParticipantsRestInterceptor(), - ) - client = ParticipantsClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.ParticipantsRestInterceptor, "post_update_participant") as post, \ - mock.patch.object(transports.ParticipantsRestInterceptor, "pre_update_participant") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = gcd_participant.UpdateParticipantRequest.pb(gcd_participant.UpdateParticipantRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = gcd_participant.Participant.to_json(gcd_participant.Participant()) - - request = gcd_participant.UpdateParticipantRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = gcd_participant.Participant() - - client.update_participant(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_update_participant_rest_bad_request(transport: str = 'rest', request_type=gcd_participant.UpdateParticipantRequest): - client = ParticipantsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'participant': {'name': 'projects/sample1/conversations/sample2/participants/sample3'}} - request_init["participant"] = {'name': 'projects/sample1/conversations/sample2/participants/sample3', 'role': 1, 'sip_recording_media_label': 'sip_recording_media_label_value', 'obfuscated_external_user_id': 'obfuscated_external_user_id_value', 'documents_metadata_filters': {}} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.update_participant(request) - - -def test_update_participant_rest_flattened(): - client = ParticipantsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = gcd_participant.Participant() - - # get arguments that satisfy an http rule for this method - sample_request = {'participant': {'name': 'projects/sample1/conversations/sample2/participants/sample3'}} - - # get truthy value for each flattened field - mock_args = dict( - participant=gcd_participant.Participant(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - pb_return_value = gcd_participant.Participant.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.update_participant(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v2/{participant.name=projects/*/conversations/*/participants/*}" % client.transport._host, args[1]) - - -def test_update_participant_rest_flattened_error(transport: str = 'rest'): - client = ParticipantsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.update_participant( - gcd_participant.UpdateParticipantRequest(), - participant=gcd_participant.Participant(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - - -def test_update_participant_rest_error(): - client = ParticipantsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - gcd_participant.AnalyzeContentRequest, - dict, -]) -def test_analyze_content_rest(request_type): - client = ParticipantsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'participant': 'projects/sample1/conversations/sample2/participants/sample3'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = gcd_participant.AnalyzeContentResponse( - reply_text='reply_text_value', - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - pb_return_value = gcd_participant.AnalyzeContentResponse.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.analyze_content(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, gcd_participant.AnalyzeContentResponse) - assert response.reply_text == 'reply_text_value' - - -def test_analyze_content_rest_required_fields(request_type=gcd_participant.AnalyzeContentRequest): - transport_class = transports.ParticipantsRestTransport - - request_init = {} - request_init["participant"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - including_default_value_fields=False, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).analyze_content._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["participant"] = 'participant_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).analyze_content._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "participant" in jsonified_request - assert jsonified_request["participant"] == 'participant_value' - - client = ParticipantsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = gcd_participant.AnalyzeContentResponse() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "post", - 'query_params': pb_request, - } - transcode_result['body'] = pb_request - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - - pb_return_value = gcd_participant.AnalyzeContentResponse.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.analyze_content(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_analyze_content_rest_unset_required_fields(): - transport = transports.ParticipantsRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.analyze_content._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("participant", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_analyze_content_rest_interceptors(null_interceptor): - transport = transports.ParticipantsRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.ParticipantsRestInterceptor(), - ) - client = ParticipantsClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.ParticipantsRestInterceptor, "post_analyze_content") as post, \ - mock.patch.object(transports.ParticipantsRestInterceptor, "pre_analyze_content") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = gcd_participant.AnalyzeContentRequest.pb(gcd_participant.AnalyzeContentRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = gcd_participant.AnalyzeContentResponse.to_json(gcd_participant.AnalyzeContentResponse()) - - request = gcd_participant.AnalyzeContentRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = gcd_participant.AnalyzeContentResponse() - - client.analyze_content(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_analyze_content_rest_bad_request(transport: str = 'rest', request_type=gcd_participant.AnalyzeContentRequest): - client = ParticipantsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'participant': 'projects/sample1/conversations/sample2/participants/sample3'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.analyze_content(request) - - -def test_analyze_content_rest_flattened(): - client = ParticipantsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = gcd_participant.AnalyzeContentResponse() - - # get arguments that satisfy an http rule for this method - sample_request = {'participant': 'projects/sample1/conversations/sample2/participants/sample3'} - - # get truthy value for each flattened field - mock_args = dict( - participant='participant_value', - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - pb_return_value = gcd_participant.AnalyzeContentResponse.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.analyze_content(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v2/{participant=projects/*/conversations/*/participants/*}:analyzeContent" % client.transport._host, args[1]) - - -def test_analyze_content_rest_flattened_error(transport: str = 'rest'): - client = ParticipantsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.analyze_content( - gcd_participant.AnalyzeContentRequest(), - participant='participant_value', - text_input=session.TextInput(text='text_value'), - event_input=session.EventInput(name='name_value'), - ) - - -def test_analyze_content_rest_error(): - client = ParticipantsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -def test_streaming_analyze_content_rest_no_http_options(): - client = ParticipantsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request = participant.StreamingAnalyzeContentRequest() - requests = [request] - with pytest.raises(RuntimeError): - client.streaming_analyze_content(requests) - - -@pytest.mark.parametrize("request_type", [ - participant.SuggestArticlesRequest, - dict, -]) -def test_suggest_articles_rest(request_type): - client = ParticipantsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1/conversations/sample2/participants/sample3'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = participant.SuggestArticlesResponse( - latest_message='latest_message_value', - context_size=1311, - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - pb_return_value = participant.SuggestArticlesResponse.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.suggest_articles(request) - - # 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 - - -def test_suggest_articles_rest_required_fields(request_type=participant.SuggestArticlesRequest): - transport_class = transports.ParticipantsRestTransport - - request_init = {} - request_init["parent"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - including_default_value_fields=False, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).suggest_articles._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["parent"] = 'parent_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).suggest_articles._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "parent" in jsonified_request - assert jsonified_request["parent"] == 'parent_value' - - client = ParticipantsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = participant.SuggestArticlesResponse() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "post", - 'query_params': pb_request, - } - transcode_result['body'] = pb_request - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - - pb_return_value = participant.SuggestArticlesResponse.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.suggest_articles(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_suggest_articles_rest_unset_required_fields(): - transport = transports.ParticipantsRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.suggest_articles._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("parent", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_suggest_articles_rest_interceptors(null_interceptor): - transport = transports.ParticipantsRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.ParticipantsRestInterceptor(), - ) - client = ParticipantsClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.ParticipantsRestInterceptor, "post_suggest_articles") as post, \ - mock.patch.object(transports.ParticipantsRestInterceptor, "pre_suggest_articles") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = participant.SuggestArticlesRequest.pb(participant.SuggestArticlesRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = participant.SuggestArticlesResponse.to_json(participant.SuggestArticlesResponse()) - - request = participant.SuggestArticlesRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = participant.SuggestArticlesResponse() - - client.suggest_articles(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_suggest_articles_rest_bad_request(transport: str = 'rest', request_type=participant.SuggestArticlesRequest): - client = ParticipantsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1/conversations/sample2/participants/sample3'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.suggest_articles(request) - - -def test_suggest_articles_rest_flattened(): - client = ParticipantsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = participant.SuggestArticlesResponse() - - # get arguments that satisfy an http rule for this method - sample_request = {'parent': 'projects/sample1/conversations/sample2/participants/sample3'} - - # get truthy value for each flattened field - mock_args = dict( - parent='parent_value', - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - pb_return_value = participant.SuggestArticlesResponse.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.suggest_articles(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v2/{parent=projects/*/conversations/*/participants/*}/suggestions:suggestArticles" % client.transport._host, args[1]) - - -def test_suggest_articles_rest_flattened_error(transport: str = 'rest'): - client = ParticipantsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.suggest_articles( - participant.SuggestArticlesRequest(), - parent='parent_value', - ) - - -def test_suggest_articles_rest_error(): - client = ParticipantsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - participant.SuggestFaqAnswersRequest, - dict, -]) -def test_suggest_faq_answers_rest(request_type): - client = ParticipantsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1/conversations/sample2/participants/sample3'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = participant.SuggestFaqAnswersResponse( - latest_message='latest_message_value', - context_size=1311, - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - pb_return_value = participant.SuggestFaqAnswersResponse.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.suggest_faq_answers(request) - - # 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 - - -def test_suggest_faq_answers_rest_required_fields(request_type=participant.SuggestFaqAnswersRequest): - transport_class = transports.ParticipantsRestTransport - - request_init = {} - request_init["parent"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - including_default_value_fields=False, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).suggest_faq_answers._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["parent"] = 'parent_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).suggest_faq_answers._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "parent" in jsonified_request - assert jsonified_request["parent"] == 'parent_value' - - client = ParticipantsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = participant.SuggestFaqAnswersResponse() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "post", - 'query_params': pb_request, - } - transcode_result['body'] = pb_request - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - - pb_return_value = participant.SuggestFaqAnswersResponse.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.suggest_faq_answers(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_suggest_faq_answers_rest_unset_required_fields(): - transport = transports.ParticipantsRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.suggest_faq_answers._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("parent", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_suggest_faq_answers_rest_interceptors(null_interceptor): - transport = transports.ParticipantsRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.ParticipantsRestInterceptor(), - ) - client = ParticipantsClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.ParticipantsRestInterceptor, "post_suggest_faq_answers") as post, \ - mock.patch.object(transports.ParticipantsRestInterceptor, "pre_suggest_faq_answers") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = participant.SuggestFaqAnswersRequest.pb(participant.SuggestFaqAnswersRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = participant.SuggestFaqAnswersResponse.to_json(participant.SuggestFaqAnswersResponse()) - - request = participant.SuggestFaqAnswersRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = participant.SuggestFaqAnswersResponse() - - client.suggest_faq_answers(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_suggest_faq_answers_rest_bad_request(transport: str = 'rest', request_type=participant.SuggestFaqAnswersRequest): - client = ParticipantsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1/conversations/sample2/participants/sample3'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.suggest_faq_answers(request) - - -def test_suggest_faq_answers_rest_flattened(): - client = ParticipantsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = participant.SuggestFaqAnswersResponse() - - # get arguments that satisfy an http rule for this method - sample_request = {'parent': 'projects/sample1/conversations/sample2/participants/sample3'} - - # get truthy value for each flattened field - mock_args = dict( - parent='parent_value', - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - pb_return_value = participant.SuggestFaqAnswersResponse.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.suggest_faq_answers(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v2/{parent=projects/*/conversations/*/participants/*}/suggestions:suggestFaqAnswers" % client.transport._host, args[1]) - - -def test_suggest_faq_answers_rest_flattened_error(transport: str = 'rest'): - client = ParticipantsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.suggest_faq_answers( - participant.SuggestFaqAnswersRequest(), - parent='parent_value', - ) - - -def test_suggest_faq_answers_rest_error(): - client = ParticipantsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - participant.SuggestSmartRepliesRequest, - dict, -]) -def test_suggest_smart_replies_rest(request_type): - client = ParticipantsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1/conversations/sample2/participants/sample3'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = participant.SuggestSmartRepliesResponse( - latest_message='latest_message_value', - context_size=1311, - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - pb_return_value = participant.SuggestSmartRepliesResponse.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.suggest_smart_replies(request) - - # 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 - - -def test_suggest_smart_replies_rest_required_fields(request_type=participant.SuggestSmartRepliesRequest): - transport_class = transports.ParticipantsRestTransport - - request_init = {} - request_init["parent"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - including_default_value_fields=False, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).suggest_smart_replies._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["parent"] = 'parent_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).suggest_smart_replies._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "parent" in jsonified_request - assert jsonified_request["parent"] == 'parent_value' - - client = ParticipantsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = participant.SuggestSmartRepliesResponse() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "post", - 'query_params': pb_request, - } - transcode_result['body'] = pb_request - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - - pb_return_value = participant.SuggestSmartRepliesResponse.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.suggest_smart_replies(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_suggest_smart_replies_rest_unset_required_fields(): - transport = transports.ParticipantsRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.suggest_smart_replies._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("parent", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_suggest_smart_replies_rest_interceptors(null_interceptor): - transport = transports.ParticipantsRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.ParticipantsRestInterceptor(), - ) - client = ParticipantsClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.ParticipantsRestInterceptor, "post_suggest_smart_replies") as post, \ - mock.patch.object(transports.ParticipantsRestInterceptor, "pre_suggest_smart_replies") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = participant.SuggestSmartRepliesRequest.pb(participant.SuggestSmartRepliesRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = participant.SuggestSmartRepliesResponse.to_json(participant.SuggestSmartRepliesResponse()) - - request = participant.SuggestSmartRepliesRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = participant.SuggestSmartRepliesResponse() - - client.suggest_smart_replies(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_suggest_smart_replies_rest_bad_request(transport: str = 'rest', request_type=participant.SuggestSmartRepliesRequest): - client = ParticipantsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1/conversations/sample2/participants/sample3'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.suggest_smart_replies(request) - - -def test_suggest_smart_replies_rest_flattened(): - client = ParticipantsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = participant.SuggestSmartRepliesResponse() - - # get arguments that satisfy an http rule for this method - sample_request = {'parent': 'projects/sample1/conversations/sample2/participants/sample3'} - - # get truthy value for each flattened field - mock_args = dict( - parent='parent_value', - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - pb_return_value = participant.SuggestSmartRepliesResponse.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.suggest_smart_replies(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v2/{parent=projects/*/conversations/*/participants/*}/suggestions:suggestSmartReplies" % client.transport._host, args[1]) - - -def test_suggest_smart_replies_rest_flattened_error(transport: str = 'rest'): - client = ParticipantsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.suggest_smart_replies( - participant.SuggestSmartRepliesRequest(), - parent='parent_value', - ) - - -def test_suggest_smart_replies_rest_error(): - client = ParticipantsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -def test_streaming_analyze_content_rest_error(): - client = ParticipantsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - # Since a `google.api.http` annotation is required for using a rest transport - # method, this should error. - with pytest.raises(NotImplementedError) as not_implemented_error: - client.streaming_analyze_content({}) - assert ( - "Method StreamingAnalyzeContent is not available over REST transport" - in str(not_implemented_error.value) - ) - - -def test_credentials_transport_error(): - # It is an error to provide credentials and a transport instance. - transport = transports.ParticipantsGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = ParticipantsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # It is an error to provide a credentials file and a transport instance. - transport = transports.ParticipantsGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = ParticipantsClient( - client_options={"credentials_file": "credentials.json"}, - transport=transport, - ) - - # It is an error to provide an api_key and a transport instance. - transport = transports.ParticipantsGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - options = client_options.ClientOptions() - options.api_key = "api_key" - with pytest.raises(ValueError): - client = ParticipantsClient( - client_options=options, - transport=transport, - ) - - # It is an error to provide an api_key and a credential. - options = mock.Mock() - options.api_key = "api_key" - with pytest.raises(ValueError): - client = ParticipantsClient( - client_options=options, - credentials=ga_credentials.AnonymousCredentials() - ) - - # It is an error to provide scopes and a transport instance. - transport = transports.ParticipantsGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = ParticipantsClient( - client_options={"scopes": ["1", "2"]}, - transport=transport, - ) - - -def test_transport_instance(): - # A client may be instantiated with a custom transport instance. - transport = transports.ParticipantsGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - client = ParticipantsClient(transport=transport) - assert client.transport is transport - -def test_transport_get_channel(): - # A client may be instantiated with a custom transport instance. - transport = transports.ParticipantsGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - - transport = transports.ParticipantsGrpcAsyncIOTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - -@pytest.mark.parametrize("transport_class", [ - transports.ParticipantsGrpcTransport, - transports.ParticipantsGrpcAsyncIOTransport, - transports.ParticipantsRestTransport, -]) -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() - -@pytest.mark.parametrize("transport_name", [ - "grpc", - "rest", -]) -def test_transport_kind(transport_name): - transport = ParticipantsClient.get_transport_class(transport_name)( - credentials=ga_credentials.AnonymousCredentials(), - ) - assert transport.kind == transport_name - -def test_transport_grpc_default(): - # A client should use the gRPC transport by default. - 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(core_exceptions.DuplicateCredentialArgs): - transport = transports.ParticipantsTransport( - credentials=ga_credentials.AnonymousCredentials(), - credentials_file="credentials.json" - ) - - -def test_participants_base_transport(): - # Instantiate the base transport. - with mock.patch('google.cloud.dialogflow_v2.services.participants.transports.ParticipantsTransport.__init__') as Transport: - Transport.return_value = None - transport = transports.ParticipantsTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Every method on the transport should just blindly - # raise NotImplementedError. - methods = ( - 'create_participant', - 'get_participant', - 'list_participants', - 'update_participant', - 'analyze_content', - 'streaming_analyze_content', - 'suggest_articles', - 'suggest_faq_answers', - 'suggest_smart_replies', - 'get_location', - 'list_locations', - 'get_operation', - 'cancel_operation', - 'list_operations', - ) - for method in methods: - with pytest.raises(NotImplementedError): - getattr(transport, method)(request=object()) - - with pytest.raises(NotImplementedError): - transport.close() - - # Catch all for all remaining methods and properties - remainder = [ - 'kind', - ] - for r in remainder: - with pytest.raises(NotImplementedError): - getattr(transport, r)() - - -def test_participants_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.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", - ) - - -def test_participants_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.participants.transports.ParticipantsTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.ParticipantsTransport() - adc.assert_called_once() - - -def test_participants_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) - 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, - ) - - -@pytest.mark.parametrize( - "transport_class", - [ - transports.ParticipantsGrpcTransport, - transports.ParticipantsGrpcAsyncIOTransport, - ], -) -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(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, - transports.ParticipantsRestTransport, - ], -) -def test_participants_transport_auth_gdch_credentials(transport_class): - host = 'https://language.com' - api_audience_tests = [None, 'https://language2.com'] - api_audience_expect = [host, 'https://language2.com'] - for t, e in zip(api_audience_tests, api_audience_expect): - with mock.patch.object(google.auth, 'default', autospec=True) as adc: - gdch_mock = mock.MagicMock() - type(gdch_mock).with_gdch_audience = mock.PropertyMock(return_value=gdch_mock) - adc.return_value = (gdch_mock, None) - transport_class(host=host, api_audience=t) - gdch_mock.with_gdch_audience.assert_called_once_with( - e - ) - - -@pytest.mark.parametrize( - "transport_class,grpc_helpers", - [ - (transports.ParticipantsGrpcTransport, grpc_helpers), - (transports.ParticipantsGrpcAsyncIOTransport, grpc_helpers_async) - ], -) -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", [transports.ParticipantsGrpcTransport, transports.ParticipantsGrpcAsyncIOTransport]) -def test_participants_grpc_transport_client_cert_source_for_mtls( - transport_class -): - cred = ga_credentials.AnonymousCredentials() - - # Check ssl_channel_credentials is used if provided. - with mock.patch.object(transport_class, "create_channel") as mock_create_channel: - mock_ssl_channel_creds = mock.Mock() - transport_class( - host="squid.clam.whelk", - credentials=cred, - ssl_channel_credentials=mock_ssl_channel_creds - ) - mock_create_channel.assert_called_once_with( - "squid.clam.whelk:443", - credentials=cred, - credentials_file=None, - scopes=None, - ssl_credentials=mock_ssl_channel_creds, - quota_project_id=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - # Check if ssl_channel_credentials is not provided, then client_cert_source_for_mtls - # is used. - with mock.patch.object(transport_class, "create_channel", return_value=mock.Mock()): - with mock.patch("grpc.ssl_channel_credentials") as mock_ssl_cred: - transport_class( - credentials=cred, - client_cert_source_for_mtls=client_cert_source_callback - ) - expected_cert, expected_key = client_cert_source_callback() - mock_ssl_cred.assert_called_once_with( - certificate_chain=expected_cert, - private_key=expected_key - ) - -def test_participants_http_transport_client_cert_source_for_mtls(): - cred = ga_credentials.AnonymousCredentials() - with mock.patch("google.auth.transport.requests.AuthorizedSession.configure_mtls_channel") as mock_configure_mtls_channel: - transports.ParticipantsRestTransport ( - credentials=cred, - client_cert_source_for_mtls=client_cert_source_callback - ) - mock_configure_mtls_channel.assert_called_once_with(client_cert_source_callback) - - -@pytest.mark.parametrize("transport_name", [ - "grpc", - "grpc_asyncio", - "rest", -]) -def test_participants_host_no_port(transport_name): - client = ParticipantsClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='dialogflow.googleapis.com'), - transport=transport_name, - ) - assert client.transport._host == ( - 'dialogflow.googleapis.com:443' - if transport_name in ['grpc', 'grpc_asyncio'] - else 'https://dialogflow.googleapis.com' - ) - -@pytest.mark.parametrize("transport_name", [ - "grpc", - "grpc_asyncio", - "rest", -]) -def test_participants_host_with_port(transport_name): - client = ParticipantsClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='dialogflow.googleapis.com:8000'), - transport=transport_name, - ) - assert client.transport._host == ( - 'dialogflow.googleapis.com:8000' - if transport_name in ['grpc', 'grpc_asyncio'] - else 'https://dialogflow.googleapis.com:8000' - ) - -@pytest.mark.parametrize("transport_name", [ - "rest", -]) -def test_participants_client_transport_session_collision(transport_name): - creds1 = ga_credentials.AnonymousCredentials() - creds2 = ga_credentials.AnonymousCredentials() - client1 = ParticipantsClient( - credentials=creds1, - transport=transport_name, - ) - client2 = ParticipantsClient( - credentials=creds2, - transport=transport_name, - ) - session1 = client1.transport.create_participant._session - session2 = client2.transport.create_participant._session - assert session1 != session2 - session1 = client1.transport.get_participant._session - session2 = client2.transport.get_participant._session - assert session1 != session2 - session1 = client1.transport.list_participants._session - session2 = client2.transport.list_participants._session - assert session1 != session2 - session1 = client1.transport.update_participant._session - session2 = client2.transport.update_participant._session - assert session1 != session2 - session1 = client1.transport.analyze_content._session - session2 = client2.transport.analyze_content._session - assert session1 != session2 - session1 = client1.transport.streaming_analyze_content._session - session2 = client2.transport.streaming_analyze_content._session - assert session1 != session2 - session1 = client1.transport.suggest_articles._session - session2 = client2.transport.suggest_articles._session - assert session1 != session2 - session1 = client1.transport.suggest_faq_answers._session - session2 = client2.transport.suggest_faq_answers._session - assert session1 != session2 - session1 = client1.transport.suggest_smart_replies._session - session2 = client2.transport.suggest_smart_replies._session - assert session1 != session2 -def test_participants_grpc_transport_channel(): - channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.ParticipantsGrpcTransport( - 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_participants_grpc_asyncio_transport_channel(): - channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.ParticipantsGrpcAsyncIOTransport( - 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.ParticipantsGrpcTransport, transports.ParticipantsGrpcAsyncIOTransport]) -def test_participants_transport_channel_mtls_with_client_cert_source( - transport_class -): - with mock.patch("grpc.ssl_channel_credentials", autospec=True) as grpc_ssl_channel_cred: - with mock.patch.object(transport_class, "create_channel") as grpc_create_channel: - mock_ssl_cred = mock.Mock() - grpc_ssl_channel_cred.return_value = mock_ssl_cred - - mock_grpc_channel = mock.Mock() - grpc_create_channel.return_value = mock_grpc_channel - - cred = ga_credentials.AnonymousCredentials() - with pytest.warns(DeprecationWarning): - with mock.patch.object(google.auth, 'default') as adc: - adc.return_value = (cred, None) - transport = transport_class( - host="squid.clam.whelk", - api_mtls_endpoint="mtls.squid.clam.whelk", - client_cert_source=client_cert_source_callback, - ) - adc.assert_called_once() - - grpc_ssl_channel_cred.assert_called_once_with( - certificate_chain=b"cert bytes", private_key=b"key bytes" - ) - grpc_create_channel.assert_called_once_with( - "mtls.squid.clam.whelk:443", - credentials=cred, - credentials_file=None, - scopes=None, - ssl_credentials=mock_ssl_cred, - quota_project_id=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - assert transport.grpc_channel == mock_grpc_channel - assert transport._ssl_channel_credentials == mock_ssl_cred - - -# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are -# removed from grpc/grpc_asyncio transport constructor. -@pytest.mark.parametrize("transport_class", [transports.ParticipantsGrpcTransport, transports.ParticipantsGrpcAsyncIOTransport]) -def test_participants_transport_channel_mtls_with_adc( - transport_class -): - mock_ssl_cred = mock.Mock() - with mock.patch.multiple( - "google.auth.transport.grpc.SslCredentials", - __init__=mock.Mock(return_value=None), - ssl_credentials=mock.PropertyMock(return_value=mock_ssl_cred), - ): - with mock.patch.object(transport_class, "create_channel") as grpc_create_channel: - mock_grpc_channel = mock.Mock() - grpc_create_channel.return_value = mock_grpc_channel - mock_cred = mock.Mock() - - with pytest.warns(DeprecationWarning): - transport = transport_class( - host="squid.clam.whelk", - credentials=mock_cred, - api_mtls_endpoint="mtls.squid.clam.whelk", - client_cert_source=None, - ) - - grpc_create_channel.assert_called_once_with( - "mtls.squid.clam.whelk:443", - credentials=mock_cred, - credentials_file=None, - scopes=None, - ssl_credentials=mock_ssl_cred, - quota_project_id=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - assert transport.grpc_channel == mock_grpc_channel - - -def test_answer_record_path(): - project = "squid" - answer_record = "clam" - expected = "projects/{project}/answerRecords/{answer_record}".format(project=project, answer_record=answer_record, ) - actual = ParticipantsClient.answer_record_path(project, answer_record) - assert expected == actual - - -def test_parse_answer_record_path(): - expected = { - "project": "whelk", - "answer_record": "octopus", - } - path = ParticipantsClient.answer_record_path(**expected) - - # Check that the path construction is reversible. - actual = ParticipantsClient.parse_answer_record_path(path) - assert expected == actual - -def test_context_path(): - project = "oyster" - session = "nudibranch" - context = "cuttlefish" - expected = "projects/{project}/agent/sessions/{session}/contexts/{context}".format(project=project, session=session, context=context, ) - actual = ParticipantsClient.context_path(project, session, context) - assert expected == actual - - -def test_parse_context_path(): - expected = { - "project": "mussel", - "session": "winkle", - "context": "nautilus", - } - path = ParticipantsClient.context_path(**expected) - - # Check that the path construction is reversible. - actual = ParticipantsClient.parse_context_path(path) - assert expected == actual - -def test_intent_path(): - project = "scallop" - intent = "abalone" - expected = "projects/{project}/agent/intents/{intent}".format(project=project, intent=intent, ) - actual = ParticipantsClient.intent_path(project, intent) - assert expected == actual - - -def test_parse_intent_path(): - expected = { - "project": "squid", - "intent": "clam", - } - path = ParticipantsClient.intent_path(**expected) - - # Check that the path construction is reversible. - actual = ParticipantsClient.parse_intent_path(path) - assert expected == actual - -def test_message_path(): - project = "whelk" - conversation = "octopus" - message = "oyster" - expected = "projects/{project}/conversations/{conversation}/messages/{message}".format(project=project, conversation=conversation, message=message, ) - actual = ParticipantsClient.message_path(project, conversation, message) - assert expected == actual - - -def test_parse_message_path(): - expected = { - "project": "nudibranch", - "conversation": "cuttlefish", - "message": "mussel", - } - path = ParticipantsClient.message_path(**expected) - - # Check that the path construction is reversible. - actual = ParticipantsClient.parse_message_path(path) - assert expected == actual - -def test_participant_path(): - project = "winkle" - conversation = "nautilus" - participant = "scallop" - expected = "projects/{project}/conversations/{conversation}/participants/{participant}".format(project=project, conversation=conversation, participant=participant, ) - actual = ParticipantsClient.participant_path(project, conversation, participant) - assert expected == actual - - -def test_parse_participant_path(): - expected = { - "project": "abalone", - "conversation": "squid", - "participant": "clam", - } - path = ParticipantsClient.participant_path(**expected) - - # Check that the path construction is reversible. - actual = ParticipantsClient.parse_participant_path(path) - assert expected == actual - -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, ) - actual = ParticipantsClient.session_entity_type_path(project, session, entity_type) - assert expected == actual - - -def test_parse_session_entity_type_path(): - expected = { - "project": "nudibranch", - "session": "cuttlefish", - "entity_type": "mussel", - } - path = ParticipantsClient.session_entity_type_path(**expected) - - # Check that the path construction is reversible. - actual = ParticipantsClient.parse_session_entity_type_path(path) - assert expected == actual - -def test_common_billing_account_path(): - billing_account = "winkle" - expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) - actual = ParticipantsClient.common_billing_account_path(billing_account) - assert expected == actual - - -def test_parse_common_billing_account_path(): - expected = { - "billing_account": "nautilus", - } - path = ParticipantsClient.common_billing_account_path(**expected) - - # Check that the path construction is reversible. - actual = ParticipantsClient.parse_common_billing_account_path(path) - assert expected == actual - -def test_common_folder_path(): - folder = "scallop" - expected = "folders/{folder}".format(folder=folder, ) - actual = ParticipantsClient.common_folder_path(folder) - assert expected == actual - - -def test_parse_common_folder_path(): - expected = { - "folder": "abalone", - } - path = ParticipantsClient.common_folder_path(**expected) - - # Check that the path construction is reversible. - actual = ParticipantsClient.parse_common_folder_path(path) - assert expected == actual - -def test_common_organization_path(): - organization = "squid" - expected = "organizations/{organization}".format(organization=organization, ) - actual = ParticipantsClient.common_organization_path(organization) - assert expected == actual - - -def test_parse_common_organization_path(): - expected = { - "organization": "clam", - } - path = ParticipantsClient.common_organization_path(**expected) - - # Check that the path construction is reversible. - actual = ParticipantsClient.parse_common_organization_path(path) - assert expected == actual - -def test_common_project_path(): - project = "whelk" - expected = "projects/{project}".format(project=project, ) - actual = ParticipantsClient.common_project_path(project) - assert expected == actual - - -def test_parse_common_project_path(): - expected = { - "project": "octopus", - } - path = ParticipantsClient.common_project_path(**expected) - - # Check that the path construction is reversible. - actual = ParticipantsClient.parse_common_project_path(path) - assert expected == actual - -def test_common_location_path(): - project = "oyster" - location = "nudibranch" - expected = "projects/{project}/locations/{location}".format(project=project, location=location, ) - actual = ParticipantsClient.common_location_path(project, location) - assert expected == actual - - -def test_parse_common_location_path(): - expected = { - "project": "cuttlefish", - "location": "mussel", - } - path = ParticipantsClient.common_location_path(**expected) - - # Check that the path construction is reversible. - actual = ParticipantsClient.parse_common_location_path(path) - assert expected == actual - - -def test_client_with_default_client_info(): - client_info = gapic_v1.client_info.ClientInfo() - - with mock.patch.object(transports.ParticipantsTransport, '_prep_wrapped_messages') as prep: - client = ParticipantsClient( - credentials=ga_credentials.AnonymousCredentials(), - client_info=client_info, - ) - prep.assert_called_once_with(client_info) - - with mock.patch.object(transports.ParticipantsTransport, '_prep_wrapped_messages') as prep: - transport_class = ParticipantsClient.get_transport_class() - transport = transport_class( - credentials=ga_credentials.AnonymousCredentials(), - client_info=client_info, - ) - prep.assert_called_once_with(client_info) - -@pytest.mark.asyncio -async def test_transport_close_async(): - client = ParticipantsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - with mock.patch.object(type(getattr(client.transport, "grpc_channel")), "close") as close: - async with client: - close.assert_not_called() - close.assert_called_once() - - -def test_get_location_rest_bad_request(transport: str = 'rest', request_type=locations_pb2.GetLocationRequest): - client = ParticipantsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - request = request_type() - request = json_format.ParseDict({'name': 'projects/sample1/locations/sample2'}, request) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.get_location(request) - -@pytest.mark.parametrize("request_type", [ - locations_pb2.GetLocationRequest, - dict, -]) -def test_get_location_rest(request_type): - client = ParticipantsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request_init = {'name': 'projects/sample1/locations/sample2'} - request = request_type(**request_init) - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = locations_pb2.Location() - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.get_location(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, locations_pb2.Location) - -def test_list_locations_rest_bad_request(transport: str = 'rest', request_type=locations_pb2.ListLocationsRequest): - client = ParticipantsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - request = request_type() - request = json_format.ParseDict({'name': 'projects/sample1'}, request) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.list_locations(request) - -@pytest.mark.parametrize("request_type", [ - locations_pb2.ListLocationsRequest, - dict, -]) -def test_list_locations_rest(request_type): - client = ParticipantsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request_init = {'name': 'projects/sample1'} - request = request_type(**request_init) - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = locations_pb2.ListLocationsResponse() - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.list_locations(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, locations_pb2.ListLocationsResponse) - -def test_cancel_operation_rest_bad_request(transport: str = 'rest', request_type=operations_pb2.CancelOperationRequest): - client = ParticipantsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - request = request_type() - request = json_format.ParseDict({'name': 'projects/sample1/operations/sample2'}, request) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.cancel_operation(request) - -@pytest.mark.parametrize("request_type", [ - operations_pb2.CancelOperationRequest, - dict, -]) -def test_cancel_operation_rest(request_type): - client = ParticipantsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request_init = {'name': 'projects/sample1/operations/sample2'} - request = request_type(**request_init) - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = None - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = '{}' - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.cancel_operation(request) - - # Establish that the response is the type that we expect. - assert response is None - -def test_get_operation_rest_bad_request(transport: str = 'rest', request_type=operations_pb2.GetOperationRequest): - client = ParticipantsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - request = request_type() - request = json_format.ParseDict({'name': 'projects/sample1/operations/sample2'}, request) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.get_operation(request) - -@pytest.mark.parametrize("request_type", [ - operations_pb2.GetOperationRequest, - dict, -]) -def test_get_operation_rest(request_type): - client = ParticipantsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request_init = {'name': 'projects/sample1/operations/sample2'} - request = request_type(**request_init) - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation() - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.get_operation(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, operations_pb2.Operation) - -def test_list_operations_rest_bad_request(transport: str = 'rest', request_type=operations_pb2.ListOperationsRequest): - client = ParticipantsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - request = request_type() - request = json_format.ParseDict({'name': 'projects/sample1'}, request) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.list_operations(request) - -@pytest.mark.parametrize("request_type", [ - operations_pb2.ListOperationsRequest, - dict, -]) -def test_list_operations_rest(request_type): - client = ParticipantsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request_init = {'name': 'projects/sample1'} - request = request_type(**request_init) - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = operations_pb2.ListOperationsResponse() - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.list_operations(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, operations_pb2.ListOperationsResponse) - - -def test_cancel_operation(transport: str = "grpc"): - client = ParticipantsClient( - 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 = operations_pb2.CancelOperationRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = None - response = client.cancel_operation(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 response is the type that we expect. - assert response is None -@pytest.mark.asyncio -async def test_cancel_operation_async(transport: str = "grpc"): - client = ParticipantsAsyncClient( - 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 = operations_pb2.CancelOperationRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - None - ) - response = await client.cancel_operation(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 response is the type that we expect. - assert response is None - -def test_cancel_operation_field_headers(): - 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 = operations_pb2.CancelOperationRequest() - request.name = "locations" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call: - call.return_value = None - - client.cancel_operation(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=locations",) in kw["metadata"] -@pytest.mark.asyncio -async def test_cancel_operation_field_headers_async(): - 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 = operations_pb2.CancelOperationRequest() - request.name = "locations" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - None - ) - await client.cancel_operation(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=locations",) in kw["metadata"] - -def test_cancel_operation_from_dict(): - 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.cancel_operation), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = None - - response = client.cancel_operation( - request={ - "name": "locations", - } - ) - call.assert_called() -@pytest.mark.asyncio -async def test_cancel_operation_from_dict_async(): - 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.cancel_operation), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - None - ) - response = await client.cancel_operation( - request={ - "name": "locations", - } - ) - call.assert_called() - - -def test_get_operation(transport: str = "grpc"): - client = ParticipantsClient( - 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 = operations_pb2.GetOperationRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_operation), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation() - response = client.get_operation(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 response is the type that we expect. - assert isinstance(response, operations_pb2.Operation) -@pytest.mark.asyncio -async def test_get_operation_async(transport: str = "grpc"): - client = ParticipantsAsyncClient( - 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 = operations_pb2.GetOperationRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_operation), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation() - ) - response = await client.get_operation(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 response is the type that we expect. - assert isinstance(response, operations_pb2.Operation) - -def test_get_operation_field_headers(): - 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 = operations_pb2.GetOperationRequest() - request.name = "locations" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_operation), "__call__") as call: - call.return_value = operations_pb2.Operation() - - client.get_operation(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=locations",) in kw["metadata"] -@pytest.mark.asyncio -async def test_get_operation_field_headers_async(): - 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 = operations_pb2.GetOperationRequest() - request.name = "locations" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_operation), "__call__") as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation() - ) - await client.get_operation(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=locations",) in kw["metadata"] - -def test_get_operation_from_dict(): - 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_operation), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation() - - response = client.get_operation( - request={ - "name": "locations", - } - ) - call.assert_called() -@pytest.mark.asyncio -async def test_get_operation_from_dict_async(): - 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_operation), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation() - ) - response = await client.get_operation( - request={ - "name": "locations", - } - ) - call.assert_called() - - -def test_list_operations(transport: str = "grpc"): - client = ParticipantsClient( - 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 = operations_pb2.ListOperationsRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_operations), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.ListOperationsResponse() - response = client.list_operations(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 response is the type that we expect. - assert isinstance(response, operations_pb2.ListOperationsResponse) -@pytest.mark.asyncio -async def test_list_operations_async(transport: str = "grpc"): - client = ParticipantsAsyncClient( - 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 = operations_pb2.ListOperationsRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_operations), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.ListOperationsResponse() - ) - response = await client.list_operations(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 response is the type that we expect. - assert isinstance(response, operations_pb2.ListOperationsResponse) - -def test_list_operations_field_headers(): - 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 = operations_pb2.ListOperationsRequest() - request.name = "locations" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_operations), "__call__") as call: - call.return_value = operations_pb2.ListOperationsResponse() - - client.list_operations(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=locations",) in kw["metadata"] -@pytest.mark.asyncio -async def test_list_operations_field_headers_async(): - 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 = operations_pb2.ListOperationsRequest() - request.name = "locations" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_operations), "__call__") as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.ListOperationsResponse() - ) - await client.list_operations(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=locations",) in kw["metadata"] - -def test_list_operations_from_dict(): - 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_operations), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.ListOperationsResponse() - - response = client.list_operations( - request={ - "name": "locations", - } - ) - call.assert_called() -@pytest.mark.asyncio -async def test_list_operations_from_dict_async(): - 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.list_operations), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.ListOperationsResponse() - ) - response = await client.list_operations( - request={ - "name": "locations", - } - ) - call.assert_called() - - -def test_list_locations(transport: str = "grpc"): - client = ParticipantsClient( - 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 = locations_pb2.ListLocationsRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_locations), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = locations_pb2.ListLocationsResponse() - response = client.list_locations(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 response is the type that we expect. - assert isinstance(response, locations_pb2.ListLocationsResponse) -@pytest.mark.asyncio -async def test_list_locations_async(transport: str = "grpc"): - client = ParticipantsAsyncClient( - 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 = locations_pb2.ListLocationsRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_locations), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - locations_pb2.ListLocationsResponse() - ) - response = await client.list_locations(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 response is the type that we expect. - assert isinstance(response, locations_pb2.ListLocationsResponse) - -def test_list_locations_field_headers(): - 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 = locations_pb2.ListLocationsRequest() - request.name = "locations" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_locations), "__call__") as call: - call.return_value = locations_pb2.ListLocationsResponse() - - client.list_locations(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=locations",) in kw["metadata"] -@pytest.mark.asyncio -async def test_list_locations_field_headers_async(): - 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 = locations_pb2.ListLocationsRequest() - request.name = "locations" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_locations), "__call__") as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - locations_pb2.ListLocationsResponse() - ) - await client.list_locations(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=locations",) in kw["metadata"] - -def test_list_locations_from_dict(): - 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_locations), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = locations_pb2.ListLocationsResponse() - - response = client.list_locations( - request={ - "name": "locations", - } - ) - call.assert_called() -@pytest.mark.asyncio -async def test_list_locations_from_dict_async(): - 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.list_locations), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - locations_pb2.ListLocationsResponse() - ) - response = await client.list_locations( - request={ - "name": "locations", - } - ) - call.assert_called() - - -def test_get_location(transport: str = "grpc"): - client = ParticipantsClient( - 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 = locations_pb2.GetLocationRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_location), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = locations_pb2.Location() - response = client.get_location(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 response is the type that we expect. - assert isinstance(response, locations_pb2.Location) -@pytest.mark.asyncio -async def test_get_location_async(transport: str = "grpc_asyncio"): - client = ParticipantsAsyncClient( - 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 = locations_pb2.GetLocationRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_location), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - locations_pb2.Location() - ) - response = await client.get_location(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 response is the type that we expect. - assert isinstance(response, locations_pb2.Location) - -def test_get_location_field_headers(): - 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 = locations_pb2.GetLocationRequest() - request.name = "locations/abc" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_location), "__call__") as call: - call.return_value = locations_pb2.Location() - - client.get_location(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=locations/abc",) in kw["metadata"] -@pytest.mark.asyncio -async def test_get_location_field_headers_async(): - 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 = locations_pb2.GetLocationRequest() - request.name = "locations/abc" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_location), "__call__") as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - locations_pb2.Location() - ) - await client.get_location(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=locations/abc",) in kw["metadata"] - -def test_get_location_from_dict(): - 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_locations), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = locations_pb2.Location() - - response = client.get_location( - request={ - "name": "locations/abc", - } - ) - call.assert_called() -@pytest.mark.asyncio -async def test_get_location_from_dict_async(): - 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.list_locations), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - locations_pb2.Location() - ) - response = await client.get_location( - request={ - "name": "locations", - } - ) - call.assert_called() - - -def test_transport_close(): - transports = { - "rest": "_session", - "grpc": "_grpc_channel", - } - - for transport, close_name in transports.items(): - client = ParticipantsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport - ) - with mock.patch.object(type(getattr(client.transport, close_name)), "close") as close: - with client: - close.assert_not_called() - close.assert_called_once() - -def test_client_ctx(): - transports = [ - 'rest', - 'grpc', - ] - for transport in transports: - client = ParticipantsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport - ) - # Test client calls underlying transport. - with mock.patch.object(type(client.transport), "close") as close: - close.assert_not_called() - with client: - pass - close.assert_called() - -@pytest.mark.parametrize("client_class,transport_class", [ - (ParticipantsClient, transports.ParticipantsGrpcTransport), - (ParticipantsAsyncClient, transports.ParticipantsGrpcAsyncIOTransport), -]) -def test_api_key_credentials(client_class, transport_class): - with mock.patch.object( - google.auth._default, "get_api_key_credentials", create=True - ) as get_api_key_credentials: - mock_cred = mock.Mock() - get_api_key_credentials.return_value = mock_cred - options = client_options.ClientOptions() - options.api_key = "api_key" - 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=mock_cred, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) diff --git a/owl-bot-staging/v2/tests/unit/gapic/dialogflow_v2/test_session_entity_types.py b/owl-bot-staging/v2/tests/unit/gapic/dialogflow_v2/test_session_entity_types.py deleted file mode 100644 index b58e39b71..000000000 --- a/owl-bot-staging/v2/tests/unit/gapic/dialogflow_v2/test_session_entity_types.py +++ /dev/null @@ -1,4725 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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 -# try/except added for compatibility with python < 3.8 -try: - from unittest import mock - from unittest.mock import AsyncMock # pragma: NO COVER -except ImportError: # pragma: NO COVER - import mock - -import grpc -from grpc.experimental import aio -from collections.abc import Iterable -from google.protobuf import json_format -import json -import math -import pytest -from proto.marshal.rules.dates import DurationRule, TimestampRule -from proto.marshal.rules import wrappers -from requests import Response -from requests import Request, PreparedRequest -from requests.sessions import Session -from google.protobuf import json_format - -from google.api_core import client_options -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import grpc_helpers -from google.api_core import grpc_helpers_async -from google.api_core import path_template -from google.auth import credentials as ga_credentials -from google.auth.exceptions import MutualTLSChannelError -from google.cloud.dialogflow_v2.services.session_entity_types import SessionEntityTypesAsyncClient -from google.cloud.dialogflow_v2.services.session_entity_types import SessionEntityTypesClient -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.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.cloud.location import locations_pb2 -from google.longrunning import operations_pb2 -from google.oauth2 import service_account -from google.protobuf import field_mask_pb2 # type: ignore -import google.auth - - -def client_cert_source_callback(): - return b"cert bytes", b"key bytes" - - -# If default endpoint is localhost, then default mtls endpoint will be the same. -# This method modifies the default endpoint so the client can produce a different -# mtls endpoint for endpoint testing purposes. -def modify_default_endpoint(client): - return "foo.googleapis.com" if ("localhost" in client.DEFAULT_ENDPOINT) else client.DEFAULT_ENDPOINT - - -def test__get_default_mtls_endpoint(): - api_endpoint = "example.googleapis.com" - api_mtls_endpoint = "example.mtls.googleapis.com" - sandbox_endpoint = "example.sandbox.googleapis.com" - sandbox_mtls_endpoint = "example.mtls.sandbox.googleapis.com" - non_googleapi = "api.example.com" - - assert SessionEntityTypesClient._get_default_mtls_endpoint(None) is None - assert SessionEntityTypesClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint - assert SessionEntityTypesClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint - assert SessionEntityTypesClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint - assert SessionEntityTypesClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint - assert SessionEntityTypesClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi - - -@pytest.mark.parametrize("client_class,transport_name", [ - (SessionEntityTypesClient, "grpc"), - (SessionEntityTypesAsyncClient, "grpc_asyncio"), - (SessionEntityTypesClient, "rest"), -]) -def test_session_entity_types_client_from_service_account_info(client_class, transport_name): - 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, transport=transport_name) - assert client.transport._credentials == creds - assert isinstance(client, client_class) - - assert client.transport._host == ( - 'dialogflow.googleapis.com:443' - if transport_name in ['grpc', 'grpc_asyncio'] - else - 'https://dialogflow.googleapis.com' - ) - - -@pytest.mark.parametrize("transport_class,transport_name", [ - (transports.SessionEntityTypesGrpcTransport, "grpc"), - (transports.SessionEntityTypesGrpcAsyncIOTransport, "grpc_asyncio"), - (transports.SessionEntityTypesRestTransport, "rest"), -]) -def test_session_entity_types_client_service_account_always_use_jwt(transport_class, transport_name): - with mock.patch.object(service_account.Credentials, 'with_always_use_jwt_access', create=True) as use_jwt: - creds = service_account.Credentials(None, None, None) - transport = transport_class(credentials=creds, always_use_jwt_access=True) - use_jwt.assert_called_once_with(True) - - with mock.patch.object(service_account.Credentials, 'with_always_use_jwt_access', create=True) as use_jwt: - creds = service_account.Credentials(None, None, None) - transport = transport_class(credentials=creds, always_use_jwt_access=False) - use_jwt.assert_not_called() - - -@pytest.mark.parametrize("client_class,transport_name", [ - (SessionEntityTypesClient, "grpc"), - (SessionEntityTypesAsyncClient, "grpc_asyncio"), - (SessionEntityTypesClient, "rest"), -]) -def test_session_entity_types_client_from_service_account_file(client_class, transport_name): - 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", transport=transport_name) - assert client.transport._credentials == creds - assert isinstance(client, client_class) - - client = client_class.from_service_account_json("dummy/file/path.json", transport=transport_name) - assert client.transport._credentials == creds - assert isinstance(client, client_class) - - assert client.transport._host == ( - 'dialogflow.googleapis.com:443' - if transport_name in ['grpc', 'grpc_asyncio'] - else - 'https://dialogflow.googleapis.com' - ) - - -def test_session_entity_types_client_get_transport_class(): - transport = SessionEntityTypesClient.get_transport_class() - available_transports = [ - transports.SessionEntityTypesGrpcTransport, - transports.SessionEntityTypesRestTransport, - ] - assert transport in available_transports - - transport = SessionEntityTypesClient.get_transport_class("grpc") - assert transport == transports.SessionEntityTypesGrpcTransport - - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (SessionEntityTypesClient, transports.SessionEntityTypesGrpcTransport, "grpc"), - (SessionEntityTypesAsyncClient, transports.SessionEntityTypesGrpcAsyncIOTransport, "grpc_asyncio"), - (SessionEntityTypesClient, transports.SessionEntityTypesRestTransport, "rest"), -]) -@mock.patch.object(SessionEntityTypesClient, "DEFAULT_ENDPOINT", modify_default_endpoint(SessionEntityTypesClient)) -@mock.patch.object(SessionEntityTypesAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(SessionEntityTypesAsyncClient)) -def test_session_entity_types_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(SessionEntityTypesClient, '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(SessionEntityTypesClient, 'get_transport_class') as gtc: - client = client_class(transport=transport_name) - gtc.assert_called() - - # Check the case api_endpoint is provided. - options = client_options.ClientOptions(api_endpoint="squid.clam.whelk") - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(transport=transport_name, client_options=options) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host="squid.clam.whelk", - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is - # "never". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is - # "always". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_MTLS_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # 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(transport=transport_name) - - # 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(transport=transport_name) - - # 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, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id="octopus", - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - # Check the case api_endpoint is provided - options = client_options.ClientOptions(api_audience="https://language.googleapis.com") - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience="https://language.googleapis.com" - ) - -@pytest.mark.parametrize("client_class,transport_class,transport_name,use_client_cert_env", [ - (SessionEntityTypesClient, transports.SessionEntityTypesGrpcTransport, "grpc", "true"), - (SessionEntityTypesAsyncClient, transports.SessionEntityTypesGrpcAsyncIOTransport, "grpc_asyncio", "true"), - (SessionEntityTypesClient, transports.SessionEntityTypesGrpcTransport, "grpc", "false"), - (SessionEntityTypesAsyncClient, transports.SessionEntityTypesGrpcAsyncIOTransport, "grpc_asyncio", "false"), - (SessionEntityTypesClient, transports.SessionEntityTypesRestTransport, "rest", "true"), - (SessionEntityTypesClient, transports.SessionEntityTypesRestTransport, "rest", "false"), -]) -@mock.patch.object(SessionEntityTypesClient, "DEFAULT_ENDPOINT", modify_default_endpoint(SessionEntityTypesClient)) -@mock.patch.object(SessionEntityTypesAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(SessionEntityTypesAsyncClient)) -@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) -def test_session_entity_types_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, transport=transport_name) - - if use_client_cert_env == "false": - expected_client_cert_source = None - expected_host = client.DEFAULT_ENDPOINT - else: - expected_client_cert_source = client_cert_source_callback - expected_host = client.DEFAULT_MTLS_ENDPOINT - - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=expected_host, - scopes=None, - client_cert_source_for_mtls=expected_client_cert_source, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case ADC client cert is provided. Whether client cert is used depends on - # GOOGLE_API_USE_CLIENT_CERTIFICATE value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): - with mock.patch.object(transport_class, '__init__') as patched: - with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): - with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=client_cert_source_callback): - if use_client_cert_env == "false": - expected_host = client.DEFAULT_ENDPOINT - expected_client_cert_source = None - else: - expected_host = client.DEFAULT_MTLS_ENDPOINT - expected_client_cert_source = client_cert_source_callback - - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=expected_host, - scopes=None, - client_cert_source_for_mtls=expected_client_cert_source, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case client_cert_source and ADC client cert are not provided. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): - with mock.patch.object(transport_class, '__init__') as patched: - with mock.patch("google.auth.transport.mtls.has_default_client_cert_source", return_value=False): - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - -@pytest.mark.parametrize("client_class", [ - SessionEntityTypesClient, SessionEntityTypesAsyncClient -]) -@mock.patch.object(SessionEntityTypesClient, "DEFAULT_ENDPOINT", modify_default_endpoint(SessionEntityTypesClient)) -@mock.patch.object(SessionEntityTypesAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(SessionEntityTypesAsyncClient)) -def test_session_entity_types_client_get_mtls_endpoint_and_cert_source(client_class): - mock_client_cert_source = mock.Mock() - - # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "true". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - mock_api_endpoint = "foo" - options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) - assert api_endpoint == mock_api_endpoint - assert cert_source == mock_client_cert_source - - # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "false". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): - mock_client_cert_source = mock.Mock() - mock_api_endpoint = "foo" - options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) - assert api_endpoint == mock_api_endpoint - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "never". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_ENDPOINT - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "always". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert doesn't exist. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=False): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_ENDPOINT - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert exists. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - 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=mock_client_cert_source): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT - assert cert_source == mock_client_cert_source - - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (SessionEntityTypesClient, transports.SessionEntityTypesGrpcTransport, "grpc"), - (SessionEntityTypesAsyncClient, transports.SessionEntityTypesGrpcAsyncIOTransport, "grpc_asyncio"), - (SessionEntityTypesClient, transports.SessionEntityTypesRestTransport, "rest"), -]) -def test_session_entity_types_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, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=["1", "2"], - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - -@pytest.mark.parametrize("client_class,transport_class,transport_name,grpc_helpers", [ - (SessionEntityTypesClient, transports.SessionEntityTypesGrpcTransport, "grpc", grpc_helpers), - (SessionEntityTypesAsyncClient, transports.SessionEntityTypesGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), - (SessionEntityTypesClient, transports.SessionEntityTypesRestTransport, "rest", None), -]) -def test_session_entity_types_client_client_options_credentials_file(client_class, transport_class, transport_name, grpc_helpers): - # 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, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file="credentials.json", - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - -def test_session_entity_types_client_client_options_from_dict(): - with mock.patch('google.cloud.dialogflow_v2.services.session_entity_types.transports.SessionEntityTypesGrpcTransport.__init__') as grpc_transport: - grpc_transport.return_value = None - client = SessionEntityTypesClient( - client_options={'api_endpoint': 'squid.clam.whelk'} - ) - grpc_transport.assert_called_once_with( - credentials=None, - credentials_file=None, - host="squid.clam.whelk", - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - -@pytest.mark.parametrize("client_class,transport_class,transport_name,grpc_helpers", [ - (SessionEntityTypesClient, transports.SessionEntityTypesGrpcTransport, "grpc", grpc_helpers), - (SessionEntityTypesAsyncClient, transports.SessionEntityTypesGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), -]) -def test_session_entity_types_client_create_channel_credentials_file(client_class, transport_class, transport_name, grpc_helpers): - # 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, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file="credentials.json", - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # test that the credentials from file are saved and used as the credentials. - with mock.patch.object( - google.auth, "load_credentials_from_file", autospec=True - ) as load_creds, mock.patch.object( - google.auth, "default", autospec=True - ) as adc, mock.patch.object( - grpc_helpers, "create_channel" - ) as create_channel: - creds = ga_credentials.AnonymousCredentials() - file_creds = ga_credentials.AnonymousCredentials() - load_creds.return_value = (file_creds, None) - adc.return_value = (creds, None) - client = client_class(client_options=options, transport=transport_name) - create_channel.assert_called_with( - "dialogflow.googleapis.com:443", - credentials=file_creds, - credentials_file=None, - quota_project_id=None, - default_scopes=( - 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/dialogflow', -), - scopes=None, - default_host="dialogflow.googleapis.com", - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - -@pytest.mark.parametrize("request_type", [ - session_entity_type.ListSessionEntityTypesRequest, - dict, -]) -def test_list_session_entity_types(request_type, transport: str = 'grpc'): - client = SessionEntityTypesClient( - 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_session_entity_types), - '__call__') as call: - # Designate an appropriate return value for the call. - 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' - - -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=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_session_entity_types), - '__call__') as call: - client.list_session_entity_types() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == session_entity_type.ListSessionEntityTypesRequest() - -@pytest.mark.asyncio -async def test_list_session_entity_types_async(transport: str = 'grpc_asyncio', request_type=session_entity_type.ListSessionEntityTypesRequest): - client = SessionEntityTypesAsyncClient( - 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_session_entity_types), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(session_entity_type.ListSessionEntityTypesResponse( - 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' - - -@pytest.mark.asyncio -async def test_list_session_entity_types_async_from_dict(): - await test_list_session_entity_types_async(request_type=dict) - - -def test_list_session_entity_types_field_headers(): - 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. - with mock.patch.object( - 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. - 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_session_entity_types_field_headers_async(): - client = SessionEntityTypesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value 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. - with mock.patch.object( - type(client.transport.list_session_entity_types), - '__call__') as call: - 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. - 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_session_entity_types_flattened(): - client = SessionEntityTypesClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_session_entity_types), - '__call__') 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', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - arg = args[0].parent - mock_val = 'parent_value' - assert arg == mock_val - - -def test_list_session_entity_types_flattened_error(): - client = SessionEntityTypesClient( - 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_session_entity_types( - session_entity_type.ListSessionEntityTypesRequest(), - parent='parent_value', - ) - -@pytest.mark.asyncio -async def test_list_session_entity_types_flattened_async(): - client = SessionEntityTypesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_session_entity_types), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = session_entity_type.ListSessionEntityTypesResponse() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(session_entity_type.ListSessionEntityTypesResponse()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.list_session_entity_types( - 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] - arg = args[0].parent - mock_val = 'parent_value' - assert arg == mock_val - -@pytest.mark.asyncio -async def test_list_session_entity_types_flattened_error_async(): - client = SessionEntityTypesAsyncClient( - 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_session_entity_types( - session_entity_type.ListSessionEntityTypesRequest(), - parent='parent_value', - ) - - -def test_list_session_entity_types_pager(transport_name: str = "grpc"): - client = SessionEntityTypesClient( - credentials=ga_credentials.AnonymousCredentials, - transport=transport_name, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_session_entity_types), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - session_entity_type.ListSessionEntityTypesResponse( - session_entity_types=[ - session_entity_type.SessionEntityType(), - session_entity_type.SessionEntityType(), - session_entity_type.SessionEntityType(), - ], - next_page_token='abc', - ), - session_entity_type.ListSessionEntityTypesResponse( - session_entity_types=[], - next_page_token='def', - ), - session_entity_type.ListSessionEntityTypesResponse( - session_entity_types=[ - session_entity_type.SessionEntityType(), - ], - next_page_token='ghi', - ), - session_entity_type.ListSessionEntityTypesResponse( - session_entity_types=[ - session_entity_type.SessionEntityType(), - session_entity_type.SessionEntityType(), - ], - ), - RuntimeError, - ) - - metadata = () - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ('parent', ''), - )), - ) - pager = client.list_session_entity_types(request={}) - - assert pager._metadata == metadata - - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, session_entity_type.SessionEntityType) - for i in results) -def test_list_session_entity_types_pages(transport_name: str = "grpc"): - client = SessionEntityTypesClient( - credentials=ga_credentials.AnonymousCredentials, - transport=transport_name, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_session_entity_types), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - session_entity_type.ListSessionEntityTypesResponse( - session_entity_types=[ - session_entity_type.SessionEntityType(), - session_entity_type.SessionEntityType(), - session_entity_type.SessionEntityType(), - ], - next_page_token='abc', - ), - session_entity_type.ListSessionEntityTypesResponse( - session_entity_types=[], - next_page_token='def', - ), - session_entity_type.ListSessionEntityTypesResponse( - session_entity_types=[ - session_entity_type.SessionEntityType(), - ], - next_page_token='ghi', - ), - session_entity_type.ListSessionEntityTypesResponse( - session_entity_types=[ - session_entity_type.SessionEntityType(), - session_entity_type.SessionEntityType(), - ], - ), - RuntimeError, - ) - pages = list(client.list_session_entity_types(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_session_entity_types_async_pager(): - client = SessionEntityTypesAsyncClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_session_entity_types), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - session_entity_type.ListSessionEntityTypesResponse( - session_entity_types=[ - session_entity_type.SessionEntityType(), - session_entity_type.SessionEntityType(), - session_entity_type.SessionEntityType(), - ], - next_page_token='abc', - ), - session_entity_type.ListSessionEntityTypesResponse( - session_entity_types=[], - next_page_token='def', - ), - session_entity_type.ListSessionEntityTypesResponse( - session_entity_types=[ - session_entity_type.SessionEntityType(), - ], - next_page_token='ghi', - ), - session_entity_type.ListSessionEntityTypesResponse( - session_entity_types=[ - session_entity_type.SessionEntityType(), - session_entity_type.SessionEntityType(), - ], - ), - RuntimeError, - ) - async_pager = await client.list_session_entity_types(request={},) - assert async_pager.next_page_token == 'abc' - responses = [] - async for response in async_pager: # pragma: no branch - responses.append(response) - - assert len(responses) == 6 - assert all(isinstance(i, session_entity_type.SessionEntityType) - for i in responses) - - -@pytest.mark.asyncio -async def test_list_session_entity_types_async_pages(): - client = SessionEntityTypesAsyncClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_session_entity_types), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - session_entity_type.ListSessionEntityTypesResponse( - session_entity_types=[ - session_entity_type.SessionEntityType(), - session_entity_type.SessionEntityType(), - session_entity_type.SessionEntityType(), - ], - next_page_token='abc', - ), - session_entity_type.ListSessionEntityTypesResponse( - session_entity_types=[], - next_page_token='def', - ), - session_entity_type.ListSessionEntityTypesResponse( - session_entity_types=[ - session_entity_type.SessionEntityType(), - ], - next_page_token='ghi', - ), - session_entity_type.ListSessionEntityTypesResponse( - session_entity_types=[ - session_entity_type.SessionEntityType(), - session_entity_type.SessionEntityType(), - ], - ), - RuntimeError, - ) - pages = [] - async for page_ in (await client.list_session_entity_types(request={})).pages: # pragma: no branch - pages.append(page_) - for page_, token in zip(pages, ['abc','def','ghi', '']): - assert page_.raw_page.next_page_token == token - -@pytest.mark.parametrize("request_type", [ - session_entity_type.GetSessionEntityTypeRequest, - dict, -]) -def test_get_session_entity_type(request_type, transport: str = 'grpc'): - client = SessionEntityTypesClient( - 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_session_entity_type), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = session_entity_type.SessionEntityType( - 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 - - -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=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_session_entity_type), - '__call__') as call: - client.get_session_entity_type() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == session_entity_type.GetSessionEntityTypeRequest() - -@pytest.mark.asyncio -async def test_get_session_entity_type_async(transport: str = 'grpc_asyncio', request_type=session_entity_type.GetSessionEntityTypeRequest): - client = SessionEntityTypesAsyncClient( - 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_session_entity_type), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(session_entity_type.SessionEntityType( - name='name_value', - 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 - - -@pytest.mark.asyncio -async def test_get_session_entity_type_async_from_dict(): - await test_get_session_entity_type_async(request_type=dict) - - -def test_get_session_entity_type_field_headers(): - 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. - with mock.patch.object( - 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. - 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_session_entity_type_field_headers_async(): - client = SessionEntityTypesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value 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. - with mock.patch.object( - type(client.transport.get_session_entity_type), - '__call__') as call: - 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. - 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_session_entity_type_flattened(): - client = SessionEntityTypesClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_session_entity_type), - '__call__') 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', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - arg = args[0].name - mock_val = 'name_value' - assert arg == mock_val - - -def test_get_session_entity_type_flattened_error(): - client = SessionEntityTypesClient( - 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_session_entity_type( - session_entity_type.GetSessionEntityTypeRequest(), - name='name_value', - ) - -@pytest.mark.asyncio -async def test_get_session_entity_type_flattened_async(): - client = SessionEntityTypesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_session_entity_type), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = session_entity_type.SessionEntityType() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(session_entity_type.SessionEntityType()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.get_session_entity_type( - 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] - arg = args[0].name - mock_val = 'name_value' - assert arg == mock_val - -@pytest.mark.asyncio -async def test_get_session_entity_type_flattened_error_async(): - client = SessionEntityTypesAsyncClient( - 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_session_entity_type( - session_entity_type.GetSessionEntityTypeRequest(), - name='name_value', - ) - - -@pytest.mark.parametrize("request_type", [ - gcd_session_entity_type.CreateSessionEntityTypeRequest, - dict, -]) -def test_create_session_entity_type(request_type, transport: str = 'grpc'): - client = SessionEntityTypesClient( - 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_session_entity_type), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcd_session_entity_type.SessionEntityType( - 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 - - -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=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_session_entity_type), - '__call__') as call: - client.create_session_entity_type() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == gcd_session_entity_type.CreateSessionEntityTypeRequest() - -@pytest.mark.asyncio -async def test_create_session_entity_type_async(transport: str = 'grpc_asyncio', request_type=gcd_session_entity_type.CreateSessionEntityTypeRequest): - client = SessionEntityTypesAsyncClient( - 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_session_entity_type), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gcd_session_entity_type.SessionEntityType( - name='name_value', - 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 - - -@pytest.mark.asyncio -async def test_create_session_entity_type_async_from_dict(): - await test_create_session_entity_type_async(request_type=dict) - - -def test_create_session_entity_type_field_headers(): - 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. - with mock.patch.object( - 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. - 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_session_entity_type_field_headers_async(): - client = SessionEntityTypesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value 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. - with mock.patch.object( - type(client.transport.create_session_entity_type), - '__call__') as call: - 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. - 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_session_entity_type_flattened(): - client = SessionEntityTypesClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_session_entity_type), - '__call__') 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( - parent='parent_value', - session_entity_type=gcd_session_entity_type.SessionEntityType(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] - arg = args[0].parent - mock_val = 'parent_value' - assert arg == mock_val - arg = args[0].session_entity_type - mock_val = gcd_session_entity_type.SessionEntityType(name='name_value') - assert arg == mock_val - - -def test_create_session_entity_type_flattened_error(): - client = SessionEntityTypesClient( - 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_session_entity_type( - gcd_session_entity_type.CreateSessionEntityTypeRequest(), - parent='parent_value', - session_entity_type=gcd_session_entity_type.SessionEntityType(name='name_value'), - ) - -@pytest.mark.asyncio -async def test_create_session_entity_type_flattened_async(): - client = SessionEntityTypesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_session_entity_type), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcd_session_entity_type.SessionEntityType() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcd_session_entity_type.SessionEntityType()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.create_session_entity_type( - parent='parent_value', - session_entity_type=gcd_session_entity_type.SessionEntityType(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] - arg = args[0].parent - mock_val = 'parent_value' - assert arg == mock_val - arg = args[0].session_entity_type - mock_val = gcd_session_entity_type.SessionEntityType(name='name_value') - assert arg == mock_val - -@pytest.mark.asyncio -async def test_create_session_entity_type_flattened_error_async(): - client = SessionEntityTypesAsyncClient( - 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_session_entity_type( - gcd_session_entity_type.CreateSessionEntityTypeRequest(), - parent='parent_value', - session_entity_type=gcd_session_entity_type.SessionEntityType(name='name_value'), - ) - - -@pytest.mark.parametrize("request_type", [ - gcd_session_entity_type.UpdateSessionEntityTypeRequest, - dict, -]) -def test_update_session_entity_type(request_type, transport: str = 'grpc'): - client = SessionEntityTypesClient( - 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_session_entity_type), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcd_session_entity_type.SessionEntityType( - 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 - - -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=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_session_entity_type), - '__call__') as call: - client.update_session_entity_type() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == gcd_session_entity_type.UpdateSessionEntityTypeRequest() - -@pytest.mark.asyncio -async def test_update_session_entity_type_async(transport: str = 'grpc_asyncio', request_type=gcd_session_entity_type.UpdateSessionEntityTypeRequest): - client = SessionEntityTypesAsyncClient( - 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_session_entity_type), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gcd_session_entity_type.SessionEntityType( - name='name_value', - 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 - - -@pytest.mark.asyncio -async def test_update_session_entity_type_async_from_dict(): - await test_update_session_entity_type_async(request_type=dict) - - -def test_update_session_entity_type_field_headers(): - 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 = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - 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. - 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', - 'session_entity_type.name=name_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_update_session_entity_type_field_headers_async(): - client = SessionEntityTypesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value 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 = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_session_entity_type), - '__call__') as call: - 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. - 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', - 'session_entity_type.name=name_value', - ) in kw['metadata'] - - -def test_update_session_entity_type_flattened(): - client = SessionEntityTypesClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_session_entity_type), - '__call__') 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_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] - arg = args[0].session_entity_type - mock_val = gcd_session_entity_type.SessionEntityType(name='name_value') - assert arg == mock_val - arg = args[0].update_mask - mock_val = field_mask_pb2.FieldMask(paths=['paths_value']) - assert arg == mock_val - - -def test_update_session_entity_type_flattened_error(): - client = SessionEntityTypesClient( - 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_session_entity_type( - gcd_session_entity_type.UpdateSessionEntityTypeRequest(), - session_entity_type=gcd_session_entity_type.SessionEntityType(name='name_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=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_session_entity_type), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcd_session_entity_type.SessionEntityType() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcd_session_entity_type.SessionEntityType()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.update_session_entity_type( - session_entity_type=gcd_session_entity_type.SessionEntityType(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] - arg = args[0].session_entity_type - mock_val = gcd_session_entity_type.SessionEntityType(name='name_value') - assert arg == mock_val - arg = args[0].update_mask - mock_val = field_mask_pb2.FieldMask(paths=['paths_value']) - assert arg == mock_val - -@pytest.mark.asyncio -async def test_update_session_entity_type_flattened_error_async(): - client = SessionEntityTypesAsyncClient( - 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_session_entity_type( - gcd_session_entity_type.UpdateSessionEntityTypeRequest(), - session_entity_type=gcd_session_entity_type.SessionEntityType(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - - -@pytest.mark.parametrize("request_type", [ - session_entity_type.DeleteSessionEntityTypeRequest, - dict, -]) -def test_delete_session_entity_type(request_type, transport: str = 'grpc'): - client = SessionEntityTypesClient( - 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_session_entity_type), - '__call__') 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. - assert response is None - - -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=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_session_entity_type), - '__call__') as call: - client.delete_session_entity_type() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == session_entity_type.DeleteSessionEntityTypeRequest() - -@pytest.mark.asyncio -async def test_delete_session_entity_type_async(transport: str = 'grpc_asyncio', request_type=session_entity_type.DeleteSessionEntityTypeRequest): - client = SessionEntityTypesAsyncClient( - 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_session_entity_type), - '__call__') 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. - assert response is None - - -@pytest.mark.asyncio -async def test_delete_session_entity_type_async_from_dict(): - await test_delete_session_entity_type_async(request_type=dict) - - -def test_delete_session_entity_type_field_headers(): - 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. - with mock.patch.object( - 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. - 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_session_entity_type_field_headers_async(): - client = SessionEntityTypesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value 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. - with mock.patch.object( - 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. - 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_session_entity_type_flattened(): - client = SessionEntityTypesClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_session_entity_type), - '__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_session_entity_type( - 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] - arg = args[0].name - mock_val = 'name_value' - assert arg == mock_val - - -def test_delete_session_entity_type_flattened_error(): - client = SessionEntityTypesClient( - 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_session_entity_type( - session_entity_type.DeleteSessionEntityTypeRequest(), - name='name_value', - ) - -@pytest.mark.asyncio -async def test_delete_session_entity_type_flattened_async(): - client = SessionEntityTypesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_session_entity_type), - '__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_session_entity_type( - 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] - arg = args[0].name - mock_val = 'name_value' - assert arg == mock_val - -@pytest.mark.asyncio -async def test_delete_session_entity_type_flattened_error_async(): - client = SessionEntityTypesAsyncClient( - 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_session_entity_type( - session_entity_type.DeleteSessionEntityTypeRequest(), - name='name_value', - ) - - -@pytest.mark.parametrize("request_type", [ - session_entity_type.ListSessionEntityTypesRequest, - dict, -]) -def test_list_session_entity_types_rest(request_type): - client = SessionEntityTypesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1/agent/sessions/sample2'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = session_entity_type.ListSessionEntityTypesResponse( - next_page_token='next_page_token_value', - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - pb_return_value = session_entity_type.ListSessionEntityTypesResponse.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.list_session_entity_types(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListSessionEntityTypesPager) - assert response.next_page_token == 'next_page_token_value' - - -def test_list_session_entity_types_rest_required_fields(request_type=session_entity_type.ListSessionEntityTypesRequest): - transport_class = transports.SessionEntityTypesRestTransport - - request_init = {} - request_init["parent"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - including_default_value_fields=False, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).list_session_entity_types._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["parent"] = 'parent_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).list_session_entity_types._get_unset_required_fields(jsonified_request) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("page_size", "page_token", )) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "parent" in jsonified_request - assert jsonified_request["parent"] == 'parent_value' - - client = SessionEntityTypesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = session_entity_type.ListSessionEntityTypesResponse() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "get", - 'query_params': pb_request, - } - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - - pb_return_value = session_entity_type.ListSessionEntityTypesResponse.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.list_session_entity_types(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_list_session_entity_types_rest_unset_required_fields(): - transport = transports.SessionEntityTypesRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.list_session_entity_types._get_unset_required_fields({}) - assert set(unset_fields) == (set(("pageSize", "pageToken", )) & set(("parent", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_list_session_entity_types_rest_interceptors(null_interceptor): - transport = transports.SessionEntityTypesRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.SessionEntityTypesRestInterceptor(), - ) - client = SessionEntityTypesClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.SessionEntityTypesRestInterceptor, "post_list_session_entity_types") as post, \ - mock.patch.object(transports.SessionEntityTypesRestInterceptor, "pre_list_session_entity_types") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = session_entity_type.ListSessionEntityTypesRequest.pb(session_entity_type.ListSessionEntityTypesRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = session_entity_type.ListSessionEntityTypesResponse.to_json(session_entity_type.ListSessionEntityTypesResponse()) - - request = session_entity_type.ListSessionEntityTypesRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = session_entity_type.ListSessionEntityTypesResponse() - - client.list_session_entity_types(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_list_session_entity_types_rest_bad_request(transport: str = 'rest', request_type=session_entity_type.ListSessionEntityTypesRequest): - client = SessionEntityTypesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1/agent/sessions/sample2'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.list_session_entity_types(request) - - -def test_list_session_entity_types_rest_flattened(): - client = SessionEntityTypesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = session_entity_type.ListSessionEntityTypesResponse() - - # get arguments that satisfy an http rule for this method - sample_request = {'parent': 'projects/sample1/agent/sessions/sample2'} - - # get truthy value for each flattened field - mock_args = dict( - parent='parent_value', - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - pb_return_value = session_entity_type.ListSessionEntityTypesResponse.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.list_session_entity_types(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v2/{parent=projects/*/agent/sessions/*}/entityTypes" % client.transport._host, args[1]) - - -def test_list_session_entity_types_rest_flattened_error(transport: str = 'rest'): - client = SessionEntityTypesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.list_session_entity_types( - session_entity_type.ListSessionEntityTypesRequest(), - parent='parent_value', - ) - - -def test_list_session_entity_types_rest_pager(transport: str = 'rest'): - client = SessionEntityTypesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # TODO(kbandes): remove this mock unless there's a good reason for it. - #with mock.patch.object(path_template, 'transcode') as transcode: - # Set the response as a series of pages - response = ( - session_entity_type.ListSessionEntityTypesResponse( - session_entity_types=[ - session_entity_type.SessionEntityType(), - session_entity_type.SessionEntityType(), - session_entity_type.SessionEntityType(), - ], - next_page_token='abc', - ), - session_entity_type.ListSessionEntityTypesResponse( - session_entity_types=[], - next_page_token='def', - ), - session_entity_type.ListSessionEntityTypesResponse( - session_entity_types=[ - session_entity_type.SessionEntityType(), - ], - next_page_token='ghi', - ), - session_entity_type.ListSessionEntityTypesResponse( - session_entity_types=[ - session_entity_type.SessionEntityType(), - session_entity_type.SessionEntityType(), - ], - ), - ) - # Two responses for two calls - response = response + response - - # Wrap the values into proper Response objs - response = tuple(session_entity_type.ListSessionEntityTypesResponse.to_json(x) for x in response) - return_values = tuple(Response() for i in response) - for return_val, response_val in zip(return_values, response): - return_val._content = response_val.encode('UTF-8') - return_val.status_code = 200 - req.side_effect = return_values - - sample_request = {'parent': 'projects/sample1/agent/sessions/sample2'} - - pager = client.list_session_entity_types(request=sample_request) - - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, session_entity_type.SessionEntityType) - for i in results) - - pages = list(client.list_session_entity_types(request=sample_request).pages) - for page_, token in zip(pages, ['abc','def','ghi', '']): - assert page_.raw_page.next_page_token == token - - -@pytest.mark.parametrize("request_type", [ - session_entity_type.GetSessionEntityTypeRequest, - dict, -]) -def test_get_session_entity_type_rest(request_type): - client = SessionEntityTypesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/agent/sessions/sample2/entityTypes/sample3'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = session_entity_type.SessionEntityType( - name='name_value', - entity_override_mode=session_entity_type.SessionEntityType.EntityOverrideMode.ENTITY_OVERRIDE_MODE_OVERRIDE, - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - pb_return_value = session_entity_type.SessionEntityType.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.get_session_entity_type(request) - - # 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 - - -def test_get_session_entity_type_rest_required_fields(request_type=session_entity_type.GetSessionEntityTypeRequest): - transport_class = transports.SessionEntityTypesRestTransport - - request_init = {} - request_init["name"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - including_default_value_fields=False, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_session_entity_type._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["name"] = 'name_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_session_entity_type._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "name" in jsonified_request - assert jsonified_request["name"] == 'name_value' - - client = SessionEntityTypesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = session_entity_type.SessionEntityType() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "get", - 'query_params': pb_request, - } - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - - pb_return_value = session_entity_type.SessionEntityType.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.get_session_entity_type(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_get_session_entity_type_rest_unset_required_fields(): - transport = transports.SessionEntityTypesRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.get_session_entity_type._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_get_session_entity_type_rest_interceptors(null_interceptor): - transport = transports.SessionEntityTypesRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.SessionEntityTypesRestInterceptor(), - ) - client = SessionEntityTypesClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.SessionEntityTypesRestInterceptor, "post_get_session_entity_type") as post, \ - mock.patch.object(transports.SessionEntityTypesRestInterceptor, "pre_get_session_entity_type") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = session_entity_type.GetSessionEntityTypeRequest.pb(session_entity_type.GetSessionEntityTypeRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = session_entity_type.SessionEntityType.to_json(session_entity_type.SessionEntityType()) - - request = session_entity_type.GetSessionEntityTypeRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = session_entity_type.SessionEntityType() - - client.get_session_entity_type(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_get_session_entity_type_rest_bad_request(transport: str = 'rest', request_type=session_entity_type.GetSessionEntityTypeRequest): - client = SessionEntityTypesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/agent/sessions/sample2/entityTypes/sample3'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.get_session_entity_type(request) - - -def test_get_session_entity_type_rest_flattened(): - client = SessionEntityTypesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = session_entity_type.SessionEntityType() - - # get arguments that satisfy an http rule for this method - sample_request = {'name': 'projects/sample1/agent/sessions/sample2/entityTypes/sample3'} - - # get truthy value for each flattened field - mock_args = dict( - name='name_value', - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - pb_return_value = session_entity_type.SessionEntityType.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.get_session_entity_type(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v2/{name=projects/*/agent/sessions/*/entityTypes/*}" % client.transport._host, args[1]) - - -def test_get_session_entity_type_rest_flattened_error(transport: str = 'rest'): - client = SessionEntityTypesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.get_session_entity_type( - session_entity_type.GetSessionEntityTypeRequest(), - name='name_value', - ) - - -def test_get_session_entity_type_rest_error(): - client = SessionEntityTypesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - gcd_session_entity_type.CreateSessionEntityTypeRequest, - dict, -]) -def test_create_session_entity_type_rest(request_type): - client = SessionEntityTypesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1/agent/sessions/sample2'} - request_init["session_entity_type"] = {'name': 'name_value', 'entity_override_mode': 1, 'entities': [{'value': 'value_value', 'synonyms': ['synonyms_value1', 'synonyms_value2']}]} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = gcd_session_entity_type.SessionEntityType( - name='name_value', - entity_override_mode=gcd_session_entity_type.SessionEntityType.EntityOverrideMode.ENTITY_OVERRIDE_MODE_OVERRIDE, - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - pb_return_value = gcd_session_entity_type.SessionEntityType.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.create_session_entity_type(request) - - # 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 - - -def test_create_session_entity_type_rest_required_fields(request_type=gcd_session_entity_type.CreateSessionEntityTypeRequest): - transport_class = transports.SessionEntityTypesRestTransport - - request_init = {} - request_init["parent"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - including_default_value_fields=False, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_session_entity_type._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["parent"] = 'parent_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_session_entity_type._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "parent" in jsonified_request - assert jsonified_request["parent"] == 'parent_value' - - client = SessionEntityTypesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = gcd_session_entity_type.SessionEntityType() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "post", - 'query_params': pb_request, - } - transcode_result['body'] = pb_request - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - - pb_return_value = gcd_session_entity_type.SessionEntityType.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.create_session_entity_type(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_create_session_entity_type_rest_unset_required_fields(): - transport = transports.SessionEntityTypesRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.create_session_entity_type._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("parent", "sessionEntityType", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_create_session_entity_type_rest_interceptors(null_interceptor): - transport = transports.SessionEntityTypesRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.SessionEntityTypesRestInterceptor(), - ) - client = SessionEntityTypesClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.SessionEntityTypesRestInterceptor, "post_create_session_entity_type") as post, \ - mock.patch.object(transports.SessionEntityTypesRestInterceptor, "pre_create_session_entity_type") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = gcd_session_entity_type.CreateSessionEntityTypeRequest.pb(gcd_session_entity_type.CreateSessionEntityTypeRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = gcd_session_entity_type.SessionEntityType.to_json(gcd_session_entity_type.SessionEntityType()) - - request = gcd_session_entity_type.CreateSessionEntityTypeRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = gcd_session_entity_type.SessionEntityType() - - client.create_session_entity_type(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_create_session_entity_type_rest_bad_request(transport: str = 'rest', request_type=gcd_session_entity_type.CreateSessionEntityTypeRequest): - client = SessionEntityTypesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1/agent/sessions/sample2'} - request_init["session_entity_type"] = {'name': 'name_value', 'entity_override_mode': 1, 'entities': [{'value': 'value_value', 'synonyms': ['synonyms_value1', 'synonyms_value2']}]} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.create_session_entity_type(request) - - -def test_create_session_entity_type_rest_flattened(): - client = SessionEntityTypesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = gcd_session_entity_type.SessionEntityType() - - # get arguments that satisfy an http rule for this method - sample_request = {'parent': 'projects/sample1/agent/sessions/sample2'} - - # get truthy value for each flattened field - mock_args = dict( - parent='parent_value', - session_entity_type=gcd_session_entity_type.SessionEntityType(name='name_value'), - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - pb_return_value = gcd_session_entity_type.SessionEntityType.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.create_session_entity_type(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v2/{parent=projects/*/agent/sessions/*}/entityTypes" % client.transport._host, args[1]) - - -def test_create_session_entity_type_rest_flattened_error(transport: str = 'rest'): - client = SessionEntityTypesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.create_session_entity_type( - gcd_session_entity_type.CreateSessionEntityTypeRequest(), - parent='parent_value', - session_entity_type=gcd_session_entity_type.SessionEntityType(name='name_value'), - ) - - -def test_create_session_entity_type_rest_error(): - client = SessionEntityTypesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - gcd_session_entity_type.UpdateSessionEntityTypeRequest, - dict, -]) -def test_update_session_entity_type_rest(request_type): - client = SessionEntityTypesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'session_entity_type': {'name': 'projects/sample1/agent/sessions/sample2/entityTypes/sample3'}} - request_init["session_entity_type"] = {'name': 'projects/sample1/agent/sessions/sample2/entityTypes/sample3', 'entity_override_mode': 1, 'entities': [{'value': 'value_value', 'synonyms': ['synonyms_value1', 'synonyms_value2']}]} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = gcd_session_entity_type.SessionEntityType( - name='name_value', - entity_override_mode=gcd_session_entity_type.SessionEntityType.EntityOverrideMode.ENTITY_OVERRIDE_MODE_OVERRIDE, - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - pb_return_value = gcd_session_entity_type.SessionEntityType.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.update_session_entity_type(request) - - # 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 - - -def test_update_session_entity_type_rest_required_fields(request_type=gcd_session_entity_type.UpdateSessionEntityTypeRequest): - transport_class = transports.SessionEntityTypesRestTransport - - request_init = {} - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - including_default_value_fields=False, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).update_session_entity_type._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).update_session_entity_type._get_unset_required_fields(jsonified_request) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("update_mask", )) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - - client = SessionEntityTypesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = gcd_session_entity_type.SessionEntityType() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "patch", - 'query_params': pb_request, - } - transcode_result['body'] = pb_request - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - - pb_return_value = gcd_session_entity_type.SessionEntityType.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.update_session_entity_type(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_update_session_entity_type_rest_unset_required_fields(): - transport = transports.SessionEntityTypesRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.update_session_entity_type._get_unset_required_fields({}) - assert set(unset_fields) == (set(("updateMask", )) & set(("sessionEntityType", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_update_session_entity_type_rest_interceptors(null_interceptor): - transport = transports.SessionEntityTypesRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.SessionEntityTypesRestInterceptor(), - ) - client = SessionEntityTypesClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.SessionEntityTypesRestInterceptor, "post_update_session_entity_type") as post, \ - mock.patch.object(transports.SessionEntityTypesRestInterceptor, "pre_update_session_entity_type") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = gcd_session_entity_type.UpdateSessionEntityTypeRequest.pb(gcd_session_entity_type.UpdateSessionEntityTypeRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = gcd_session_entity_type.SessionEntityType.to_json(gcd_session_entity_type.SessionEntityType()) - - request = gcd_session_entity_type.UpdateSessionEntityTypeRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = gcd_session_entity_type.SessionEntityType() - - client.update_session_entity_type(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_update_session_entity_type_rest_bad_request(transport: str = 'rest', request_type=gcd_session_entity_type.UpdateSessionEntityTypeRequest): - client = SessionEntityTypesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'session_entity_type': {'name': 'projects/sample1/agent/sessions/sample2/entityTypes/sample3'}} - request_init["session_entity_type"] = {'name': 'projects/sample1/agent/sessions/sample2/entityTypes/sample3', 'entity_override_mode': 1, 'entities': [{'value': 'value_value', 'synonyms': ['synonyms_value1', 'synonyms_value2']}]} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.update_session_entity_type(request) - - -def test_update_session_entity_type_rest_flattened(): - client = SessionEntityTypesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = gcd_session_entity_type.SessionEntityType() - - # get arguments that satisfy an http rule for this method - sample_request = {'session_entity_type': {'name': 'projects/sample1/agent/sessions/sample2/entityTypes/sample3'}} - - # get truthy value for each flattened field - mock_args = dict( - session_entity_type=gcd_session_entity_type.SessionEntityType(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - pb_return_value = gcd_session_entity_type.SessionEntityType.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.update_session_entity_type(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v2/{session_entity_type.name=projects/*/agent/sessions/*/entityTypes/*}" % client.transport._host, args[1]) - - -def test_update_session_entity_type_rest_flattened_error(transport: str = 'rest'): - client = SessionEntityTypesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.update_session_entity_type( - gcd_session_entity_type.UpdateSessionEntityTypeRequest(), - session_entity_type=gcd_session_entity_type.SessionEntityType(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - - -def test_update_session_entity_type_rest_error(): - client = SessionEntityTypesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - session_entity_type.DeleteSessionEntityTypeRequest, - dict, -]) -def test_delete_session_entity_type_rest(request_type): - client = SessionEntityTypesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/agent/sessions/sample2/entityTypes/sample3'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = None - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = '' - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.delete_session_entity_type(request) - - # Establish that the response is the type that we expect. - assert response is None - - -def test_delete_session_entity_type_rest_required_fields(request_type=session_entity_type.DeleteSessionEntityTypeRequest): - transport_class = transports.SessionEntityTypesRestTransport - - request_init = {} - request_init["name"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - including_default_value_fields=False, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).delete_session_entity_type._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["name"] = 'name_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).delete_session_entity_type._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "name" in jsonified_request - assert jsonified_request["name"] == 'name_value' - - client = SessionEntityTypesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = None - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "delete", - 'query_params': pb_request, - } - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - json_return_value = '' - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.delete_session_entity_type(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_delete_session_entity_type_rest_unset_required_fields(): - transport = transports.SessionEntityTypesRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.delete_session_entity_type._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_delete_session_entity_type_rest_interceptors(null_interceptor): - transport = transports.SessionEntityTypesRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.SessionEntityTypesRestInterceptor(), - ) - client = SessionEntityTypesClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.SessionEntityTypesRestInterceptor, "pre_delete_session_entity_type") as pre: - pre.assert_not_called() - pb_message = session_entity_type.DeleteSessionEntityTypeRequest.pb(session_entity_type.DeleteSessionEntityTypeRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - - request = session_entity_type.DeleteSessionEntityTypeRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - - client.delete_session_entity_type(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - - -def test_delete_session_entity_type_rest_bad_request(transport: str = 'rest', request_type=session_entity_type.DeleteSessionEntityTypeRequest): - client = SessionEntityTypesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/agent/sessions/sample2/entityTypes/sample3'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.delete_session_entity_type(request) - - -def test_delete_session_entity_type_rest_flattened(): - client = SessionEntityTypesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = None - - # get arguments that satisfy an http rule for this method - sample_request = {'name': 'projects/sample1/agent/sessions/sample2/entityTypes/sample3'} - - # get truthy value for each flattened field - mock_args = dict( - name='name_value', - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = '' - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.delete_session_entity_type(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v2/{name=projects/*/agent/sessions/*/entityTypes/*}" % client.transport._host, args[1]) - - -def test_delete_session_entity_type_rest_flattened_error(transport: str = 'rest'): - client = SessionEntityTypesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.delete_session_entity_type( - session_entity_type.DeleteSessionEntityTypeRequest(), - name='name_value', - ) - - -def test_delete_session_entity_type_rest_error(): - client = SessionEntityTypesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -def test_credentials_transport_error(): - # It is an error to provide credentials and a transport instance. - transport = transports.SessionEntityTypesGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = SessionEntityTypesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # It is an error to provide a credentials file and a transport instance. - transport = transports.SessionEntityTypesGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = SessionEntityTypesClient( - client_options={"credentials_file": "credentials.json"}, - transport=transport, - ) - - # It is an error to provide an api_key and a transport instance. - transport = transports.SessionEntityTypesGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - options = client_options.ClientOptions() - options.api_key = "api_key" - with pytest.raises(ValueError): - client = SessionEntityTypesClient( - client_options=options, - transport=transport, - ) - - # It is an error to provide an api_key and a credential. - options = mock.Mock() - options.api_key = "api_key" - with pytest.raises(ValueError): - client = SessionEntityTypesClient( - client_options=options, - credentials=ga_credentials.AnonymousCredentials() - ) - - # It is an error to provide scopes and a transport instance. - transport = transports.SessionEntityTypesGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = SessionEntityTypesClient( - client_options={"scopes": ["1", "2"]}, - transport=transport, - ) - - -def test_transport_instance(): - # A client may be instantiated with a custom transport instance. - transport = transports.SessionEntityTypesGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - client = SessionEntityTypesClient(transport=transport) - assert client.transport is transport - -def test_transport_get_channel(): - # A client may be instantiated with a custom transport instance. - transport = transports.SessionEntityTypesGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - - transport = transports.SessionEntityTypesGrpcAsyncIOTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - -@pytest.mark.parametrize("transport_class", [ - transports.SessionEntityTypesGrpcTransport, - transports.SessionEntityTypesGrpcAsyncIOTransport, - transports.SessionEntityTypesRestTransport, -]) -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() - -@pytest.mark.parametrize("transport_name", [ - "grpc", - "rest", -]) -def test_transport_kind(transport_name): - transport = SessionEntityTypesClient.get_transport_class(transport_name)( - credentials=ga_credentials.AnonymousCredentials(), - ) - assert transport.kind == transport_name - -def test_transport_grpc_default(): - # A client should use the gRPC transport by default. - 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(core_exceptions.DuplicateCredentialArgs): - transport = transports.SessionEntityTypesTransport( - credentials=ga_credentials.AnonymousCredentials(), - credentials_file="credentials.json" - ) - - -def test_session_entity_types_base_transport(): - # Instantiate the base transport. - with mock.patch('google.cloud.dialogflow_v2.services.session_entity_types.transports.SessionEntityTypesTransport.__init__') as Transport: - Transport.return_value = None - transport = transports.SessionEntityTypesTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Every method on the transport should just blindly - # raise NotImplementedError. - methods = ( - 'list_session_entity_types', - 'get_session_entity_type', - 'create_session_entity_type', - 'update_session_entity_type', - 'delete_session_entity_type', - 'get_location', - 'list_locations', - 'get_operation', - 'cancel_operation', - 'list_operations', - ) - for method in methods: - with pytest.raises(NotImplementedError): - getattr(transport, method)(request=object()) - - with pytest.raises(NotImplementedError): - transport.close() - - # Catch all for all remaining methods and properties - remainder = [ - 'kind', - ] - for r in remainder: - with pytest.raises(NotImplementedError): - getattr(transport, r)() - - -def test_session_entity_types_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.session_entity_types.transports.SessionEntityTypesTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.SessionEntityTypesTransport( - credentials_file="credentials.json", - quota_project_id="octopus", - ) - load_creds.assert_called_once_with("credentials.json", - scopes=None, - default_scopes=( - 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/dialogflow', -), - quota_project_id="octopus", - ) - - -def test_session_entity_types_base_transport_with_adc(): - # Test the default credentials are used if credentials and credentials_file are None. - with mock.patch.object(google.auth, 'default', autospec=True) as adc, mock.patch('google.cloud.dialogflow_v2.services.session_entity_types.transports.SessionEntityTypesTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.SessionEntityTypesTransport() - adc.assert_called_once() - - -def test_session_entity_types_auth_adc(): - # If no credentials are provided, we should use ADC credentials. - with mock.patch.object(google.auth, 'default', autospec=True) as adc: - 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, - ) - - -@pytest.mark.parametrize( - "transport_class", - [ - transports.SessionEntityTypesGrpcTransport, - transports.SessionEntityTypesGrpcAsyncIOTransport, - ], -) -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(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, - transports.SessionEntityTypesRestTransport, - ], -) -def test_session_entity_types_transport_auth_gdch_credentials(transport_class): - host = 'https://language.com' - api_audience_tests = [None, 'https://language2.com'] - api_audience_expect = [host, 'https://language2.com'] - for t, e in zip(api_audience_tests, api_audience_expect): - with mock.patch.object(google.auth, 'default', autospec=True) as adc: - gdch_mock = mock.MagicMock() - type(gdch_mock).with_gdch_audience = mock.PropertyMock(return_value=gdch_mock) - adc.return_value = (gdch_mock, None) - transport_class(host=host, api_audience=t) - gdch_mock.with_gdch_audience.assert_called_once_with( - e - ) - - -@pytest.mark.parametrize( - "transport_class,grpc_helpers", - [ - (transports.SessionEntityTypesGrpcTransport, grpc_helpers), - (transports.SessionEntityTypesGrpcAsyncIOTransport, grpc_helpers_async) - ], -) -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", [transports.SessionEntityTypesGrpcTransport, transports.SessionEntityTypesGrpcAsyncIOTransport]) -def test_session_entity_types_grpc_transport_client_cert_source_for_mtls( - transport_class -): - cred = ga_credentials.AnonymousCredentials() - - # Check ssl_channel_credentials is used if provided. - with mock.patch.object(transport_class, "create_channel") as mock_create_channel: - mock_ssl_channel_creds = mock.Mock() - transport_class( - host="squid.clam.whelk", - credentials=cred, - ssl_channel_credentials=mock_ssl_channel_creds - ) - mock_create_channel.assert_called_once_with( - "squid.clam.whelk:443", - credentials=cred, - credentials_file=None, - scopes=None, - ssl_credentials=mock_ssl_channel_creds, - quota_project_id=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - # Check if ssl_channel_credentials is not provided, then client_cert_source_for_mtls - # is used. - with mock.patch.object(transport_class, "create_channel", return_value=mock.Mock()): - with mock.patch("grpc.ssl_channel_credentials") as mock_ssl_cred: - transport_class( - credentials=cred, - client_cert_source_for_mtls=client_cert_source_callback - ) - expected_cert, expected_key = client_cert_source_callback() - mock_ssl_cred.assert_called_once_with( - certificate_chain=expected_cert, - private_key=expected_key - ) - -def test_session_entity_types_http_transport_client_cert_source_for_mtls(): - cred = ga_credentials.AnonymousCredentials() - with mock.patch("google.auth.transport.requests.AuthorizedSession.configure_mtls_channel") as mock_configure_mtls_channel: - transports.SessionEntityTypesRestTransport ( - credentials=cred, - client_cert_source_for_mtls=client_cert_source_callback - ) - mock_configure_mtls_channel.assert_called_once_with(client_cert_source_callback) - - -@pytest.mark.parametrize("transport_name", [ - "grpc", - "grpc_asyncio", - "rest", -]) -def test_session_entity_types_host_no_port(transport_name): - client = SessionEntityTypesClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='dialogflow.googleapis.com'), - transport=transport_name, - ) - assert client.transport._host == ( - 'dialogflow.googleapis.com:443' - if transport_name in ['grpc', 'grpc_asyncio'] - else 'https://dialogflow.googleapis.com' - ) - -@pytest.mark.parametrize("transport_name", [ - "grpc", - "grpc_asyncio", - "rest", -]) -def test_session_entity_types_host_with_port(transport_name): - client = SessionEntityTypesClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='dialogflow.googleapis.com:8000'), - transport=transport_name, - ) - assert client.transport._host == ( - 'dialogflow.googleapis.com:8000' - if transport_name in ['grpc', 'grpc_asyncio'] - else 'https://dialogflow.googleapis.com:8000' - ) - -@pytest.mark.parametrize("transport_name", [ - "rest", -]) -def test_session_entity_types_client_transport_session_collision(transport_name): - creds1 = ga_credentials.AnonymousCredentials() - creds2 = ga_credentials.AnonymousCredentials() - client1 = SessionEntityTypesClient( - credentials=creds1, - transport=transport_name, - ) - client2 = SessionEntityTypesClient( - credentials=creds2, - transport=transport_name, - ) - session1 = client1.transport.list_session_entity_types._session - session2 = client2.transport.list_session_entity_types._session - assert session1 != session2 - session1 = client1.transport.get_session_entity_type._session - session2 = client2.transport.get_session_entity_type._session - assert session1 != session2 - session1 = client1.transport.create_session_entity_type._session - session2 = client2.transport.create_session_entity_type._session - assert session1 != session2 - session1 = client1.transport.update_session_entity_type._session - session2 = client2.transport.update_session_entity_type._session - assert session1 != session2 - session1 = client1.transport.delete_session_entity_type._session - session2 = client2.transport.delete_session_entity_type._session - assert session1 != session2 -def test_session_entity_types_grpc_transport_channel(): - channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.SessionEntityTypesGrpcTransport( - 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_session_entity_types_grpc_asyncio_transport_channel(): - channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.SessionEntityTypesGrpcAsyncIOTransport( - 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.SessionEntityTypesGrpcTransport, transports.SessionEntityTypesGrpcAsyncIOTransport]) -def test_session_entity_types_transport_channel_mtls_with_client_cert_source( - transport_class -): - with mock.patch("grpc.ssl_channel_credentials", autospec=True) as grpc_ssl_channel_cred: - with mock.patch.object(transport_class, "create_channel") as grpc_create_channel: - mock_ssl_cred = mock.Mock() - grpc_ssl_channel_cred.return_value = mock_ssl_cred - - mock_grpc_channel = mock.Mock() - grpc_create_channel.return_value = mock_grpc_channel - - cred = ga_credentials.AnonymousCredentials() - with pytest.warns(DeprecationWarning): - with mock.patch.object(google.auth, 'default') as adc: - adc.return_value = (cred, None) - transport = transport_class( - host="squid.clam.whelk", - api_mtls_endpoint="mtls.squid.clam.whelk", - client_cert_source=client_cert_source_callback, - ) - adc.assert_called_once() - - grpc_ssl_channel_cred.assert_called_once_with( - certificate_chain=b"cert bytes", private_key=b"key bytes" - ) - grpc_create_channel.assert_called_once_with( - "mtls.squid.clam.whelk:443", - credentials=cred, - credentials_file=None, - scopes=None, - ssl_credentials=mock_ssl_cred, - quota_project_id=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - assert transport.grpc_channel == mock_grpc_channel - assert transport._ssl_channel_credentials == mock_ssl_cred - - -# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are -# removed from grpc/grpc_asyncio transport constructor. -@pytest.mark.parametrize("transport_class", [transports.SessionEntityTypesGrpcTransport, transports.SessionEntityTypesGrpcAsyncIOTransport]) -def test_session_entity_types_transport_channel_mtls_with_adc( - transport_class -): - mock_ssl_cred = mock.Mock() - with mock.patch.multiple( - "google.auth.transport.grpc.SslCredentials", - __init__=mock.Mock(return_value=None), - ssl_credentials=mock.PropertyMock(return_value=mock_ssl_cred), - ): - with mock.patch.object(transport_class, "create_channel") as grpc_create_channel: - mock_grpc_channel = mock.Mock() - grpc_create_channel.return_value = mock_grpc_channel - mock_cred = mock.Mock() - - with pytest.warns(DeprecationWarning): - transport = transport_class( - host="squid.clam.whelk", - credentials=mock_cred, - api_mtls_endpoint="mtls.squid.clam.whelk", - client_cert_source=None, - ) - - grpc_create_channel.assert_called_once_with( - "mtls.squid.clam.whelk:443", - credentials=mock_cred, - credentials_file=None, - scopes=None, - ssl_credentials=mock_ssl_cred, - quota_project_id=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - assert transport.grpc_channel == mock_grpc_channel - - -def test_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, ) - actual = SessionEntityTypesClient.session_entity_type_path(project, session, entity_type) - assert expected == actual - - -def test_parse_session_entity_type_path(): - expected = { - "project": "octopus", - "session": "oyster", - "entity_type": "nudibranch", - } - path = SessionEntityTypesClient.session_entity_type_path(**expected) - - # Check that the path construction is reversible. - actual = SessionEntityTypesClient.parse_session_entity_type_path(path) - assert expected == actual - -def test_common_billing_account_path(): - billing_account = "cuttlefish" - expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) - actual = SessionEntityTypesClient.common_billing_account_path(billing_account) - assert expected == actual - - -def test_parse_common_billing_account_path(): - expected = { - "billing_account": "mussel", - } - path = SessionEntityTypesClient.common_billing_account_path(**expected) - - # Check that the path construction is reversible. - actual = SessionEntityTypesClient.parse_common_billing_account_path(path) - assert expected == actual - -def test_common_folder_path(): - folder = "winkle" - expected = "folders/{folder}".format(folder=folder, ) - actual = SessionEntityTypesClient.common_folder_path(folder) - assert expected == actual - - -def test_parse_common_folder_path(): - expected = { - "folder": "nautilus", - } - path = SessionEntityTypesClient.common_folder_path(**expected) - - # Check that the path construction is reversible. - actual = SessionEntityTypesClient.parse_common_folder_path(path) - assert expected == actual - -def test_common_organization_path(): - organization = "scallop" - expected = "organizations/{organization}".format(organization=organization, ) - actual = SessionEntityTypesClient.common_organization_path(organization) - assert expected == actual - - -def test_parse_common_organization_path(): - expected = { - "organization": "abalone", - } - path = SessionEntityTypesClient.common_organization_path(**expected) - - # Check that the path construction is reversible. - actual = SessionEntityTypesClient.parse_common_organization_path(path) - assert expected == actual - -def test_common_project_path(): - project = "squid" - expected = "projects/{project}".format(project=project, ) - actual = SessionEntityTypesClient.common_project_path(project) - assert expected == actual - - -def test_parse_common_project_path(): - expected = { - "project": "clam", - } - path = SessionEntityTypesClient.common_project_path(**expected) - - # Check that the path construction is reversible. - actual = SessionEntityTypesClient.parse_common_project_path(path) - assert expected == actual - -def test_common_location_path(): - project = "whelk" - location = "octopus" - expected = "projects/{project}/locations/{location}".format(project=project, location=location, ) - actual = SessionEntityTypesClient.common_location_path(project, location) - assert expected == actual - - -def test_parse_common_location_path(): - expected = { - "project": "oyster", - "location": "nudibranch", - } - path = SessionEntityTypesClient.common_location_path(**expected) - - # Check that the path construction is reversible. - actual = SessionEntityTypesClient.parse_common_location_path(path) - assert expected == actual - - -def test_client_with_default_client_info(): - client_info = gapic_v1.client_info.ClientInfo() - - with mock.patch.object(transports.SessionEntityTypesTransport, '_prep_wrapped_messages') as prep: - client = SessionEntityTypesClient( - credentials=ga_credentials.AnonymousCredentials(), - client_info=client_info, - ) - prep.assert_called_once_with(client_info) - - with mock.patch.object(transports.SessionEntityTypesTransport, '_prep_wrapped_messages') as prep: - transport_class = SessionEntityTypesClient.get_transport_class() - transport = transport_class( - credentials=ga_credentials.AnonymousCredentials(), - client_info=client_info, - ) - prep.assert_called_once_with(client_info) - -@pytest.mark.asyncio -async def test_transport_close_async(): - client = SessionEntityTypesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - with mock.patch.object(type(getattr(client.transport, "grpc_channel")), "close") as close: - async with client: - close.assert_not_called() - close.assert_called_once() - - -def test_get_location_rest_bad_request(transport: str = 'rest', request_type=locations_pb2.GetLocationRequest): - client = SessionEntityTypesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - request = request_type() - request = json_format.ParseDict({'name': 'projects/sample1/locations/sample2'}, request) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.get_location(request) - -@pytest.mark.parametrize("request_type", [ - locations_pb2.GetLocationRequest, - dict, -]) -def test_get_location_rest(request_type): - client = SessionEntityTypesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request_init = {'name': 'projects/sample1/locations/sample2'} - request = request_type(**request_init) - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = locations_pb2.Location() - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.get_location(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, locations_pb2.Location) - -def test_list_locations_rest_bad_request(transport: str = 'rest', request_type=locations_pb2.ListLocationsRequest): - client = SessionEntityTypesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - request = request_type() - request = json_format.ParseDict({'name': 'projects/sample1'}, request) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.list_locations(request) - -@pytest.mark.parametrize("request_type", [ - locations_pb2.ListLocationsRequest, - dict, -]) -def test_list_locations_rest(request_type): - client = SessionEntityTypesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request_init = {'name': 'projects/sample1'} - request = request_type(**request_init) - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = locations_pb2.ListLocationsResponse() - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.list_locations(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, locations_pb2.ListLocationsResponse) - -def test_cancel_operation_rest_bad_request(transport: str = 'rest', request_type=operations_pb2.CancelOperationRequest): - client = SessionEntityTypesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - request = request_type() - request = json_format.ParseDict({'name': 'projects/sample1/operations/sample2'}, request) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.cancel_operation(request) - -@pytest.mark.parametrize("request_type", [ - operations_pb2.CancelOperationRequest, - dict, -]) -def test_cancel_operation_rest(request_type): - client = SessionEntityTypesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request_init = {'name': 'projects/sample1/operations/sample2'} - request = request_type(**request_init) - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = None - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = '{}' - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.cancel_operation(request) - - # Establish that the response is the type that we expect. - assert response is None - -def test_get_operation_rest_bad_request(transport: str = 'rest', request_type=operations_pb2.GetOperationRequest): - client = SessionEntityTypesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - request = request_type() - request = json_format.ParseDict({'name': 'projects/sample1/operations/sample2'}, request) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.get_operation(request) - -@pytest.mark.parametrize("request_type", [ - operations_pb2.GetOperationRequest, - dict, -]) -def test_get_operation_rest(request_type): - client = SessionEntityTypesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request_init = {'name': 'projects/sample1/operations/sample2'} - request = request_type(**request_init) - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation() - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.get_operation(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, operations_pb2.Operation) - -def test_list_operations_rest_bad_request(transport: str = 'rest', request_type=operations_pb2.ListOperationsRequest): - client = SessionEntityTypesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - request = request_type() - request = json_format.ParseDict({'name': 'projects/sample1'}, request) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.list_operations(request) - -@pytest.mark.parametrize("request_type", [ - operations_pb2.ListOperationsRequest, - dict, -]) -def test_list_operations_rest(request_type): - client = SessionEntityTypesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request_init = {'name': 'projects/sample1'} - request = request_type(**request_init) - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = operations_pb2.ListOperationsResponse() - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.list_operations(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, operations_pb2.ListOperationsResponse) - - -def test_cancel_operation(transport: str = "grpc"): - client = SessionEntityTypesClient( - 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 = operations_pb2.CancelOperationRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = None - response = client.cancel_operation(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 response is the type that we expect. - assert response is None -@pytest.mark.asyncio -async def test_cancel_operation_async(transport: str = "grpc"): - client = SessionEntityTypesAsyncClient( - 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 = operations_pb2.CancelOperationRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - None - ) - response = await client.cancel_operation(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 response is the type that we expect. - assert response is None - -def test_cancel_operation_field_headers(): - 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 = operations_pb2.CancelOperationRequest() - request.name = "locations" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call: - call.return_value = None - - client.cancel_operation(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=locations",) in kw["metadata"] -@pytest.mark.asyncio -async def test_cancel_operation_field_headers_async(): - client = SessionEntityTypesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = operations_pb2.CancelOperationRequest() - request.name = "locations" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - None - ) - await client.cancel_operation(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=locations",) in kw["metadata"] - -def test_cancel_operation_from_dict(): - client = SessionEntityTypesClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = None - - response = client.cancel_operation( - request={ - "name": "locations", - } - ) - call.assert_called() -@pytest.mark.asyncio -async def test_cancel_operation_from_dict_async(): - client = SessionEntityTypesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - None - ) - response = await client.cancel_operation( - request={ - "name": "locations", - } - ) - call.assert_called() - - -def test_get_operation(transport: str = "grpc"): - client = SessionEntityTypesClient( - 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 = operations_pb2.GetOperationRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_operation), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation() - response = client.get_operation(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 response is the type that we expect. - assert isinstance(response, operations_pb2.Operation) -@pytest.mark.asyncio -async def test_get_operation_async(transport: str = "grpc"): - client = SessionEntityTypesAsyncClient( - 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 = operations_pb2.GetOperationRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_operation), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation() - ) - response = await client.get_operation(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 response is the type that we expect. - assert isinstance(response, operations_pb2.Operation) - -def test_get_operation_field_headers(): - 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 = operations_pb2.GetOperationRequest() - request.name = "locations" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_operation), "__call__") as call: - call.return_value = operations_pb2.Operation() - - client.get_operation(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=locations",) in kw["metadata"] -@pytest.mark.asyncio -async def test_get_operation_field_headers_async(): - client = SessionEntityTypesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = operations_pb2.GetOperationRequest() - request.name = "locations" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_operation), "__call__") as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation() - ) - await client.get_operation(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=locations",) in kw["metadata"] - -def test_get_operation_from_dict(): - client = SessionEntityTypesClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_operation), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation() - - response = client.get_operation( - request={ - "name": "locations", - } - ) - call.assert_called() -@pytest.mark.asyncio -async def test_get_operation_from_dict_async(): - client = SessionEntityTypesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_operation), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation() - ) - response = await client.get_operation( - request={ - "name": "locations", - } - ) - call.assert_called() - - -def test_list_operations(transport: str = "grpc"): - client = SessionEntityTypesClient( - 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 = operations_pb2.ListOperationsRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_operations), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.ListOperationsResponse() - response = client.list_operations(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 response is the type that we expect. - assert isinstance(response, operations_pb2.ListOperationsResponse) -@pytest.mark.asyncio -async def test_list_operations_async(transport: str = "grpc"): - client = SessionEntityTypesAsyncClient( - 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 = operations_pb2.ListOperationsRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_operations), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.ListOperationsResponse() - ) - response = await client.list_operations(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 response is the type that we expect. - assert isinstance(response, operations_pb2.ListOperationsResponse) - -def test_list_operations_field_headers(): - 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 = operations_pb2.ListOperationsRequest() - request.name = "locations" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_operations), "__call__") as call: - call.return_value = operations_pb2.ListOperationsResponse() - - client.list_operations(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=locations",) in kw["metadata"] -@pytest.mark.asyncio -async def test_list_operations_field_headers_async(): - client = SessionEntityTypesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = operations_pb2.ListOperationsRequest() - request.name = "locations" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_operations), "__call__") as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.ListOperationsResponse() - ) - await client.list_operations(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=locations",) in kw["metadata"] - -def test_list_operations_from_dict(): - client = SessionEntityTypesClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_operations), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.ListOperationsResponse() - - response = client.list_operations( - request={ - "name": "locations", - } - ) - call.assert_called() -@pytest.mark.asyncio -async def test_list_operations_from_dict_async(): - client = SessionEntityTypesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_operations), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.ListOperationsResponse() - ) - response = await client.list_operations( - request={ - "name": "locations", - } - ) - call.assert_called() - - -def test_list_locations(transport: str = "grpc"): - client = SessionEntityTypesClient( - 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 = locations_pb2.ListLocationsRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_locations), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = locations_pb2.ListLocationsResponse() - response = client.list_locations(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 response is the type that we expect. - assert isinstance(response, locations_pb2.ListLocationsResponse) -@pytest.mark.asyncio -async def test_list_locations_async(transport: str = "grpc"): - client = SessionEntityTypesAsyncClient( - 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 = locations_pb2.ListLocationsRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_locations), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - locations_pb2.ListLocationsResponse() - ) - response = await client.list_locations(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 response is the type that we expect. - assert isinstance(response, locations_pb2.ListLocationsResponse) - -def test_list_locations_field_headers(): - 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 = locations_pb2.ListLocationsRequest() - request.name = "locations" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_locations), "__call__") as call: - call.return_value = locations_pb2.ListLocationsResponse() - - client.list_locations(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=locations",) in kw["metadata"] -@pytest.mark.asyncio -async def test_list_locations_field_headers_async(): - client = SessionEntityTypesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = locations_pb2.ListLocationsRequest() - request.name = "locations" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_locations), "__call__") as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - locations_pb2.ListLocationsResponse() - ) - await client.list_locations(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=locations",) in kw["metadata"] - -def test_list_locations_from_dict(): - client = SessionEntityTypesClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_locations), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = locations_pb2.ListLocationsResponse() - - response = client.list_locations( - request={ - "name": "locations", - } - ) - call.assert_called() -@pytest.mark.asyncio -async def test_list_locations_from_dict_async(): - client = SessionEntityTypesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_locations), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - locations_pb2.ListLocationsResponse() - ) - response = await client.list_locations( - request={ - "name": "locations", - } - ) - call.assert_called() - - -def test_get_location(transport: str = "grpc"): - client = SessionEntityTypesClient( - 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 = locations_pb2.GetLocationRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_location), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = locations_pb2.Location() - response = client.get_location(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 response is the type that we expect. - assert isinstance(response, locations_pb2.Location) -@pytest.mark.asyncio -async def test_get_location_async(transport: str = "grpc_asyncio"): - client = SessionEntityTypesAsyncClient( - 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 = locations_pb2.GetLocationRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_location), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - locations_pb2.Location() - ) - response = await client.get_location(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 response is the type that we expect. - assert isinstance(response, locations_pb2.Location) - -def test_get_location_field_headers(): - 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 = locations_pb2.GetLocationRequest() - request.name = "locations/abc" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_location), "__call__") as call: - call.return_value = locations_pb2.Location() - - client.get_location(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=locations/abc",) in kw["metadata"] -@pytest.mark.asyncio -async def test_get_location_field_headers_async(): - client = SessionEntityTypesAsyncClient( - credentials=ga_credentials.AnonymousCredentials() - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = locations_pb2.GetLocationRequest() - request.name = "locations/abc" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_location), "__call__") as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - locations_pb2.Location() - ) - await client.get_location(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=locations/abc",) in kw["metadata"] - -def test_get_location_from_dict(): - client = SessionEntityTypesClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_locations), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = locations_pb2.Location() - - response = client.get_location( - request={ - "name": "locations/abc", - } - ) - call.assert_called() -@pytest.mark.asyncio -async def test_get_location_from_dict_async(): - client = SessionEntityTypesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_locations), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - locations_pb2.Location() - ) - response = await client.get_location( - request={ - "name": "locations", - } - ) - call.assert_called() - - -def test_transport_close(): - transports = { - "rest": "_session", - "grpc": "_grpc_channel", - } - - for transport, close_name in transports.items(): - client = SessionEntityTypesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport - ) - with mock.patch.object(type(getattr(client.transport, close_name)), "close") as close: - with client: - close.assert_not_called() - close.assert_called_once() - -def test_client_ctx(): - transports = [ - 'rest', - 'grpc', - ] - for transport in transports: - client = SessionEntityTypesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport - ) - # Test client calls underlying transport. - with mock.patch.object(type(client.transport), "close") as close: - close.assert_not_called() - with client: - pass - close.assert_called() - -@pytest.mark.parametrize("client_class,transport_class", [ - (SessionEntityTypesClient, transports.SessionEntityTypesGrpcTransport), - (SessionEntityTypesAsyncClient, transports.SessionEntityTypesGrpcAsyncIOTransport), -]) -def test_api_key_credentials(client_class, transport_class): - with mock.patch.object( - google.auth._default, "get_api_key_credentials", create=True - ) as get_api_key_credentials: - mock_cred = mock.Mock() - get_api_key_credentials.return_value = mock_cred - options = client_options.ClientOptions() - options.api_key = "api_key" - 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=mock_cred, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) diff --git a/owl-bot-staging/v2/tests/unit/gapic/dialogflow_v2/test_sessions.py b/owl-bot-staging/v2/tests/unit/gapic/dialogflow_v2/test_sessions.py deleted file mode 100644 index 89591604b..000000000 --- a/owl-bot-staging/v2/tests/unit/gapic/dialogflow_v2/test_sessions.py +++ /dev/null @@ -1,2759 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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 -# try/except added for compatibility with python < 3.8 -try: - from unittest import mock - from unittest.mock import AsyncMock # pragma: NO COVER -except ImportError: # pragma: NO COVER - import mock - -import grpc -from grpc.experimental import aio -from collections.abc import Iterable -from google.protobuf import json_format -import json -import math -import pytest -from proto.marshal.rules.dates import DurationRule, TimestampRule -from proto.marshal.rules import wrappers -from requests import Response -from requests import Request, PreparedRequest -from requests.sessions import Session -from google.protobuf import json_format - -from google.api_core import client_options -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import grpc_helpers -from google.api_core import grpc_helpers_async -from google.api_core import path_template -from google.auth import credentials as ga_credentials -from google.auth.exceptions import MutualTLSChannelError -from google.cloud.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.types import audio_config -from google.cloud.dialogflow_v2.types import context -from google.cloud.dialogflow_v2.types import entity_type -from google.cloud.dialogflow_v2.types import session -from google.cloud.dialogflow_v2.types import session as gcd_session -from google.cloud.dialogflow_v2.types import session_entity_type -from google.cloud.location import locations_pb2 -from google.longrunning import operations_pb2 -from google.oauth2 import service_account -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 - - -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 SessionsClient._get_default_mtls_endpoint(None) is None - assert SessionsClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint - assert SessionsClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint - assert SessionsClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint - assert SessionsClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint - assert SessionsClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi - - -@pytest.mark.parametrize("client_class,transport_name", [ - (SessionsClient, "grpc"), - (SessionsAsyncClient, "grpc_asyncio"), - (SessionsClient, "rest"), -]) -def test_sessions_client_from_service_account_info(client_class, transport_name): - 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, transport=transport_name) - assert client.transport._credentials == creds - assert isinstance(client, client_class) - - assert client.transport._host == ( - 'dialogflow.googleapis.com:443' - if transport_name in ['grpc', 'grpc_asyncio'] - else - 'https://dialogflow.googleapis.com' - ) - - -@pytest.mark.parametrize("transport_class,transport_name", [ - (transports.SessionsGrpcTransport, "grpc"), - (transports.SessionsGrpcAsyncIOTransport, "grpc_asyncio"), - (transports.SessionsRestTransport, "rest"), -]) -def test_sessions_client_service_account_always_use_jwt(transport_class, transport_name): - with mock.patch.object(service_account.Credentials, 'with_always_use_jwt_access', create=True) as use_jwt: - creds = service_account.Credentials(None, None, None) - transport = transport_class(credentials=creds, always_use_jwt_access=True) - use_jwt.assert_called_once_with(True) - - with mock.patch.object(service_account.Credentials, 'with_always_use_jwt_access', create=True) as use_jwt: - creds = service_account.Credentials(None, None, None) - transport = transport_class(credentials=creds, always_use_jwt_access=False) - use_jwt.assert_not_called() - - -@pytest.mark.parametrize("client_class,transport_name", [ - (SessionsClient, "grpc"), - (SessionsAsyncClient, "grpc_asyncio"), - (SessionsClient, "rest"), -]) -def test_sessions_client_from_service_account_file(client_class, transport_name): - 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", transport=transport_name) - assert client.transport._credentials == creds - assert isinstance(client, client_class) - - client = client_class.from_service_account_json("dummy/file/path.json", transport=transport_name) - assert client.transport._credentials == creds - assert isinstance(client, client_class) - - assert client.transport._host == ( - 'dialogflow.googleapis.com:443' - if transport_name in ['grpc', 'grpc_asyncio'] - else - 'https://dialogflow.googleapis.com' - ) - - -def test_sessions_client_get_transport_class(): - transport = SessionsClient.get_transport_class() - available_transports = [ - transports.SessionsGrpcTransport, - transports.SessionsRestTransport, - ] - assert transport in available_transports - - transport = SessionsClient.get_transport_class("grpc") - assert transport == transports.SessionsGrpcTransport - - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (SessionsClient, transports.SessionsGrpcTransport, "grpc"), - (SessionsAsyncClient, transports.SessionsGrpcAsyncIOTransport, "grpc_asyncio"), - (SessionsClient, transports.SessionsRestTransport, "rest"), -]) -@mock.patch.object(SessionsClient, "DEFAULT_ENDPOINT", modify_default_endpoint(SessionsClient)) -@mock.patch.object(SessionsAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(SessionsAsyncClient)) -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=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(SessionsClient, 'get_transport_class') as gtc: - client = client_class(transport=transport_name) - gtc.assert_called() - - # Check the case api_endpoint is provided. - options = client_options.ClientOptions(api_endpoint="squid.clam.whelk") - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(transport=transport_name, client_options=options) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host="squid.clam.whelk", - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is - # "never". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is - # "always". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_MTLS_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # 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(transport=transport_name) - - # 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(transport=transport_name) - - # 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, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id="octopus", - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - # Check the case api_endpoint is provided - options = client_options.ClientOptions(api_audience="https://language.googleapis.com") - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience="https://language.googleapis.com" - ) - -@pytest.mark.parametrize("client_class,transport_class,transport_name,use_client_cert_env", [ - (SessionsClient, transports.SessionsGrpcTransport, "grpc", "true"), - (SessionsAsyncClient, transports.SessionsGrpcAsyncIOTransport, "grpc_asyncio", "true"), - (SessionsClient, transports.SessionsGrpcTransport, "grpc", "false"), - (SessionsAsyncClient, transports.SessionsGrpcAsyncIOTransport, "grpc_asyncio", "false"), - (SessionsClient, transports.SessionsRestTransport, "rest", "true"), - (SessionsClient, transports.SessionsRestTransport, "rest", "false"), -]) -@mock.patch.object(SessionsClient, "DEFAULT_ENDPOINT", modify_default_endpoint(SessionsClient)) -@mock.patch.object(SessionsAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(SessionsAsyncClient)) -@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) -def test_sessions_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, transport=transport_name) - - if use_client_cert_env == "false": - expected_client_cert_source = None - expected_host = client.DEFAULT_ENDPOINT - else: - expected_client_cert_source = client_cert_source_callback - expected_host = client.DEFAULT_MTLS_ENDPOINT - - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=expected_host, - scopes=None, - client_cert_source_for_mtls=expected_client_cert_source, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case ADC client cert is provided. Whether client cert is used depends on - # GOOGLE_API_USE_CLIENT_CERTIFICATE value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): - with mock.patch.object(transport_class, '__init__') as patched: - with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): - with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=client_cert_source_callback): - if use_client_cert_env == "false": - expected_host = client.DEFAULT_ENDPOINT - expected_client_cert_source = None - else: - expected_host = client.DEFAULT_MTLS_ENDPOINT - expected_client_cert_source = client_cert_source_callback - - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=expected_host, - scopes=None, - client_cert_source_for_mtls=expected_client_cert_source, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case client_cert_source and ADC client cert are not provided. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): - with mock.patch.object(transport_class, '__init__') as patched: - with mock.patch("google.auth.transport.mtls.has_default_client_cert_source", return_value=False): - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - -@pytest.mark.parametrize("client_class", [ - SessionsClient, SessionsAsyncClient -]) -@mock.patch.object(SessionsClient, "DEFAULT_ENDPOINT", modify_default_endpoint(SessionsClient)) -@mock.patch.object(SessionsAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(SessionsAsyncClient)) -def test_sessions_client_get_mtls_endpoint_and_cert_source(client_class): - mock_client_cert_source = mock.Mock() - - # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "true". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - mock_api_endpoint = "foo" - options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) - assert api_endpoint == mock_api_endpoint - assert cert_source == mock_client_cert_source - - # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "false". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): - mock_client_cert_source = mock.Mock() - mock_api_endpoint = "foo" - options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) - assert api_endpoint == mock_api_endpoint - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "never". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_ENDPOINT - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "always". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert doesn't exist. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=False): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_ENDPOINT - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert exists. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - 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=mock_client_cert_source): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT - assert cert_source == mock_client_cert_source - - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (SessionsClient, transports.SessionsGrpcTransport, "grpc"), - (SessionsAsyncClient, transports.SessionsGrpcAsyncIOTransport, "grpc_asyncio"), - (SessionsClient, transports.SessionsRestTransport, "rest"), -]) -def test_sessions_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, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=["1", "2"], - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - -@pytest.mark.parametrize("client_class,transport_class,transport_name,grpc_helpers", [ - (SessionsClient, transports.SessionsGrpcTransport, "grpc", grpc_helpers), - (SessionsAsyncClient, transports.SessionsGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), - (SessionsClient, transports.SessionsRestTransport, "rest", None), -]) -def test_sessions_client_client_options_credentials_file(client_class, transport_class, transport_name, grpc_helpers): - # 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, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file="credentials.json", - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - -def test_sessions_client_client_options_from_dict(): - with mock.patch('google.cloud.dialogflow_v2.services.sessions.transports.SessionsGrpcTransport.__init__') as grpc_transport: - grpc_transport.return_value = None - client = SessionsClient( - client_options={'api_endpoint': 'squid.clam.whelk'} - ) - grpc_transport.assert_called_once_with( - credentials=None, - credentials_file=None, - host="squid.clam.whelk", - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - -@pytest.mark.parametrize("client_class,transport_class,transport_name,grpc_helpers", [ - (SessionsClient, transports.SessionsGrpcTransport, "grpc", grpc_helpers), - (SessionsAsyncClient, transports.SessionsGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), -]) -def test_sessions_client_create_channel_credentials_file(client_class, transport_class, transport_name, grpc_helpers): - # 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, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file="credentials.json", - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # test that the credentials from file are saved and used as the credentials. - with mock.patch.object( - google.auth, "load_credentials_from_file", autospec=True - ) as load_creds, mock.patch.object( - google.auth, "default", autospec=True - ) as adc, mock.patch.object( - grpc_helpers, "create_channel" - ) as create_channel: - creds = ga_credentials.AnonymousCredentials() - file_creds = ga_credentials.AnonymousCredentials() - load_creds.return_value = (file_creds, None) - adc.return_value = (creds, None) - client = client_class(client_options=options, transport=transport_name) - create_channel.assert_called_with( - "dialogflow.googleapis.com:443", - credentials=file_creds, - credentials_file=None, - quota_project_id=None, - default_scopes=( - 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/dialogflow', -), - scopes=None, - default_host="dialogflow.googleapis.com", - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - -@pytest.mark.parametrize("request_type", [ - gcd_session.DetectIntentRequest, - dict, -]) -def test_detect_intent(request_type, transport: str = 'grpc'): - client = SessionsClient( - 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.detect_intent), - '__call__') as call: - # Designate an appropriate return value for the call. - 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' - - -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=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.detect_intent), - '__call__') as call: - client.detect_intent() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == gcd_session.DetectIntentRequest() - -@pytest.mark.asyncio -async def test_detect_intent_async(transport: str = 'grpc_asyncio', request_type=gcd_session.DetectIntentRequest): - client = SessionsAsyncClient( - 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.detect_intent), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gcd_session.DetectIntentResponse( - 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' - - -@pytest.mark.asyncio -async def test_detect_intent_async_from_dict(): - await test_detect_intent_async(request_type=dict) - - -def test_detect_intent_field_headers(): - 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. - 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', - 'session=session_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_detect_intent_field_headers_async(): - 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. - with mock.patch.object( - type(client.transport.detect_intent), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcd_session.DetectIntentResponse()) - 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] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'session=session_value', - ) in kw['metadata'] - - -def test_detect_intent_flattened(): - 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( - session='session_value', - query_input=gcd_session.QueryInput(audio_config=audio_config.InputAudioConfig(audio_encoding=audio_config.AudioEncoding.AUDIO_ENCODING_LINEAR_16)), - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - arg = args[0].session - mock_val = 'session_value' - assert arg == mock_val - arg = args[0].query_input - mock_val = gcd_session.QueryInput(audio_config=audio_config.InputAudioConfig(audio_encoding=audio_config.AudioEncoding.AUDIO_ENCODING_LINEAR_16)) - assert arg == mock_val - - -def test_detect_intent_flattened_error(): - client = SessionsClient( - 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.detect_intent( - gcd_session.DetectIntentRequest(), - session='session_value', - query_input=gcd_session.QueryInput(audio_config=audio_config.InputAudioConfig(audio_encoding=audio_config.AudioEncoding.AUDIO_ENCODING_LINEAR_16)), - ) - -@pytest.mark.asyncio -async def test_detect_intent_flattened_async(): - 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: - # Designate an appropriate return value for the call. - call.return_value = gcd_session.DetectIntentResponse() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcd_session.DetectIntentResponse()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.detect_intent( - session='session_value', - query_input=gcd_session.QueryInput(audio_config=audio_config.InputAudioConfig(audio_encoding=audio_config.AudioEncoding.AUDIO_ENCODING_LINEAR_16)), - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - arg = args[0].session - mock_val = 'session_value' - assert arg == mock_val - arg = args[0].query_input - mock_val = gcd_session.QueryInput(audio_config=audio_config.InputAudioConfig(audio_encoding=audio_config.AudioEncoding.AUDIO_ENCODING_LINEAR_16)) - assert arg == mock_val - -@pytest.mark.asyncio -async def test_detect_intent_flattened_error_async(): - client = SessionsAsyncClient( - 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.detect_intent( - gcd_session.DetectIntentRequest(), - session='session_value', - query_input=gcd_session.QueryInput(audio_config=audio_config.InputAudioConfig(audio_encoding=audio_config.AudioEncoding.AUDIO_ENCODING_LINEAR_16)), - ) - - -@pytest.mark.parametrize("request_type", [ - session.StreamingDetectIntentRequest, - dict, -]) -def test_streaming_detect_intent(request_type, transport: str = 'grpc'): - client = SessionsClient( - 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. - with mock.patch.object( - type(client.transport.streaming_detect_intent), - '__call__') 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. - for message in response: - assert isinstance(message, session.StreamingDetectIntentResponse) - - -@pytest.mark.asyncio -async def test_streaming_detect_intent_async(transport: str = 'grpc_asyncio', request_type=session.StreamingDetectIntentRequest): - client = SessionsAsyncClient( - 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. - with mock.patch.object( - type(client.transport.streaming_detect_intent), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = mock.Mock(aio.StreamStreamCall, autospec=True) - 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. - message = await response.read() - assert isinstance(message, session.StreamingDetectIntentResponse) - - -@pytest.mark.asyncio -async def test_streaming_detect_intent_async_from_dict(): - await test_streaming_detect_intent_async(request_type=dict) - - -@pytest.mark.parametrize("request_type", [ - gcd_session.DetectIntentRequest, - dict, -]) -def test_detect_intent_rest(request_type): - client = SessionsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'session': 'projects/sample1/agent/sessions/sample2'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = gcd_session.DetectIntentResponse( - response_id='response_id_value', - output_audio=b'output_audio_blob', - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - pb_return_value = gcd_session.DetectIntentResponse.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.detect_intent(request) - - # 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' - - -def test_detect_intent_rest_required_fields(request_type=gcd_session.DetectIntentRequest): - transport_class = transports.SessionsRestTransport - - request_init = {} - request_init["session"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - including_default_value_fields=False, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).detect_intent._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["session"] = 'session_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).detect_intent._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "session" in jsonified_request - assert jsonified_request["session"] == 'session_value' - - client = SessionsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = gcd_session.DetectIntentResponse() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "post", - 'query_params': pb_request, - } - transcode_result['body'] = pb_request - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - - pb_return_value = gcd_session.DetectIntentResponse.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.detect_intent(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_detect_intent_rest_unset_required_fields(): - transport = transports.SessionsRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.detect_intent._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("session", "queryInput", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_detect_intent_rest_interceptors(null_interceptor): - transport = transports.SessionsRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.SessionsRestInterceptor(), - ) - client = SessionsClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.SessionsRestInterceptor, "post_detect_intent") as post, \ - mock.patch.object(transports.SessionsRestInterceptor, "pre_detect_intent") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = gcd_session.DetectIntentRequest.pb(gcd_session.DetectIntentRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = gcd_session.DetectIntentResponse.to_json(gcd_session.DetectIntentResponse()) - - request = gcd_session.DetectIntentRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = gcd_session.DetectIntentResponse() - - client.detect_intent(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_detect_intent_rest_bad_request(transport: str = 'rest', request_type=gcd_session.DetectIntentRequest): - client = SessionsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'session': 'projects/sample1/agent/sessions/sample2'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.detect_intent(request) - - -def test_detect_intent_rest_flattened(): - client = SessionsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = gcd_session.DetectIntentResponse() - - # get arguments that satisfy an http rule for this method - sample_request = {'session': 'projects/sample1/agent/sessions/sample2'} - - # get truthy value for each flattened field - mock_args = dict( - session='session_value', - query_input=gcd_session.QueryInput(audio_config=audio_config.InputAudioConfig(audio_encoding=audio_config.AudioEncoding.AUDIO_ENCODING_LINEAR_16)), - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - pb_return_value = gcd_session.DetectIntentResponse.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.detect_intent(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v2/{session=projects/*/agent/sessions/*}:detectIntent" % client.transport._host, args[1]) - - -def test_detect_intent_rest_flattened_error(transport: str = 'rest'): - client = SessionsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.detect_intent( - gcd_session.DetectIntentRequest(), - session='session_value', - query_input=gcd_session.QueryInput(audio_config=audio_config.InputAudioConfig(audio_encoding=audio_config.AudioEncoding.AUDIO_ENCODING_LINEAR_16)), - ) - - -def test_detect_intent_rest_error(): - client = SessionsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -def test_streaming_detect_intent_rest_no_http_options(): - client = SessionsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request = session.StreamingDetectIntentRequest() - requests = [request] - with pytest.raises(RuntimeError): - client.streaming_detect_intent(requests) - - -def test_streaming_detect_intent_rest_error(): - client = SessionsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - # Since a `google.api.http` annotation is required for using a rest transport - # method, this should error. - with pytest.raises(NotImplementedError) as not_implemented_error: - client.streaming_detect_intent({}) - assert ( - "Method StreamingDetectIntent is not available over REST transport" - in str(not_implemented_error.value) - ) - - -def test_credentials_transport_error(): - # It is an error to provide credentials and a transport instance. - transport = transports.SessionsGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = SessionsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # It is an error to provide a credentials file and a transport instance. - transport = transports.SessionsGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = SessionsClient( - client_options={"credentials_file": "credentials.json"}, - transport=transport, - ) - - # It is an error to provide an api_key and a transport instance. - transport = transports.SessionsGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - options = client_options.ClientOptions() - options.api_key = "api_key" - with pytest.raises(ValueError): - client = SessionsClient( - client_options=options, - transport=transport, - ) - - # It is an error to provide an api_key and a credential. - options = mock.Mock() - options.api_key = "api_key" - with pytest.raises(ValueError): - client = SessionsClient( - client_options=options, - credentials=ga_credentials.AnonymousCredentials() - ) - - # It is an error to provide scopes and a transport instance. - transport = transports.SessionsGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = SessionsClient( - client_options={"scopes": ["1", "2"]}, - transport=transport, - ) - - -def test_transport_instance(): - # A client may be instantiated with a custom transport instance. - transport = transports.SessionsGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - client = SessionsClient(transport=transport) - assert client.transport is transport - -def test_transport_get_channel(): - # A client may be instantiated with a custom transport instance. - transport = transports.SessionsGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - - transport = transports.SessionsGrpcAsyncIOTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - -@pytest.mark.parametrize("transport_class", [ - transports.SessionsGrpcTransport, - transports.SessionsGrpcAsyncIOTransport, - transports.SessionsRestTransport, -]) -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() - -@pytest.mark.parametrize("transport_name", [ - "grpc", - "rest", -]) -def test_transport_kind(transport_name): - transport = SessionsClient.get_transport_class(transport_name)( - credentials=ga_credentials.AnonymousCredentials(), - ) - assert transport.kind == transport_name - -def test_transport_grpc_default(): - # A client should use the gRPC transport by default. - 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(core_exceptions.DuplicateCredentialArgs): - transport = transports.SessionsTransport( - credentials=ga_credentials.AnonymousCredentials(), - credentials_file="credentials.json" - ) - - -def test_sessions_base_transport(): - # Instantiate the base transport. - with mock.patch('google.cloud.dialogflow_v2.services.sessions.transports.SessionsTransport.__init__') as Transport: - Transport.return_value = None - transport = transports.SessionsTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Every method on the transport should just blindly - # raise NotImplementedError. - methods = ( - 'detect_intent', - 'streaming_detect_intent', - 'get_location', - 'list_locations', - 'get_operation', - 'cancel_operation', - 'list_operations', - ) - for method in methods: - with pytest.raises(NotImplementedError): - getattr(transport, method)(request=object()) - - with pytest.raises(NotImplementedError): - transport.close() - - # Catch all for all remaining methods and properties - remainder = [ - 'kind', - ] - for r in remainder: - with pytest.raises(NotImplementedError): - getattr(transport, r)() - - -def test_sessions_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.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", - ) - - -def test_sessions_base_transport_with_adc(): - # Test the default credentials are used if credentials and credentials_file are None. - with mock.patch.object(google.auth, 'default', autospec=True) as adc, mock.patch('google.cloud.dialogflow_v2.services.sessions.transports.SessionsTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.SessionsTransport() - adc.assert_called_once() - - -def test_sessions_auth_adc(): - # If no credentials are provided, we should use ADC credentials. - with mock.patch.object(google.auth, 'default', autospec=True) as adc: - 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, - ) - - -@pytest.mark.parametrize( - "transport_class", - [ - transports.SessionsGrpcTransport, - transports.SessionsGrpcAsyncIOTransport, - ], -) -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(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, - transports.SessionsRestTransport, - ], -) -def test_sessions_transport_auth_gdch_credentials(transport_class): - host = 'https://language.com' - api_audience_tests = [None, 'https://language2.com'] - api_audience_expect = [host, 'https://language2.com'] - for t, e in zip(api_audience_tests, api_audience_expect): - with mock.patch.object(google.auth, 'default', autospec=True) as adc: - gdch_mock = mock.MagicMock() - type(gdch_mock).with_gdch_audience = mock.PropertyMock(return_value=gdch_mock) - adc.return_value = (gdch_mock, None) - transport_class(host=host, api_audience=t) - gdch_mock.with_gdch_audience.assert_called_once_with( - e - ) - - -@pytest.mark.parametrize( - "transport_class,grpc_helpers", - [ - (transports.SessionsGrpcTransport, grpc_helpers), - (transports.SessionsGrpcAsyncIOTransport, grpc_helpers_async) - ], -) -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", [transports.SessionsGrpcTransport, transports.SessionsGrpcAsyncIOTransport]) -def test_sessions_grpc_transport_client_cert_source_for_mtls( - transport_class -): - cred = ga_credentials.AnonymousCredentials() - - # Check ssl_channel_credentials is used if provided. - with mock.patch.object(transport_class, "create_channel") as mock_create_channel: - mock_ssl_channel_creds = mock.Mock() - transport_class( - host="squid.clam.whelk", - credentials=cred, - ssl_channel_credentials=mock_ssl_channel_creds - ) - mock_create_channel.assert_called_once_with( - "squid.clam.whelk:443", - credentials=cred, - credentials_file=None, - scopes=None, - ssl_credentials=mock_ssl_channel_creds, - quota_project_id=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - # Check if ssl_channel_credentials is not provided, then client_cert_source_for_mtls - # is used. - with mock.patch.object(transport_class, "create_channel", return_value=mock.Mock()): - with mock.patch("grpc.ssl_channel_credentials") as mock_ssl_cred: - transport_class( - credentials=cred, - client_cert_source_for_mtls=client_cert_source_callback - ) - expected_cert, expected_key = client_cert_source_callback() - mock_ssl_cred.assert_called_once_with( - certificate_chain=expected_cert, - private_key=expected_key - ) - -def test_sessions_http_transport_client_cert_source_for_mtls(): - cred = ga_credentials.AnonymousCredentials() - with mock.patch("google.auth.transport.requests.AuthorizedSession.configure_mtls_channel") as mock_configure_mtls_channel: - transports.SessionsRestTransport ( - credentials=cred, - client_cert_source_for_mtls=client_cert_source_callback - ) - mock_configure_mtls_channel.assert_called_once_with(client_cert_source_callback) - - -@pytest.mark.parametrize("transport_name", [ - "grpc", - "grpc_asyncio", - "rest", -]) -def test_sessions_host_no_port(transport_name): - client = SessionsClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='dialogflow.googleapis.com'), - transport=transport_name, - ) - assert client.transport._host == ( - 'dialogflow.googleapis.com:443' - if transport_name in ['grpc', 'grpc_asyncio'] - else 'https://dialogflow.googleapis.com' - ) - -@pytest.mark.parametrize("transport_name", [ - "grpc", - "grpc_asyncio", - "rest", -]) -def test_sessions_host_with_port(transport_name): - client = SessionsClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='dialogflow.googleapis.com:8000'), - transport=transport_name, - ) - assert client.transport._host == ( - 'dialogflow.googleapis.com:8000' - if transport_name in ['grpc', 'grpc_asyncio'] - else 'https://dialogflow.googleapis.com:8000' - ) - -@pytest.mark.parametrize("transport_name", [ - "rest", -]) -def test_sessions_client_transport_session_collision(transport_name): - creds1 = ga_credentials.AnonymousCredentials() - creds2 = ga_credentials.AnonymousCredentials() - client1 = SessionsClient( - credentials=creds1, - transport=transport_name, - ) - client2 = SessionsClient( - credentials=creds2, - transport=transport_name, - ) - session1 = client1.transport.detect_intent._session - session2 = client2.transport.detect_intent._session - assert session1 != session2 - session1 = client1.transport.streaming_detect_intent._session - session2 = client2.transport.streaming_detect_intent._session - assert session1 != session2 -def test_sessions_grpc_transport_channel(): - channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.SessionsGrpcTransport( - 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_sessions_grpc_asyncio_transport_channel(): - channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.SessionsGrpcAsyncIOTransport( - 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.SessionsGrpcTransport, transports.SessionsGrpcAsyncIOTransport]) -def test_sessions_transport_channel_mtls_with_client_cert_source( - transport_class -): - with mock.patch("grpc.ssl_channel_credentials", autospec=True) as grpc_ssl_channel_cred: - with mock.patch.object(transport_class, "create_channel") as grpc_create_channel: - mock_ssl_cred = mock.Mock() - grpc_ssl_channel_cred.return_value = mock_ssl_cred - - mock_grpc_channel = mock.Mock() - grpc_create_channel.return_value = mock_grpc_channel - - cred = ga_credentials.AnonymousCredentials() - with pytest.warns(DeprecationWarning): - with mock.patch.object(google.auth, 'default') as adc: - adc.return_value = (cred, None) - transport = transport_class( - host="squid.clam.whelk", - api_mtls_endpoint="mtls.squid.clam.whelk", - client_cert_source=client_cert_source_callback, - ) - adc.assert_called_once() - - grpc_ssl_channel_cred.assert_called_once_with( - certificate_chain=b"cert bytes", private_key=b"key bytes" - ) - grpc_create_channel.assert_called_once_with( - "mtls.squid.clam.whelk:443", - credentials=cred, - credentials_file=None, - scopes=None, - ssl_credentials=mock_ssl_cred, - quota_project_id=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - assert transport.grpc_channel == mock_grpc_channel - assert transport._ssl_channel_credentials == mock_ssl_cred - - -# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are -# removed from grpc/grpc_asyncio transport constructor. -@pytest.mark.parametrize("transport_class", [transports.SessionsGrpcTransport, transports.SessionsGrpcAsyncIOTransport]) -def test_sessions_transport_channel_mtls_with_adc( - transport_class -): - mock_ssl_cred = mock.Mock() - with mock.patch.multiple( - "google.auth.transport.grpc.SslCredentials", - __init__=mock.Mock(return_value=None), - ssl_credentials=mock.PropertyMock(return_value=mock_ssl_cred), - ): - with mock.patch.object(transport_class, "create_channel") as grpc_create_channel: - mock_grpc_channel = mock.Mock() - grpc_create_channel.return_value = mock_grpc_channel - mock_cred = mock.Mock() - - with pytest.warns(DeprecationWarning): - transport = transport_class( - host="squid.clam.whelk", - credentials=mock_cred, - api_mtls_endpoint="mtls.squid.clam.whelk", - client_cert_source=None, - ) - - grpc_create_channel.assert_called_once_with( - "mtls.squid.clam.whelk:443", - credentials=mock_cred, - credentials_file=None, - scopes=None, - ssl_credentials=mock_ssl_cred, - quota_project_id=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - assert transport.grpc_channel == mock_grpc_channel - - -def test_context_path(): - project = "squid" - session = "clam" - context = "whelk" - expected = "projects/{project}/agent/sessions/{session}/contexts/{context}".format(project=project, session=session, context=context, ) - actual = SessionsClient.context_path(project, session, context) - assert expected == actual - - -def test_parse_context_path(): - expected = { - "project": "octopus", - "session": "oyster", - "context": "nudibranch", - } - path = SessionsClient.context_path(**expected) - - # Check that the path construction is reversible. - actual = SessionsClient.parse_context_path(path) - assert expected == actual - -def test_intent_path(): - project = "cuttlefish" - intent = "mussel" - expected = "projects/{project}/agent/intents/{intent}".format(project=project, intent=intent, ) - actual = SessionsClient.intent_path(project, intent) - assert expected == actual - - -def test_parse_intent_path(): - expected = { - "project": "winkle", - "intent": "nautilus", - } - path = SessionsClient.intent_path(**expected) - - # Check that the path construction is reversible. - actual = SessionsClient.parse_intent_path(path) - assert expected == actual - -def test_session_path(): - project = "scallop" - session = "abalone" - expected = "projects/{project}/agent/sessions/{session}".format(project=project, session=session, ) - actual = SessionsClient.session_path(project, session) - assert expected == actual - - -def test_parse_session_path(): - expected = { - "project": "squid", - "session": "clam", - } - path = SessionsClient.session_path(**expected) - - # Check that the path construction is reversible. - actual = SessionsClient.parse_session_path(path) - assert expected == actual - -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, ) - actual = SessionsClient.session_entity_type_path(project, session, entity_type) - assert expected == actual - - -def test_parse_session_entity_type_path(): - expected = { - "project": "nudibranch", - "session": "cuttlefish", - "entity_type": "mussel", - } - path = SessionsClient.session_entity_type_path(**expected) - - # Check that the path construction is reversible. - actual = SessionsClient.parse_session_entity_type_path(path) - assert expected == actual - -def test_common_billing_account_path(): - billing_account = "winkle" - expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) - actual = SessionsClient.common_billing_account_path(billing_account) - assert expected == actual - - -def test_parse_common_billing_account_path(): - expected = { - "billing_account": "nautilus", - } - path = SessionsClient.common_billing_account_path(**expected) - - # Check that the path construction is reversible. - actual = SessionsClient.parse_common_billing_account_path(path) - assert expected == actual - -def test_common_folder_path(): - folder = "scallop" - expected = "folders/{folder}".format(folder=folder, ) - actual = SessionsClient.common_folder_path(folder) - assert expected == actual - - -def test_parse_common_folder_path(): - expected = { - "folder": "abalone", - } - path = SessionsClient.common_folder_path(**expected) - - # Check that the path construction is reversible. - actual = SessionsClient.parse_common_folder_path(path) - assert expected == actual - -def test_common_organization_path(): - organization = "squid" - expected = "organizations/{organization}".format(organization=organization, ) - actual = SessionsClient.common_organization_path(organization) - assert expected == actual - - -def test_parse_common_organization_path(): - expected = { - "organization": "clam", - } - path = SessionsClient.common_organization_path(**expected) - - # Check that the path construction is reversible. - actual = SessionsClient.parse_common_organization_path(path) - assert expected == actual - -def test_common_project_path(): - project = "whelk" - expected = "projects/{project}".format(project=project, ) - actual = SessionsClient.common_project_path(project) - assert expected == actual - - -def test_parse_common_project_path(): - expected = { - "project": "octopus", - } - path = SessionsClient.common_project_path(**expected) - - # Check that the path construction is reversible. - actual = SessionsClient.parse_common_project_path(path) - assert expected == actual - -def test_common_location_path(): - project = "oyster" - location = "nudibranch" - expected = "projects/{project}/locations/{location}".format(project=project, location=location, ) - actual = SessionsClient.common_location_path(project, location) - assert expected == actual - - -def test_parse_common_location_path(): - expected = { - "project": "cuttlefish", - "location": "mussel", - } - path = SessionsClient.common_location_path(**expected) - - # Check that the path construction is reversible. - actual = SessionsClient.parse_common_location_path(path) - assert expected == actual - - -def test_client_with_default_client_info(): - client_info = gapic_v1.client_info.ClientInfo() - - with mock.patch.object(transports.SessionsTransport, '_prep_wrapped_messages') as prep: - client = SessionsClient( - credentials=ga_credentials.AnonymousCredentials(), - client_info=client_info, - ) - prep.assert_called_once_with(client_info) - - with mock.patch.object(transports.SessionsTransport, '_prep_wrapped_messages') as prep: - transport_class = SessionsClient.get_transport_class() - transport = transport_class( - credentials=ga_credentials.AnonymousCredentials(), - client_info=client_info, - ) - prep.assert_called_once_with(client_info) - -@pytest.mark.asyncio -async def test_transport_close_async(): - client = SessionsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - with mock.patch.object(type(getattr(client.transport, "grpc_channel")), "close") as close: - async with client: - close.assert_not_called() - close.assert_called_once() - - -def test_get_location_rest_bad_request(transport: str = 'rest', request_type=locations_pb2.GetLocationRequest): - client = SessionsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - request = request_type() - request = json_format.ParseDict({'name': 'projects/sample1/locations/sample2'}, request) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.get_location(request) - -@pytest.mark.parametrize("request_type", [ - locations_pb2.GetLocationRequest, - dict, -]) -def test_get_location_rest(request_type): - client = SessionsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request_init = {'name': 'projects/sample1/locations/sample2'} - request = request_type(**request_init) - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = locations_pb2.Location() - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.get_location(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, locations_pb2.Location) - -def test_list_locations_rest_bad_request(transport: str = 'rest', request_type=locations_pb2.ListLocationsRequest): - client = SessionsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - request = request_type() - request = json_format.ParseDict({'name': 'projects/sample1'}, request) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.list_locations(request) - -@pytest.mark.parametrize("request_type", [ - locations_pb2.ListLocationsRequest, - dict, -]) -def test_list_locations_rest(request_type): - client = SessionsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request_init = {'name': 'projects/sample1'} - request = request_type(**request_init) - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = locations_pb2.ListLocationsResponse() - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.list_locations(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, locations_pb2.ListLocationsResponse) - -def test_cancel_operation_rest_bad_request(transport: str = 'rest', request_type=operations_pb2.CancelOperationRequest): - client = SessionsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - request = request_type() - request = json_format.ParseDict({'name': 'projects/sample1/operations/sample2'}, request) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.cancel_operation(request) - -@pytest.mark.parametrize("request_type", [ - operations_pb2.CancelOperationRequest, - dict, -]) -def test_cancel_operation_rest(request_type): - client = SessionsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request_init = {'name': 'projects/sample1/operations/sample2'} - request = request_type(**request_init) - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = None - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = '{}' - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.cancel_operation(request) - - # Establish that the response is the type that we expect. - assert response is None - -def test_get_operation_rest_bad_request(transport: str = 'rest', request_type=operations_pb2.GetOperationRequest): - client = SessionsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - request = request_type() - request = json_format.ParseDict({'name': 'projects/sample1/operations/sample2'}, request) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.get_operation(request) - -@pytest.mark.parametrize("request_type", [ - operations_pb2.GetOperationRequest, - dict, -]) -def test_get_operation_rest(request_type): - client = SessionsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request_init = {'name': 'projects/sample1/operations/sample2'} - request = request_type(**request_init) - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation() - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.get_operation(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, operations_pb2.Operation) - -def test_list_operations_rest_bad_request(transport: str = 'rest', request_type=operations_pb2.ListOperationsRequest): - client = SessionsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - request = request_type() - request = json_format.ParseDict({'name': 'projects/sample1'}, request) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.list_operations(request) - -@pytest.mark.parametrize("request_type", [ - operations_pb2.ListOperationsRequest, - dict, -]) -def test_list_operations_rest(request_type): - client = SessionsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request_init = {'name': 'projects/sample1'} - request = request_type(**request_init) - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = operations_pb2.ListOperationsResponse() - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.list_operations(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, operations_pb2.ListOperationsResponse) - - -def test_cancel_operation(transport: str = "grpc"): - client = SessionsClient( - 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 = operations_pb2.CancelOperationRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = None - response = client.cancel_operation(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 response is the type that we expect. - assert response is None -@pytest.mark.asyncio -async def test_cancel_operation_async(transport: str = "grpc"): - client = SessionsAsyncClient( - 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 = operations_pb2.CancelOperationRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - None - ) - response = await client.cancel_operation(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 response is the type that we expect. - assert response is None - -def test_cancel_operation_field_headers(): - 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 = operations_pb2.CancelOperationRequest() - request.name = "locations" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call: - call.return_value = None - - client.cancel_operation(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=locations",) in kw["metadata"] -@pytest.mark.asyncio -async def test_cancel_operation_field_headers_async(): - 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 = operations_pb2.CancelOperationRequest() - request.name = "locations" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - None - ) - await client.cancel_operation(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=locations",) in kw["metadata"] - -def test_cancel_operation_from_dict(): - 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.cancel_operation), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = None - - response = client.cancel_operation( - request={ - "name": "locations", - } - ) - call.assert_called() -@pytest.mark.asyncio -async def test_cancel_operation_from_dict_async(): - 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.cancel_operation), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - None - ) - response = await client.cancel_operation( - request={ - "name": "locations", - } - ) - call.assert_called() - - -def test_get_operation(transport: str = "grpc"): - client = SessionsClient( - 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 = operations_pb2.GetOperationRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_operation), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation() - response = client.get_operation(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 response is the type that we expect. - assert isinstance(response, operations_pb2.Operation) -@pytest.mark.asyncio -async def test_get_operation_async(transport: str = "grpc"): - client = SessionsAsyncClient( - 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 = operations_pb2.GetOperationRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_operation), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation() - ) - response = await client.get_operation(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 response is the type that we expect. - assert isinstance(response, operations_pb2.Operation) - -def test_get_operation_field_headers(): - 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 = operations_pb2.GetOperationRequest() - request.name = "locations" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_operation), "__call__") as call: - call.return_value = operations_pb2.Operation() - - client.get_operation(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=locations",) in kw["metadata"] -@pytest.mark.asyncio -async def test_get_operation_field_headers_async(): - 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 = operations_pb2.GetOperationRequest() - request.name = "locations" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_operation), "__call__") as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation() - ) - await client.get_operation(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=locations",) in kw["metadata"] - -def test_get_operation_from_dict(): - 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.get_operation), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation() - - response = client.get_operation( - request={ - "name": "locations", - } - ) - call.assert_called() -@pytest.mark.asyncio -async def test_get_operation_from_dict_async(): - 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.get_operation), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation() - ) - response = await client.get_operation( - request={ - "name": "locations", - } - ) - call.assert_called() - - -def test_list_operations(transport: str = "grpc"): - client = SessionsClient( - 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 = operations_pb2.ListOperationsRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_operations), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.ListOperationsResponse() - response = client.list_operations(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 response is the type that we expect. - assert isinstance(response, operations_pb2.ListOperationsResponse) -@pytest.mark.asyncio -async def test_list_operations_async(transport: str = "grpc"): - client = SessionsAsyncClient( - 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 = operations_pb2.ListOperationsRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_operations), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.ListOperationsResponse() - ) - response = await client.list_operations(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 response is the type that we expect. - assert isinstance(response, operations_pb2.ListOperationsResponse) - -def test_list_operations_field_headers(): - 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 = operations_pb2.ListOperationsRequest() - request.name = "locations" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_operations), "__call__") as call: - call.return_value = operations_pb2.ListOperationsResponse() - - client.list_operations(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=locations",) in kw["metadata"] -@pytest.mark.asyncio -async def test_list_operations_field_headers_async(): - 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 = operations_pb2.ListOperationsRequest() - request.name = "locations" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_operations), "__call__") as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.ListOperationsResponse() - ) - await client.list_operations(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=locations",) in kw["metadata"] - -def test_list_operations_from_dict(): - 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.list_operations), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.ListOperationsResponse() - - response = client.list_operations( - request={ - "name": "locations", - } - ) - call.assert_called() -@pytest.mark.asyncio -async def test_list_operations_from_dict_async(): - 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.list_operations), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.ListOperationsResponse() - ) - response = await client.list_operations( - request={ - "name": "locations", - } - ) - call.assert_called() - - -def test_list_locations(transport: str = "grpc"): - client = SessionsClient( - 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 = locations_pb2.ListLocationsRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_locations), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = locations_pb2.ListLocationsResponse() - response = client.list_locations(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 response is the type that we expect. - assert isinstance(response, locations_pb2.ListLocationsResponse) -@pytest.mark.asyncio -async def test_list_locations_async(transport: str = "grpc"): - client = SessionsAsyncClient( - 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 = locations_pb2.ListLocationsRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_locations), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - locations_pb2.ListLocationsResponse() - ) - response = await client.list_locations(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 response is the type that we expect. - assert isinstance(response, locations_pb2.ListLocationsResponse) - -def test_list_locations_field_headers(): - 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 = locations_pb2.ListLocationsRequest() - request.name = "locations" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_locations), "__call__") as call: - call.return_value = locations_pb2.ListLocationsResponse() - - client.list_locations(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=locations",) in kw["metadata"] -@pytest.mark.asyncio -async def test_list_locations_field_headers_async(): - 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 = locations_pb2.ListLocationsRequest() - request.name = "locations" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_locations), "__call__") as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - locations_pb2.ListLocationsResponse() - ) - await client.list_locations(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=locations",) in kw["metadata"] - -def test_list_locations_from_dict(): - 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.list_locations), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = locations_pb2.ListLocationsResponse() - - response = client.list_locations( - request={ - "name": "locations", - } - ) - call.assert_called() -@pytest.mark.asyncio -async def test_list_locations_from_dict_async(): - 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.list_locations), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - locations_pb2.ListLocationsResponse() - ) - response = await client.list_locations( - request={ - "name": "locations", - } - ) - call.assert_called() - - -def test_get_location(transport: str = "grpc"): - client = SessionsClient( - 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 = locations_pb2.GetLocationRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_location), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = locations_pb2.Location() - response = client.get_location(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 response is the type that we expect. - assert isinstance(response, locations_pb2.Location) -@pytest.mark.asyncio -async def test_get_location_async(transport: str = "grpc_asyncio"): - client = SessionsAsyncClient( - 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 = locations_pb2.GetLocationRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_location), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - locations_pb2.Location() - ) - response = await client.get_location(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 response is the type that we expect. - assert isinstance(response, locations_pb2.Location) - -def test_get_location_field_headers(): - 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 = locations_pb2.GetLocationRequest() - request.name = "locations/abc" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_location), "__call__") as call: - call.return_value = locations_pb2.Location() - - client.get_location(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=locations/abc",) in kw["metadata"] -@pytest.mark.asyncio -async def test_get_location_field_headers_async(): - 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 = locations_pb2.GetLocationRequest() - request.name = "locations/abc" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_location), "__call__") as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - locations_pb2.Location() - ) - await client.get_location(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=locations/abc",) in kw["metadata"] - -def test_get_location_from_dict(): - 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.list_locations), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = locations_pb2.Location() - - response = client.get_location( - request={ - "name": "locations/abc", - } - ) - call.assert_called() -@pytest.mark.asyncio -async def test_get_location_from_dict_async(): - 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.list_locations), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - locations_pb2.Location() - ) - response = await client.get_location( - request={ - "name": "locations", - } - ) - call.assert_called() - - -def test_transport_close(): - transports = { - "rest": "_session", - "grpc": "_grpc_channel", - } - - for transport, close_name in transports.items(): - client = SessionsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport - ) - with mock.patch.object(type(getattr(client.transport, close_name)), "close") as close: - with client: - close.assert_not_called() - close.assert_called_once() - -def test_client_ctx(): - transports = [ - 'rest', - 'grpc', - ] - for transport in transports: - client = SessionsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport - ) - # Test client calls underlying transport. - with mock.patch.object(type(client.transport), "close") as close: - close.assert_not_called() - with client: - pass - close.assert_called() - -@pytest.mark.parametrize("client_class,transport_class", [ - (SessionsClient, transports.SessionsGrpcTransport), - (SessionsAsyncClient, transports.SessionsGrpcAsyncIOTransport), -]) -def test_api_key_credentials(client_class, transport_class): - with mock.patch.object( - google.auth._default, "get_api_key_credentials", create=True - ) as get_api_key_credentials: - mock_cred = mock.Mock() - get_api_key_credentials.return_value = mock_cred - options = client_options.ClientOptions() - options.api_key = "api_key" - 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=mock_cred, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) diff --git a/owl-bot-staging/v2/tests/unit/gapic/dialogflow_v2/test_versions.py b/owl-bot-staging/v2/tests/unit/gapic/dialogflow_v2/test_versions.py deleted file mode 100644 index 18e297374..000000000 --- a/owl-bot-staging/v2/tests/unit/gapic/dialogflow_v2/test_versions.py +++ /dev/null @@ -1,4759 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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 -# try/except added for compatibility with python < 3.8 -try: - from unittest import mock - from unittest.mock import AsyncMock # pragma: NO COVER -except ImportError: # pragma: NO COVER - import mock - -import grpc -from grpc.experimental import aio -from collections.abc import Iterable -from google.protobuf import json_format -import json -import math -import pytest -from proto.marshal.rules.dates import DurationRule, TimestampRule -from proto.marshal.rules import wrappers -from requests import Response -from requests import Request, PreparedRequest -from requests.sessions import Session -from google.protobuf import json_format - -from google.api_core import client_options -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import grpc_helpers -from google.api_core import grpc_helpers_async -from google.api_core import path_template -from google.auth import credentials as ga_credentials -from google.auth.exceptions import MutualTLSChannelError -from google.cloud.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.types import version -from google.cloud.dialogflow_v2.types import version as gcd_version -from google.cloud.location import locations_pb2 -from google.longrunning import operations_pb2 -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 - - -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,transport_name", [ - (VersionsClient, "grpc"), - (VersionsAsyncClient, "grpc_asyncio"), - (VersionsClient, "rest"), -]) -def test_versions_client_from_service_account_info(client_class, transport_name): - 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, transport=transport_name) - assert client.transport._credentials == creds - assert isinstance(client, client_class) - - assert client.transport._host == ( - 'dialogflow.googleapis.com:443' - if transport_name in ['grpc', 'grpc_asyncio'] - else - 'https://dialogflow.googleapis.com' - ) - - -@pytest.mark.parametrize("transport_class,transport_name", [ - (transports.VersionsGrpcTransport, "grpc"), - (transports.VersionsGrpcAsyncIOTransport, "grpc_asyncio"), - (transports.VersionsRestTransport, "rest"), -]) -def test_versions_client_service_account_always_use_jwt(transport_class, transport_name): - with mock.patch.object(service_account.Credentials, 'with_always_use_jwt_access', create=True) as use_jwt: - creds = service_account.Credentials(None, None, None) - transport = transport_class(credentials=creds, always_use_jwt_access=True) - use_jwt.assert_called_once_with(True) - - with mock.patch.object(service_account.Credentials, 'with_always_use_jwt_access', create=True) as use_jwt: - creds = service_account.Credentials(None, None, None) - transport = transport_class(credentials=creds, always_use_jwt_access=False) - use_jwt.assert_not_called() - - -@pytest.mark.parametrize("client_class,transport_name", [ - (VersionsClient, "grpc"), - (VersionsAsyncClient, "grpc_asyncio"), - (VersionsClient, "rest"), -]) -def test_versions_client_from_service_account_file(client_class, transport_name): - 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", transport=transport_name) - assert client.transport._credentials == creds - assert isinstance(client, client_class) - - client = client_class.from_service_account_json("dummy/file/path.json", transport=transport_name) - assert client.transport._credentials == creds - assert isinstance(client, client_class) - - assert client.transport._host == ( - 'dialogflow.googleapis.com:443' - if transport_name in ['grpc', 'grpc_asyncio'] - else - 'https://dialogflow.googleapis.com' - ) - - -def test_versions_client_get_transport_class(): - transport = VersionsClient.get_transport_class() - available_transports = [ - transports.VersionsGrpcTransport, - transports.VersionsRestTransport, - ] - 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"), - (VersionsClient, transports.VersionsRestTransport, "rest"), -]) -@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(transport=transport_name, client_options=options) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host="squid.clam.whelk", - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is - # "never". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is - # "always". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_MTLS_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # 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(transport=transport_name) - - # 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(transport=transport_name) - - # 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, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id="octopus", - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - # Check the case api_endpoint is provided - options = client_options.ClientOptions(api_audience="https://language.googleapis.com") - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience="https://language.googleapis.com" - ) - -@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"), - (VersionsClient, transports.VersionsRestTransport, "rest", "true"), - (VersionsClient, transports.VersionsRestTransport, "rest", "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, transport=transport_name) - - if use_client_cert_env == "false": - expected_client_cert_source = None - expected_host = client.DEFAULT_ENDPOINT - else: - expected_client_cert_source = client_cert_source_callback - expected_host = client.DEFAULT_MTLS_ENDPOINT - - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=expected_host, - scopes=None, - client_cert_source_for_mtls=expected_client_cert_source, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case ADC client cert is provided. Whether client cert is used depends on - # GOOGLE_API_USE_CLIENT_CERTIFICATE value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): - with mock.patch.object(transport_class, '__init__') as patched: - with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): - with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=client_cert_source_callback): - if use_client_cert_env == "false": - expected_host = client.DEFAULT_ENDPOINT - expected_client_cert_source = None - else: - expected_host = client.DEFAULT_MTLS_ENDPOINT - expected_client_cert_source = client_cert_source_callback - - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=expected_host, - scopes=None, - client_cert_source_for_mtls=expected_client_cert_source, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case client_cert_source and ADC client cert are not provided. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): - with mock.patch.object(transport_class, '__init__') as patched: - with mock.patch("google.auth.transport.mtls.has_default_client_cert_source", return_value=False): - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - -@pytest.mark.parametrize("client_class", [ - VersionsClient, VersionsAsyncClient -]) -@mock.patch.object(VersionsClient, "DEFAULT_ENDPOINT", modify_default_endpoint(VersionsClient)) -@mock.patch.object(VersionsAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(VersionsAsyncClient)) -def test_versions_client_get_mtls_endpoint_and_cert_source(client_class): - mock_client_cert_source = mock.Mock() - - # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "true". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - mock_api_endpoint = "foo" - options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) - assert api_endpoint == mock_api_endpoint - assert cert_source == mock_client_cert_source - - # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "false". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): - mock_client_cert_source = mock.Mock() - mock_api_endpoint = "foo" - options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) - assert api_endpoint == mock_api_endpoint - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "never". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_ENDPOINT - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "always". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert doesn't exist. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=False): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_ENDPOINT - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert exists. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - 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=mock_client_cert_source): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT - assert cert_source == mock_client_cert_source - - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (VersionsClient, transports.VersionsGrpcTransport, "grpc"), - (VersionsAsyncClient, transports.VersionsGrpcAsyncIOTransport, "grpc_asyncio"), - (VersionsClient, transports.VersionsRestTransport, "rest"), -]) -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, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=["1", "2"], - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - -@pytest.mark.parametrize("client_class,transport_class,transport_name,grpc_helpers", [ - (VersionsClient, transports.VersionsGrpcTransport, "grpc", grpc_helpers), - (VersionsAsyncClient, transports.VersionsGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), - (VersionsClient, transports.VersionsRestTransport, "rest", None), -]) -def test_versions_client_client_options_credentials_file(client_class, transport_class, transport_name, grpc_helpers): - # 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, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file="credentials.json", - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - -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, - always_use_jwt_access=True, - api_audience=None, - ) - - -@pytest.mark.parametrize("client_class,transport_class,transport_name,grpc_helpers", [ - (VersionsClient, transports.VersionsGrpcTransport, "grpc", grpc_helpers), - (VersionsAsyncClient, transports.VersionsGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), -]) -def test_versions_client_create_channel_credentials_file(client_class, transport_class, transport_name, grpc_helpers): - # 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, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file="credentials.json", - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # test that the credentials from file are saved and used as the credentials. - with mock.patch.object( - google.auth, "load_credentials_from_file", autospec=True - ) as load_creds, mock.patch.object( - google.auth, "default", autospec=True - ) as adc, mock.patch.object( - grpc_helpers, "create_channel" - ) as create_channel: - creds = ga_credentials.AnonymousCredentials() - file_creds = ga_credentials.AnonymousCredentials() - load_creds.return_value = (file_creds, None) - adc.return_value = (creds, None) - client = client_class(client_options=options, transport=transport_name) - create_channel.assert_called_with( - "dialogflow.googleapis.com:443", - credentials=file_creds, - credentials_file=None, - quota_project_id=None, - default_scopes=( - 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/dialogflow', -), - scopes=None, - default_host="dialogflow.googleapis.com", - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - -@pytest.mark.parametrize("request_type", [ - version.ListVersionsRequest, - dict, -]) -def test_list_versions(request_type, transport: str = 'grpc'): - 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_empty_call(): - # 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] - arg = args[0].parent - mock_val = 'parent_value' - assert arg == mock_val - - -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] - arg = args[0].parent - mock_val = 'parent_value' - assert arg == mock_val - -@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(transport_name: str = "grpc"): - client = VersionsClient( - credentials=ga_credentials.AnonymousCredentials, - transport=transport_name, - ) - - # 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 = list(pager) - assert len(results) == 6 - assert all(isinstance(i, version.Version) - for i in results) -def test_list_versions_pages(transport_name: str = "grpc"): - client = VersionsClient( - credentials=ga_credentials.AnonymousCredentials, - transport=transport_name, - ) - - # 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: # pragma: no branch - 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: # pragma: no branch - pages.append(page_) - for page_, token in zip(pages, ['abc','def','ghi', '']): - assert page_.raw_page.next_page_token == token - -@pytest.mark.parametrize("request_type", [ - version.GetVersionRequest, - dict, -]) -def test_get_version(request_type, transport: str = 'grpc'): - 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_empty_call(): - # 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] - arg = args[0].name - mock_val = 'name_value' - assert arg == mock_val - - -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] - arg = args[0].name - mock_val = 'name_value' - assert arg == mock_val - -@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', - ) - - -@pytest.mark.parametrize("request_type", [ - gcd_version.CreateVersionRequest, - dict, -]) -def test_create_version(request_type, transport: str = 'grpc'): - 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_empty_call(): - # 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] - arg = args[0].parent - mock_val = 'parent_value' - assert arg == mock_val - arg = args[0].version - mock_val = gcd_version.Version(name='name_value') - assert arg == mock_val - - -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] - arg = args[0].parent - mock_val = 'parent_value' - assert arg == mock_val - arg = args[0].version - mock_val = gcd_version.Version(name='name_value') - assert arg == mock_val - -@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'), - ) - - -@pytest.mark.parametrize("request_type", [ - gcd_version.UpdateVersionRequest, - dict, -]) -def test_update_version(request_type, transport: str = 'grpc'): - 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_empty_call(): - # 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 = '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=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 = '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=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] - arg = args[0].version - mock_val = gcd_version.Version(name='name_value') - assert arg == mock_val - arg = args[0].update_mask - mock_val = field_mask_pb2.FieldMask(paths=['paths_value']) - assert arg == mock_val - - -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] - arg = args[0].version - mock_val = gcd_version.Version(name='name_value') - assert arg == mock_val - arg = args[0].update_mask - mock_val = field_mask_pb2.FieldMask(paths=['paths_value']) - assert arg == mock_val - -@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']), - ) - - -@pytest.mark.parametrize("request_type", [ - version.DeleteVersionRequest, - dict, -]) -def test_delete_version(request_type, transport: str = 'grpc'): - 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_empty_call(): - # 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] - arg = args[0].name - mock_val = 'name_value' - assert arg == mock_val - - -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] - arg = args[0].name - mock_val = 'name_value' - assert arg == mock_val - -@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', - ) - - -@pytest.mark.parametrize("request_type", [ - version.ListVersionsRequest, - dict, -]) -def test_list_versions_rest(request_type): - client = VersionsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1/agent'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = version.ListVersionsResponse( - next_page_token='next_page_token_value', - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - pb_return_value = version.ListVersionsResponse.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.list_versions(request) - - # 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_rest_required_fields(request_type=version.ListVersionsRequest): - transport_class = transports.VersionsRestTransport - - request_init = {} - request_init["parent"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - including_default_value_fields=False, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).list_versions._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["parent"] = 'parent_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).list_versions._get_unset_required_fields(jsonified_request) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("page_size", "page_token", )) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "parent" in jsonified_request - assert jsonified_request["parent"] == 'parent_value' - - client = VersionsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = version.ListVersionsResponse() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "get", - 'query_params': pb_request, - } - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - - pb_return_value = version.ListVersionsResponse.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.list_versions(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_list_versions_rest_unset_required_fields(): - transport = transports.VersionsRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.list_versions._get_unset_required_fields({}) - assert set(unset_fields) == (set(("pageSize", "pageToken", )) & set(("parent", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_list_versions_rest_interceptors(null_interceptor): - transport = transports.VersionsRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.VersionsRestInterceptor(), - ) - client = VersionsClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.VersionsRestInterceptor, "post_list_versions") as post, \ - mock.patch.object(transports.VersionsRestInterceptor, "pre_list_versions") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = version.ListVersionsRequest.pb(version.ListVersionsRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = version.ListVersionsResponse.to_json(version.ListVersionsResponse()) - - request = version.ListVersionsRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = version.ListVersionsResponse() - - client.list_versions(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_list_versions_rest_bad_request(transport: str = 'rest', request_type=version.ListVersionsRequest): - client = VersionsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1/agent'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.list_versions(request) - - -def test_list_versions_rest_flattened(): - client = VersionsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = version.ListVersionsResponse() - - # get arguments that satisfy an http rule for this method - sample_request = {'parent': 'projects/sample1/agent'} - - # get truthy value for each flattened field - mock_args = dict( - parent='parent_value', - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - pb_return_value = version.ListVersionsResponse.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.list_versions(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v2/{parent=projects/*/agent}/versions" % client.transport._host, args[1]) - - -def test_list_versions_rest_flattened_error(transport: str = 'rest'): - client = VersionsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # 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', - ) - - -def test_list_versions_rest_pager(transport: str = 'rest'): - client = VersionsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # TODO(kbandes): remove this mock unless there's a good reason for it. - #with mock.patch.object(path_template, 'transcode') as transcode: - # Set the response as a series of pages - response = ( - 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(), - ], - ), - ) - # Two responses for two calls - response = response + response - - # Wrap the values into proper Response objs - response = tuple(version.ListVersionsResponse.to_json(x) for x in response) - return_values = tuple(Response() for i in response) - for return_val, response_val in zip(return_values, response): - return_val._content = response_val.encode('UTF-8') - return_val.status_code = 200 - req.side_effect = return_values - - sample_request = {'parent': 'projects/sample1/agent'} - - pager = client.list_versions(request=sample_request) - - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, version.Version) - for i in results) - - pages = list(client.list_versions(request=sample_request).pages) - for page_, token in zip(pages, ['abc','def','ghi', '']): - assert page_.raw_page.next_page_token == token - - -@pytest.mark.parametrize("request_type", [ - version.GetVersionRequest, - dict, -]) -def test_get_version_rest(request_type): - client = VersionsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/agent/versions/sample2'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = version.Version( - name='name_value', - description='description_value', - version_number=1518, - status=version.Version.VersionStatus.IN_PROGRESS, - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - pb_return_value = version.Version.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.get_version(request) - - # 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_rest_required_fields(request_type=version.GetVersionRequest): - transport_class = transports.VersionsRestTransport - - request_init = {} - request_init["name"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - including_default_value_fields=False, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_version._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["name"] = 'name_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_version._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "name" in jsonified_request - assert jsonified_request["name"] == 'name_value' - - client = VersionsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = version.Version() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "get", - 'query_params': pb_request, - } - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - - pb_return_value = version.Version.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.get_version(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_get_version_rest_unset_required_fields(): - transport = transports.VersionsRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.get_version._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_get_version_rest_interceptors(null_interceptor): - transport = transports.VersionsRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.VersionsRestInterceptor(), - ) - client = VersionsClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.VersionsRestInterceptor, "post_get_version") as post, \ - mock.patch.object(transports.VersionsRestInterceptor, "pre_get_version") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = version.GetVersionRequest.pb(version.GetVersionRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = version.Version.to_json(version.Version()) - - request = version.GetVersionRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = version.Version() - - client.get_version(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_get_version_rest_bad_request(transport: str = 'rest', request_type=version.GetVersionRequest): - client = VersionsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/agent/versions/sample2'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.get_version(request) - - -def test_get_version_rest_flattened(): - client = VersionsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = version.Version() - - # get arguments that satisfy an http rule for this method - sample_request = {'name': 'projects/sample1/agent/versions/sample2'} - - # get truthy value for each flattened field - mock_args = dict( - name='name_value', - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - pb_return_value = version.Version.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.get_version(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v2/{name=projects/*/agent/versions/*}" % client.transport._host, args[1]) - - -def test_get_version_rest_flattened_error(transport: str = 'rest'): - client = VersionsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # 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', - ) - - -def test_get_version_rest_error(): - client = VersionsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - gcd_version.CreateVersionRequest, - dict, -]) -def test_create_version_rest(request_type): - client = VersionsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1/agent'} - request_init["version"] = {'name': 'name_value', 'description': 'description_value', 'version_number': 1518, 'create_time': {'seconds': 751, 'nanos': 543}, 'status': 1} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = gcd_version.Version( - name='name_value', - description='description_value', - version_number=1518, - status=gcd_version.Version.VersionStatus.IN_PROGRESS, - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - pb_return_value = gcd_version.Version.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.create_version(request) - - # 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_rest_required_fields(request_type=gcd_version.CreateVersionRequest): - transport_class = transports.VersionsRestTransport - - request_init = {} - request_init["parent"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - including_default_value_fields=False, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_version._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["parent"] = 'parent_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_version._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "parent" in jsonified_request - assert jsonified_request["parent"] == 'parent_value' - - client = VersionsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = gcd_version.Version() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "post", - 'query_params': pb_request, - } - transcode_result['body'] = pb_request - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - - pb_return_value = gcd_version.Version.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.create_version(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_create_version_rest_unset_required_fields(): - transport = transports.VersionsRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.create_version._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("parent", "version", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_create_version_rest_interceptors(null_interceptor): - transport = transports.VersionsRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.VersionsRestInterceptor(), - ) - client = VersionsClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.VersionsRestInterceptor, "post_create_version") as post, \ - mock.patch.object(transports.VersionsRestInterceptor, "pre_create_version") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = gcd_version.CreateVersionRequest.pb(gcd_version.CreateVersionRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = gcd_version.Version.to_json(gcd_version.Version()) - - request = gcd_version.CreateVersionRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = gcd_version.Version() - - client.create_version(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_create_version_rest_bad_request(transport: str = 'rest', request_type=gcd_version.CreateVersionRequest): - client = VersionsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1/agent'} - request_init["version"] = {'name': 'name_value', 'description': 'description_value', 'version_number': 1518, 'create_time': {'seconds': 751, 'nanos': 543}, 'status': 1} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.create_version(request) - - -def test_create_version_rest_flattened(): - client = VersionsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = gcd_version.Version() - - # get arguments that satisfy an http rule for this method - sample_request = {'parent': 'projects/sample1/agent'} - - # get truthy value for each flattened field - mock_args = dict( - parent='parent_value', - version=gcd_version.Version(name='name_value'), - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - pb_return_value = gcd_version.Version.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.create_version(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v2/{parent=projects/*/agent}/versions" % client.transport._host, args[1]) - - -def test_create_version_rest_flattened_error(transport: str = 'rest'): - client = VersionsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # 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'), - ) - - -def test_create_version_rest_error(): - client = VersionsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - gcd_version.UpdateVersionRequest, - dict, -]) -def test_update_version_rest(request_type): - client = VersionsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'version': {'name': 'projects/sample1/agent/versions/sample2'}} - request_init["version"] = {'name': 'projects/sample1/agent/versions/sample2', 'description': 'description_value', 'version_number': 1518, 'create_time': {'seconds': 751, 'nanos': 543}, 'status': 1} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = gcd_version.Version( - name='name_value', - description='description_value', - version_number=1518, - status=gcd_version.Version.VersionStatus.IN_PROGRESS, - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - pb_return_value = gcd_version.Version.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.update_version(request) - - # 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_rest_required_fields(request_type=gcd_version.UpdateVersionRequest): - transport_class = transports.VersionsRestTransport - - request_init = {} - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - including_default_value_fields=False, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).update_version._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).update_version._get_unset_required_fields(jsonified_request) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("update_mask", )) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - - client = VersionsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = gcd_version.Version() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "patch", - 'query_params': pb_request, - } - transcode_result['body'] = pb_request - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - - pb_return_value = gcd_version.Version.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.update_version(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_update_version_rest_unset_required_fields(): - transport = transports.VersionsRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.update_version._get_unset_required_fields({}) - assert set(unset_fields) == (set(("updateMask", )) & set(("version", "updateMask", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_update_version_rest_interceptors(null_interceptor): - transport = transports.VersionsRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.VersionsRestInterceptor(), - ) - client = VersionsClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.VersionsRestInterceptor, "post_update_version") as post, \ - mock.patch.object(transports.VersionsRestInterceptor, "pre_update_version") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = gcd_version.UpdateVersionRequest.pb(gcd_version.UpdateVersionRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = gcd_version.Version.to_json(gcd_version.Version()) - - request = gcd_version.UpdateVersionRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = gcd_version.Version() - - client.update_version(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_update_version_rest_bad_request(transport: str = 'rest', request_type=gcd_version.UpdateVersionRequest): - client = VersionsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'version': {'name': 'projects/sample1/agent/versions/sample2'}} - request_init["version"] = {'name': 'projects/sample1/agent/versions/sample2', 'description': 'description_value', 'version_number': 1518, 'create_time': {'seconds': 751, 'nanos': 543}, 'status': 1} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.update_version(request) - - -def test_update_version_rest_flattened(): - client = VersionsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = gcd_version.Version() - - # get arguments that satisfy an http rule for this method - sample_request = {'version': {'name': 'projects/sample1/agent/versions/sample2'}} - - # get truthy value for each flattened field - mock_args = dict( - version=gcd_version.Version(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - pb_return_value = gcd_version.Version.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.update_version(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v2/{version.name=projects/*/agent/versions/*}" % client.transport._host, args[1]) - - -def test_update_version_rest_flattened_error(transport: str = 'rest'): - client = VersionsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # 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']), - ) - - -def test_update_version_rest_error(): - client = VersionsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - version.DeleteVersionRequest, - dict, -]) -def test_delete_version_rest(request_type): - client = VersionsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/agent/versions/sample2'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = None - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = '' - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.delete_version(request) - - # Establish that the response is the type that we expect. - assert response is None - - -def test_delete_version_rest_required_fields(request_type=version.DeleteVersionRequest): - transport_class = transports.VersionsRestTransport - - request_init = {} - request_init["name"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - including_default_value_fields=False, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).delete_version._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["name"] = 'name_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).delete_version._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "name" in jsonified_request - assert jsonified_request["name"] == 'name_value' - - client = VersionsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = None - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "delete", - 'query_params': pb_request, - } - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - json_return_value = '' - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.delete_version(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_delete_version_rest_unset_required_fields(): - transport = transports.VersionsRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.delete_version._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_delete_version_rest_interceptors(null_interceptor): - transport = transports.VersionsRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.VersionsRestInterceptor(), - ) - client = VersionsClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.VersionsRestInterceptor, "pre_delete_version") as pre: - pre.assert_not_called() - pb_message = version.DeleteVersionRequest.pb(version.DeleteVersionRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - - request = version.DeleteVersionRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - - client.delete_version(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - - -def test_delete_version_rest_bad_request(transport: str = 'rest', request_type=version.DeleteVersionRequest): - client = VersionsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/agent/versions/sample2'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.delete_version(request) - - -def test_delete_version_rest_flattened(): - client = VersionsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = None - - # get arguments that satisfy an http rule for this method - sample_request = {'name': 'projects/sample1/agent/versions/sample2'} - - # get truthy value for each flattened field - mock_args = dict( - name='name_value', - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = '' - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.delete_version(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v2/{name=projects/*/agent/versions/*}" % client.transport._host, args[1]) - - -def test_delete_version_rest_flattened_error(transport: str = 'rest'): - client = VersionsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # 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', - ) - - -def test_delete_version_rest_error(): - client = VersionsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -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 an api_key and a transport instance. - transport = transports.VersionsGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - options = client_options.ClientOptions() - options.api_key = "api_key" - with pytest.raises(ValueError): - client = VersionsClient( - client_options=options, - transport=transport, - ) - - # It is an error to provide an api_key and a credential. - options = mock.Mock() - options.api_key = "api_key" - with pytest.raises(ValueError): - client = VersionsClient( - client_options=options, - credentials=ga_credentials.AnonymousCredentials() - ) - - # 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, - transports.VersionsRestTransport, -]) -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() - -@pytest.mark.parametrize("transport_name", [ - "grpc", - "rest", -]) -def test_transport_kind(transport_name): - transport = VersionsClient.get_transport_class(transport_name)( - credentials=ga_credentials.AnonymousCredentials(), - ) - assert transport.kind == transport_name - -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', - 'get_location', - 'list_locations', - 'get_operation', - 'cancel_operation', - 'list_operations', - ) - for method in methods: - with pytest.raises(NotImplementedError): - getattr(transport, method)(request=object()) - - with pytest.raises(NotImplementedError): - transport.close() - - # Catch all for all remaining methods and properties - remainder = [ - 'kind', - ] - for r in remainder: - with pytest.raises(NotImplementedError): - getattr(transport, r)() - - -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", - ) - - -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() - - -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, - ) - - -@pytest.mark.parametrize( - "transport_class", - [ - transports.VersionsGrpcTransport, - transports.VersionsGrpcAsyncIOTransport, - ], -) -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, - transports.VersionsRestTransport, - ], -) -def test_versions_transport_auth_gdch_credentials(transport_class): - host = 'https://language.com' - api_audience_tests = [None, 'https://language2.com'] - api_audience_expect = [host, 'https://language2.com'] - for t, e in zip(api_audience_tests, api_audience_expect): - with mock.patch.object(google.auth, 'default', autospec=True) as adc: - gdch_mock = mock.MagicMock() - type(gdch_mock).with_gdch_audience = mock.PropertyMock(return_value=gdch_mock) - adc.return_value = (gdch_mock, None) - transport_class(host=host, api_audience=t) - gdch_mock.with_gdch_audience.assert_called_once_with( - e - ) - - -@pytest.mark.parametrize( - "transport_class,grpc_helpers", - [ - (transports.VersionsGrpcTransport, grpc_helpers), - (transports.VersionsGrpcAsyncIOTransport, grpc_helpers_async) - ], -) -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", [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=None, - ssl_credentials=mock_ssl_channel_creds, - quota_project_id=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - # Check if ssl_channel_credentials is not provided, then client_cert_source_for_mtls - # is used. - with mock.patch.object(transport_class, "create_channel", return_value=mock.Mock()): - with mock.patch("grpc.ssl_channel_credentials") as mock_ssl_cred: - transport_class( - credentials=cred, - client_cert_source_for_mtls=client_cert_source_callback - ) - expected_cert, expected_key = client_cert_source_callback() - mock_ssl_cred.assert_called_once_with( - certificate_chain=expected_cert, - private_key=expected_key - ) - -def test_versions_http_transport_client_cert_source_for_mtls(): - cred = ga_credentials.AnonymousCredentials() - with mock.patch("google.auth.transport.requests.AuthorizedSession.configure_mtls_channel") as mock_configure_mtls_channel: - transports.VersionsRestTransport ( - credentials=cred, - client_cert_source_for_mtls=client_cert_source_callback - ) - mock_configure_mtls_channel.assert_called_once_with(client_cert_source_callback) - - -@pytest.mark.parametrize("transport_name", [ - "grpc", - "grpc_asyncio", - "rest", -]) -def test_versions_host_no_port(transport_name): - client = VersionsClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='dialogflow.googleapis.com'), - transport=transport_name, - ) - assert client.transport._host == ( - 'dialogflow.googleapis.com:443' - if transport_name in ['grpc', 'grpc_asyncio'] - else 'https://dialogflow.googleapis.com' - ) - -@pytest.mark.parametrize("transport_name", [ - "grpc", - "grpc_asyncio", - "rest", -]) -def test_versions_host_with_port(transport_name): - client = VersionsClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='dialogflow.googleapis.com:8000'), - transport=transport_name, - ) - assert client.transport._host == ( - 'dialogflow.googleapis.com:8000' - if transport_name in ['grpc', 'grpc_asyncio'] - else 'https://dialogflow.googleapis.com:8000' - ) - -@pytest.mark.parametrize("transport_name", [ - "rest", -]) -def test_versions_client_transport_session_collision(transport_name): - creds1 = ga_credentials.AnonymousCredentials() - creds2 = ga_credentials.AnonymousCredentials() - client1 = VersionsClient( - credentials=creds1, - transport=transport_name, - ) - client2 = VersionsClient( - credentials=creds2, - transport=transport_name, - ) - session1 = client1.transport.list_versions._session - session2 = client2.transport.list_versions._session - assert session1 != session2 - session1 = client1.transport.get_version._session - session2 = client2.transport.get_version._session - assert session1 != session2 - session1 = client1.transport.create_version._session - session2 = client2.transport.create_version._session - assert session1 != session2 - session1 = client1.transport.update_version._session - session2 = client2.transport.update_version._session - assert session1 != session2 - session1 = client1.transport.delete_version._session - session2 = client2.transport.delete_version._session - assert session1 != session2 -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=None, - ssl_credentials=mock_ssl_cred, - quota_project_id=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - assert transport.grpc_channel == mock_grpc_channel - assert transport._ssl_channel_credentials == mock_ssl_cred - - -# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are -# removed from grpc/grpc_asyncio transport constructor. -@pytest.mark.parametrize("transport_class", [transports.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=None, - ssl_credentials=mock_ssl_cred, - quota_project_id=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - assert transport.grpc_channel == mock_grpc_channel - - -def test_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_with_default_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) - -@pytest.mark.asyncio -async def test_transport_close_async(): - client = VersionsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - with mock.patch.object(type(getattr(client.transport, "grpc_channel")), "close") as close: - async with client: - close.assert_not_called() - close.assert_called_once() - - -def test_get_location_rest_bad_request(transport: str = 'rest', request_type=locations_pb2.GetLocationRequest): - client = VersionsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - request = request_type() - request = json_format.ParseDict({'name': 'projects/sample1/locations/sample2'}, request) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.get_location(request) - -@pytest.mark.parametrize("request_type", [ - locations_pb2.GetLocationRequest, - dict, -]) -def test_get_location_rest(request_type): - client = VersionsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request_init = {'name': 'projects/sample1/locations/sample2'} - request = request_type(**request_init) - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = locations_pb2.Location() - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.get_location(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, locations_pb2.Location) - -def test_list_locations_rest_bad_request(transport: str = 'rest', request_type=locations_pb2.ListLocationsRequest): - client = VersionsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - request = request_type() - request = json_format.ParseDict({'name': 'projects/sample1'}, request) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.list_locations(request) - -@pytest.mark.parametrize("request_type", [ - locations_pb2.ListLocationsRequest, - dict, -]) -def test_list_locations_rest(request_type): - client = VersionsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request_init = {'name': 'projects/sample1'} - request = request_type(**request_init) - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = locations_pb2.ListLocationsResponse() - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.list_locations(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, locations_pb2.ListLocationsResponse) - -def test_cancel_operation_rest_bad_request(transport: str = 'rest', request_type=operations_pb2.CancelOperationRequest): - client = VersionsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - request = request_type() - request = json_format.ParseDict({'name': 'projects/sample1/operations/sample2'}, request) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.cancel_operation(request) - -@pytest.mark.parametrize("request_type", [ - operations_pb2.CancelOperationRequest, - dict, -]) -def test_cancel_operation_rest(request_type): - client = VersionsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request_init = {'name': 'projects/sample1/operations/sample2'} - request = request_type(**request_init) - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = None - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = '{}' - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.cancel_operation(request) - - # Establish that the response is the type that we expect. - assert response is None - -def test_get_operation_rest_bad_request(transport: str = 'rest', request_type=operations_pb2.GetOperationRequest): - client = VersionsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - request = request_type() - request = json_format.ParseDict({'name': 'projects/sample1/operations/sample2'}, request) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.get_operation(request) - -@pytest.mark.parametrize("request_type", [ - operations_pb2.GetOperationRequest, - dict, -]) -def test_get_operation_rest(request_type): - client = VersionsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request_init = {'name': 'projects/sample1/operations/sample2'} - request = request_type(**request_init) - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation() - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.get_operation(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, operations_pb2.Operation) - -def test_list_operations_rest_bad_request(transport: str = 'rest', request_type=operations_pb2.ListOperationsRequest): - client = VersionsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - request = request_type() - request = json_format.ParseDict({'name': 'projects/sample1'}, request) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.list_operations(request) - -@pytest.mark.parametrize("request_type", [ - operations_pb2.ListOperationsRequest, - dict, -]) -def test_list_operations_rest(request_type): - client = VersionsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request_init = {'name': 'projects/sample1'} - request = request_type(**request_init) - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = operations_pb2.ListOperationsResponse() - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.list_operations(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, operations_pb2.ListOperationsResponse) - - -def test_cancel_operation(transport: str = "grpc"): - 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 = operations_pb2.CancelOperationRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = None - response = client.cancel_operation(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 response is the type that we expect. - assert response is None -@pytest.mark.asyncio -async def test_cancel_operation_async(transport: str = "grpc"): - 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 = operations_pb2.CancelOperationRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - None - ) - response = await client.cancel_operation(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 response is the type that we expect. - assert response is None - -def test_cancel_operation_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 = operations_pb2.CancelOperationRequest() - request.name = "locations" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call: - call.return_value = None - - client.cancel_operation(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=locations",) in kw["metadata"] -@pytest.mark.asyncio -async def test_cancel_operation_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 = operations_pb2.CancelOperationRequest() - request.name = "locations" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - None - ) - await client.cancel_operation(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=locations",) in kw["metadata"] - -def test_cancel_operation_from_dict(): - 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.cancel_operation), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = None - - response = client.cancel_operation( - request={ - "name": "locations", - } - ) - call.assert_called() -@pytest.mark.asyncio -async def test_cancel_operation_from_dict_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.cancel_operation), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - None - ) - response = await client.cancel_operation( - request={ - "name": "locations", - } - ) - call.assert_called() - - -def test_get_operation(transport: str = "grpc"): - 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 = operations_pb2.GetOperationRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_operation), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation() - response = client.get_operation(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 response is the type that we expect. - assert isinstance(response, operations_pb2.Operation) -@pytest.mark.asyncio -async def test_get_operation_async(transport: str = "grpc"): - 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 = operations_pb2.GetOperationRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_operation), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation() - ) - response = await client.get_operation(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 response is the type that we expect. - assert isinstance(response, operations_pb2.Operation) - -def test_get_operation_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 = operations_pb2.GetOperationRequest() - request.name = "locations" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_operation), "__call__") as call: - call.return_value = operations_pb2.Operation() - - client.get_operation(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=locations",) in kw["metadata"] -@pytest.mark.asyncio -async def test_get_operation_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 = operations_pb2.GetOperationRequest() - request.name = "locations" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_operation), "__call__") as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation() - ) - await client.get_operation(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=locations",) in kw["metadata"] - -def test_get_operation_from_dict(): - 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_operation), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation() - - response = client.get_operation( - request={ - "name": "locations", - } - ) - call.assert_called() -@pytest.mark.asyncio -async def test_get_operation_from_dict_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_operation), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation() - ) - response = await client.get_operation( - request={ - "name": "locations", - } - ) - call.assert_called() - - -def test_list_operations(transport: str = "grpc"): - 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 = operations_pb2.ListOperationsRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_operations), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.ListOperationsResponse() - response = client.list_operations(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 response is the type that we expect. - assert isinstance(response, operations_pb2.ListOperationsResponse) -@pytest.mark.asyncio -async def test_list_operations_async(transport: str = "grpc"): - 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 = operations_pb2.ListOperationsRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_operations), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.ListOperationsResponse() - ) - response = await client.list_operations(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 response is the type that we expect. - assert isinstance(response, operations_pb2.ListOperationsResponse) - -def test_list_operations_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 = operations_pb2.ListOperationsRequest() - request.name = "locations" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_operations), "__call__") as call: - call.return_value = operations_pb2.ListOperationsResponse() - - client.list_operations(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=locations",) in kw["metadata"] -@pytest.mark.asyncio -async def test_list_operations_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 = operations_pb2.ListOperationsRequest() - request.name = "locations" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_operations), "__call__") as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.ListOperationsResponse() - ) - await client.list_operations(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=locations",) in kw["metadata"] - -def test_list_operations_from_dict(): - 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_operations), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.ListOperationsResponse() - - response = client.list_operations( - request={ - "name": "locations", - } - ) - call.assert_called() -@pytest.mark.asyncio -async def test_list_operations_from_dict_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_operations), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.ListOperationsResponse() - ) - response = await client.list_operations( - request={ - "name": "locations", - } - ) - call.assert_called() - - -def test_list_locations(transport: str = "grpc"): - 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 = locations_pb2.ListLocationsRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_locations), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = locations_pb2.ListLocationsResponse() - response = client.list_locations(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 response is the type that we expect. - assert isinstance(response, locations_pb2.ListLocationsResponse) -@pytest.mark.asyncio -async def test_list_locations_async(transport: str = "grpc"): - 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 = locations_pb2.ListLocationsRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_locations), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - locations_pb2.ListLocationsResponse() - ) - response = await client.list_locations(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 response is the type that we expect. - assert isinstance(response, locations_pb2.ListLocationsResponse) - -def test_list_locations_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 = locations_pb2.ListLocationsRequest() - request.name = "locations" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_locations), "__call__") as call: - call.return_value = locations_pb2.ListLocationsResponse() - - client.list_locations(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=locations",) in kw["metadata"] -@pytest.mark.asyncio -async def test_list_locations_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 = locations_pb2.ListLocationsRequest() - request.name = "locations" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_locations), "__call__") as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - locations_pb2.ListLocationsResponse() - ) - await client.list_locations(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=locations",) in kw["metadata"] - -def test_list_locations_from_dict(): - 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_locations), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = locations_pb2.ListLocationsResponse() - - response = client.list_locations( - request={ - "name": "locations", - } - ) - call.assert_called() -@pytest.mark.asyncio -async def test_list_locations_from_dict_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_locations), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - locations_pb2.ListLocationsResponse() - ) - response = await client.list_locations( - request={ - "name": "locations", - } - ) - call.assert_called() - - -def test_get_location(transport: str = "grpc"): - 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 = locations_pb2.GetLocationRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_location), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = locations_pb2.Location() - response = client.get_location(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 response is the type that we expect. - assert isinstance(response, locations_pb2.Location) -@pytest.mark.asyncio -async def test_get_location_async(transport: str = "grpc_asyncio"): - 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 = locations_pb2.GetLocationRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_location), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - locations_pb2.Location() - ) - response = await client.get_location(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 response is the type that we expect. - assert isinstance(response, locations_pb2.Location) - -def test_get_location_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 = locations_pb2.GetLocationRequest() - request.name = "locations/abc" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_location), "__call__") as call: - call.return_value = locations_pb2.Location() - - client.get_location(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=locations/abc",) in kw["metadata"] -@pytest.mark.asyncio -async def test_get_location_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 = locations_pb2.GetLocationRequest() - request.name = "locations/abc" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_location), "__call__") as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - locations_pb2.Location() - ) - await client.get_location(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=locations/abc",) in kw["metadata"] - -def test_get_location_from_dict(): - 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_locations), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = locations_pb2.Location() - - response = client.get_location( - request={ - "name": "locations/abc", - } - ) - call.assert_called() -@pytest.mark.asyncio -async def test_get_location_from_dict_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_locations), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - locations_pb2.Location() - ) - response = await client.get_location( - request={ - "name": "locations", - } - ) - call.assert_called() - - -def test_transport_close(): - transports = { - "rest": "_session", - "grpc": "_grpc_channel", - } - - for transport, close_name in transports.items(): - client = VersionsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport - ) - with mock.patch.object(type(getattr(client.transport, close_name)), "close") as close: - with client: - close.assert_not_called() - close.assert_called_once() - -def test_client_ctx(): - transports = [ - 'rest', - 'grpc', - ] - for transport in transports: - client = VersionsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport - ) - # Test client calls underlying transport. - with mock.patch.object(type(client.transport), "close") as close: - close.assert_not_called() - with client: - pass - close.assert_called() - -@pytest.mark.parametrize("client_class,transport_class", [ - (VersionsClient, transports.VersionsGrpcTransport), - (VersionsAsyncClient, transports.VersionsGrpcAsyncIOTransport), -]) -def test_api_key_credentials(client_class, transport_class): - with mock.patch.object( - google.auth._default, "get_api_key_credentials", create=True - ) as get_api_key_credentials: - mock_cred = mock.Mock() - get_api_key_credentials.return_value = mock_cred - options = client_options.ClientOptions() - options.api_key = "api_key" - 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=mock_cred, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) diff --git a/owl-bot-staging/v2beta1/.coveragerc b/owl-bot-staging/v2beta1/.coveragerc deleted file mode 100644 index 3e1752c7a..000000000 --- a/owl-bot-staging/v2beta1/.coveragerc +++ /dev/null @@ -1,13 +0,0 @@ -[run] -branch = True - -[report] -show_missing = True -omit = - google/cloud/dialogflow/__init__.py - google/cloud/dialogflow/gapic_version.py -exclude_lines = - # Re-enable the standard pragma - pragma: NO COVER - # Ignore debug-only repr - def __repr__ diff --git a/owl-bot-staging/v2beta1/.flake8 b/owl-bot-staging/v2beta1/.flake8 deleted file mode 100644 index 29227d4cf..000000000 --- a/owl-bot-staging/v2beta1/.flake8 +++ /dev/null @@ -1,33 +0,0 @@ -# -*- 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 -# -# https://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -# Generated by synthtool. DO NOT EDIT! -[flake8] -ignore = E203, E266, E501, W503 -exclude = - # Exclude generated code. - **/proto/** - **/gapic/** - **/services/** - **/types/** - *_pb2.py - - # Standard linting exemptions. - **/.nox/** - __pycache__, - .git, - *.pyc, - conf.py diff --git a/owl-bot-staging/v2beta1/MANIFEST.in b/owl-bot-staging/v2beta1/MANIFEST.in deleted file mode 100644 index a267e6fb4..000000000 --- a/owl-bot-staging/v2beta1/MANIFEST.in +++ /dev/null @@ -1,2 +0,0 @@ -recursive-include google/cloud/dialogflow *.py -recursive-include google/cloud/dialogflow_v2beta1 *.py diff --git a/owl-bot-staging/v2beta1/README.rst b/owl-bot-staging/v2beta1/README.rst deleted file mode 100644 index 6a2fa7289..000000000 --- a/owl-bot-staging/v2beta1/README.rst +++ /dev/null @@ -1,49 +0,0 @@ -Python Client for Google Cloud Dialogflow API -================================================= - -Quick Start ------------ - -In order to use this library, you first need to go through the following steps: - -1. `Select or create a Cloud Platform project.`_ -2. `Enable billing for your project.`_ -3. Enable the Google Cloud Dialogflow API. -4. `Setup Authentication.`_ - -.. _Select or create a Cloud Platform project.: https://console.cloud.google.com/project -.. _Enable billing for your project.: https://cloud.google.com/billing/docs/how-to/modify-project#enable_billing_for_a_project -.. _Setup Authentication.: https://googleapis.dev/python/google-api-core/latest/auth.html - -Installation -~~~~~~~~~~~~ - -Install this library in a `virtualenv`_ using pip. `virtualenv`_ is a tool to -create isolated Python environments. The basic problem it addresses is one of -dependencies and versions, and indirectly permissions. - -With `virtualenv`_, it's possible to install this library without needing system -install permissions, and without clashing with the installed system -dependencies. - -.. _`virtualenv`: https://virtualenv.pypa.io/en/latest/ - - -Mac/Linux -^^^^^^^^^ - -.. code-block:: console - - python3 -m venv - source /bin/activate - /bin/pip install /path/to/library - - -Windows -^^^^^^^ - -.. code-block:: console - - python3 -m venv - \Scripts\activate - \Scripts\pip.exe install \path\to\library diff --git a/owl-bot-staging/v2beta1/docs/conf.py b/owl-bot-staging/v2beta1/docs/conf.py deleted file mode 100644 index 269123c63..000000000 --- a/owl-bot-staging/v2beta1/docs/conf.py +++ /dev/null @@ -1,376 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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. -# -# -# google-cloud-dialogflow documentation build configuration file -# -# This file is execfile()d with the current directory set to its -# containing dir. -# -# Note that not all possible configuration values are present in this -# autogenerated file. -# -# All configuration values have a default; values that are commented out -# serve to show the default. - -import sys -import os -import shlex - -# If extensions (or modules to document with autodoc) are in another directory, -# add these directories to sys.path here. If the directory is relative to the -# documentation root, use os.path.abspath to make it absolute, like shown here. -sys.path.insert(0, os.path.abspath("..")) - -__version__ = "0.1.0" - -# -- General configuration ------------------------------------------------ - -# If your documentation needs a minimal Sphinx version, state it here. -needs_sphinx = "4.0.1" - -# Add any Sphinx extension module names here, as strings. They can be -# extensions coming with Sphinx (named 'sphinx.ext.*') or your custom -# ones. -extensions = [ - "sphinx.ext.autodoc", - "sphinx.ext.autosummary", - "sphinx.ext.intersphinx", - "sphinx.ext.coverage", - "sphinx.ext.napoleon", - "sphinx.ext.todo", - "sphinx.ext.viewcode", -] - -# autodoc/autosummary flags -autoclass_content = "both" -autodoc_default_flags = ["members"] -autosummary_generate = True - - -# Add any paths that contain templates here, relative to this directory. -templates_path = ["_templates"] - -# Allow markdown includes (so releases.md can include CHANGLEOG.md) -# http://www.sphinx-doc.org/en/master/markdown.html -source_parsers = {".md": "recommonmark.parser.CommonMarkParser"} - -# The suffix(es) of source filenames. -# You can specify multiple suffix as a list of string: -source_suffix = [".rst", ".md"] - -# The encoding of source files. -# source_encoding = 'utf-8-sig' - -# The root toctree document. -root_doc = "index" - -# General information about the project. -project = u"google-cloud-dialogflow" -copyright = u"2022, Google, LLC" -author = u"Google APIs" # TODO: autogenerate this bit - -# The version info for the project you're documenting, acts as replacement for -# |version| and |release|, also used in various other places throughout the -# built documents. -# -# The full version, including alpha/beta/rc tags. -release = __version__ -# The short X.Y version. -version = ".".join(release.split(".")[0:2]) - -# The language for content autogenerated by Sphinx. Refer to documentation -# for a list of supported languages. -# -# This is also used if you do content translation via gettext catalogs. -# Usually you set "language" from the command line for these cases. -language = None - -# There are two options for replacing |today|: either, you set today to some -# non-false value, then it is used: -# today = '' -# Else, today_fmt is used as the format for a strftime call. -# today_fmt = '%B %d, %Y' - -# List of patterns, relative to source directory, that match files and -# directories to ignore when looking for source files. -exclude_patterns = ["_build"] - -# The reST default role (used for this markup: `text`) to use for all -# documents. -# default_role = None - -# If true, '()' will be appended to :func: etc. cross-reference text. -# add_function_parentheses = True - -# If true, the current module name will be prepended to all description -# unit titles (such as .. function::). -# add_module_names = True - -# If true, sectionauthor and moduleauthor directives will be shown in the -# output. They are ignored by default. -# show_authors = False - -# The name of the Pygments (syntax highlighting) style to use. -pygments_style = "sphinx" - -# A list of ignored prefixes for module index sorting. -# modindex_common_prefix = [] - -# If true, keep warnings as "system message" paragraphs in the built documents. -# keep_warnings = False - -# If true, `todo` and `todoList` produce output, else they produce nothing. -todo_include_todos = True - - -# -- Options for HTML output ---------------------------------------------- - -# The theme to use for HTML and HTML Help pages. See the documentation for -# a list of builtin themes. -html_theme = "alabaster" - -# Theme options are theme-specific and customize the look and feel of a theme -# further. For a list of options available for each theme, see the -# documentation. -html_theme_options = { - "description": "Google Cloud Client Libraries for Python", - "github_user": "googleapis", - "github_repo": "google-cloud-python", - "github_banner": True, - "font_family": "'Roboto', Georgia, sans", - "head_font_family": "'Roboto', Georgia, serif", - "code_font_family": "'Roboto Mono', 'Consolas', monospace", -} - -# Add any paths that contain custom themes here, relative to this directory. -# html_theme_path = [] - -# The name for this set of Sphinx documents. If None, it defaults to -# " v documentation". -# html_title = None - -# A shorter title for the navigation bar. Default is the same as html_title. -# html_short_title = None - -# The name of an image file (relative to this directory) to place at the top -# of the sidebar. -# html_logo = None - -# The name of an image file (within the static path) to use as favicon of the -# docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32 -# pixels large. -# html_favicon = None - -# Add any paths that contain custom static files (such as style sheets) here, -# relative to this directory. They are copied after the builtin static files, -# so a file named "default.css" will overwrite the builtin "default.css". -html_static_path = ["_static"] - -# Add any extra paths that contain custom files (such as robots.txt or -# .htaccess) here, relative to this directory. These files are copied -# directly to the root of the documentation. -# html_extra_path = [] - -# If not '', a 'Last updated on:' timestamp is inserted at every page bottom, -# using the given strftime format. -# html_last_updated_fmt = '%b %d, %Y' - -# If true, SmartyPants will be used to convert quotes and dashes to -# typographically correct entities. -# html_use_smartypants = True - -# Custom sidebar templates, maps document names to template names. -# html_sidebars = {} - -# Additional templates that should be rendered to pages, maps page names to -# template names. -# html_additional_pages = {} - -# If false, no module index is generated. -# html_domain_indices = True - -# If false, no index is generated. -# html_use_index = True - -# If true, the index is split into individual pages for each letter. -# html_split_index = False - -# If true, links to the reST sources are added to the pages. -# html_show_sourcelink = True - -# If true, "Created using Sphinx" is shown in the HTML footer. Default is True. -# html_show_sphinx = True - -# If true, "(C) Copyright ..." is shown in the HTML footer. Default is True. -# html_show_copyright = True - -# If true, an OpenSearch description file will be output, and all pages will -# contain a tag referring to it. The value of this option must be the -# base URL from which the finished HTML is served. -# html_use_opensearch = '' - -# This is the file name suffix for HTML files (e.g. ".xhtml"). -# html_file_suffix = None - -# Language to be used for generating the HTML full-text search index. -# Sphinx supports the following languages: -# 'da', 'de', 'en', 'es', 'fi', 'fr', 'hu', 'it', 'ja' -# 'nl', 'no', 'pt', 'ro', 'ru', 'sv', 'tr' -# html_search_language = 'en' - -# A dictionary with options for the search language support, empty by default. -# Now only 'ja' uses this config value -# html_search_options = {'type': 'default'} - -# The name of a javascript file (relative to the configuration directory) that -# implements a search results scorer. If empty, the default will be used. -# html_search_scorer = 'scorer.js' - -# Output file base name for HTML help builder. -htmlhelp_basename = "google-cloud-dialogflow-doc" - -# -- Options for warnings ------------------------------------------------------ - - -suppress_warnings = [ - # Temporarily suppress this to avoid "more than one target found for - # cross-reference" warning, which are intractable for us to avoid while in - # a mono-repo. - # See https://github.com/sphinx-doc/sphinx/blob - # /2a65ffeef5c107c19084fabdd706cdff3f52d93c/sphinx/domains/python.py#L843 - "ref.python" -] - -# -- Options for LaTeX output --------------------------------------------- - -latex_elements = { - # The paper size ('letterpaper' or 'a4paper'). - # 'papersize': 'letterpaper', - # The font size ('10pt', '11pt' or '12pt'). - # 'pointsize': '10pt', - # Additional stuff for the LaTeX preamble. - # 'preamble': '', - # Latex figure (float) alignment - # 'figure_align': 'htbp', -} - -# Grouping the document tree into LaTeX files. List of tuples -# (source start file, target name, title, -# author, documentclass [howto, manual, or own class]). -latex_documents = [ - ( - root_doc, - "google-cloud-dialogflow.tex", - u"google-cloud-dialogflow Documentation", - author, - "manual", - ) -] - -# The name of an image file (relative to this directory) to place at the top of -# the title page. -# latex_logo = None - -# For "manual" documents, if this is true, then toplevel headings are parts, -# not chapters. -# latex_use_parts = False - -# If true, show page references after internal links. -# latex_show_pagerefs = False - -# If true, show URL addresses after external links. -# latex_show_urls = False - -# Documents to append as an appendix to all manuals. -# latex_appendices = [] - -# If false, no module index is generated. -# latex_domain_indices = True - - -# -- Options for manual page output --------------------------------------- - -# One entry per manual page. List of tuples -# (source start file, name, description, authors, manual section). -man_pages = [ - ( - root_doc, - "google-cloud-dialogflow", - u"Google Cloud Dialogflow Documentation", - [author], - 1, - ) -] - -# If true, show URL addresses after external links. -# man_show_urls = False - - -# -- Options for Texinfo output ------------------------------------------- - -# Grouping the document tree into Texinfo files. List of tuples -# (source start file, target name, title, author, -# dir menu entry, description, category) -texinfo_documents = [ - ( - root_doc, - "google-cloud-dialogflow", - u"google-cloud-dialogflow Documentation", - author, - "google-cloud-dialogflow", - "GAPIC library for Google Cloud Dialogflow API", - "APIs", - ) -] - -# Documents to append as an appendix to all manuals. -# texinfo_appendices = [] - -# If false, no module index is generated. -# texinfo_domain_indices = True - -# How to display URL addresses: 'footnote', 'no', or 'inline'. -# texinfo_show_urls = 'footnote' - -# If true, do not generate a @detailmenu in the "Top" node's menu. -# texinfo_no_detailmenu = False - - -# Example configuration for intersphinx: refer to the Python standard library. -intersphinx_mapping = { - "python": ("http://python.readthedocs.org/en/latest/", None), - "gax": ("https://gax-python.readthedocs.org/en/latest/", None), - "google-auth": ("https://google-auth.readthedocs.io/en/stable", None), - "google-gax": ("https://gax-python.readthedocs.io/en/latest/", None), - "google.api_core": ("https://googleapis.dev/python/google-api-core/latest/", None), - "grpc": ("https://grpc.io/grpc/python/", None), - "requests": ("http://requests.kennethreitz.org/en/stable/", None), - "proto": ("https://proto-plus-python.readthedocs.io/en/stable", None), - "protobuf": ("https://googleapis.dev/python/protobuf/latest/", None), -} - - -# Napoleon settings -napoleon_google_docstring = True -napoleon_numpy_docstring = True -napoleon_include_private_with_doc = False -napoleon_include_special_with_doc = True -napoleon_use_admonition_for_examples = False -napoleon_use_admonition_for_notes = False -napoleon_use_admonition_for_references = False -napoleon_use_ivar = False -napoleon_use_param = True -napoleon_use_rtype = True diff --git a/owl-bot-staging/v2beta1/docs/dialogflow_v2beta1/agents.rst b/owl-bot-staging/v2beta1/docs/dialogflow_v2beta1/agents.rst deleted file mode 100644 index 154fdf432..000000000 --- a/owl-bot-staging/v2beta1/docs/dialogflow_v2beta1/agents.rst +++ /dev/null @@ -1,10 +0,0 @@ -Agents ------------------------- - -.. automodule:: google.cloud.dialogflow_v2beta1.services.agents - :members: - :inherited-members: - -.. automodule:: google.cloud.dialogflow_v2beta1.services.agents.pagers - :members: - :inherited-members: diff --git a/owl-bot-staging/v2beta1/docs/dialogflow_v2beta1/answer_records.rst b/owl-bot-staging/v2beta1/docs/dialogflow_v2beta1/answer_records.rst deleted file mode 100644 index 1f890c79c..000000000 --- a/owl-bot-staging/v2beta1/docs/dialogflow_v2beta1/answer_records.rst +++ /dev/null @@ -1,10 +0,0 @@ -AnswerRecords -------------------------------- - -.. automodule:: google.cloud.dialogflow_v2beta1.services.answer_records - :members: - :inherited-members: - -.. automodule:: google.cloud.dialogflow_v2beta1.services.answer_records.pagers - :members: - :inherited-members: diff --git a/owl-bot-staging/v2beta1/docs/dialogflow_v2beta1/contexts.rst b/owl-bot-staging/v2beta1/docs/dialogflow_v2beta1/contexts.rst deleted file mode 100644 index e6be19355..000000000 --- a/owl-bot-staging/v2beta1/docs/dialogflow_v2beta1/contexts.rst +++ /dev/null @@ -1,10 +0,0 @@ -Contexts --------------------------- - -.. automodule:: google.cloud.dialogflow_v2beta1.services.contexts - :members: - :inherited-members: - -.. automodule:: google.cloud.dialogflow_v2beta1.services.contexts.pagers - :members: - :inherited-members: diff --git a/owl-bot-staging/v2beta1/docs/dialogflow_v2beta1/conversation_profiles.rst b/owl-bot-staging/v2beta1/docs/dialogflow_v2beta1/conversation_profiles.rst deleted file mode 100644 index 959fe3698..000000000 --- a/owl-bot-staging/v2beta1/docs/dialogflow_v2beta1/conversation_profiles.rst +++ /dev/null @@ -1,10 +0,0 @@ -ConversationProfiles --------------------------------------- - -.. automodule:: google.cloud.dialogflow_v2beta1.services.conversation_profiles - :members: - :inherited-members: - -.. automodule:: google.cloud.dialogflow_v2beta1.services.conversation_profiles.pagers - :members: - :inherited-members: diff --git a/owl-bot-staging/v2beta1/docs/dialogflow_v2beta1/conversations.rst b/owl-bot-staging/v2beta1/docs/dialogflow_v2beta1/conversations.rst deleted file mode 100644 index 60267bd79..000000000 --- a/owl-bot-staging/v2beta1/docs/dialogflow_v2beta1/conversations.rst +++ /dev/null @@ -1,10 +0,0 @@ -Conversations -------------------------------- - -.. automodule:: google.cloud.dialogflow_v2beta1.services.conversations - :members: - :inherited-members: - -.. automodule:: google.cloud.dialogflow_v2beta1.services.conversations.pagers - :members: - :inherited-members: diff --git a/owl-bot-staging/v2beta1/docs/dialogflow_v2beta1/documents.rst b/owl-bot-staging/v2beta1/docs/dialogflow_v2beta1/documents.rst deleted file mode 100644 index 7151feda6..000000000 --- a/owl-bot-staging/v2beta1/docs/dialogflow_v2beta1/documents.rst +++ /dev/null @@ -1,10 +0,0 @@ -Documents ---------------------------- - -.. automodule:: google.cloud.dialogflow_v2beta1.services.documents - :members: - :inherited-members: - -.. automodule:: google.cloud.dialogflow_v2beta1.services.documents.pagers - :members: - :inherited-members: diff --git a/owl-bot-staging/v2beta1/docs/dialogflow_v2beta1/entity_types.rst b/owl-bot-staging/v2beta1/docs/dialogflow_v2beta1/entity_types.rst deleted file mode 100644 index 99defb836..000000000 --- a/owl-bot-staging/v2beta1/docs/dialogflow_v2beta1/entity_types.rst +++ /dev/null @@ -1,10 +0,0 @@ -EntityTypes ------------------------------ - -.. automodule:: google.cloud.dialogflow_v2beta1.services.entity_types - :members: - :inherited-members: - -.. automodule:: google.cloud.dialogflow_v2beta1.services.entity_types.pagers - :members: - :inherited-members: diff --git a/owl-bot-staging/v2beta1/docs/dialogflow_v2beta1/environments.rst b/owl-bot-staging/v2beta1/docs/dialogflow_v2beta1/environments.rst deleted file mode 100644 index 3c4d6f333..000000000 --- a/owl-bot-staging/v2beta1/docs/dialogflow_v2beta1/environments.rst +++ /dev/null @@ -1,10 +0,0 @@ -Environments ------------------------------- - -.. automodule:: google.cloud.dialogflow_v2beta1.services.environments - :members: - :inherited-members: - -.. automodule:: google.cloud.dialogflow_v2beta1.services.environments.pagers - :members: - :inherited-members: diff --git a/owl-bot-staging/v2beta1/docs/dialogflow_v2beta1/fulfillments.rst b/owl-bot-staging/v2beta1/docs/dialogflow_v2beta1/fulfillments.rst deleted file mode 100644 index 33be7d8a0..000000000 --- a/owl-bot-staging/v2beta1/docs/dialogflow_v2beta1/fulfillments.rst +++ /dev/null @@ -1,6 +0,0 @@ -Fulfillments ------------------------------- - -.. automodule:: google.cloud.dialogflow_v2beta1.services.fulfillments - :members: - :inherited-members: diff --git a/owl-bot-staging/v2beta1/docs/dialogflow_v2beta1/intents.rst b/owl-bot-staging/v2beta1/docs/dialogflow_v2beta1/intents.rst deleted file mode 100644 index 50e85e80d..000000000 --- a/owl-bot-staging/v2beta1/docs/dialogflow_v2beta1/intents.rst +++ /dev/null @@ -1,10 +0,0 @@ -Intents -------------------------- - -.. automodule:: google.cloud.dialogflow_v2beta1.services.intents - :members: - :inherited-members: - -.. automodule:: google.cloud.dialogflow_v2beta1.services.intents.pagers - :members: - :inherited-members: diff --git a/owl-bot-staging/v2beta1/docs/dialogflow_v2beta1/knowledge_bases.rst b/owl-bot-staging/v2beta1/docs/dialogflow_v2beta1/knowledge_bases.rst deleted file mode 100644 index 70e0d5ab6..000000000 --- a/owl-bot-staging/v2beta1/docs/dialogflow_v2beta1/knowledge_bases.rst +++ /dev/null @@ -1,10 +0,0 @@ -KnowledgeBases --------------------------------- - -.. automodule:: google.cloud.dialogflow_v2beta1.services.knowledge_bases - :members: - :inherited-members: - -.. automodule:: google.cloud.dialogflow_v2beta1.services.knowledge_bases.pagers - :members: - :inherited-members: diff --git a/owl-bot-staging/v2beta1/docs/dialogflow_v2beta1/participants.rst b/owl-bot-staging/v2beta1/docs/dialogflow_v2beta1/participants.rst deleted file mode 100644 index b2a73ebe3..000000000 --- a/owl-bot-staging/v2beta1/docs/dialogflow_v2beta1/participants.rst +++ /dev/null @@ -1,10 +0,0 @@ -Participants ------------------------------- - -.. automodule:: google.cloud.dialogflow_v2beta1.services.participants - :members: - :inherited-members: - -.. automodule:: google.cloud.dialogflow_v2beta1.services.participants.pagers - :members: - :inherited-members: diff --git a/owl-bot-staging/v2beta1/docs/dialogflow_v2beta1/services.rst b/owl-bot-staging/v2beta1/docs/dialogflow_v2beta1/services.rst deleted file mode 100644 index dc7790aa3..000000000 --- a/owl-bot-staging/v2beta1/docs/dialogflow_v2beta1/services.rst +++ /dev/null @@ -1,20 +0,0 @@ -Services for Google Cloud Dialogflow v2beta1 API -================================================ -.. toctree:: - :maxdepth: 2 - - agents - answer_records - contexts - conversation_profiles - conversations - documents - entity_types - environments - fulfillments - intents - knowledge_bases - participants - session_entity_types - sessions - versions diff --git a/owl-bot-staging/v2beta1/docs/dialogflow_v2beta1/session_entity_types.rst b/owl-bot-staging/v2beta1/docs/dialogflow_v2beta1/session_entity_types.rst deleted file mode 100644 index 4fe3bcb31..000000000 --- a/owl-bot-staging/v2beta1/docs/dialogflow_v2beta1/session_entity_types.rst +++ /dev/null @@ -1,10 +0,0 @@ -SessionEntityTypes ------------------------------------- - -.. automodule:: google.cloud.dialogflow_v2beta1.services.session_entity_types - :members: - :inherited-members: - -.. automodule:: google.cloud.dialogflow_v2beta1.services.session_entity_types.pagers - :members: - :inherited-members: diff --git a/owl-bot-staging/v2beta1/docs/dialogflow_v2beta1/sessions.rst b/owl-bot-staging/v2beta1/docs/dialogflow_v2beta1/sessions.rst deleted file mode 100644 index da6517c63..000000000 --- a/owl-bot-staging/v2beta1/docs/dialogflow_v2beta1/sessions.rst +++ /dev/null @@ -1,6 +0,0 @@ -Sessions --------------------------- - -.. automodule:: google.cloud.dialogflow_v2beta1.services.sessions - :members: - :inherited-members: diff --git a/owl-bot-staging/v2beta1/docs/dialogflow_v2beta1/types.rst b/owl-bot-staging/v2beta1/docs/dialogflow_v2beta1/types.rst deleted file mode 100644 index e50759342..000000000 --- a/owl-bot-staging/v2beta1/docs/dialogflow_v2beta1/types.rst +++ /dev/null @@ -1,6 +0,0 @@ -Types for Google Cloud Dialogflow v2beta1 API -============================================= - -.. automodule:: google.cloud.dialogflow_v2beta1.types - :members: - :show-inheritance: diff --git a/owl-bot-staging/v2beta1/docs/dialogflow_v2beta1/versions.rst b/owl-bot-staging/v2beta1/docs/dialogflow_v2beta1/versions.rst deleted file mode 100644 index c74ba0edf..000000000 --- a/owl-bot-staging/v2beta1/docs/dialogflow_v2beta1/versions.rst +++ /dev/null @@ -1,10 +0,0 @@ -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/owl-bot-staging/v2beta1/docs/index.rst b/owl-bot-staging/v2beta1/docs/index.rst deleted file mode 100644 index ffce78914..000000000 --- a/owl-bot-staging/v2beta1/docs/index.rst +++ /dev/null @@ -1,7 +0,0 @@ -API Reference -------------- -.. toctree:: - :maxdepth: 2 - - dialogflow_v2beta1/services - dialogflow_v2beta1/types diff --git a/owl-bot-staging/v2beta1/google/cloud/dialogflow/__init__.py b/owl-bot-staging/v2beta1/google/cloud/dialogflow/__init__.py deleted file mode 100644 index a227c27ef..000000000 --- a/owl-bot-staging/v2beta1/google/cloud/dialogflow/__init__.py +++ /dev/null @@ -1,495 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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 google.cloud.dialogflow import gapic_version as package_version - -__version__ = package_version.__version__ - - -from google.cloud.dialogflow_v2beta1.services.agents.client import AgentsClient -from google.cloud.dialogflow_v2beta1.services.agents.async_client import AgentsAsyncClient -from google.cloud.dialogflow_v2beta1.services.answer_records.client import AnswerRecordsClient -from google.cloud.dialogflow_v2beta1.services.answer_records.async_client import AnswerRecordsAsyncClient -from google.cloud.dialogflow_v2beta1.services.contexts.client import ContextsClient -from google.cloud.dialogflow_v2beta1.services.contexts.async_client import ContextsAsyncClient -from google.cloud.dialogflow_v2beta1.services.conversation_profiles.client import ConversationProfilesClient -from google.cloud.dialogflow_v2beta1.services.conversation_profiles.async_client import ConversationProfilesAsyncClient -from google.cloud.dialogflow_v2beta1.services.conversations.client import ConversationsClient -from google.cloud.dialogflow_v2beta1.services.conversations.async_client import ConversationsAsyncClient -from google.cloud.dialogflow_v2beta1.services.documents.client import DocumentsClient -from google.cloud.dialogflow_v2beta1.services.documents.async_client import DocumentsAsyncClient -from google.cloud.dialogflow_v2beta1.services.entity_types.client import EntityTypesClient -from google.cloud.dialogflow_v2beta1.services.entity_types.async_client import EntityTypesAsyncClient -from google.cloud.dialogflow_v2beta1.services.environments.client import EnvironmentsClient -from google.cloud.dialogflow_v2beta1.services.environments.async_client import EnvironmentsAsyncClient -from google.cloud.dialogflow_v2beta1.services.fulfillments.client import FulfillmentsClient -from google.cloud.dialogflow_v2beta1.services.fulfillments.async_client import FulfillmentsAsyncClient -from google.cloud.dialogflow_v2beta1.services.intents.client import IntentsClient -from google.cloud.dialogflow_v2beta1.services.intents.async_client import IntentsAsyncClient -from google.cloud.dialogflow_v2beta1.services.knowledge_bases.client import KnowledgeBasesClient -from google.cloud.dialogflow_v2beta1.services.knowledge_bases.async_client import KnowledgeBasesAsyncClient -from google.cloud.dialogflow_v2beta1.services.participants.client import ParticipantsClient -from google.cloud.dialogflow_v2beta1.services.participants.async_client import ParticipantsAsyncClient -from google.cloud.dialogflow_v2beta1.services.session_entity_types.client import SessionEntityTypesClient -from google.cloud.dialogflow_v2beta1.services.session_entity_types.async_client import SessionEntityTypesAsyncClient -from google.cloud.dialogflow_v2beta1.services.sessions.client import SessionsClient -from google.cloud.dialogflow_v2beta1.services.sessions.async_client import SessionsAsyncClient -from google.cloud.dialogflow_v2beta1.services.versions.client import VersionsClient -from google.cloud.dialogflow_v2beta1.services.versions.async_client import VersionsAsyncClient - -from google.cloud.dialogflow_v2beta1.types.agent import Agent -from google.cloud.dialogflow_v2beta1.types.agent import DeleteAgentRequest -from google.cloud.dialogflow_v2beta1.types.agent import ExportAgentRequest -from google.cloud.dialogflow_v2beta1.types.agent import ExportAgentResponse -from google.cloud.dialogflow_v2beta1.types.agent import GetAgentRequest -from google.cloud.dialogflow_v2beta1.types.agent import GetValidationResultRequest -from google.cloud.dialogflow_v2beta1.types.agent import ImportAgentRequest -from google.cloud.dialogflow_v2beta1.types.agent import RestoreAgentRequest -from google.cloud.dialogflow_v2beta1.types.agent import SearchAgentsRequest -from google.cloud.dialogflow_v2beta1.types.agent import SearchAgentsResponse -from google.cloud.dialogflow_v2beta1.types.agent import SetAgentRequest -from google.cloud.dialogflow_v2beta1.types.agent import SubAgent -from google.cloud.dialogflow_v2beta1.types.agent import TrainAgentRequest -from google.cloud.dialogflow_v2beta1.types.answer_record import AgentAssistantFeedback -from google.cloud.dialogflow_v2beta1.types.answer_record import AgentAssistantRecord -from google.cloud.dialogflow_v2beta1.types.answer_record import AnswerFeedback -from google.cloud.dialogflow_v2beta1.types.answer_record import AnswerRecord -from google.cloud.dialogflow_v2beta1.types.answer_record import GetAnswerRecordRequest -from google.cloud.dialogflow_v2beta1.types.answer_record import ListAnswerRecordsRequest -from google.cloud.dialogflow_v2beta1.types.answer_record import ListAnswerRecordsResponse -from google.cloud.dialogflow_v2beta1.types.answer_record import UpdateAnswerRecordRequest -from google.cloud.dialogflow_v2beta1.types.audio_config import BargeInConfig -from google.cloud.dialogflow_v2beta1.types.audio_config import InputAudioConfig -from google.cloud.dialogflow_v2beta1.types.audio_config import OutputAudioConfig -from google.cloud.dialogflow_v2beta1.types.audio_config import SpeechContext -from google.cloud.dialogflow_v2beta1.types.audio_config import SpeechToTextConfig -from google.cloud.dialogflow_v2beta1.types.audio_config import SpeechWordInfo -from google.cloud.dialogflow_v2beta1.types.audio_config import SynthesizeSpeechConfig -from google.cloud.dialogflow_v2beta1.types.audio_config import TelephonyDtmfEvents -from google.cloud.dialogflow_v2beta1.types.audio_config import VoiceSelectionParams -from google.cloud.dialogflow_v2beta1.types.audio_config import AudioEncoding -from google.cloud.dialogflow_v2beta1.types.audio_config import OutputAudioEncoding -from google.cloud.dialogflow_v2beta1.types.audio_config import SpeechModelVariant -from google.cloud.dialogflow_v2beta1.types.audio_config import SsmlVoiceGender -from google.cloud.dialogflow_v2beta1.types.audio_config import TelephonyDtmf -from google.cloud.dialogflow_v2beta1.types.context import Context -from google.cloud.dialogflow_v2beta1.types.context import CreateContextRequest -from google.cloud.dialogflow_v2beta1.types.context import DeleteAllContextsRequest -from google.cloud.dialogflow_v2beta1.types.context import DeleteContextRequest -from google.cloud.dialogflow_v2beta1.types.context import GetContextRequest -from google.cloud.dialogflow_v2beta1.types.context import ListContextsRequest -from google.cloud.dialogflow_v2beta1.types.context import ListContextsResponse -from google.cloud.dialogflow_v2beta1.types.context import UpdateContextRequest -from google.cloud.dialogflow_v2beta1.types.conversation import BatchCreateMessagesRequest -from google.cloud.dialogflow_v2beta1.types.conversation import BatchCreateMessagesResponse -from google.cloud.dialogflow_v2beta1.types.conversation import CompleteConversationRequest -from google.cloud.dialogflow_v2beta1.types.conversation import Conversation -from google.cloud.dialogflow_v2beta1.types.conversation import ConversationPhoneNumber -from google.cloud.dialogflow_v2beta1.types.conversation import CreateConversationRequest -from google.cloud.dialogflow_v2beta1.types.conversation import CreateMessageRequest -from google.cloud.dialogflow_v2beta1.types.conversation import GetConversationRequest -from google.cloud.dialogflow_v2beta1.types.conversation import ListConversationsRequest -from google.cloud.dialogflow_v2beta1.types.conversation import ListConversationsResponse -from google.cloud.dialogflow_v2beta1.types.conversation import ListMessagesRequest -from google.cloud.dialogflow_v2beta1.types.conversation import ListMessagesResponse -from google.cloud.dialogflow_v2beta1.types.conversation import SuggestConversationSummaryRequest -from google.cloud.dialogflow_v2beta1.types.conversation import SuggestConversationSummaryResponse -from google.cloud.dialogflow_v2beta1.types.conversation_event import ConversationEvent -from google.cloud.dialogflow_v2beta1.types.conversation_profile import AutomatedAgentConfig -from google.cloud.dialogflow_v2beta1.types.conversation_profile import ClearSuggestionFeatureConfigOperationMetadata -from google.cloud.dialogflow_v2beta1.types.conversation_profile import ClearSuggestionFeatureConfigRequest -from google.cloud.dialogflow_v2beta1.types.conversation_profile import ConversationProfile -from google.cloud.dialogflow_v2beta1.types.conversation_profile import CreateConversationProfileRequest -from google.cloud.dialogflow_v2beta1.types.conversation_profile import DeleteConversationProfileRequest -from google.cloud.dialogflow_v2beta1.types.conversation_profile import GetConversationProfileRequest -from google.cloud.dialogflow_v2beta1.types.conversation_profile import HumanAgentAssistantConfig -from google.cloud.dialogflow_v2beta1.types.conversation_profile import HumanAgentHandoffConfig -from google.cloud.dialogflow_v2beta1.types.conversation_profile import ListConversationProfilesRequest -from google.cloud.dialogflow_v2beta1.types.conversation_profile import ListConversationProfilesResponse -from google.cloud.dialogflow_v2beta1.types.conversation_profile import LoggingConfig -from google.cloud.dialogflow_v2beta1.types.conversation_profile import NotificationConfig -from google.cloud.dialogflow_v2beta1.types.conversation_profile import SetSuggestionFeatureConfigOperationMetadata -from google.cloud.dialogflow_v2beta1.types.conversation_profile import SetSuggestionFeatureConfigRequest -from google.cloud.dialogflow_v2beta1.types.conversation_profile import UpdateConversationProfileRequest -from google.cloud.dialogflow_v2beta1.types.document import CreateDocumentRequest -from google.cloud.dialogflow_v2beta1.types.document import DeleteDocumentRequest -from google.cloud.dialogflow_v2beta1.types.document import Document -from google.cloud.dialogflow_v2beta1.types.document import ExportOperationMetadata -from google.cloud.dialogflow_v2beta1.types.document import GetDocumentRequest -from google.cloud.dialogflow_v2beta1.types.document import ImportDocumentsRequest -from google.cloud.dialogflow_v2beta1.types.document import ImportDocumentsResponse -from google.cloud.dialogflow_v2beta1.types.document import ImportDocumentTemplate -from google.cloud.dialogflow_v2beta1.types.document import KnowledgeOperationMetadata -from google.cloud.dialogflow_v2beta1.types.document import ListDocumentsRequest -from google.cloud.dialogflow_v2beta1.types.document import ListDocumentsResponse -from google.cloud.dialogflow_v2beta1.types.document import ReloadDocumentRequest -from google.cloud.dialogflow_v2beta1.types.document import UpdateDocumentRequest -from google.cloud.dialogflow_v2beta1.types.entity_type import BatchCreateEntitiesRequest -from google.cloud.dialogflow_v2beta1.types.entity_type import BatchDeleteEntitiesRequest -from google.cloud.dialogflow_v2beta1.types.entity_type import BatchDeleteEntityTypesRequest -from google.cloud.dialogflow_v2beta1.types.entity_type import BatchUpdateEntitiesRequest -from google.cloud.dialogflow_v2beta1.types.entity_type import BatchUpdateEntityTypesRequest -from google.cloud.dialogflow_v2beta1.types.entity_type import BatchUpdateEntityTypesResponse -from google.cloud.dialogflow_v2beta1.types.entity_type import CreateEntityTypeRequest -from google.cloud.dialogflow_v2beta1.types.entity_type import DeleteEntityTypeRequest -from google.cloud.dialogflow_v2beta1.types.entity_type import EntityType -from google.cloud.dialogflow_v2beta1.types.entity_type import EntityTypeBatch -from google.cloud.dialogflow_v2beta1.types.entity_type import GetEntityTypeRequest -from google.cloud.dialogflow_v2beta1.types.entity_type import ListEntityTypesRequest -from google.cloud.dialogflow_v2beta1.types.entity_type import ListEntityTypesResponse -from google.cloud.dialogflow_v2beta1.types.entity_type import UpdateEntityTypeRequest -from google.cloud.dialogflow_v2beta1.types.environment import CreateEnvironmentRequest -from google.cloud.dialogflow_v2beta1.types.environment import DeleteEnvironmentRequest -from google.cloud.dialogflow_v2beta1.types.environment import Environment -from google.cloud.dialogflow_v2beta1.types.environment import EnvironmentHistory -from google.cloud.dialogflow_v2beta1.types.environment import GetEnvironmentHistoryRequest -from google.cloud.dialogflow_v2beta1.types.environment import GetEnvironmentRequest -from google.cloud.dialogflow_v2beta1.types.environment import ListEnvironmentsRequest -from google.cloud.dialogflow_v2beta1.types.environment import ListEnvironmentsResponse -from google.cloud.dialogflow_v2beta1.types.environment import TextToSpeechSettings -from google.cloud.dialogflow_v2beta1.types.environment import UpdateEnvironmentRequest -from google.cloud.dialogflow_v2beta1.types.fulfillment import Fulfillment -from google.cloud.dialogflow_v2beta1.types.fulfillment import GetFulfillmentRequest -from google.cloud.dialogflow_v2beta1.types.fulfillment import UpdateFulfillmentRequest -from google.cloud.dialogflow_v2beta1.types.gcs import GcsDestination -from google.cloud.dialogflow_v2beta1.types.gcs import GcsSource -from google.cloud.dialogflow_v2beta1.types.gcs import GcsSources -from google.cloud.dialogflow_v2beta1.types.human_agent_assistant_event import HumanAgentAssistantEvent -from google.cloud.dialogflow_v2beta1.types.intent import BatchDeleteIntentsRequest -from google.cloud.dialogflow_v2beta1.types.intent import BatchUpdateIntentsRequest -from google.cloud.dialogflow_v2beta1.types.intent import BatchUpdateIntentsResponse -from google.cloud.dialogflow_v2beta1.types.intent import CreateIntentRequest -from google.cloud.dialogflow_v2beta1.types.intent import DeleteIntentRequest -from google.cloud.dialogflow_v2beta1.types.intent import GetIntentRequest -from google.cloud.dialogflow_v2beta1.types.intent import Intent -from google.cloud.dialogflow_v2beta1.types.intent import IntentBatch -from google.cloud.dialogflow_v2beta1.types.intent import ListIntentsRequest -from google.cloud.dialogflow_v2beta1.types.intent import ListIntentsResponse -from google.cloud.dialogflow_v2beta1.types.intent import UpdateIntentRequest -from google.cloud.dialogflow_v2beta1.types.intent import IntentView -from google.cloud.dialogflow_v2beta1.types.knowledge_base import CreateKnowledgeBaseRequest -from google.cloud.dialogflow_v2beta1.types.knowledge_base import DeleteKnowledgeBaseRequest -from google.cloud.dialogflow_v2beta1.types.knowledge_base import GetKnowledgeBaseRequest -from google.cloud.dialogflow_v2beta1.types.knowledge_base import KnowledgeBase -from google.cloud.dialogflow_v2beta1.types.knowledge_base import ListKnowledgeBasesRequest -from google.cloud.dialogflow_v2beta1.types.knowledge_base import ListKnowledgeBasesResponse -from google.cloud.dialogflow_v2beta1.types.knowledge_base import UpdateKnowledgeBaseRequest -from google.cloud.dialogflow_v2beta1.types.participant import AnalyzeContentRequest -from google.cloud.dialogflow_v2beta1.types.participant import AnalyzeContentResponse -from google.cloud.dialogflow_v2beta1.types.participant import AnnotatedMessagePart -from google.cloud.dialogflow_v2beta1.types.participant import ArticleAnswer -from google.cloud.dialogflow_v2beta1.types.participant import AssistQueryParameters -from google.cloud.dialogflow_v2beta1.types.participant import AudioInput -from google.cloud.dialogflow_v2beta1.types.participant import AutomatedAgentReply -from google.cloud.dialogflow_v2beta1.types.participant import CompileSuggestionRequest -from google.cloud.dialogflow_v2beta1.types.participant import CompileSuggestionResponse -from google.cloud.dialogflow_v2beta1.types.participant import CreateParticipantRequest -from google.cloud.dialogflow_v2beta1.types.participant import DtmfParameters -from google.cloud.dialogflow_v2beta1.types.participant import FaqAnswer -from google.cloud.dialogflow_v2beta1.types.participant import GetParticipantRequest -from google.cloud.dialogflow_v2beta1.types.participant import InputTextConfig -from google.cloud.dialogflow_v2beta1.types.participant import ListParticipantsRequest -from google.cloud.dialogflow_v2beta1.types.participant import ListParticipantsResponse -from google.cloud.dialogflow_v2beta1.types.participant import ListSuggestionsRequest -from google.cloud.dialogflow_v2beta1.types.participant import ListSuggestionsResponse -from google.cloud.dialogflow_v2beta1.types.participant import Message -from google.cloud.dialogflow_v2beta1.types.participant import MessageAnnotation -from google.cloud.dialogflow_v2beta1.types.participant import OutputAudio -from google.cloud.dialogflow_v2beta1.types.participant import Participant -from google.cloud.dialogflow_v2beta1.types.participant import ResponseMessage -from google.cloud.dialogflow_v2beta1.types.participant import SmartReplyAnswer -from google.cloud.dialogflow_v2beta1.types.participant import StreamingAnalyzeContentRequest -from google.cloud.dialogflow_v2beta1.types.participant import StreamingAnalyzeContentResponse -from google.cloud.dialogflow_v2beta1.types.participant import SuggestArticlesRequest -from google.cloud.dialogflow_v2beta1.types.participant import SuggestArticlesResponse -from google.cloud.dialogflow_v2beta1.types.participant import SuggestFaqAnswersRequest -from google.cloud.dialogflow_v2beta1.types.participant import SuggestFaqAnswersResponse -from google.cloud.dialogflow_v2beta1.types.participant import Suggestion -from google.cloud.dialogflow_v2beta1.types.participant import SuggestionFeature -from google.cloud.dialogflow_v2beta1.types.participant import SuggestionResult -from google.cloud.dialogflow_v2beta1.types.participant import SuggestSmartRepliesRequest -from google.cloud.dialogflow_v2beta1.types.participant import SuggestSmartRepliesResponse -from google.cloud.dialogflow_v2beta1.types.participant import UpdateParticipantRequest -from google.cloud.dialogflow_v2beta1.types.session import DetectIntentRequest -from google.cloud.dialogflow_v2beta1.types.session import DetectIntentResponse -from google.cloud.dialogflow_v2beta1.types.session import EventInput -from google.cloud.dialogflow_v2beta1.types.session import KnowledgeAnswers -from google.cloud.dialogflow_v2beta1.types.session import QueryInput -from google.cloud.dialogflow_v2beta1.types.session import QueryParameters -from google.cloud.dialogflow_v2beta1.types.session import QueryResult -from google.cloud.dialogflow_v2beta1.types.session import Sentiment -from google.cloud.dialogflow_v2beta1.types.session import SentimentAnalysisRequestConfig -from google.cloud.dialogflow_v2beta1.types.session import SentimentAnalysisResult -from google.cloud.dialogflow_v2beta1.types.session import StreamingDetectIntentRequest -from google.cloud.dialogflow_v2beta1.types.session import StreamingDetectIntentResponse -from google.cloud.dialogflow_v2beta1.types.session import StreamingRecognitionResult -from google.cloud.dialogflow_v2beta1.types.session import TextInput -from google.cloud.dialogflow_v2beta1.types.session_entity_type import CreateSessionEntityTypeRequest -from google.cloud.dialogflow_v2beta1.types.session_entity_type import DeleteSessionEntityTypeRequest -from google.cloud.dialogflow_v2beta1.types.session_entity_type import GetSessionEntityTypeRequest -from google.cloud.dialogflow_v2beta1.types.session_entity_type import ListSessionEntityTypesRequest -from google.cloud.dialogflow_v2beta1.types.session_entity_type import ListSessionEntityTypesResponse -from google.cloud.dialogflow_v2beta1.types.session_entity_type import SessionEntityType -from google.cloud.dialogflow_v2beta1.types.session_entity_type import UpdateSessionEntityTypeRequest -from google.cloud.dialogflow_v2beta1.types.validation_result import ValidationError -from google.cloud.dialogflow_v2beta1.types.validation_result import ValidationResult -from google.cloud.dialogflow_v2beta1.types.version import CreateVersionRequest -from google.cloud.dialogflow_v2beta1.types.version import DeleteVersionRequest -from google.cloud.dialogflow_v2beta1.types.version import GetVersionRequest -from google.cloud.dialogflow_v2beta1.types.version import ListVersionsRequest -from google.cloud.dialogflow_v2beta1.types.version import ListVersionsResponse -from google.cloud.dialogflow_v2beta1.types.version import UpdateVersionRequest -from google.cloud.dialogflow_v2beta1.types.version import Version -from google.cloud.dialogflow_v2beta1.types.webhook import OriginalDetectIntentRequest -from google.cloud.dialogflow_v2beta1.types.webhook import WebhookRequest -from google.cloud.dialogflow_v2beta1.types.webhook import WebhookResponse - -__all__ = ('AgentsClient', - 'AgentsAsyncClient', - 'AnswerRecordsClient', - 'AnswerRecordsAsyncClient', - 'ContextsClient', - 'ContextsAsyncClient', - 'ConversationProfilesClient', - 'ConversationProfilesAsyncClient', - 'ConversationsClient', - 'ConversationsAsyncClient', - 'DocumentsClient', - 'DocumentsAsyncClient', - 'EntityTypesClient', - 'EntityTypesAsyncClient', - 'EnvironmentsClient', - 'EnvironmentsAsyncClient', - 'FulfillmentsClient', - 'FulfillmentsAsyncClient', - 'IntentsClient', - 'IntentsAsyncClient', - 'KnowledgeBasesClient', - 'KnowledgeBasesAsyncClient', - 'ParticipantsClient', - 'ParticipantsAsyncClient', - 'SessionEntityTypesClient', - 'SessionEntityTypesAsyncClient', - 'SessionsClient', - 'SessionsAsyncClient', - 'VersionsClient', - 'VersionsAsyncClient', - 'Agent', - 'DeleteAgentRequest', - 'ExportAgentRequest', - 'ExportAgentResponse', - 'GetAgentRequest', - 'GetValidationResultRequest', - 'ImportAgentRequest', - 'RestoreAgentRequest', - 'SearchAgentsRequest', - 'SearchAgentsResponse', - 'SetAgentRequest', - 'SubAgent', - 'TrainAgentRequest', - 'AgentAssistantFeedback', - 'AgentAssistantRecord', - 'AnswerFeedback', - 'AnswerRecord', - 'GetAnswerRecordRequest', - 'ListAnswerRecordsRequest', - 'ListAnswerRecordsResponse', - 'UpdateAnswerRecordRequest', - 'BargeInConfig', - 'InputAudioConfig', - 'OutputAudioConfig', - 'SpeechContext', - 'SpeechToTextConfig', - 'SpeechWordInfo', - 'SynthesizeSpeechConfig', - 'TelephonyDtmfEvents', - 'VoiceSelectionParams', - 'AudioEncoding', - 'OutputAudioEncoding', - 'SpeechModelVariant', - 'SsmlVoiceGender', - 'TelephonyDtmf', - 'Context', - 'CreateContextRequest', - 'DeleteAllContextsRequest', - 'DeleteContextRequest', - 'GetContextRequest', - 'ListContextsRequest', - 'ListContextsResponse', - 'UpdateContextRequest', - 'BatchCreateMessagesRequest', - 'BatchCreateMessagesResponse', - 'CompleteConversationRequest', - 'Conversation', - 'ConversationPhoneNumber', - 'CreateConversationRequest', - 'CreateMessageRequest', - 'GetConversationRequest', - 'ListConversationsRequest', - 'ListConversationsResponse', - 'ListMessagesRequest', - 'ListMessagesResponse', - 'SuggestConversationSummaryRequest', - 'SuggestConversationSummaryResponse', - 'ConversationEvent', - 'AutomatedAgentConfig', - 'ClearSuggestionFeatureConfigOperationMetadata', - 'ClearSuggestionFeatureConfigRequest', - 'ConversationProfile', - 'CreateConversationProfileRequest', - 'DeleteConversationProfileRequest', - 'GetConversationProfileRequest', - 'HumanAgentAssistantConfig', - 'HumanAgentHandoffConfig', - 'ListConversationProfilesRequest', - 'ListConversationProfilesResponse', - 'LoggingConfig', - 'NotificationConfig', - 'SetSuggestionFeatureConfigOperationMetadata', - 'SetSuggestionFeatureConfigRequest', - 'UpdateConversationProfileRequest', - 'CreateDocumentRequest', - 'DeleteDocumentRequest', - 'Document', - 'ExportOperationMetadata', - 'GetDocumentRequest', - 'ImportDocumentsRequest', - 'ImportDocumentsResponse', - 'ImportDocumentTemplate', - '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', - 'GcsDestination', - 'GcsSource', - 'GcsSources', - 'HumanAgentAssistantEvent', - 'BatchDeleteIntentsRequest', - 'BatchUpdateIntentsRequest', - 'BatchUpdateIntentsResponse', - 'CreateIntentRequest', - 'DeleteIntentRequest', - 'GetIntentRequest', - 'Intent', - 'IntentBatch', - 'ListIntentsRequest', - 'ListIntentsResponse', - 'UpdateIntentRequest', - 'IntentView', - 'CreateKnowledgeBaseRequest', - 'DeleteKnowledgeBaseRequest', - 'GetKnowledgeBaseRequest', - 'KnowledgeBase', - 'ListKnowledgeBasesRequest', - 'ListKnowledgeBasesResponse', - 'UpdateKnowledgeBaseRequest', - 'AnalyzeContentRequest', - 'AnalyzeContentResponse', - 'AnnotatedMessagePart', - 'ArticleAnswer', - 'AssistQueryParameters', - 'AudioInput', - 'AutomatedAgentReply', - 'CompileSuggestionRequest', - 'CompileSuggestionResponse', - 'CreateParticipantRequest', - 'DtmfParameters', - 'FaqAnswer', - 'GetParticipantRequest', - 'InputTextConfig', - 'ListParticipantsRequest', - 'ListParticipantsResponse', - 'ListSuggestionsRequest', - 'ListSuggestionsResponse', - 'Message', - 'MessageAnnotation', - 'OutputAudio', - 'Participant', - 'ResponseMessage', - 'SmartReplyAnswer', - 'StreamingAnalyzeContentRequest', - 'StreamingAnalyzeContentResponse', - 'SuggestArticlesRequest', - 'SuggestArticlesResponse', - 'SuggestFaqAnswersRequest', - 'SuggestFaqAnswersResponse', - 'Suggestion', - 'SuggestionFeature', - 'SuggestionResult', - 'SuggestSmartRepliesRequest', - 'SuggestSmartRepliesResponse', - 'UpdateParticipantRequest', - 'DetectIntentRequest', - 'DetectIntentResponse', - 'EventInput', - 'KnowledgeAnswers', - 'QueryInput', - 'QueryParameters', - 'QueryResult', - 'Sentiment', - 'SentimentAnalysisRequestConfig', - 'SentimentAnalysisResult', - 'StreamingDetectIntentRequest', - 'StreamingDetectIntentResponse', - 'StreamingRecognitionResult', - 'TextInput', - 'CreateSessionEntityTypeRequest', - 'DeleteSessionEntityTypeRequest', - 'GetSessionEntityTypeRequest', - 'ListSessionEntityTypesRequest', - 'ListSessionEntityTypesResponse', - 'SessionEntityType', - 'UpdateSessionEntityTypeRequest', - 'ValidationError', - 'ValidationResult', - 'CreateVersionRequest', - 'DeleteVersionRequest', - 'GetVersionRequest', - 'ListVersionsRequest', - 'ListVersionsResponse', - 'UpdateVersionRequest', - 'Version', - 'OriginalDetectIntentRequest', - 'WebhookRequest', - 'WebhookResponse', -) diff --git a/owl-bot-staging/v2beta1/google/cloud/dialogflow/gapic_version.py b/owl-bot-staging/v2beta1/google/cloud/dialogflow/gapic_version.py deleted file mode 100644 index 405b1cebc..000000000 --- a/owl-bot-staging/v2beta1/google/cloud/dialogflow/gapic_version.py +++ /dev/null @@ -1,16 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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. -# -__version__ = "0.1.0" # {x-release-please-version} diff --git a/owl-bot-staging/v2beta1/google/cloud/dialogflow/py.typed b/owl-bot-staging/v2beta1/google/cloud/dialogflow/py.typed deleted file mode 100644 index 2c6e5af62..000000000 --- a/owl-bot-staging/v2beta1/google/cloud/dialogflow/py.typed +++ /dev/null @@ -1,2 +0,0 @@ -# Marker file for PEP 561. -# The google-cloud-dialogflow package uses inline types. diff --git a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/__init__.py b/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/__init__.py deleted file mode 100644 index c14d4734c..000000000 --- a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/__init__.py +++ /dev/null @@ -1,496 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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 google.cloud.dialogflow_v2beta1 import gapic_version as package_version - -__version__ = package_version.__version__ - - -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 -from .types.agent import ExportAgentResponse -from .types.agent import GetAgentRequest -from .types.agent import GetValidationResultRequest -from .types.agent import ImportAgentRequest -from .types.agent import RestoreAgentRequest -from .types.agent import SearchAgentsRequest -from .types.agent import SearchAgentsResponse -from .types.agent import SetAgentRequest -from .types.agent import SubAgent -from .types.agent import TrainAgentRequest -from .types.answer_record import AgentAssistantFeedback -from .types.answer_record import AgentAssistantRecord -from .types.answer_record import AnswerFeedback -from .types.answer_record import AnswerRecord -from .types.answer_record import GetAnswerRecordRequest -from .types.answer_record import ListAnswerRecordsRequest -from .types.answer_record import ListAnswerRecordsResponse -from .types.answer_record import UpdateAnswerRecordRequest -from .types.audio_config import BargeInConfig -from .types.audio_config import InputAudioConfig -from .types.audio_config import OutputAudioConfig -from .types.audio_config import SpeechContext -from .types.audio_config import SpeechToTextConfig -from .types.audio_config import SpeechWordInfo -from .types.audio_config import SynthesizeSpeechConfig -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 -from .types.context import DeleteContextRequest -from .types.context import GetContextRequest -from .types.context import ListContextsRequest -from .types.context import ListContextsResponse -from .types.context import UpdateContextRequest -from .types.conversation import BatchCreateMessagesRequest -from .types.conversation import BatchCreateMessagesResponse -from .types.conversation import CompleteConversationRequest -from .types.conversation import Conversation -from .types.conversation import ConversationPhoneNumber -from .types.conversation import CreateConversationRequest -from .types.conversation import CreateMessageRequest -from .types.conversation import GetConversationRequest -from .types.conversation import ListConversationsRequest -from .types.conversation import ListConversationsResponse -from .types.conversation import ListMessagesRequest -from .types.conversation import ListMessagesResponse -from .types.conversation import SuggestConversationSummaryRequest -from .types.conversation import SuggestConversationSummaryResponse -from .types.conversation_event import ConversationEvent -from .types.conversation_profile import AutomatedAgentConfig -from .types.conversation_profile import ClearSuggestionFeatureConfigOperationMetadata -from .types.conversation_profile import ClearSuggestionFeatureConfigRequest -from .types.conversation_profile import ConversationProfile -from .types.conversation_profile import CreateConversationProfileRequest -from .types.conversation_profile import DeleteConversationProfileRequest -from .types.conversation_profile import GetConversationProfileRequest -from .types.conversation_profile import HumanAgentAssistantConfig -from .types.conversation_profile import HumanAgentHandoffConfig -from .types.conversation_profile import ListConversationProfilesRequest -from .types.conversation_profile import ListConversationProfilesResponse -from .types.conversation_profile import LoggingConfig -from .types.conversation_profile import NotificationConfig -from .types.conversation_profile import SetSuggestionFeatureConfigOperationMetadata -from .types.conversation_profile import SetSuggestionFeatureConfigRequest -from .types.conversation_profile import UpdateConversationProfileRequest -from .types.document import CreateDocumentRequest -from .types.document import DeleteDocumentRequest -from .types.document import Document -from .types.document import ExportOperationMetadata -from .types.document import GetDocumentRequest -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 -from .types.document import ReloadDocumentRequest -from .types.document import UpdateDocumentRequest -from .types.entity_type import BatchCreateEntitiesRequest -from .types.entity_type import BatchDeleteEntitiesRequest -from .types.entity_type import BatchDeleteEntityTypesRequest -from .types.entity_type import BatchUpdateEntitiesRequest -from .types.entity_type import BatchUpdateEntityTypesRequest -from .types.entity_type import BatchUpdateEntityTypesResponse -from .types.entity_type import CreateEntityTypeRequest -from .types.entity_type import DeleteEntityTypeRequest -from .types.entity_type import EntityType -from .types.entity_type import EntityTypeBatch -from .types.entity_type import GetEntityTypeRequest -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 GcsDestination -from .types.gcs import GcsSource -from .types.gcs import GcsSources -from .types.human_agent_assistant_event import HumanAgentAssistantEvent -from .types.intent import BatchDeleteIntentsRequest -from .types.intent import BatchUpdateIntentsRequest -from .types.intent import BatchUpdateIntentsResponse -from .types.intent import CreateIntentRequest -from .types.intent import DeleteIntentRequest -from .types.intent import GetIntentRequest -from .types.intent import Intent -from .types.intent import IntentBatch -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 -from .types.knowledge_base import KnowledgeBase -from .types.knowledge_base import ListKnowledgeBasesRequest -from .types.knowledge_base import ListKnowledgeBasesResponse -from .types.knowledge_base import UpdateKnowledgeBaseRequest -from .types.participant import AnalyzeContentRequest -from .types.participant import AnalyzeContentResponse -from .types.participant import AnnotatedMessagePart -from .types.participant import ArticleAnswer -from .types.participant import AssistQueryParameters -from .types.participant import AudioInput -from .types.participant import AutomatedAgentReply -from .types.participant import CompileSuggestionRequest -from .types.participant import CompileSuggestionResponse -from .types.participant import CreateParticipantRequest -from .types.participant import DtmfParameters -from .types.participant import FaqAnswer -from .types.participant import GetParticipantRequest -from .types.participant import InputTextConfig -from .types.participant import ListParticipantsRequest -from .types.participant import ListParticipantsResponse -from .types.participant import ListSuggestionsRequest -from .types.participant import ListSuggestionsResponse -from .types.participant import Message -from .types.participant import MessageAnnotation -from .types.participant import OutputAudio -from .types.participant import Participant -from .types.participant import ResponseMessage -from .types.participant import SmartReplyAnswer -from .types.participant import StreamingAnalyzeContentRequest -from .types.participant import StreamingAnalyzeContentResponse -from .types.participant import SuggestArticlesRequest -from .types.participant import SuggestArticlesResponse -from .types.participant import SuggestFaqAnswersRequest -from .types.participant import SuggestFaqAnswersResponse -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 -from .types.session import EventInput -from .types.session import KnowledgeAnswers -from .types.session import QueryInput -from .types.session import QueryParameters -from .types.session import QueryResult -from .types.session import Sentiment -from .types.session import SentimentAnalysisRequestConfig -from .types.session import SentimentAnalysisResult -from .types.session import StreamingDetectIntentRequest -from .types.session import StreamingDetectIntentResponse -from .types.session import StreamingRecognitionResult -from .types.session import TextInput -from .types.session_entity_type import CreateSessionEntityTypeRequest -from .types.session_entity_type import DeleteSessionEntityTypeRequest -from .types.session_entity_type import GetSessionEntityTypeRequest -from .types.session_entity_type import ListSessionEntityTypesRequest -from .types.session_entity_type import ListSessionEntityTypesResponse -from .types.session_entity_type import SessionEntityType -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__ = ( - 'AgentsAsyncClient', - 'AnswerRecordsAsyncClient', - 'ContextsAsyncClient', - 'ConversationProfilesAsyncClient', - 'ConversationsAsyncClient', - 'DocumentsAsyncClient', - 'EntityTypesAsyncClient', - 'EnvironmentsAsyncClient', - 'FulfillmentsAsyncClient', - 'IntentsAsyncClient', - 'KnowledgeBasesAsyncClient', - 'ParticipantsAsyncClient', - 'SessionEntityTypesAsyncClient', - 'SessionsAsyncClient', - 'VersionsAsyncClient', -'Agent', -'AgentAssistantFeedback', -'AgentAssistantRecord', -'AgentsClient', -'AnalyzeContentRequest', -'AnalyzeContentResponse', -'AnnotatedMessagePart', -'AnswerFeedback', -'AnswerRecord', -'AnswerRecordsClient', -'ArticleAnswer', -'AssistQueryParameters', -'AudioEncoding', -'AudioInput', -'AutomatedAgentConfig', -'AutomatedAgentReply', -'BargeInConfig', -'BatchCreateEntitiesRequest', -'BatchCreateMessagesRequest', -'BatchCreateMessagesResponse', -'BatchDeleteEntitiesRequest', -'BatchDeleteEntityTypesRequest', -'BatchDeleteIntentsRequest', -'BatchUpdateEntitiesRequest', -'BatchUpdateEntityTypesRequest', -'BatchUpdateEntityTypesResponse', -'BatchUpdateIntentsRequest', -'BatchUpdateIntentsResponse', -'ClearSuggestionFeatureConfigOperationMetadata', -'ClearSuggestionFeatureConfigRequest', -'CompileSuggestionRequest', -'CompileSuggestionResponse', -'CompleteConversationRequest', -'Context', -'ContextsClient', -'Conversation', -'ConversationEvent', -'ConversationPhoneNumber', -'ConversationProfile', -'ConversationProfilesClient', -'ConversationsClient', -'CreateContextRequest', -'CreateConversationProfileRequest', -'CreateConversationRequest', -'CreateDocumentRequest', -'CreateEntityTypeRequest', -'CreateEnvironmentRequest', -'CreateIntentRequest', -'CreateKnowledgeBaseRequest', -'CreateMessageRequest', -'CreateParticipantRequest', -'CreateSessionEntityTypeRequest', -'CreateVersionRequest', -'DeleteAgentRequest', -'DeleteAllContextsRequest', -'DeleteContextRequest', -'DeleteConversationProfileRequest', -'DeleteDocumentRequest', -'DeleteEntityTypeRequest', -'DeleteEnvironmentRequest', -'DeleteIntentRequest', -'DeleteKnowledgeBaseRequest', -'DeleteSessionEntityTypeRequest', -'DeleteVersionRequest', -'DetectIntentRequest', -'DetectIntentResponse', -'Document', -'DocumentsClient', -'DtmfParameters', -'EntityType', -'EntityTypeBatch', -'EntityTypesClient', -'Environment', -'EnvironmentHistory', -'EnvironmentsClient', -'EventInput', -'ExportAgentRequest', -'ExportAgentResponse', -'ExportOperationMetadata', -'FaqAnswer', -'Fulfillment', -'FulfillmentsClient', -'GcsDestination', -'GcsSource', -'GcsSources', -'GetAgentRequest', -'GetAnswerRecordRequest', -'GetContextRequest', -'GetConversationProfileRequest', -'GetConversationRequest', -'GetDocumentRequest', -'GetEntityTypeRequest', -'GetEnvironmentHistoryRequest', -'GetEnvironmentRequest', -'GetFulfillmentRequest', -'GetIntentRequest', -'GetKnowledgeBaseRequest', -'GetParticipantRequest', -'GetSessionEntityTypeRequest', -'GetValidationResultRequest', -'GetVersionRequest', -'HumanAgentAssistantConfig', -'HumanAgentAssistantEvent', -'HumanAgentHandoffConfig', -'ImportAgentRequest', -'ImportDocumentTemplate', -'ImportDocumentsRequest', -'ImportDocumentsResponse', -'InputAudioConfig', -'InputTextConfig', -'Intent', -'IntentBatch', -'IntentView', -'IntentsClient', -'KnowledgeAnswers', -'KnowledgeBase', -'KnowledgeBasesClient', -'KnowledgeOperationMetadata', -'ListAnswerRecordsRequest', -'ListAnswerRecordsResponse', -'ListContextsRequest', -'ListContextsResponse', -'ListConversationProfilesRequest', -'ListConversationProfilesResponse', -'ListConversationsRequest', -'ListConversationsResponse', -'ListDocumentsRequest', -'ListDocumentsResponse', -'ListEntityTypesRequest', -'ListEntityTypesResponse', -'ListEnvironmentsRequest', -'ListEnvironmentsResponse', -'ListIntentsRequest', -'ListIntentsResponse', -'ListKnowledgeBasesRequest', -'ListKnowledgeBasesResponse', -'ListMessagesRequest', -'ListMessagesResponse', -'ListParticipantsRequest', -'ListParticipantsResponse', -'ListSessionEntityTypesRequest', -'ListSessionEntityTypesResponse', -'ListSuggestionsRequest', -'ListSuggestionsResponse', -'ListVersionsRequest', -'ListVersionsResponse', -'LoggingConfig', -'Message', -'MessageAnnotation', -'NotificationConfig', -'OriginalDetectIntentRequest', -'OutputAudio', -'OutputAudioConfig', -'OutputAudioEncoding', -'Participant', -'ParticipantsClient', -'QueryInput', -'QueryParameters', -'QueryResult', -'ReloadDocumentRequest', -'ResponseMessage', -'RestoreAgentRequest', -'SearchAgentsRequest', -'SearchAgentsResponse', -'Sentiment', -'SentimentAnalysisRequestConfig', -'SentimentAnalysisResult', -'SessionEntityType', -'SessionEntityTypesClient', -'SessionsClient', -'SetAgentRequest', -'SetSuggestionFeatureConfigOperationMetadata', -'SetSuggestionFeatureConfigRequest', -'SmartReplyAnswer', -'SpeechContext', -'SpeechModelVariant', -'SpeechToTextConfig', -'SpeechWordInfo', -'SsmlVoiceGender', -'StreamingAnalyzeContentRequest', -'StreamingAnalyzeContentResponse', -'StreamingDetectIntentRequest', -'StreamingDetectIntentResponse', -'StreamingRecognitionResult', -'SubAgent', -'SuggestArticlesRequest', -'SuggestArticlesResponse', -'SuggestConversationSummaryRequest', -'SuggestConversationSummaryResponse', -'SuggestFaqAnswersRequest', -'SuggestFaqAnswersResponse', -'SuggestSmartRepliesRequest', -'SuggestSmartRepliesResponse', -'Suggestion', -'SuggestionFeature', -'SuggestionResult', -'SynthesizeSpeechConfig', -'TelephonyDtmf', -'TelephonyDtmfEvents', -'TextInput', -'TextToSpeechSettings', -'TrainAgentRequest', -'UpdateAnswerRecordRequest', -'UpdateContextRequest', -'UpdateConversationProfileRequest', -'UpdateDocumentRequest', -'UpdateEntityTypeRequest', -'UpdateEnvironmentRequest', -'UpdateFulfillmentRequest', -'UpdateIntentRequest', -'UpdateKnowledgeBaseRequest', -'UpdateParticipantRequest', -'UpdateSessionEntityTypeRequest', -'UpdateVersionRequest', -'ValidationError', -'ValidationResult', -'Version', -'VersionsClient', -'VoiceSelectionParams', -'WebhookRequest', -'WebhookResponse', -) diff --git a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/gapic_metadata.json b/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/gapic_metadata.json deleted file mode 100644 index 62c0128c9..000000000 --- a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/gapic_metadata.json +++ /dev/null @@ -1,1674 +0,0 @@ - { - "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" - ] - } - } - }, - "rest": { - "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" - ] - } - } - } - } - }, - "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" - ] - } - } - }, - "rest": { - "libraryClient": "AnswerRecordsClient", - "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" - ] - } - } - }, - "rest": { - "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" - ] - } - } - } - } - }, - "ConversationProfiles": { - "clients": { - "grpc": { - "libraryClient": "ConversationProfilesClient", - "rpcs": { - "ClearSuggestionFeatureConfig": { - "methods": [ - "clear_suggestion_feature_config" - ] - }, - "CreateConversationProfile": { - "methods": [ - "create_conversation_profile" - ] - }, - "DeleteConversationProfile": { - "methods": [ - "delete_conversation_profile" - ] - }, - "GetConversationProfile": { - "methods": [ - "get_conversation_profile" - ] - }, - "ListConversationProfiles": { - "methods": [ - "list_conversation_profiles" - ] - }, - "SetSuggestionFeatureConfig": { - "methods": [ - "set_suggestion_feature_config" - ] - }, - "UpdateConversationProfile": { - "methods": [ - "update_conversation_profile" - ] - } - } - }, - "grpc-async": { - "libraryClient": "ConversationProfilesAsyncClient", - "rpcs": { - "ClearSuggestionFeatureConfig": { - "methods": [ - "clear_suggestion_feature_config" - ] - }, - "CreateConversationProfile": { - "methods": [ - "create_conversation_profile" - ] - }, - "DeleteConversationProfile": { - "methods": [ - "delete_conversation_profile" - ] - }, - "GetConversationProfile": { - "methods": [ - "get_conversation_profile" - ] - }, - "ListConversationProfiles": { - "methods": [ - "list_conversation_profiles" - ] - }, - "SetSuggestionFeatureConfig": { - "methods": [ - "set_suggestion_feature_config" - ] - }, - "UpdateConversationProfile": { - "methods": [ - "update_conversation_profile" - ] - } - } - }, - "rest": { - "libraryClient": "ConversationProfilesClient", - "rpcs": { - "ClearSuggestionFeatureConfig": { - "methods": [ - "clear_suggestion_feature_config" - ] - }, - "CreateConversationProfile": { - "methods": [ - "create_conversation_profile" - ] - }, - "DeleteConversationProfile": { - "methods": [ - "delete_conversation_profile" - ] - }, - "GetConversationProfile": { - "methods": [ - "get_conversation_profile" - ] - }, - "ListConversationProfiles": { - "methods": [ - "list_conversation_profiles" - ] - }, - "SetSuggestionFeatureConfig": { - "methods": [ - "set_suggestion_feature_config" - ] - }, - "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" - ] - }, - "SuggestConversationSummary": { - "methods": [ - "suggest_conversation_summary" - ] - } - } - }, - "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" - ] - }, - "SuggestConversationSummary": { - "methods": [ - "suggest_conversation_summary" - ] - } - } - }, - "rest": { - "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" - ] - }, - "SuggestConversationSummary": { - "methods": [ - "suggest_conversation_summary" - ] - } - } - } - } - }, - "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" - ] - } - } - }, - "rest": { - "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" - ] - } - } - } - } - }, - "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" - ] - } - } - }, - "rest": { - "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" - ] - } - } - } - } - }, - "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" - ] - } - } - }, - "rest": { - "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" - ] - } - } - } - } - }, - "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" - ] - } - } - }, - "rest": { - "libraryClient": "FulfillmentsClient", - "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" - ] - } - } - }, - "rest": { - "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" - ] - } - } - } - } - }, - "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" - ] - } - } - }, - "rest": { - "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" - ] - } - } - } - } - }, - "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" - ] - }, - "StreamingAnalyzeContent": { - "methods": [ - "streaming_analyze_content" - ] - }, - "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" - ] - }, - "StreamingAnalyzeContent": { - "methods": [ - "streaming_analyze_content" - ] - }, - "SuggestArticles": { - "methods": [ - "suggest_articles" - ] - }, - "SuggestFaqAnswers": { - "methods": [ - "suggest_faq_answers" - ] - }, - "SuggestSmartReplies": { - "methods": [ - "suggest_smart_replies" - ] - }, - "UpdateParticipant": { - "methods": [ - "update_participant" - ] - } - } - }, - "rest": { - "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" - ] - }, - "StreamingAnalyzeContent": { - "methods": [ - "streaming_analyze_content" - ] - }, - "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" - ] - } - } - }, - "rest": { - "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" - ] - } - } - } - } - }, - "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" - ] - } - } - }, - "rest": { - "libraryClient": "SessionsClient", - "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" - ] - } - } - }, - "rest": { - "libraryClient": "VersionsClient", - "rpcs": { - "CreateVersion": { - "methods": [ - "create_version" - ] - }, - "DeleteVersion": { - "methods": [ - "delete_version" - ] - }, - "GetVersion": { - "methods": [ - "get_version" - ] - }, - "ListVersions": { - "methods": [ - "list_versions" - ] - }, - "UpdateVersion": { - "methods": [ - "update_version" - ] - } - } - } - } - } - } -} diff --git a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/gapic_version.py b/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/gapic_version.py deleted file mode 100644 index 405b1cebc..000000000 --- a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/gapic_version.py +++ /dev/null @@ -1,16 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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. -# -__version__ = "0.1.0" # {x-release-please-version} diff --git a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/py.typed b/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/py.typed deleted file mode 100644 index 2c6e5af62..000000000 --- a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/py.typed +++ /dev/null @@ -1,2 +0,0 @@ -# Marker file for PEP 561. -# The google-cloud-dialogflow package uses inline types. diff --git a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/__init__.py b/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/__init__.py deleted file mode 100644 index e8e1c3845..000000000 --- a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/__init__.py +++ /dev/null @@ -1,15 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/agents/__init__.py b/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/agents/__init__.py deleted file mode 100644 index 59831995e..000000000 --- a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/agents/__init__.py +++ /dev/null @@ -1,22 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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 AgentsClient -from .async_client import AgentsAsyncClient - -__all__ = ( - 'AgentsClient', - 'AgentsAsyncClient', -) diff --git a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/agents/async_client.py b/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/agents/async_client.py deleted file mode 100644 index 5608332e4..000000000 --- a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/agents/async_client.py +++ /dev/null @@ -1,1509 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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, Mapping, MutableMapping, MutableSequence, Optional, Sequence, Tuple, Type, Union - -from google.cloud.dialogflow_v2beta1 import gapic_version as package_version - -from google.api_core.client_options import ClientOptions -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import retry as retries -from google.auth import credentials as ga_credentials # type: ignore -from google.oauth2 import service_account # type: ignore - -try: - OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] -except AttributeError: # pragma: NO COVER - OptionalRetry = Union[retries.Retry, object] # type: ignore - -from google.api_core import operation # type: ignore -from google.api_core import operation_async # type: ignore -from google.cloud.dialogflow_v2beta1.services.agents import pagers -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.cloud.location import locations_pb2 # type: ignore -from google.longrunning import operations_pb2 -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 - - -class AgentsAsyncClient: - """Service for managing - [Agents][google.cloud.dialogflow.v2beta1.Agent]. - """ - - _client: AgentsClient - - DEFAULT_ENDPOINT = AgentsClient.DEFAULT_ENDPOINT - DEFAULT_MTLS_ENDPOINT = AgentsClient.DEFAULT_MTLS_ENDPOINT - - 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) - - @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: - AgentsAsyncClient: The constructed client. - """ - return AgentsClient.from_service_account_info.__func__(AgentsAsyncClient, 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: - AgentsAsyncClient: The constructed client. - """ - return AgentsClient.from_service_account_file.__func__(AgentsAsyncClient, filename, *args, **kwargs) # type: ignore - - from_service_account_json = from_service_account_file - - @classmethod - def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[ClientOptions] = None): - """Return the API endpoint and client cert source for mutual TLS. - - The client cert source is determined in the following order: - (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the - client cert source is None. - (2) if `client_options.client_cert_source` is provided, use the provided one; if the - default client cert source exists, use the default one; otherwise the client cert - source is None. - - The API endpoint is determined in the following order: - (1) if `client_options.api_endpoint` if provided, use the provided one. - (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the - default mTLS endpoint; if the environment variable is "never", use the default API - endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise - use the default API endpoint. - - More details can be found at https://google.aip.dev/auth/4114. - - Args: - client_options (google.api_core.client_options.ClientOptions): Custom options for the - client. Only the `api_endpoint` and `client_cert_source` properties may be used - in this method. - - Returns: - Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the - client cert source to use. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If any errors happen. - """ - return AgentsClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore - - @property - def transport(self) -> AgentsTransport: - """Returns the transport used by the client instance. - - Returns: - AgentsTransport: The transport used by the client instance. - """ - return self._client.transport - - get_transport_class = functools.partial(type(AgentsClient).get_transport_class, type(AgentsClient)) - - def __init__(self, *, - credentials: Optional[ga_credentials.Credentials] = None, - transport: Union[str, AgentsTransport] = "grpc_asyncio", - client_options: Optional[ClientOptions] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the agents 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, ~.AgentsTransport]): 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 = AgentsClient( - credentials=credentials, - transport=transport, - client_options=client_options, - client_info=client_info, - - ) - - async def get_agent(self, - request: Optional[Union[agent.GetAgentRequest, dict]] = None, - *, - parent: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> agent.Agent: - r"""Retrieves the specified agent. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import dialogflow_v2beta1 - - async def sample_get_agent(): - # Create a client - client = dialogflow_v2beta1.AgentsAsyncClient() - - # Initialize request argument(s) - request = dialogflow_v2beta1.GetAgentRequest( - parent="parent_value", - ) - - # Make the request - response = await client.get_agent(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.dialogflow_v2beta1.types.GetAgentRequest, dict]]): - The request object. The request message for - [Agents.GetAgent][google.cloud.dialogflow.v2beta1.Agents.GetAgent]. - parent (:class:`str`): - Required. The project that the agent to fetch is - associated with. Format: ``projects/`` or - ``projects//locations/``. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.dialogflow_v2beta1.types.Agent: - A Dialogflow agent is a virtual agent that handles conversations with your - end-users. It is a natural language understanding - module that understands the nuances of human - language. Dialogflow translates end-user text or - audio during a conversation to structured data that - your apps and services can understand. You design and - build a Dialogflow agent to handle the types of - conversations required for your system. - - For more information about agents, see the [Agent - guide](\ https://cloud.google.com/dialogflow/docs/agents-overview). - - """ - # Create or coerce a protobuf request object. - # Quick 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 = agent.GetAgentRequest(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.get_agent, - 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 set_agent(self, - request: Optional[Union[gcd_agent.SetAgentRequest, dict]] = None, - *, - agent: Optional[gcd_agent.Agent] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gcd_agent.Agent: - r"""Creates/updates the specified agent. - - Note: You should always train an agent prior to sending it - queries. See the `training - documentation `__. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import dialogflow_v2beta1 - - async def sample_set_agent(): - # Create a client - client = dialogflow_v2beta1.AgentsAsyncClient() - - # Initialize request argument(s) - agent = dialogflow_v2beta1.Agent() - agent.parent = "parent_value" - - request = dialogflow_v2beta1.SetAgentRequest( - agent=agent, - ) - - # Make the request - response = await client.set_agent(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.dialogflow_v2beta1.types.SetAgentRequest, dict]]): - The request object. The request message for - [Agents.SetAgent][google.cloud.dialogflow.v2beta1.Agents.SetAgent]. - agent (:class:`google.cloud.dialogflow_v2beta1.types.Agent`): - Required. The agent to update. - 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. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.dialogflow_v2beta1.types.Agent: - A Dialogflow agent is a virtual agent that handles conversations with your - end-users. It is a natural language understanding - module that understands the nuances of human - language. Dialogflow translates end-user text or - audio during a conversation to structured data that - your apps and services can understand. You design and - build a Dialogflow agent to handle the types of - conversations required for your system. - - For more information about agents, see the [Agent - guide](\ https://cloud.google.com/dialogflow/docs/agents-overview). - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([agent]) - 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_agent.SetAgentRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if agent is not None: - request.agent = agent - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.set_agent, - 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(( - ("agent.parent", request.agent.parent), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def delete_agent(self, - request: Optional[Union[agent.DeleteAgentRequest, dict]] = None, - *, - parent: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> None: - r"""Deletes the specified agent. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import dialogflow_v2beta1 - - async def sample_delete_agent(): - # Create a client - client = dialogflow_v2beta1.AgentsAsyncClient() - - # Initialize request argument(s) - request = dialogflow_v2beta1.DeleteAgentRequest( - parent="parent_value", - ) - - # Make the request - await client.delete_agent(request=request) - - Args: - request (Optional[Union[google.cloud.dialogflow_v2beta1.types.DeleteAgentRequest, dict]]): - The request object. The request message for - [Agents.DeleteAgent][google.cloud.dialogflow.v2beta1.Agents.DeleteAgent]. - parent (:class:`str`): - Required. The project that the agent to delete is - associated with. Format: ``projects/`` or - ``projects//locations/``. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - """ - # Create or coerce a protobuf request object. - # Quick 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 = agent.DeleteAgentRequest(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.delete_agent, - 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. - await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - async def search_agents(self, - request: Optional[Union[agent.SearchAgentsRequest, dict]] = None, - *, - parent: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.SearchAgentsAsyncPager: - r"""Returns the list of agents. Since there is at most one - conversational agent per project, this method is useful - primarily for listing all agents across projects the caller has - access to. One can achieve that with a wildcard project - collection id "-". Refer to `List - Sub-Collections `__. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import dialogflow_v2beta1 - - async def sample_search_agents(): - # Create a client - client = dialogflow_v2beta1.AgentsAsyncClient() - - # Initialize request argument(s) - request = dialogflow_v2beta1.SearchAgentsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.search_agents(request=request) - - # Handle the response - async for response in page_result: - print(response) - - Args: - request (Optional[Union[google.cloud.dialogflow_v2beta1.types.SearchAgentsRequest, dict]]): - The request object. The request message for - [Agents.SearchAgents][google.cloud.dialogflow.v2beta1.Agents.SearchAgents]. - parent (:class:`str`): - Required. The project to list agents from. Format: - ``projects/`` or - ``projects//locations/``. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.dialogflow_v2beta1.services.agents.pagers.SearchAgentsAsyncPager: - The response message for - [Agents.SearchAgents][google.cloud.dialogflow.v2beta1.Agents.SearchAgents]. - - Iterating over this object will yield results and - resolve additional pages automatically. - - """ - # Create or coerce a protobuf request object. - # Quick 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 = agent.SearchAgentsRequest(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.search_agents, - 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.SearchAgentsAsyncPager( - method=rpc, - request=request, - response=response, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def train_agent(self, - request: Optional[Union[agent.TrainAgentRequest, dict]] = None, - *, - parent: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation_async.AsyncOperation: - r"""Trains the specified agent. - - This method is a `long-running - operation `__. - The returned ``Operation`` type has the following - method-specific fields: - - - ``metadata``: An empty `Struct - message `__ - - ``response``: An `Empty - message `__ - - Note: You should always train an agent prior to sending it - queries. See the `training - documentation `__. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import dialogflow_v2beta1 - - async def sample_train_agent(): - # Create a client - client = dialogflow_v2beta1.AgentsAsyncClient() - - # Initialize request argument(s) - request = dialogflow_v2beta1.TrainAgentRequest( - parent="parent_value", - ) - - # Make the request - operation = client.train_agent(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.dialogflow_v2beta1.types.TrainAgentRequest, dict]]): - The request object. The request message for - [Agents.TrainAgent][google.cloud.dialogflow.v2beta1.Agents.TrainAgent]. - parent (:class:`str`): - Required. The project that the agent to train is - associated with. Format: ``projects/`` or - ``projects//locations/``. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.api_core.operation_async.AsyncOperation: - An object representing a long-running operation. - - The result type for the operation will be :class:`google.protobuf.empty_pb2.Empty` A generic empty message that you can re-use to avoid defining duplicated - empty messages in your APIs. A typical example is to - use it as the request or the response type of an API - method. For instance: - - service Foo { - rpc Bar(google.protobuf.Empty) returns - (google.protobuf.Empty); - - } - - """ - # Create or coerce a protobuf request object. - # Quick 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 = agent.TrainAgentRequest(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.train_agent, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Wrap the response in an operation future. - response = operation_async.from_gapic( - response, - self._client._transport.operations_client, - empty_pb2.Empty, - metadata_type=struct_pb2.Struct, - ) - - # Done; return the response. - return response - - async def export_agent(self, - request: Optional[Union[agent.ExportAgentRequest, dict]] = None, - *, - parent: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation_async.AsyncOperation: - r"""Exports the specified agent to a ZIP file. - - This method is a `long-running - operation `__. - The returned ``Operation`` type has the following - method-specific fields: - - - ``metadata``: An empty `Struct - message `__ - - ``response``: - [ExportAgentResponse][google.cloud.dialogflow.v2beta1.ExportAgentResponse] - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import dialogflow_v2beta1 - - async def sample_export_agent(): - # Create a client - client = dialogflow_v2beta1.AgentsAsyncClient() - - # Initialize request argument(s) - request = dialogflow_v2beta1.ExportAgentRequest( - parent="parent_value", - ) - - # Make the request - operation = client.export_agent(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.dialogflow_v2beta1.types.ExportAgentRequest, dict]]): - The request object. The request message for - [Agents.ExportAgent][google.cloud.dialogflow.v2beta1.Agents.ExportAgent]. - parent (:class:`str`): - Required. The project that the agent to export is - associated with. Format: ``projects/`` or - ``projects//locations/``. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.api_core.operation_async.AsyncOperation: - An object representing a long-running operation. - - The result type for the operation will be :class:`google.cloud.dialogflow_v2beta1.types.ExportAgentResponse` The response message for - [Agents.ExportAgent][google.cloud.dialogflow.v2beta1.Agents.ExportAgent]. - - """ - # Create or coerce a protobuf request object. - # Quick 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 = agent.ExportAgentRequest(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.export_agent, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Wrap the response in an operation future. - response = operation_async.from_gapic( - response, - self._client._transport.operations_client, - agent.ExportAgentResponse, - metadata_type=struct_pb2.Struct, - ) - - # Done; return the response. - return response - - async def import_agent(self, - request: Optional[Union[agent.ImportAgentRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation_async.AsyncOperation: - r"""Imports the specified agent from a ZIP file. - - Uploads new intents and entity types without deleting the - existing ones. Intents and entity types with the same name are - replaced with the new versions from - [ImportAgentRequest][google.cloud.dialogflow.v2beta1.ImportAgentRequest]. - After the import, the imported draft agent will be trained - automatically (unless disabled in agent settings). However, once - the import is done, training may not be completed yet. Please - call - [TrainAgent][google.cloud.dialogflow.v2beta1.Agents.TrainAgent] - and wait for the operation it returns in order to train - explicitly. - - This method is a `long-running - operation `__. - The returned ``Operation`` type has the following - method-specific fields: - - - ``metadata``: An empty `Struct - message `__ - - ``response``: An `Empty - message `__ - - The operation only tracks when importing is complete, not when - it is done training. - - Note: You should always train an agent prior to sending it - queries. See the `training - documentation `__. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import dialogflow_v2beta1 - - async def sample_import_agent(): - # Create a client - client = dialogflow_v2beta1.AgentsAsyncClient() - - # Initialize request argument(s) - request = dialogflow_v2beta1.ImportAgentRequest( - agent_uri="agent_uri_value", - parent="parent_value", - ) - - # Make the request - operation = client.import_agent(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.dialogflow_v2beta1.types.ImportAgentRequest, dict]]): - 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. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.api_core.operation_async.AsyncOperation: - An object representing a long-running operation. - - The result type for the operation will be :class:`google.protobuf.empty_pb2.Empty` A generic empty message that you can re-use to avoid defining duplicated - empty messages in your APIs. A typical example is to - use it as the request or the response type of an API - method. For instance: - - service Foo { - rpc Bar(google.protobuf.Empty) returns - (google.protobuf.Empty); - - } - - """ - # Create or coerce a protobuf request object. - request = agent.ImportAgentRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.import_agent, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Wrap the response in an operation future. - response = operation_async.from_gapic( - response, - self._client._transport.operations_client, - empty_pb2.Empty, - metadata_type=struct_pb2.Struct, - ) - - # Done; return the response. - return response - - async def restore_agent(self, - request: Optional[Union[agent.RestoreAgentRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation_async.AsyncOperation: - r"""Restores the specified agent from a ZIP file. - - Replaces the current agent version with a new one. All the - intents and entity types in the older version are deleted. After - the restore, the restored draft agent will be trained - automatically (unless disabled in agent settings). However, once - the restore is done, training may not be completed yet. Please - call - [TrainAgent][google.cloud.dialogflow.v2beta1.Agents.TrainAgent] - and wait for the operation it returns in order to train - explicitly. - - This method is a `long-running - operation `__. - The returned ``Operation`` type has the following - method-specific fields: - - - ``metadata``: An empty `Struct - message `__ - - ``response``: An `Empty - message `__ - - The operation only tracks when restoring is complete, not when - it is done training. - - Note: You should always train an agent prior to sending it - queries. See the `training - documentation `__. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import dialogflow_v2beta1 - - async def sample_restore_agent(): - # Create a client - client = dialogflow_v2beta1.AgentsAsyncClient() - - # Initialize request argument(s) - request = dialogflow_v2beta1.RestoreAgentRequest( - agent_uri="agent_uri_value", - parent="parent_value", - ) - - # Make the request - operation = client.restore_agent(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.dialogflow_v2beta1.types.RestoreAgentRequest, dict]]): - 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. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.api_core.operation_async.AsyncOperation: - An object representing a long-running operation. - - The result type for the operation will be :class:`google.protobuf.empty_pb2.Empty` A generic empty message that you can re-use to avoid defining duplicated - empty messages in your APIs. A typical example is to - use it as the request or the response type of an API - method. For instance: - - service Foo { - rpc Bar(google.protobuf.Empty) returns - (google.protobuf.Empty); - - } - - """ - # Create or coerce a protobuf request object. - request = agent.RestoreAgentRequest(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.restore_agent, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Wrap the response in an operation future. - response = operation_async.from_gapic( - response, - self._client._transport.operations_client, - empty_pb2.Empty, - metadata_type=struct_pb2.Struct, - ) - - # Done; return the response. - return response - - async def get_validation_result(self, - request: Optional[Union[agent.GetValidationResultRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> validation_result.ValidationResult: - r"""Gets agent validation result. Agent validation is - performed during training time and is updated - automatically when training is completed. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import dialogflow_v2beta1 - - async def sample_get_validation_result(): - # Create a client - client = dialogflow_v2beta1.AgentsAsyncClient() - - # Initialize request argument(s) - request = dialogflow_v2beta1.GetValidationResultRequest( - parent="parent_value", - ) - - # Make the request - response = await client.get_validation_result(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.dialogflow_v2beta1.types.GetValidationResultRequest, dict]]): - 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. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.dialogflow_v2beta1.types.ValidationResult: - Represents the output of agent - validation. - - """ - # Create or coerce a protobuf request object. - request = agent.GetValidationResultRequest(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_validation_result, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def list_operations( - self, - request: Optional[operations_pb2.ListOperationsRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operations_pb2.ListOperationsResponse: - r"""Lists operations that match the specified filter in the request. - - Args: - request (:class:`~.operations_pb2.ListOperationsRequest`): - The request object. Request message for - `ListOperations` method. - 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: - ~.operations_pb2.ListOperationsResponse: - Response message for ``ListOperations`` method. - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = operations_pb2.ListOperationsRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._client._transport.list_operations, - 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 get_operation( - self, - request: Optional[operations_pb2.GetOperationRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operations_pb2.Operation: - r"""Gets the latest state of a long-running operation. - - Args: - request (:class:`~.operations_pb2.GetOperationRequest`): - The request object. Request message for - `GetOperation` method. - 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: - ~.operations_pb2.Operation: - An ``Operation`` object. - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = operations_pb2.GetOperationRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._client._transport.get_operation, - 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 cancel_operation( - self, - request: Optional[operations_pb2.CancelOperationRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> None: - r"""Starts asynchronous cancellation on a long-running operation. - - The server makes a best effort to cancel the operation, but success - is not guaranteed. If the server doesn't support this method, it returns - `google.rpc.Code.UNIMPLEMENTED`. - - Args: - request (:class:`~.operations_pb2.CancelOperationRequest`): - The request object. Request message for - `CancelOperation` method. - 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: - None - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = operations_pb2.CancelOperationRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._client._transport.cancel_operation, - 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_location( - self, - request: Optional[locations_pb2.GetLocationRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> locations_pb2.Location: - r"""Gets information about a location. - - Args: - request (:class:`~.location_pb2.GetLocationRequest`): - The request object. Request message for - `GetLocation` method. - 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: - ~.location_pb2.Location: - Location object. - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = locations_pb2.GetLocationRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._client._transport.get_location, - 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 list_locations( - self, - request: Optional[locations_pb2.ListLocationsRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> locations_pb2.ListLocationsResponse: - r"""Lists information about the supported locations for this service. - - Args: - request (:class:`~.location_pb2.ListLocationsRequest`): - The request object. Request message for - `ListLocations` method. - 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: - ~.location_pb2.ListLocationsResponse: - Response message for ``ListLocations`` method. - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = locations_pb2.ListLocationsRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._client._transport.list_locations, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("name", request.name),)), - ) - - # Send the request. - response = await rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - async def __aenter__(self): - return self - - async def __aexit__(self, exc_type, exc, tb): - await self.transport.close() - -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) - - -__all__ = ( - "AgentsAsyncClient", -) diff --git a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/agents/client.py b/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/agents/client.py deleted file mode 100644 index 7b544a601..000000000 --- a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/agents/client.py +++ /dev/null @@ -1,1711 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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 os -import re -from typing import Dict, Mapping, MutableMapping, MutableSequence, Optional, Sequence, Tuple, Type, Union, cast - -from google.cloud.dialogflow_v2beta1 import gapic_version as package_version - -from google.api_core import client_options as client_options_lib -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import retry as retries -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 - -try: - OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] -except AttributeError: # pragma: NO COVER - OptionalRetry = Union[retries.Retry, object] # type: ignore - -from google.api_core import operation # type: ignore -from google.api_core import operation_async # type: ignore -from google.cloud.dialogflow_v2beta1.services.agents import pagers -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.cloud.location import locations_pb2 # type: ignore -from google.longrunning import operations_pb2 -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 -from .transports.rest import AgentsRestTransport - - -class AgentsClientMeta(type): - """Metaclass for the Agents 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[AgentsTransport]] - _transport_registry["grpc"] = AgentsGrpcTransport - _transport_registry["grpc_asyncio"] = AgentsGrpcAsyncIOTransport - _transport_registry["rest"] = AgentsRestTransport - - def get_transport_class(cls, - label: Optional[str] = None, - ) -> Type[AgentsTransport]: - """Returns an appropriate transport class. - - Args: - label: The name of the desired transport. If none is - provided, then the first transport in the registry is used. - - Returns: - The transport class to use. - """ - # If a specific transport is requested, return that one. - if label: - return cls._transport_registry[label] - - # No transport is requested; return the default (that is, the first one - # in the dictionary). - return next(iter(cls._transport_registry.values())) - - -class AgentsClient(metaclass=AgentsClientMeta): - """Service for managing - [Agents][google.cloud.dialogflow.v2beta1.Agent]. - """ - - @staticmethod - def _get_default_mtls_endpoint(api_endpoint): - """Converts api endpoint to mTLS endpoint. - - Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to - "*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively. - Args: - api_endpoint (Optional[str]): the api endpoint to convert. - Returns: - str: converted mTLS api endpoint. - """ - if not api_endpoint: - return api_endpoint - - mtls_endpoint_re = re.compile( - r"(?P[^.]+)(?P\.mtls)?(?P\.sandbox)?(?P\.googleapis\.com)?" - ) - - m = mtls_endpoint_re.match(api_endpoint) - name, mtls, sandbox, googledomain = m.groups() - if mtls or not googledomain: - return api_endpoint - - if sandbox: - return api_endpoint.replace( - "sandbox.googleapis.com", "mtls.sandbox.googleapis.com" - ) - - return api_endpoint.replace(".googleapis.com", ".mtls.googleapis.com") - - DEFAULT_ENDPOINT = "dialogflow.googleapis.com" - DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore - DEFAULT_ENDPOINT - ) - - @classmethod - def from_service_account_info(cls, info: dict, *args, **kwargs): - """Creates an instance of this client using the provided credentials - info. - - Args: - info (dict): The service account private key info. - args: Additional arguments to pass to the constructor. - kwargs: Additional arguments to pass to the constructor. - - Returns: - AgentsClient: 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: - AgentsClient: 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) -> AgentsTransport: - """Returns the transport used by the client instance. - - Returns: - AgentsTransport: The transport used by the client - instance. - """ - return self._transport - - @staticmethod - def agent_path(project: str,) -> str: - """Returns a fully-qualified agent string.""" - return "projects/{project}/agent".format(project=project, ) - - @staticmethod - def parse_agent_path(path: str) -> Dict[str,str]: - """Parses a agent path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/agent$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_billing_account_path(billing_account: str, ) -> str: - """Returns a fully-qualified billing_account string.""" - return "billingAccounts/{billing_account}".format(billing_account=billing_account, ) - - @staticmethod - def parse_common_billing_account_path(path: str) -> Dict[str,str]: - """Parse a billing_account path into its component segments.""" - m = re.match(r"^billingAccounts/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_folder_path(folder: str, ) -> str: - """Returns a fully-qualified folder string.""" - return "folders/{folder}".format(folder=folder, ) - - @staticmethod - def parse_common_folder_path(path: str) -> Dict[str,str]: - """Parse a folder path into its component segments.""" - m = re.match(r"^folders/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_organization_path(organization: str, ) -> str: - """Returns a fully-qualified organization string.""" - return "organizations/{organization}".format(organization=organization, ) - - @staticmethod - def parse_common_organization_path(path: str) -> Dict[str,str]: - """Parse a organization path into its component segments.""" - m = re.match(r"^organizations/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_project_path(project: str, ) -> str: - """Returns a fully-qualified project string.""" - return "projects/{project}".format(project=project, ) - - @staticmethod - def parse_common_project_path(path: str) -> Dict[str,str]: - """Parse a project path into its component segments.""" - m = re.match(r"^projects/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_location_path(project: str, location: str, ) -> str: - """Returns a fully-qualified location string.""" - return "projects/{project}/locations/{location}".format(project=project, location=location, ) - - @staticmethod - def parse_common_location_path(path: str) -> Dict[str,str]: - """Parse a location path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)$", path) - return m.groupdict() if m else {} - - @classmethod - def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[client_options_lib.ClientOptions] = None): - """Return the API endpoint and client cert source for mutual TLS. - - The client cert source is determined in the following order: - (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the - client cert source is None. - (2) if `client_options.client_cert_source` is provided, use the provided one; if the - default client cert source exists, use the default one; otherwise the client cert - source is None. - - The API endpoint is determined in the following order: - (1) if `client_options.api_endpoint` if provided, use the provided one. - (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the - default mTLS endpoint; if the environment variable is "never", use the default API - endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise - use the default API endpoint. - - More details can be found at https://google.aip.dev/auth/4114. - - Args: - client_options (google.api_core.client_options.ClientOptions): Custom options for the - client. Only the `api_endpoint` and `client_cert_source` properties may be used - in this method. - - Returns: - Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the - client cert source to use. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If any errors happen. - """ - if client_options is None: - client_options = client_options_lib.ClientOptions() - use_client_cert = os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false") - use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") - if use_client_cert not in ("true", "false"): - raise ValueError("Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`") - if use_mtls_endpoint not in ("auto", "never", "always"): - raise MutualTLSChannelError("Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`") - - # Figure out the client cert source to use. - client_cert_source = None - if use_client_cert == "true": - if client_options.client_cert_source: - client_cert_source = client_options.client_cert_source - elif mtls.has_default_client_cert_source(): - client_cert_source = mtls.default_client_cert_source() - - # Figure out which api endpoint to use. - if client_options.api_endpoint is not None: - api_endpoint = client_options.api_endpoint - elif use_mtls_endpoint == "always" or (use_mtls_endpoint == "auto" and client_cert_source): - api_endpoint = cls.DEFAULT_MTLS_ENDPOINT - else: - api_endpoint = cls.DEFAULT_ENDPOINT - - return api_endpoint, client_cert_source - - def __init__(self, *, - credentials: Optional[ga_credentials.Credentials] = None, - transport: Optional[Union[str, AgentsTransport]] = None, - client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the agents 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, AgentsTransport]): The - transport to use. If set to None, a transport is chosen - automatically. - client_options (Optional[Union[google.api_core.client_options.ClientOptions, dict]]): 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() - client_options = cast(client_options_lib.ClientOptions, client_options) - - api_endpoint, client_cert_source_func = self.get_mtls_endpoint_and_cert_source(client_options) - - api_key_value = getattr(client_options, "api_key", None) - if api_key_value and credentials: - raise ValueError("client_options.api_key and credentials are mutually exclusive") - - # 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, AgentsTransport): - # transport is a AgentsTransport instance. - if credentials or client_options.credentials_file or api_key_value: - 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: - import google.auth._default # type: ignore - - if api_key_value and hasattr(google.auth._default, "get_api_key_credentials"): - credentials = google.auth._default.get_api_key_credentials(api_key_value) - - Transport = type(self).get_transport_class(transport) - self._transport = Transport( - credentials=credentials, - credentials_file=client_options.credentials_file, - host=api_endpoint, - scopes=client_options.scopes, - client_cert_source_for_mtls=client_cert_source_func, - quota_project_id=client_options.quota_project_id, - client_info=client_info, - always_use_jwt_access=True, - api_audience=client_options.api_audience, - ) - - def get_agent(self, - request: Optional[Union[agent.GetAgentRequest, dict]] = None, - *, - parent: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> agent.Agent: - r"""Retrieves the specified agent. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import dialogflow_v2beta1 - - def sample_get_agent(): - # Create a client - client = dialogflow_v2beta1.AgentsClient() - - # Initialize request argument(s) - request = dialogflow_v2beta1.GetAgentRequest( - parent="parent_value", - ) - - # Make the request - response = client.get_agent(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.dialogflow_v2beta1.types.GetAgentRequest, dict]): - The request object. The request message for - [Agents.GetAgent][google.cloud.dialogflow.v2beta1.Agents.GetAgent]. - parent (str): - Required. The project that the agent to fetch is - associated with. Format: ``projects/`` or - ``projects//locations/``. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.dialogflow_v2beta1.types.Agent: - A Dialogflow agent is a virtual agent that handles conversations with your - end-users. It is a natural language understanding - module that understands the nuances of human - language. Dialogflow translates end-user text or - audio during a conversation to structured data that - your apps and services can understand. You design and - build a Dialogflow agent to handle the types of - conversations required for your system. - - For more information about agents, see the [Agent - guide](\ https://cloud.google.com/dialogflow/docs/agents-overview). - - """ - # Create or coerce a protobuf request object. - # Quick 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 agent.GetAgentRequest. - # There's no risk of modifying the input as we've already verified - # 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 - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.get_agent] - - # 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 set_agent(self, - request: Optional[Union[gcd_agent.SetAgentRequest, dict]] = None, - *, - agent: Optional[gcd_agent.Agent] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gcd_agent.Agent: - r"""Creates/updates the specified agent. - - Note: You should always train an agent prior to sending it - queries. See the `training - documentation `__. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import dialogflow_v2beta1 - - def sample_set_agent(): - # Create a client - client = dialogflow_v2beta1.AgentsClient() - - # Initialize request argument(s) - agent = dialogflow_v2beta1.Agent() - agent.parent = "parent_value" - - request = dialogflow_v2beta1.SetAgentRequest( - agent=agent, - ) - - # Make the request - response = client.set_agent(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.dialogflow_v2beta1.types.SetAgentRequest, dict]): - The request object. The request message for - [Agents.SetAgent][google.cloud.dialogflow.v2beta1.Agents.SetAgent]. - agent (google.cloud.dialogflow_v2beta1.types.Agent): - Required. The agent to update. - 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. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.dialogflow_v2beta1.types.Agent: - A Dialogflow agent is a virtual agent that handles conversations with your - end-users. It is a natural language understanding - module that understands the nuances of human - language. Dialogflow translates end-user text or - audio during a conversation to structured data that - your apps and services can understand. You design and - build a Dialogflow agent to handle the types of - conversations required for your system. - - For more information about agents, see the [Agent - guide](\ https://cloud.google.com/dialogflow/docs/agents-overview). - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([agent]) - 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_agent.SetAgentRequest. - # There's no risk of modifying the input as we've already verified - # 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 - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.set_agent] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("agent.parent", request.agent.parent), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def delete_agent(self, - request: Optional[Union[agent.DeleteAgentRequest, dict]] = None, - *, - parent: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> None: - r"""Deletes the specified agent. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import dialogflow_v2beta1 - - def sample_delete_agent(): - # Create a client - client = dialogflow_v2beta1.AgentsClient() - - # Initialize request argument(s) - request = dialogflow_v2beta1.DeleteAgentRequest( - parent="parent_value", - ) - - # Make the request - client.delete_agent(request=request) - - Args: - request (Union[google.cloud.dialogflow_v2beta1.types.DeleteAgentRequest, dict]): - The request object. The request message for - [Agents.DeleteAgent][google.cloud.dialogflow.v2beta1.Agents.DeleteAgent]. - parent (str): - Required. The project that the agent to delete is - associated with. Format: ``projects/`` or - ``projects//locations/``. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - """ - # Create or coerce a protobuf request object. - # Quick 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 agent.DeleteAgentRequest. - # There's no risk of modifying the input as we've already verified - # 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 - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.delete_agent] - - # 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. - rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - def search_agents(self, - request: Optional[Union[agent.SearchAgentsRequest, dict]] = None, - *, - parent: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.SearchAgentsPager: - r"""Returns the list of agents. Since there is at most one - conversational agent per project, this method is useful - primarily for listing all agents across projects the caller has - access to. One can achieve that with a wildcard project - collection id "-". Refer to `List - Sub-Collections `__. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import dialogflow_v2beta1 - - def sample_search_agents(): - # Create a client - client = dialogflow_v2beta1.AgentsClient() - - # Initialize request argument(s) - request = dialogflow_v2beta1.SearchAgentsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.search_agents(request=request) - - # Handle the response - for response in page_result: - print(response) - - Args: - request (Union[google.cloud.dialogflow_v2beta1.types.SearchAgentsRequest, dict]): - The request object. The request message for - [Agents.SearchAgents][google.cloud.dialogflow.v2beta1.Agents.SearchAgents]. - parent (str): - Required. The project to list agents from. Format: - ``projects/`` or - ``projects//locations/``. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.dialogflow_v2beta1.services.agents.pagers.SearchAgentsPager: - The response message for - [Agents.SearchAgents][google.cloud.dialogflow.v2beta1.Agents.SearchAgents]. - - Iterating over this object will yield results and - resolve additional pages automatically. - - """ - # Create or coerce a protobuf request object. - # Quick 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 agent.SearchAgentsRequest. - # There's no risk of modifying the input as we've already verified - # 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 - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.search_agents] - - # 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.SearchAgentsPager( - method=rpc, - request=request, - response=response, - metadata=metadata, - ) - - # Done; return the response. - return response - - def train_agent(self, - request: Optional[Union[agent.TrainAgentRequest, dict]] = None, - *, - parent: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation.Operation: - r"""Trains the specified agent. - - This method is a `long-running - operation `__. - The returned ``Operation`` type has the following - method-specific fields: - - - ``metadata``: An empty `Struct - message `__ - - ``response``: An `Empty - message `__ - - Note: You should always train an agent prior to sending it - queries. See the `training - documentation `__. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import dialogflow_v2beta1 - - def sample_train_agent(): - # Create a client - client = dialogflow_v2beta1.AgentsClient() - - # Initialize request argument(s) - request = dialogflow_v2beta1.TrainAgentRequest( - parent="parent_value", - ) - - # Make the request - operation = client.train_agent(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.dialogflow_v2beta1.types.TrainAgentRequest, dict]): - The request object. The request message for - [Agents.TrainAgent][google.cloud.dialogflow.v2beta1.Agents.TrainAgent]. - parent (str): - Required. The project that the agent to train is - associated with. Format: ``projects/`` or - ``projects//locations/``. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.api_core.operation.Operation: - An object representing a long-running operation. - - The result type for the operation will be :class:`google.protobuf.empty_pb2.Empty` A generic empty message that you can re-use to avoid defining duplicated - empty messages in your APIs. A typical example is to - use it as the request or the response type of an API - method. For instance: - - service Foo { - rpc Bar(google.protobuf.Empty) returns - (google.protobuf.Empty); - - } - - """ - # Create or coerce a protobuf request object. - # Quick 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 agent.TrainAgentRequest. - # There's no risk of modifying the input as we've already verified - # 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 - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.train_agent] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Wrap the response in an operation future. - response = operation.from_gapic( - response, - self._transport.operations_client, - empty_pb2.Empty, - metadata_type=struct_pb2.Struct, - ) - - # Done; return the response. - return response - - def export_agent(self, - request: Optional[Union[agent.ExportAgentRequest, dict]] = None, - *, - parent: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation.Operation: - r"""Exports the specified agent to a ZIP file. - - This method is a `long-running - operation `__. - The returned ``Operation`` type has the following - method-specific fields: - - - ``metadata``: An empty `Struct - message `__ - - ``response``: - [ExportAgentResponse][google.cloud.dialogflow.v2beta1.ExportAgentResponse] - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import dialogflow_v2beta1 - - def sample_export_agent(): - # Create a client - client = dialogflow_v2beta1.AgentsClient() - - # Initialize request argument(s) - request = dialogflow_v2beta1.ExportAgentRequest( - parent="parent_value", - ) - - # Make the request - operation = client.export_agent(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.dialogflow_v2beta1.types.ExportAgentRequest, dict]): - The request object. The request message for - [Agents.ExportAgent][google.cloud.dialogflow.v2beta1.Agents.ExportAgent]. - parent (str): - Required. The project that the agent to export is - associated with. Format: ``projects/`` or - ``projects//locations/``. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.api_core.operation.Operation: - An object representing a long-running operation. - - The result type for the operation will be :class:`google.cloud.dialogflow_v2beta1.types.ExportAgentResponse` The response message for - [Agents.ExportAgent][google.cloud.dialogflow.v2beta1.Agents.ExportAgent]. - - """ - # Create or coerce a protobuf request object. - # Quick 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 agent.ExportAgentRequest. - # There's no risk of modifying the input as we've already verified - # 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 - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.export_agent] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Wrap the response in an operation future. - response = operation.from_gapic( - response, - self._transport.operations_client, - agent.ExportAgentResponse, - metadata_type=struct_pb2.Struct, - ) - - # Done; return the response. - return response - - def import_agent(self, - request: Optional[Union[agent.ImportAgentRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation.Operation: - r"""Imports the specified agent from a ZIP file. - - Uploads new intents and entity types without deleting the - existing ones. Intents and entity types with the same name are - replaced with the new versions from - [ImportAgentRequest][google.cloud.dialogflow.v2beta1.ImportAgentRequest]. - After the import, the imported draft agent will be trained - automatically (unless disabled in agent settings). However, once - the import is done, training may not be completed yet. Please - call - [TrainAgent][google.cloud.dialogflow.v2beta1.Agents.TrainAgent] - and wait for the operation it returns in order to train - explicitly. - - This method is a `long-running - operation `__. - The returned ``Operation`` type has the following - method-specific fields: - - - ``metadata``: An empty `Struct - message `__ - - ``response``: An `Empty - message `__ - - The operation only tracks when importing is complete, not when - it is done training. - - Note: You should always train an agent prior to sending it - queries. See the `training - documentation `__. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import dialogflow_v2beta1 - - def sample_import_agent(): - # Create a client - client = dialogflow_v2beta1.AgentsClient() - - # Initialize request argument(s) - request = dialogflow_v2beta1.ImportAgentRequest( - agent_uri="agent_uri_value", - parent="parent_value", - ) - - # Make the request - operation = client.import_agent(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.dialogflow_v2beta1.types.ImportAgentRequest, dict]): - 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. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.api_core.operation.Operation: - An object representing a long-running operation. - - The result type for the operation will be :class:`google.protobuf.empty_pb2.Empty` A generic empty message that you can re-use to avoid defining duplicated - empty messages in your APIs. A typical example is to - use it as the request or the response type of an API - method. For instance: - - service Foo { - rpc Bar(google.protobuf.Empty) returns - (google.protobuf.Empty); - - } - - """ - # 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 - # there are no flattened fields. - if not isinstance(request, agent.ImportAgentRequest): - request = agent.ImportAgentRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.import_agent] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Wrap the response in an operation future. - response = operation.from_gapic( - response, - self._transport.operations_client, - empty_pb2.Empty, - metadata_type=struct_pb2.Struct, - ) - - # Done; return the response. - return response - - def restore_agent(self, - request: Optional[Union[agent.RestoreAgentRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation.Operation: - r"""Restores the specified agent from a ZIP file. - - Replaces the current agent version with a new one. All the - intents and entity types in the older version are deleted. After - the restore, the restored draft agent will be trained - automatically (unless disabled in agent settings). However, once - the restore is done, training may not be completed yet. Please - call - [TrainAgent][google.cloud.dialogflow.v2beta1.Agents.TrainAgent] - and wait for the operation it returns in order to train - explicitly. - - This method is a `long-running - operation `__. - The returned ``Operation`` type has the following - method-specific fields: - - - ``metadata``: An empty `Struct - message `__ - - ``response``: An `Empty - message `__ - - The operation only tracks when restoring is complete, not when - it is done training. - - Note: You should always train an agent prior to sending it - queries. See the `training - documentation `__. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import dialogflow_v2beta1 - - def sample_restore_agent(): - # Create a client - client = dialogflow_v2beta1.AgentsClient() - - # Initialize request argument(s) - request = dialogflow_v2beta1.RestoreAgentRequest( - agent_uri="agent_uri_value", - parent="parent_value", - ) - - # Make the request - operation = client.restore_agent(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.dialogflow_v2beta1.types.RestoreAgentRequest, dict]): - 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. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.api_core.operation.Operation: - An object representing a long-running operation. - - The result type for the operation will be :class:`google.protobuf.empty_pb2.Empty` A generic empty message that you can re-use to avoid defining duplicated - empty messages in your APIs. A typical example is to - use it as the request or the response type of an API - method. For instance: - - service Foo { - rpc Bar(google.protobuf.Empty) returns - (google.protobuf.Empty); - - } - - """ - # 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 - # there are no flattened fields. - if not isinstance(request, agent.RestoreAgentRequest): - request = agent.RestoreAgentRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.restore_agent] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Wrap the response in an operation future. - response = operation.from_gapic( - response, - self._transport.operations_client, - empty_pb2.Empty, - metadata_type=struct_pb2.Struct, - ) - - # Done; return the response. - return response - - def get_validation_result(self, - request: Optional[Union[agent.GetValidationResultRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> validation_result.ValidationResult: - r"""Gets agent validation result. Agent validation is - performed during training time and is updated - automatically when training is completed. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import dialogflow_v2beta1 - - def sample_get_validation_result(): - # Create a client - client = dialogflow_v2beta1.AgentsClient() - - # Initialize request argument(s) - request = dialogflow_v2beta1.GetValidationResultRequest( - parent="parent_value", - ) - - # Make the request - response = client.get_validation_result(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.dialogflow_v2beta1.types.GetValidationResultRequest, dict]): - 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. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.dialogflow_v2beta1.types.ValidationResult: - Represents the output of agent - validation. - - """ - # 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 - # there are no flattened fields. - if not isinstance(request, agent.GetValidationResultRequest): - request = agent.GetValidationResultRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.get_validation_result] - - # 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 __enter__(self) -> "AgentsClient": - return self - - def __exit__(self, type, value, traceback): - """Releases underlying transport's resources. - - .. warning:: - ONLY use as a context manager if the transport is NOT shared - with other clients! Exiting the with block will CLOSE the transport - and may cause errors in other clients! - """ - self.transport.close() - - def list_operations( - self, - request: Optional[operations_pb2.ListOperationsRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operations_pb2.ListOperationsResponse: - r"""Lists operations that match the specified filter in the request. - - Args: - request (:class:`~.operations_pb2.ListOperationsRequest`): - The request object. Request message for - `ListOperations` method. - 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: - ~.operations_pb2.ListOperationsResponse: - Response message for ``ListOperations`` method. - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = operations_pb2.ListOperationsRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._transport.list_operations, - 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 = rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - def get_operation( - self, - request: Optional[operations_pb2.GetOperationRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operations_pb2.Operation: - r"""Gets the latest state of a long-running operation. - - Args: - request (:class:`~.operations_pb2.GetOperationRequest`): - The request object. Request message for - `GetOperation` method. - 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: - ~.operations_pb2.Operation: - An ``Operation`` object. - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = operations_pb2.GetOperationRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._transport.get_operation, - 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 = rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - def cancel_operation( - self, - request: Optional[operations_pb2.CancelOperationRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> None: - r"""Starts asynchronous cancellation on a long-running operation. - - The server makes a best effort to cancel the operation, but success - is not guaranteed. If the server doesn't support this method, it returns - `google.rpc.Code.UNIMPLEMENTED`. - - Args: - request (:class:`~.operations_pb2.CancelOperationRequest`): - The request object. Request message for - `CancelOperation` method. - 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: - None - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = operations_pb2.CancelOperationRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._transport.cancel_operation, - 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. - rpc(request, retry=retry, timeout=timeout, metadata=metadata,) - - def get_location( - self, - request: Optional[locations_pb2.GetLocationRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> locations_pb2.Location: - r"""Gets information about a location. - - Args: - request (:class:`~.location_pb2.GetLocationRequest`): - The request object. Request message for - `GetLocation` method. - 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: - ~.location_pb2.Location: - Location object. - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = locations_pb2.GetLocationRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._transport.get_location, - 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 = rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - def list_locations( - self, - request: Optional[locations_pb2.ListLocationsRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> locations_pb2.ListLocationsResponse: - r"""Lists information about the supported locations for this service. - - Args: - request (:class:`~.location_pb2.ListLocationsRequest`): - The request object. Request message for - `ListLocations` method. - 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: - ~.location_pb2.ListLocationsResponse: - Response message for ``ListLocations`` method. - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = locations_pb2.ListLocationsRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._transport.list_locations, - 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 = rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) - - -__all__ = ( - "AgentsClient", -) diff --git a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/agents/pagers.py b/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/agents/pagers.py deleted file mode 100644 index 89ff827c2..000000000 --- a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/agents/pagers.py +++ /dev/null @@ -1,139 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from typing import Any, AsyncIterator, Awaitable, Callable, Sequence, Tuple, Optional, Iterator - -from google.cloud.dialogflow_v2beta1.types import agent - - -class SearchAgentsPager: - """A pager for iterating through ``search_agents`` requests. - - This class thinly wraps an initial - :class:`google.cloud.dialogflow_v2beta1.types.SearchAgentsResponse` object, and - provides an ``__iter__`` method to iterate through its - ``agents`` field. - - If there are more pages, the ``__iter__`` method will make additional - ``SearchAgents`` requests and continue to iterate - through the ``agents`` field on the - corresponding responses. - - All the usual :class:`google.cloud.dialogflow_v2beta1.types.SearchAgentsResponse` - 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[..., agent.SearchAgentsResponse], - request: agent.SearchAgentsRequest, - response: agent.SearchAgentsResponse, - *, - 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.SearchAgentsRequest): - The initial request object. - response (google.cloud.dialogflow_v2beta1.types.SearchAgentsResponse): - 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 = agent.SearchAgentsRequest(request) - self._response = response - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - def pages(self) -> Iterator[agent.SearchAgentsResponse]: - yield self._response - while self._response.next_page_token: - self._request.page_token = self._response.next_page_token - self._response = self._method(self._request, metadata=self._metadata) - yield self._response - - def __iter__(self) -> Iterator[agent.Agent]: - for page in self.pages: - yield from page.agents - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class SearchAgentsAsyncPager: - """A pager for iterating through ``search_agents`` requests. - - This class thinly wraps an initial - :class:`google.cloud.dialogflow_v2beta1.types.SearchAgentsResponse` object, and - provides an ``__aiter__`` method to iterate through its - ``agents`` field. - - If there are more pages, the ``__aiter__`` method will make additional - ``SearchAgents`` requests and continue to iterate - through the ``agents`` field on the - corresponding responses. - - All the usual :class:`google.cloud.dialogflow_v2beta1.types.SearchAgentsResponse` - 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[agent.SearchAgentsResponse]], - request: agent.SearchAgentsRequest, - response: agent.SearchAgentsResponse, - *, - metadata: Sequence[Tuple[str, str]] = ()): - """Instantiates the pager. - - Args: - method (Callable): The method that was originally called, and - which instantiated this pager. - request (google.cloud.dialogflow_v2beta1.types.SearchAgentsRequest): - The initial request object. - response (google.cloud.dialogflow_v2beta1.types.SearchAgentsResponse): - 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 = agent.SearchAgentsRequest(request) - self._response = response - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - async def pages(self) -> AsyncIterator[agent.SearchAgentsResponse]: - yield self._response - while self._response.next_page_token: - self._request.page_token = self._response.next_page_token - self._response = await self._method(self._request, metadata=self._metadata) - yield self._response - def __aiter__(self) -> AsyncIterator[agent.Agent]: - async def async_generator(): - async for page in self.pages: - for response in page.agents: - yield response - - return async_generator() - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) diff --git a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/agents/transports/__init__.py b/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/agents/transports/__init__.py deleted file mode 100644 index dc2a4d0f8..000000000 --- a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/agents/transports/__init__.py +++ /dev/null @@ -1,38 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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 AgentsTransport -from .grpc import AgentsGrpcTransport -from .grpc_asyncio import AgentsGrpcAsyncIOTransport -from .rest import AgentsRestTransport -from .rest import AgentsRestInterceptor - - -# Compile a registry of transports. -_transport_registry = OrderedDict() # type: Dict[str, Type[AgentsTransport]] -_transport_registry['grpc'] = AgentsGrpcTransport -_transport_registry['grpc_asyncio'] = AgentsGrpcAsyncIOTransport -_transport_registry['rest'] = AgentsRestTransport - -__all__ = ( - 'AgentsTransport', - 'AgentsGrpcTransport', - 'AgentsGrpcAsyncIOTransport', - 'AgentsRestTransport', - 'AgentsRestInterceptor', -) diff --git a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/agents/transports/base.py b/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/agents/transports/base.py deleted file mode 100644 index 77d553980..000000000 --- a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/agents/transports/base.py +++ /dev/null @@ -1,316 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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 - -from google.cloud.dialogflow_v2beta1 import gapic_version as package_version - -import google.auth # type: ignore -import google.api_core -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import retry as retries -from google.api_core import operations_v1 -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 agent -from google.cloud.dialogflow_v2beta1.types import agent as gcd_agent -from google.cloud.dialogflow_v2beta1.types import validation_result -from google.cloud.location import locations_pb2 # type: ignore -from google.longrunning import operations_pb2 -from google.longrunning import operations_pb2 # type: ignore -from google.protobuf import empty_pb2 # type: ignore - -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) - - -class AgentsTransport(abc.ABC): - """Abstract transport class for Agents.""" - - 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: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - api_audience: Optional[str] = None, - **kwargs, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. - scopes (Optional[Sequence[str]]): A list of scopes. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - """ - - scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} - - # Save the scopes. - self._scopes = scopes - - # If no credentials are provided, then determine the appropriate - # defaults. - if credentials and credentials_file: - raise core_exceptions.DuplicateCredentialArgs("'credentials_file' and 'credentials' are mutually exclusive") - - if credentials_file is not None: - credentials, _ = google.auth.load_credentials_from_file( - credentials_file, - **scopes_kwargs, - quota_project_id=quota_project_id - ) - elif credentials is None: - credentials, _ = google.auth.default(**scopes_kwargs, quota_project_id=quota_project_id) - # Don't apply audience if the credentials file passed from user. - if hasattr(credentials, "with_gdch_audience"): - credentials = credentials.with_gdch_audience(api_audience if api_audience else host) - - # If the credentials are service account credentials, then always try to use self signed JWT. - if always_use_jwt_access and isinstance(credentials, service_account.Credentials) and hasattr(service_account.Credentials, "with_always_use_jwt_access"): - credentials = credentials.with_always_use_jwt_access(True) - - # Save the credentials. - self._credentials = credentials - - # Save the hostname. Default to port 443 (HTTPS) if none is specified. - if ':' not in host: - host += ':443' - self._host = host - - def _prep_wrapped_messages(self, client_info): - # Precompute the wrapped methods. - self._wrapped_methods = { - self.get_agent: gapic_v1.method.wrap_method( - self.get_agent, - default_timeout=None, - client_info=client_info, - ), - self.set_agent: gapic_v1.method.wrap_method( - self.set_agent, - default_timeout=None, - client_info=client_info, - ), - self.delete_agent: gapic_v1.method.wrap_method( - self.delete_agent, - default_timeout=None, - client_info=client_info, - ), - self.search_agents: gapic_v1.method.wrap_method( - self.search_agents, - default_timeout=None, - client_info=client_info, - ), - self.train_agent: gapic_v1.method.wrap_method( - self.train_agent, - default_timeout=None, - client_info=client_info, - ), - self.export_agent: gapic_v1.method.wrap_method( - self.export_agent, - default_timeout=None, - client_info=client_info, - ), - self.import_agent: gapic_v1.method.wrap_method( - self.import_agent, - default_timeout=None, - client_info=client_info, - ), - self.restore_agent: gapic_v1.method.wrap_method( - self.restore_agent, - default_timeout=None, - client_info=client_info, - ), - self.get_validation_result: gapic_v1.method.wrap_method( - self.get_validation_result, - default_timeout=None, - client_info=client_info, - ), - } - - def close(self): - """Closes resources associated with the transport. - - .. warning:: - Only call this method if the transport is NOT shared - with other clients - this may cause errors in other clients! - """ - raise NotImplementedError() - - @property - def operations_client(self): - """Return the client designed to process long-running operations.""" - raise NotImplementedError() - - @property - def get_agent(self) -> Callable[ - [agent.GetAgentRequest], - Union[ - agent.Agent, - Awaitable[agent.Agent] - ]]: - raise NotImplementedError() - - @property - def set_agent(self) -> Callable[ - [gcd_agent.SetAgentRequest], - Union[ - gcd_agent.Agent, - Awaitable[gcd_agent.Agent] - ]]: - raise NotImplementedError() - - @property - def delete_agent(self) -> Callable[ - [agent.DeleteAgentRequest], - Union[ - empty_pb2.Empty, - Awaitable[empty_pb2.Empty] - ]]: - raise NotImplementedError() - - @property - def search_agents(self) -> Callable[ - [agent.SearchAgentsRequest], - Union[ - agent.SearchAgentsResponse, - Awaitable[agent.SearchAgentsResponse] - ]]: - raise NotImplementedError() - - @property - def train_agent(self) -> Callable[ - [agent.TrainAgentRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: - raise NotImplementedError() - - @property - def export_agent(self) -> Callable[ - [agent.ExportAgentRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: - raise NotImplementedError() - - @property - def import_agent(self) -> Callable[ - [agent.ImportAgentRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: - raise NotImplementedError() - - @property - def restore_agent(self) -> Callable[ - [agent.RestoreAgentRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: - raise NotImplementedError() - - @property - def get_validation_result(self) -> Callable[ - [agent.GetValidationResultRequest], - Union[ - validation_result.ValidationResult, - Awaitable[validation_result.ValidationResult] - ]]: - raise NotImplementedError() - - @property - def list_operations( - self, - ) -> Callable[ - [operations_pb2.ListOperationsRequest], - Union[operations_pb2.ListOperationsResponse, Awaitable[operations_pb2.ListOperationsResponse]], - ]: - raise NotImplementedError() - - @property - def get_operation( - self, - ) -> Callable[ - [operations_pb2.GetOperationRequest], - Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], - ]: - raise NotImplementedError() - - @property - def cancel_operation( - self, - ) -> Callable[ - [operations_pb2.CancelOperationRequest], - None, - ]: - raise NotImplementedError() - - @property - def get_location(self, - ) -> Callable[ - [locations_pb2.GetLocationRequest], - Union[locations_pb2.Location, Awaitable[locations_pb2.Location]], - ]: - raise NotImplementedError() - - @property - def list_locations(self, - ) -> Callable[ - [locations_pb2.ListLocationsRequest], - Union[locations_pb2.ListLocationsResponse, Awaitable[locations_pb2.ListLocationsResponse]], - ]: - raise NotImplementedError() - - @property - def kind(self) -> str: - raise NotImplementedError() - - -__all__ = ( - 'AgentsTransport', -) diff --git a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/agents/transports/grpc.py b/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/agents/transports/grpc.py deleted file mode 100644 index f75d240db..000000000 --- a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/agents/transports/grpc.py +++ /dev/null @@ -1,678 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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 -from google.api_core import operations_v1 -from google.api_core import gapic_v1 -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 agent -from google.cloud.dialogflow_v2beta1.types import agent as gcd_agent -from google.cloud.dialogflow_v2beta1.types import validation_result -from google.cloud.location import locations_pb2 # type: ignore -from google.longrunning import operations_pb2 -from google.longrunning import operations_pb2 # type: ignore -from google.protobuf import empty_pb2 # type: ignore -from .base import AgentsTransport, DEFAULT_CLIENT_INFO - - -class AgentsGrpcTransport(AgentsTransport): - """gRPC backend transport for Agents. - - Service for managing - [Agents][google.cloud.dialogflow.v2beta1.Agent]. - - 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: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - channel: Optional[grpc.Channel] = None, - api_mtls_endpoint: Optional[str] = None, - client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, - ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, - client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - api_audience: Optional[str] = None, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - This argument is ignored if ``channel`` is provided. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional(Sequence[str])): A list of scopes. This argument is - ignored if ``channel`` is provided. - channel (Optional[grpc.Channel]): A ``Channel`` instance through - which to make calls. - api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. - If provided, it overrides the ``host`` argument and tries to create - a mutual TLS channel with client SSL credentials from - ``client_cert_source`` or application default SSL credentials. - client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): - Deprecated. A callback to provide client SSL certificate bytes and - private key bytes, both in PEM format. It is ignored if - ``api_mtls_endpoint`` is None. - ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials - for the grpc channel. It is ignored if ``channel`` is provided. - client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): - A callback to provide client certificate bytes and private key bytes, - both in PEM format. It is used to configure a mutual TLS channel. It is - ignored if ``channel`` or ``ssl_channel_credentials`` is provided. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport - creation failed for any reason. - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - self._grpc_channel = None - self._ssl_channel_credentials = ssl_channel_credentials - self._stubs: Dict[str, Callable] = {} - self._operations_client: Optional[operations_v1.OperationsClient] = None - - if api_mtls_endpoint: - warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) - if client_cert_source: - warnings.warn("client_cert_source is deprecated", DeprecationWarning) - - if channel: - # Ignore credentials if a channel was passed. - credentials = False - # If a channel was explicitly provided, set it. - self._grpc_channel = channel - self._ssl_channel_credentials = None - - else: - if api_mtls_endpoint: - host = api_mtls_endpoint - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - self._ssl_channel_credentials = SslCredentials().ssl_credentials - - else: - if client_cert_source_for_mtls and not ssl_channel_credentials: - cert, key = client_cert_source_for_mtls() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - - # The base transport sets the host, credentials and scopes - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes, - quota_project_id=quota_project_id, - client_info=client_info, - always_use_jwt_access=always_use_jwt_access, - api_audience=api_audience, - ) - - if not self._grpc_channel: - self._grpc_channel = type(self).create_channel( - self._host, - # use the credentials which are saved - credentials=self._credentials, - # Set ``credentials_file`` to ``None`` here as - # the credentials that we saved earlier should be used. - credentials_file=None, - 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: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - **kwargs) -> grpc.Channel: - """Create and return a gRPC channel object. - Args: - host (Optional[str]): The host for the channel to use. - credentials (Optional[~.Credentials]): The - authorization credentials to attach to requests. These - credentials identify this application to the service. If - none are specified, the client will attempt to ascertain - the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - kwargs (Optional[dict]): Keyword arguments, which are passed to the - channel creation. - Returns: - grpc.Channel: A gRPC channel object. - - Raises: - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - - return grpc_helpers.create_channel( - host, - credentials=credentials, - credentials_file=credentials_file, - quota_project_id=quota_project_id, - default_scopes=cls.AUTH_SCOPES, - scopes=scopes, - default_host=cls.DEFAULT_HOST, - **kwargs - ) - - @property - def grpc_channel(self) -> grpc.Channel: - """Return the channel designed to connect to this service. - """ - return self._grpc_channel - - @property - def operations_client(self) -> operations_v1.OperationsClient: - """Create the client designed to process long-running operations. - - This property caches on the instance; repeated calls return the same - client. - """ - # Quick check: Only create a new client if we do not already have one. - if self._operations_client is None: - self._operations_client = operations_v1.OperationsClient( - self.grpc_channel - ) - - # Return the client from cache. - return self._operations_client - - @property - def get_agent(self) -> Callable[ - [agent.GetAgentRequest], - agent.Agent]: - r"""Return a callable for the get agent method over gRPC. - - Retrieves the specified agent. - - Returns: - Callable[[~.GetAgentRequest], - ~.Agent]: - 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_agent' not in self._stubs: - self._stubs['get_agent'] = self.grpc_channel.unary_unary( - '/google.cloud.dialogflow.v2beta1.Agents/GetAgent', - request_serializer=agent.GetAgentRequest.serialize, - response_deserializer=agent.Agent.deserialize, - ) - return self._stubs['get_agent'] - - @property - def set_agent(self) -> Callable[ - [gcd_agent.SetAgentRequest], - gcd_agent.Agent]: - r"""Return a callable for the set agent method over gRPC. - - Creates/updates the specified agent. - - Note: You should always train an agent prior to sending it - queries. See the `training - documentation `__. - - Returns: - Callable[[~.SetAgentRequest], - ~.Agent]: - 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 'set_agent' not in self._stubs: - self._stubs['set_agent'] = self.grpc_channel.unary_unary( - '/google.cloud.dialogflow.v2beta1.Agents/SetAgent', - request_serializer=gcd_agent.SetAgentRequest.serialize, - response_deserializer=gcd_agent.Agent.deserialize, - ) - return self._stubs['set_agent'] - - @property - 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. - - Returns: - Callable[[~.DeleteAgentRequest], - ~.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_agent' not in self._stubs: - self._stubs['delete_agent'] = self.grpc_channel.unary_unary( - '/google.cloud.dialogflow.v2beta1.Agents/DeleteAgent', - request_serializer=agent.DeleteAgentRequest.serialize, - response_deserializer=empty_pb2.Empty.FromString, - ) - return self._stubs['delete_agent'] - - @property - def search_agents(self) -> Callable[ - [agent.SearchAgentsRequest], - agent.SearchAgentsResponse]: - r"""Return a callable for the search agents method over gRPC. - - Returns the list of agents. Since there is at most one - conversational agent per project, this method is useful - primarily for listing all agents across projects the caller has - access to. One can achieve that with a wildcard project - collection id "-". Refer to `List - Sub-Collections `__. - - Returns: - Callable[[~.SearchAgentsRequest], - ~.SearchAgentsResponse]: - 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 'search_agents' not in self._stubs: - self._stubs['search_agents'] = self.grpc_channel.unary_unary( - '/google.cloud.dialogflow.v2beta1.Agents/SearchAgents', - request_serializer=agent.SearchAgentsRequest.serialize, - response_deserializer=agent.SearchAgentsResponse.deserialize, - ) - return self._stubs['search_agents'] - - @property - 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. - - This method is a `long-running - operation `__. - The returned ``Operation`` type has the following - method-specific fields: - - - ``metadata``: An empty `Struct - message `__ - - ``response``: An `Empty - message `__ - - Note: You should always train an agent prior to sending it - queries. See the `training - documentation `__. - - Returns: - Callable[[~.TrainAgentRequest], - ~.Operation]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'train_agent' not in self._stubs: - self._stubs['train_agent'] = self.grpc_channel.unary_unary( - '/google.cloud.dialogflow.v2beta1.Agents/TrainAgent', - request_serializer=agent.TrainAgentRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['train_agent'] - - @property - def export_agent(self) -> 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. - - This method is a `long-running - operation `__. - The returned ``Operation`` type has the following - method-specific fields: - - - ``metadata``: An empty `Struct - message `__ - - ``response``: - [ExportAgentResponse][google.cloud.dialogflow.v2beta1.ExportAgentResponse] - - Returns: - Callable[[~.ExportAgentRequest], - ~.Operation]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'export_agent' not in self._stubs: - self._stubs['export_agent'] = self.grpc_channel.unary_unary( - '/google.cloud.dialogflow.v2beta1.Agents/ExportAgent', - request_serializer=agent.ExportAgentRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['export_agent'] - - @property - def import_agent(self) -> 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. - - Uploads new intents and entity types without deleting the - existing ones. Intents and entity types with the same name are - replaced with the new versions from - [ImportAgentRequest][google.cloud.dialogflow.v2beta1.ImportAgentRequest]. - After the import, the imported draft agent will be trained - automatically (unless disabled in agent settings). However, once - the import is done, training may not be completed yet. Please - call - [TrainAgent][google.cloud.dialogflow.v2beta1.Agents.TrainAgent] - and wait for the operation it returns in order to train - explicitly. - - This method is a `long-running - operation `__. - The returned ``Operation`` type has the following - method-specific fields: - - - ``metadata``: An empty `Struct - message `__ - - ``response``: An `Empty - message `__ - - The operation only tracks when importing is complete, not when - it is done training. - - Note: You should always train an agent prior to sending it - queries. See the `training - documentation `__. - - Returns: - Callable[[~.ImportAgentRequest], - ~.Operation]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'import_agent' not in self._stubs: - self._stubs['import_agent'] = self.grpc_channel.unary_unary( - '/google.cloud.dialogflow.v2beta1.Agents/ImportAgent', - request_serializer=agent.ImportAgentRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['import_agent'] - - @property - def restore_agent(self) -> 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. - - Replaces the current agent version with a new one. All the - intents and entity types in the older version are deleted. After - the restore, the restored draft agent will be trained - automatically (unless disabled in agent settings). However, once - the restore is done, training may not be completed yet. Please - call - [TrainAgent][google.cloud.dialogflow.v2beta1.Agents.TrainAgent] - and wait for the operation it returns in order to train - explicitly. - - This method is a `long-running - operation `__. - The returned ``Operation`` type has the following - method-specific fields: - - - ``metadata``: An empty `Struct - message `__ - - ``response``: An `Empty - message `__ - - The operation only tracks when restoring is complete, not when - it is done training. - - Note: You should always train an agent prior to sending it - queries. See the `training - documentation `__. - - Returns: - Callable[[~.RestoreAgentRequest], - ~.Operation]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'restore_agent' not in self._stubs: - self._stubs['restore_agent'] = self.grpc_channel.unary_unary( - '/google.cloud.dialogflow.v2beta1.Agents/RestoreAgent', - request_serializer=agent.RestoreAgentRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['restore_agent'] - - @property - def get_validation_result(self) -> Callable[ - [agent.GetValidationResultRequest], - validation_result.ValidationResult]: - r"""Return a callable for the get validation result method over gRPC. - - Gets agent validation result. Agent validation is - performed during training time and is updated - automatically when training is completed. - - Returns: - Callable[[~.GetValidationResultRequest], - ~.ValidationResult]: - 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_validation_result' not in self._stubs: - self._stubs['get_validation_result'] = self.grpc_channel.unary_unary( - '/google.cloud.dialogflow.v2beta1.Agents/GetValidationResult', - request_serializer=agent.GetValidationResultRequest.serialize, - response_deserializer=validation_result.ValidationResult.deserialize, - ) - return self._stubs['get_validation_result'] - - def close(self): - self.grpc_channel.close() - - @property - def cancel_operation( - self, - ) -> Callable[[operations_pb2.CancelOperationRequest], None]: - r"""Return a callable for the cancel_operation method over gRPC. - """ - # 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 "cancel_operation" not in self._stubs: - self._stubs["cancel_operation"] = self.grpc_channel.unary_unary( - "/google.longrunning.Operations/CancelOperation", - request_serializer=operations_pb2.CancelOperationRequest.SerializeToString, - response_deserializer=None, - ) - return self._stubs["cancel_operation"] - - @property - def get_operation( - self, - ) -> Callable[[operations_pb2.GetOperationRequest], operations_pb2.Operation]: - r"""Return a callable for the get_operation method over gRPC. - """ - # 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_operation" not in self._stubs: - self._stubs["get_operation"] = self.grpc_channel.unary_unary( - "/google.longrunning.Operations/GetOperation", - request_serializer=operations_pb2.GetOperationRequest.SerializeToString, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs["get_operation"] - - @property - def list_operations( - self, - ) -> Callable[[operations_pb2.ListOperationsRequest], operations_pb2.ListOperationsResponse]: - r"""Return a callable for the list_operations method over gRPC. - """ - # 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_operations" not in self._stubs: - self._stubs["list_operations"] = self.grpc_channel.unary_unary( - "/google.longrunning.Operations/ListOperations", - request_serializer=operations_pb2.ListOperationsRequest.SerializeToString, - response_deserializer=operations_pb2.ListOperationsResponse.FromString, - ) - return self._stubs["list_operations"] - - @property - def list_locations( - self, - ) -> Callable[[locations_pb2.ListLocationsRequest], locations_pb2.ListLocationsResponse]: - r"""Return a callable for the list locations method over gRPC. - """ - # 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_locations" not in self._stubs: - self._stubs["list_locations"] = self.grpc_channel.unary_unary( - "/google.cloud.location.Locations/ListLocations", - request_serializer=locations_pb2.ListLocationsRequest.SerializeToString, - response_deserializer=locations_pb2.ListLocationsResponse.FromString, - ) - return self._stubs["list_locations"] - - @property - def get_location( - self, - ) -> Callable[[locations_pb2.GetLocationRequest], locations_pb2.Location]: - r"""Return a callable for the list locations method over gRPC. - """ - # 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_location" not in self._stubs: - self._stubs["get_location"] = self.grpc_channel.unary_unary( - "/google.cloud.location.Locations/GetLocation", - request_serializer=locations_pb2.GetLocationRequest.SerializeToString, - response_deserializer=locations_pb2.Location.FromString, - ) - return self._stubs["get_location"] - - @property - def kind(self) -> str: - return "grpc" - - -__all__ = ( - 'AgentsGrpcTransport', -) diff --git a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/agents/transports/grpc_asyncio.py b/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/agents/transports/grpc_asyncio.py deleted file mode 100644 index 72f1bed1e..000000000 --- a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/agents/transports/grpc_asyncio.py +++ /dev/null @@ -1,677 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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 -from google.api_core import grpc_helpers_async -from google.api_core import operations_v1 -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore - -import grpc # type: ignore -from grpc.experimental import aio # type: ignore - -from google.cloud.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.cloud.location import locations_pb2 # type: ignore -from google.longrunning import operations_pb2 -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 - - -class AgentsGrpcAsyncIOTransport(AgentsTransport): - """gRPC AsyncIO backend transport for Agents. - - Service for managing - [Agents][google.cloud.dialogflow.v2beta1.Agent]. - - 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: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - **kwargs) -> aio.Channel: - """Create and return a gRPC AsyncIO channel object. - Args: - host (Optional[str]): The host for the channel to use. - credentials (Optional[~.Credentials]): The - authorization credentials to attach to requests. These - credentials identify this application to the service. If - none are specified, the client will attempt to ascertain - the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - kwargs (Optional[dict]): Keyword arguments, which are passed to the - channel creation. - Returns: - aio.Channel: A gRPC AsyncIO channel object. - """ - - return grpc_helpers_async.create_channel( - host, - credentials=credentials, - credentials_file=credentials_file, - quota_project_id=quota_project_id, - default_scopes=cls.AUTH_SCOPES, - scopes=scopes, - default_host=cls.DEFAULT_HOST, - **kwargs - ) - - def __init__(self, *, - host: str = 'dialogflow.googleapis.com', - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - channel: Optional[aio.Channel] = None, - api_mtls_endpoint: Optional[str] = None, - client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, - ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, - client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - api_audience: Optional[str] = None, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - This argument is ignored if ``channel`` is provided. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - channel (Optional[aio.Channel]): A ``Channel`` instance through - which to make calls. - api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. - If provided, it overrides the ``host`` argument and tries to create - a mutual TLS channel with client SSL credentials from - ``client_cert_source`` or application default SSL credentials. - client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): - Deprecated. A callback to provide client SSL certificate bytes and - private key bytes, both in PEM format. It is ignored if - ``api_mtls_endpoint`` is None. - ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials - for the grpc channel. It is ignored if ``channel`` is provided. - client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): - A callback to provide client certificate bytes and private key bytes, - both in PEM format. It is used to configure a mutual TLS channel. It is - ignored if ``channel`` or ``ssl_channel_credentials`` is provided. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - - Raises: - google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport - creation failed for any reason. - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - self._grpc_channel = None - self._ssl_channel_credentials = ssl_channel_credentials - self._stubs: Dict[str, Callable] = {} - self._operations_client: Optional[operations_v1.OperationsAsyncClient] = None - - if api_mtls_endpoint: - warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) - if client_cert_source: - warnings.warn("client_cert_source is deprecated", DeprecationWarning) - - if channel: - # Ignore credentials if a channel was passed. - credentials = False - # If a channel was explicitly provided, set it. - self._grpc_channel = channel - self._ssl_channel_credentials = None - else: - if api_mtls_endpoint: - host = api_mtls_endpoint - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - self._ssl_channel_credentials = SslCredentials().ssl_credentials - - else: - if client_cert_source_for_mtls and not ssl_channel_credentials: - cert, key = client_cert_source_for_mtls() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - - # The base transport sets the host, credentials and scopes - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes, - quota_project_id=quota_project_id, - client_info=client_info, - always_use_jwt_access=always_use_jwt_access, - api_audience=api_audience, - ) - - if not self._grpc_channel: - self._grpc_channel = type(self).create_channel( - self._host, - # use the credentials which are saved - credentials=self._credentials, - # Set ``credentials_file`` to ``None`` here as - # the credentials that we saved earlier should be used. - credentials_file=None, - 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 operations_client(self) -> operations_v1.OperationsAsyncClient: - """Create the client designed to process long-running operations. - - This property caches on the instance; repeated calls return the same - client. - """ - # Quick check: Only create a new client if we do not already have one. - if self._operations_client is None: - self._operations_client = operations_v1.OperationsAsyncClient( - self.grpc_channel - ) - - # Return the client from cache. - return self._operations_client - - @property - def get_agent(self) -> Callable[ - [agent.GetAgentRequest], - Awaitable[agent.Agent]]: - r"""Return a callable for the get agent method over gRPC. - - Retrieves the specified agent. - - Returns: - Callable[[~.GetAgentRequest], - Awaitable[~.Agent]]: - 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_agent' not in self._stubs: - self._stubs['get_agent'] = self.grpc_channel.unary_unary( - '/google.cloud.dialogflow.v2beta1.Agents/GetAgent', - request_serializer=agent.GetAgentRequest.serialize, - response_deserializer=agent.Agent.deserialize, - ) - return self._stubs['get_agent'] - - @property - def set_agent(self) -> Callable[ - [gcd_agent.SetAgentRequest], - Awaitable[gcd_agent.Agent]]: - r"""Return a callable for the set agent method over gRPC. - - Creates/updates the specified agent. - - Note: You should always train an agent prior to sending it - queries. See the `training - documentation `__. - - Returns: - Callable[[~.SetAgentRequest], - Awaitable[~.Agent]]: - 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 'set_agent' not in self._stubs: - self._stubs['set_agent'] = self.grpc_channel.unary_unary( - '/google.cloud.dialogflow.v2beta1.Agents/SetAgent', - request_serializer=gcd_agent.SetAgentRequest.serialize, - response_deserializer=gcd_agent.Agent.deserialize, - ) - return self._stubs['set_agent'] - - @property - def delete_agent(self) -> Callable[ - [agent.DeleteAgentRequest], - Awaitable[empty_pb2.Empty]]: - r"""Return a callable for the delete agent method over gRPC. - - Deletes the specified agent. - - Returns: - Callable[[~.DeleteAgentRequest], - 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_agent' not in self._stubs: - self._stubs['delete_agent'] = self.grpc_channel.unary_unary( - '/google.cloud.dialogflow.v2beta1.Agents/DeleteAgent', - request_serializer=agent.DeleteAgentRequest.serialize, - response_deserializer=empty_pb2.Empty.FromString, - ) - return self._stubs['delete_agent'] - - @property - def search_agents(self) -> Callable[ - [agent.SearchAgentsRequest], - Awaitable[agent.SearchAgentsResponse]]: - r"""Return a callable for the search agents method over gRPC. - - Returns the list of agents. Since there is at most one - conversational agent per project, this method is useful - primarily for listing all agents across projects the caller has - access to. One can achieve that with a wildcard project - collection id "-". Refer to `List - Sub-Collections `__. - - Returns: - Callable[[~.SearchAgentsRequest], - Awaitable[~.SearchAgentsResponse]]: - 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 'search_agents' not in self._stubs: - self._stubs['search_agents'] = self.grpc_channel.unary_unary( - '/google.cloud.dialogflow.v2beta1.Agents/SearchAgents', - request_serializer=agent.SearchAgentsRequest.serialize, - response_deserializer=agent.SearchAgentsResponse.deserialize, - ) - return self._stubs['search_agents'] - - @property - def train_agent(self) -> Callable[ - [agent.TrainAgentRequest], - Awaitable[operations_pb2.Operation]]: - r"""Return a callable for the train agent method over gRPC. - - Trains the specified agent. - - This method is a `long-running - operation `__. - The returned ``Operation`` type has the following - method-specific fields: - - - ``metadata``: An empty `Struct - message `__ - - ``response``: An `Empty - message `__ - - Note: You should always train an agent prior to sending it - queries. See the `training - documentation `__. - - Returns: - Callable[[~.TrainAgentRequest], - Awaitable[~.Operation]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'train_agent' not in self._stubs: - self._stubs['train_agent'] = self.grpc_channel.unary_unary( - '/google.cloud.dialogflow.v2beta1.Agents/TrainAgent', - request_serializer=agent.TrainAgentRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['train_agent'] - - @property - def export_agent(self) -> 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. - - This method is a `long-running - operation `__. - The returned ``Operation`` type has the following - method-specific fields: - - - ``metadata``: An empty `Struct - message `__ - - ``response``: - [ExportAgentResponse][google.cloud.dialogflow.v2beta1.ExportAgentResponse] - - Returns: - Callable[[~.ExportAgentRequest], - Awaitable[~.Operation]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'export_agent' not in self._stubs: - self._stubs['export_agent'] = self.grpc_channel.unary_unary( - '/google.cloud.dialogflow.v2beta1.Agents/ExportAgent', - request_serializer=agent.ExportAgentRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['export_agent'] - - @property - def import_agent(self) -> 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. - - Uploads new intents and entity types without deleting the - existing ones. Intents and entity types with the same name are - replaced with the new versions from - [ImportAgentRequest][google.cloud.dialogflow.v2beta1.ImportAgentRequest]. - After the import, the imported draft agent will be trained - automatically (unless disabled in agent settings). However, once - the import is done, training may not be completed yet. Please - call - [TrainAgent][google.cloud.dialogflow.v2beta1.Agents.TrainAgent] - and wait for the operation it returns in order to train - explicitly. - - This method is a `long-running - operation `__. - The returned ``Operation`` type has the following - method-specific fields: - - - ``metadata``: An empty `Struct - message `__ - - ``response``: An `Empty - message `__ - - The operation only tracks when importing is complete, not when - it is done training. - - Note: You should always train an agent prior to sending it - queries. See the `training - documentation `__. - - Returns: - Callable[[~.ImportAgentRequest], - Awaitable[~.Operation]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'import_agent' not in self._stubs: - self._stubs['import_agent'] = self.grpc_channel.unary_unary( - '/google.cloud.dialogflow.v2beta1.Agents/ImportAgent', - request_serializer=agent.ImportAgentRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['import_agent'] - - @property - def restore_agent(self) -> 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. - - Replaces the current agent version with a new one. All the - intents and entity types in the older version are deleted. After - the restore, the restored draft agent will be trained - automatically (unless disabled in agent settings). However, once - the restore is done, training may not be completed yet. Please - call - [TrainAgent][google.cloud.dialogflow.v2beta1.Agents.TrainAgent] - and wait for the operation it returns in order to train - explicitly. - - This method is a `long-running - operation `__. - The returned ``Operation`` type has the following - method-specific fields: - - - ``metadata``: An empty `Struct - message `__ - - ``response``: An `Empty - message `__ - - The operation only tracks when restoring is complete, not when - it is done training. - - Note: You should always train an agent prior to sending it - queries. See the `training - documentation `__. - - Returns: - Callable[[~.RestoreAgentRequest], - Awaitable[~.Operation]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'restore_agent' not in self._stubs: - self._stubs['restore_agent'] = self.grpc_channel.unary_unary( - '/google.cloud.dialogflow.v2beta1.Agents/RestoreAgent', - request_serializer=agent.RestoreAgentRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['restore_agent'] - - @property - def get_validation_result(self) -> Callable[ - [agent.GetValidationResultRequest], - Awaitable[validation_result.ValidationResult]]: - r"""Return a callable for the get validation result method over gRPC. - - Gets agent validation result. Agent validation is - performed during training time and is updated - automatically when training is completed. - - Returns: - Callable[[~.GetValidationResultRequest], - Awaitable[~.ValidationResult]]: - 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_validation_result' not in self._stubs: - self._stubs['get_validation_result'] = self.grpc_channel.unary_unary( - '/google.cloud.dialogflow.v2beta1.Agents/GetValidationResult', - request_serializer=agent.GetValidationResultRequest.serialize, - response_deserializer=validation_result.ValidationResult.deserialize, - ) - return self._stubs['get_validation_result'] - - def close(self): - return self.grpc_channel.close() - - @property - def cancel_operation( - self, - ) -> Callable[[operations_pb2.CancelOperationRequest], None]: - r"""Return a callable for the cancel_operation method over gRPC. - """ - # 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 "cancel_operation" not in self._stubs: - self._stubs["cancel_operation"] = self.grpc_channel.unary_unary( - "/google.longrunning.Operations/CancelOperation", - request_serializer=operations_pb2.CancelOperationRequest.SerializeToString, - response_deserializer=None, - ) - return self._stubs["cancel_operation"] - - @property - def get_operation( - self, - ) -> Callable[[operations_pb2.GetOperationRequest], operations_pb2.Operation]: - r"""Return a callable for the get_operation method over gRPC. - """ - # 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_operation" not in self._stubs: - self._stubs["get_operation"] = self.grpc_channel.unary_unary( - "/google.longrunning.Operations/GetOperation", - request_serializer=operations_pb2.GetOperationRequest.SerializeToString, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs["get_operation"] - - @property - def list_operations( - self, - ) -> Callable[[operations_pb2.ListOperationsRequest], operations_pb2.ListOperationsResponse]: - r"""Return a callable for the list_operations method over gRPC. - """ - # 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_operations" not in self._stubs: - self._stubs["list_operations"] = self.grpc_channel.unary_unary( - "/google.longrunning.Operations/ListOperations", - request_serializer=operations_pb2.ListOperationsRequest.SerializeToString, - response_deserializer=operations_pb2.ListOperationsResponse.FromString, - ) - return self._stubs["list_operations"] - - @property - def list_locations( - self, - ) -> Callable[[locations_pb2.ListLocationsRequest], locations_pb2.ListLocationsResponse]: - r"""Return a callable for the list locations method over gRPC. - """ - # 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_locations" not in self._stubs: - self._stubs["list_locations"] = self.grpc_channel.unary_unary( - "/google.cloud.location.Locations/ListLocations", - request_serializer=locations_pb2.ListLocationsRequest.SerializeToString, - response_deserializer=locations_pb2.ListLocationsResponse.FromString, - ) - return self._stubs["list_locations"] - - @property - def get_location( - self, - ) -> Callable[[locations_pb2.GetLocationRequest], locations_pb2.Location]: - r"""Return a callable for the list locations method over gRPC. - """ - # 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_location" not in self._stubs: - self._stubs["get_location"] = self.grpc_channel.unary_unary( - "/google.cloud.location.Locations/GetLocation", - request_serializer=locations_pb2.GetLocationRequest.SerializeToString, - response_deserializer=locations_pb2.Location.FromString, - ) - return self._stubs["get_location"] - - -__all__ = ( - 'AgentsGrpcAsyncIOTransport', -) diff --git a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/agents/transports/rest.py b/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/agents/transports/rest.py deleted file mode 100644 index c83999f4a..000000000 --- a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/agents/transports/rest.py +++ /dev/null @@ -1,1767 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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 google.auth.transport.requests import AuthorizedSession # type: ignore -import json # type: ignore -import grpc # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore -from google.auth import credentials as ga_credentials # type: ignore -from google.api_core import exceptions as core_exceptions -from google.api_core import retry as retries -from google.api_core import rest_helpers -from google.api_core import rest_streaming -from google.api_core import path_template -from google.api_core import gapic_v1 - -from google.protobuf import json_format -from google.api_core import operations_v1 -from google.cloud.location import locations_pb2 # type: ignore -from google.longrunning import operations_pb2 -from requests import __version__ as requests_version -import dataclasses -import re -from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union -import warnings - -try: - OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] -except AttributeError: # pragma: NO COVER - OptionalRetry = Union[retries.Retry, object] # 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 # type: ignore -from google.protobuf import empty_pb2 # type: ignore - -from .base import AgentsTransport, DEFAULT_CLIENT_INFO as BASE_DEFAULT_CLIENT_INFO - - -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=BASE_DEFAULT_CLIENT_INFO.gapic_version, - grpc_version=None, - rest_version=requests_version, -) - - -class AgentsRestInterceptor: - """Interceptor for Agents. - - Interceptors are used to manipulate requests, request metadata, and responses - in arbitrary ways. - Example use cases include: - * Logging - * Verifying requests according to service or custom semantics - * Stripping extraneous information from responses - - These use cases and more can be enabled by injecting an - instance of a custom subclass when constructing the AgentsRestTransport. - - .. code-block:: python - class MyCustomAgentsInterceptor(AgentsRestInterceptor): - def pre_delete_agent(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def pre_export_agent(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_export_agent(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_get_agent(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_get_agent(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_get_validation_result(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_get_validation_result(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_import_agent(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_import_agent(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_restore_agent(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_restore_agent(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_search_agents(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_search_agents(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_set_agent(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_set_agent(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_train_agent(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_train_agent(self, response): - logging.log(f"Received response: {response}") - return response - - transport = AgentsRestTransport(interceptor=MyCustomAgentsInterceptor()) - client = AgentsClient(transport=transport) - - - """ - def pre_delete_agent(self, request: agent.DeleteAgentRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[agent.DeleteAgentRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for delete_agent - - Override in a subclass to manipulate the request or metadata - before they are sent to the Agents server. - """ - return request, metadata - - def pre_export_agent(self, request: agent.ExportAgentRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[agent.ExportAgentRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for export_agent - - Override in a subclass to manipulate the request or metadata - before they are sent to the Agents server. - """ - return request, metadata - - def post_export_agent(self, response: operations_pb2.Operation) -> operations_pb2.Operation: - """Post-rpc interceptor for export_agent - - Override in a subclass to manipulate the response - after it is returned by the Agents server but before - it is returned to user code. - """ - return response - def pre_get_agent(self, request: agent.GetAgentRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[agent.GetAgentRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for get_agent - - Override in a subclass to manipulate the request or metadata - before they are sent to the Agents server. - """ - return request, metadata - - def post_get_agent(self, response: agent.Agent) -> agent.Agent: - """Post-rpc interceptor for get_agent - - Override in a subclass to manipulate the response - after it is returned by the Agents server but before - it is returned to user code. - """ - return response - def pre_get_validation_result(self, request: agent.GetValidationResultRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[agent.GetValidationResultRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for get_validation_result - - Override in a subclass to manipulate the request or metadata - before they are sent to the Agents server. - """ - return request, metadata - - def post_get_validation_result(self, response: validation_result.ValidationResult) -> validation_result.ValidationResult: - """Post-rpc interceptor for get_validation_result - - Override in a subclass to manipulate the response - after it is returned by the Agents server but before - it is returned to user code. - """ - return response - def pre_import_agent(self, request: agent.ImportAgentRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[agent.ImportAgentRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for import_agent - - Override in a subclass to manipulate the request or metadata - before they are sent to the Agents server. - """ - return request, metadata - - def post_import_agent(self, response: operations_pb2.Operation) -> operations_pb2.Operation: - """Post-rpc interceptor for import_agent - - Override in a subclass to manipulate the response - after it is returned by the Agents server but before - it is returned to user code. - """ - return response - def pre_restore_agent(self, request: agent.RestoreAgentRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[agent.RestoreAgentRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for restore_agent - - Override in a subclass to manipulate the request or metadata - before they are sent to the Agents server. - """ - return request, metadata - - def post_restore_agent(self, response: operations_pb2.Operation) -> operations_pb2.Operation: - """Post-rpc interceptor for restore_agent - - Override in a subclass to manipulate the response - after it is returned by the Agents server but before - it is returned to user code. - """ - return response - def pre_search_agents(self, request: agent.SearchAgentsRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[agent.SearchAgentsRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for search_agents - - Override in a subclass to manipulate the request or metadata - before they are sent to the Agents server. - """ - return request, metadata - - def post_search_agents(self, response: agent.SearchAgentsResponse) -> agent.SearchAgentsResponse: - """Post-rpc interceptor for search_agents - - Override in a subclass to manipulate the response - after it is returned by the Agents server but before - it is returned to user code. - """ - return response - def pre_set_agent(self, request: gcd_agent.SetAgentRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[gcd_agent.SetAgentRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for set_agent - - Override in a subclass to manipulate the request or metadata - before they are sent to the Agents server. - """ - return request, metadata - - def post_set_agent(self, response: gcd_agent.Agent) -> gcd_agent.Agent: - """Post-rpc interceptor for set_agent - - Override in a subclass to manipulate the response - after it is returned by the Agents server but before - it is returned to user code. - """ - return response - def pre_train_agent(self, request: agent.TrainAgentRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[agent.TrainAgentRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for train_agent - - Override in a subclass to manipulate the request or metadata - before they are sent to the Agents server. - """ - return request, metadata - - def post_train_agent(self, response: operations_pb2.Operation) -> operations_pb2.Operation: - """Post-rpc interceptor for train_agent - - Override in a subclass to manipulate the response - after it is returned by the Agents server but before - it is returned to user code. - """ - return response - - def pre_get_location( - self, request: locations_pb2.GetLocationRequest, metadata: Sequence[Tuple[str, str]] - ) -> Tuple[locations_pb2.GetLocationRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for get_location - - Override in a subclass to manipulate the request or metadata - before they are sent to the Agents server. - """ - return request, metadata - - def post_get_location( - self, response: locations_pb2.Location - ) -> locations_pb2.Location: - """Post-rpc interceptor for get_location - - Override in a subclass to manipulate the response - after it is returned by the Agents server but before - it is returned to user code. - """ - return response - def pre_list_locations( - self, request: locations_pb2.ListLocationsRequest, metadata: Sequence[Tuple[str, str]] - ) -> Tuple[locations_pb2.ListLocationsRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for list_locations - - Override in a subclass to manipulate the request or metadata - before they are sent to the Agents server. - """ - return request, metadata - - def post_list_locations( - self, response: locations_pb2.ListLocationsResponse - ) -> locations_pb2.ListLocationsResponse: - """Post-rpc interceptor for list_locations - - Override in a subclass to manipulate the response - after it is returned by the Agents server but before - it is returned to user code. - """ - return response - def pre_cancel_operation( - self, request: operations_pb2.CancelOperationRequest, metadata: Sequence[Tuple[str, str]] - ) -> Tuple[operations_pb2.CancelOperationRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for cancel_operation - - Override in a subclass to manipulate the request or metadata - before they are sent to the Agents server. - """ - return request, metadata - - def post_cancel_operation( - self, response: None - ) -> None: - """Post-rpc interceptor for cancel_operation - - Override in a subclass to manipulate the response - after it is returned by the Agents server but before - it is returned to user code. - """ - return response - def pre_get_operation( - self, request: operations_pb2.GetOperationRequest, metadata: Sequence[Tuple[str, str]] - ) -> Tuple[operations_pb2.GetOperationRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for get_operation - - Override in a subclass to manipulate the request or metadata - before they are sent to the Agents server. - """ - return request, metadata - - def post_get_operation( - self, response: operations_pb2.Operation - ) -> operations_pb2.Operation: - """Post-rpc interceptor for get_operation - - Override in a subclass to manipulate the response - after it is returned by the Agents server but before - it is returned to user code. - """ - return response - def pre_list_operations( - self, request: operations_pb2.ListOperationsRequest, metadata: Sequence[Tuple[str, str]] - ) -> Tuple[operations_pb2.ListOperationsRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for list_operations - - Override in a subclass to manipulate the request or metadata - before they are sent to the Agents server. - """ - return request, metadata - - def post_list_operations( - self, response: operations_pb2.ListOperationsResponse - ) -> operations_pb2.ListOperationsResponse: - """Post-rpc interceptor for list_operations - - Override in a subclass to manipulate the response - after it is returned by the Agents server but before - it is returned to user code. - """ - return response - - -@dataclasses.dataclass -class AgentsRestStub: - _session: AuthorizedSession - _host: str - _interceptor: AgentsRestInterceptor - - -class AgentsRestTransport(AgentsTransport): - """REST backend transport for Agents. - - Service for managing - [Agents][google.cloud.dialogflow.v2beta1.Agent]. - - 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 JSON representations of protocol buffers over HTTP/1.1 - - """ - - def __init__(self, *, - host: str = 'dialogflow.googleapis.com', - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - client_cert_source_for_mtls: Optional[Callable[[ - ], Tuple[bytes, bytes]]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - url_scheme: str = 'https', - interceptor: Optional[AgentsRestInterceptor] = None, - api_audience: Optional[str] = None, - ) -> 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 ignored if ``channel`` is provided. - scopes (Optional(Sequence[str])): A list of scopes. This argument is - ignored if ``channel`` is provided. - client_cert_source_for_mtls (Callable[[], Tuple[bytes, bytes]]): Client - certificate to configure mutual TLS HTTP channel. It is ignored - if ``channel`` is provided. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you are developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - url_scheme: the protocol scheme for the API endpoint. Normally - "https", but for testing or local servers, - "http" can be specified. - """ - # Run the base constructor - # TODO(yon-mg): resolve other ctor params i.e. scopes, quota, etc. - # TODO: When custom host (api_endpoint) is set, `scopes` must *also* be set on the - # credentials object - maybe_url_match = re.match("^(?Phttp(?:s)?://)?(?P.*)$", host) - if maybe_url_match is None: - raise ValueError(f"Unexpected hostname structure: {host}") # pragma: NO COVER - - url_match_items = maybe_url_match.groupdict() - - host = f"{url_scheme}://{host}" if not url_match_items["scheme"] else host - - super().__init__( - host=host, - credentials=credentials, - client_info=client_info, - always_use_jwt_access=always_use_jwt_access, - api_audience=api_audience - ) - self._session = AuthorizedSession( - self._credentials, default_host=self.DEFAULT_HOST) - self._operations_client: Optional[operations_v1.AbstractOperationsClient] = None - if client_cert_source_for_mtls: - self._session.configure_mtls_channel(client_cert_source_for_mtls) - self._interceptor = interceptor or AgentsRestInterceptor() - self._prep_wrapped_messages(client_info) - - @property - def operations_client(self) -> operations_v1.AbstractOperationsClient: - """Create the client designed to process long-running operations. - - This property caches on the instance; repeated calls return the same - client. - """ - # Only create a new client if we do not already have one. - if self._operations_client is None: - http_options: Dict[str, List[Dict[str, str]]] = { - 'google.longrunning.Operations.CancelOperation': [ - { - 'method': 'post', - 'uri': '/v2beta1/{name=projects/*/operations/*}:cancel', - }, - { - 'method': 'post', - 'uri': '/v2beta1/{name=projects/*/locations/*/operations/*}:cancel', - }, - ], - 'google.longrunning.Operations.GetOperation': [ - { - 'method': 'get', - 'uri': '/v2beta1/{name=projects/*/operations/*}', - }, - { - 'method': 'get', - 'uri': '/v2beta1/{name=projects/*/locations/*/operations/*}', - }, - ], - 'google.longrunning.Operations.ListOperations': [ - { - 'method': 'get', - 'uri': '/v2beta1/{name=projects/*}/operations', - }, - { - 'method': 'get', - 'uri': '/v2beta1/{name=projects/*/locations/*}/operations', - }, - ], - } - - rest_transport = operations_v1.OperationsRestTransport( - host=self._host, - # use the credentials which are saved - credentials=self._credentials, - scopes=self._scopes, - http_options=http_options, - path_prefix="v2beta1") - - self._operations_client = operations_v1.AbstractOperationsClient(transport=rest_transport) - - # Return the client from cache. - return self._operations_client - - class _DeleteAgent(AgentsRestStub): - def __hash__(self): - return hash("DeleteAgent") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: agent.DeleteAgentRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ): - r"""Call the delete agent method over HTTP. - - Args: - request (~.agent.DeleteAgentRequest): - The request object. The request message for - [Agents.DeleteAgent][google.cloud.dialogflow.v2beta1.Agents.DeleteAgent]. - 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. - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'delete', - 'uri': '/v2beta1/{parent=projects/*}/agent', - }, -{ - 'method': 'delete', - 'uri': '/v2beta1/{parent=projects/*/locations/*}/agent', - }, - ] - request, metadata = self._interceptor.pre_delete_agent(request, metadata) - pb_request = agent.DeleteAgentRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - including_default_value_fields=False, - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - class _ExportAgent(AgentsRestStub): - def __hash__(self): - return hash("ExportAgent") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: agent.ExportAgentRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> operations_pb2.Operation: - r"""Call the export agent method over HTTP. - - Args: - request (~.agent.ExportAgentRequest): - The request object. The request message for - [Agents.ExportAgent][google.cloud.dialogflow.v2beta1.Agents.ExportAgent]. - 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: - ~.operations_pb2.Operation: - This resource represents a - long-running operation that is the - result of a network API call. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'post', - 'uri': '/v2beta1/{parent=projects/*}/agent:export', - 'body': '*', - }, -{ - 'method': 'post', - 'uri': '/v2beta1/{parent=projects/*/locations/*}/agent:export', - 'body': '*', - }, - ] - request, metadata = self._interceptor.pre_export_agent(request, metadata) - pb_request = agent.ExportAgentRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request['body'], - including_default_value_fields=False, - use_integers_for_enums=True - ) - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - including_default_value_fields=False, - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = operations_pb2.Operation() - json_format.Parse(response.content, resp, ignore_unknown_fields=True) - resp = self._interceptor.post_export_agent(resp) - return resp - - class _GetAgent(AgentsRestStub): - def __hash__(self): - return hash("GetAgent") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: agent.GetAgentRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> agent.Agent: - r"""Call the get agent method over HTTP. - - Args: - request (~.agent.GetAgentRequest): - The request object. The request message for - [Agents.GetAgent][google.cloud.dialogflow.v2beta1.Agents.GetAgent]. - 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: - ~.agent.Agent: - A Dialogflow agent is a virtual agent that handles - conversations with your end-users. It is a natural - language understanding module that understands the - nuances of human language. Dialogflow translates - end-user text or audio during a conversation to - structured data that your apps and services can - understand. You design and build a Dialogflow agent to - handle the types of conversations required for your - system. - - For more information about agents, see the `Agent - guide `__. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v2beta1/{parent=projects/*}/agent', - }, -{ - 'method': 'get', - 'uri': '/v2beta1/{parent=projects/*/locations/*}/agent', - }, - ] - request, metadata = self._interceptor.pre_get_agent(request, metadata) - pb_request = agent.GetAgentRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - including_default_value_fields=False, - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = agent.Agent() - pb_resp = agent.Agent.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_get_agent(resp) - return resp - - class _GetValidationResult(AgentsRestStub): - def __hash__(self): - return hash("GetValidationResult") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: agent.GetValidationResultRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> validation_result.ValidationResult: - r"""Call the get validation result method over HTTP. - - Args: - request (~.agent.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. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.validation_result.ValidationResult: - Represents the output of agent - validation. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v2beta1/{parent=projects/*}/agent/validationResult', - }, -{ - 'method': 'get', - 'uri': '/v2beta1/{parent=projects/*/locations/*}/agent/validationResult', - }, - ] - request, metadata = self._interceptor.pre_get_validation_result(request, metadata) - pb_request = agent.GetValidationResultRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - including_default_value_fields=False, - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = validation_result.ValidationResult() - pb_resp = validation_result.ValidationResult.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_get_validation_result(resp) - return resp - - class _ImportAgent(AgentsRestStub): - def __hash__(self): - return hash("ImportAgent") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: agent.ImportAgentRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> operations_pb2.Operation: - r"""Call the import agent method over HTTP. - - Args: - request (~.agent.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. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.operations_pb2.Operation: - This resource represents a - long-running operation that is the - result of a network API call. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'post', - 'uri': '/v2beta1/{parent=projects/*}/agent:import', - 'body': '*', - }, -{ - 'method': 'post', - 'uri': '/v2beta1/{parent=projects/*/locations/*}/agent:import', - 'body': '*', - }, - ] - request, metadata = self._interceptor.pre_import_agent(request, metadata) - pb_request = agent.ImportAgentRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request['body'], - including_default_value_fields=False, - use_integers_for_enums=True - ) - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - including_default_value_fields=False, - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = operations_pb2.Operation() - json_format.Parse(response.content, resp, ignore_unknown_fields=True) - resp = self._interceptor.post_import_agent(resp) - return resp - - class _RestoreAgent(AgentsRestStub): - def __hash__(self): - return hash("RestoreAgent") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: agent.RestoreAgentRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> operations_pb2.Operation: - r"""Call the restore agent method over HTTP. - - Args: - request (~.agent.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. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.operations_pb2.Operation: - This resource represents a - long-running operation that is the - result of a network API call. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'post', - 'uri': '/v2beta1/{parent=projects/*}/agent:restore', - 'body': '*', - }, -{ - 'method': 'post', - 'uri': '/v2beta1/{parent=projects/*/locations/*}/agent:restore', - 'body': '*', - }, - ] - request, metadata = self._interceptor.pre_restore_agent(request, metadata) - pb_request = agent.RestoreAgentRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request['body'], - including_default_value_fields=False, - use_integers_for_enums=True - ) - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - including_default_value_fields=False, - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = operations_pb2.Operation() - json_format.Parse(response.content, resp, ignore_unknown_fields=True) - resp = self._interceptor.post_restore_agent(resp) - return resp - - class _SearchAgents(AgentsRestStub): - def __hash__(self): - return hash("SearchAgents") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: agent.SearchAgentsRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> agent.SearchAgentsResponse: - r"""Call the search agents method over HTTP. - - Args: - request (~.agent.SearchAgentsRequest): - The request object. The request message for - [Agents.SearchAgents][google.cloud.dialogflow.v2beta1.Agents.SearchAgents]. - 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: - ~.agent.SearchAgentsResponse: - The response message for - [Agents.SearchAgents][google.cloud.dialogflow.v2beta1.Agents.SearchAgents]. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v2beta1/{parent=projects/*}/agent:search', - }, -{ - 'method': 'get', - 'uri': '/v2beta1/{parent=projects/*/locations/*}/agent:search', - }, - ] - request, metadata = self._interceptor.pre_search_agents(request, metadata) - pb_request = agent.SearchAgentsRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - including_default_value_fields=False, - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = agent.SearchAgentsResponse() - pb_resp = agent.SearchAgentsResponse.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_search_agents(resp) - return resp - - class _SetAgent(AgentsRestStub): - def __hash__(self): - return hash("SetAgent") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: gcd_agent.SetAgentRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> gcd_agent.Agent: - r"""Call the set agent method over HTTP. - - Args: - request (~.gcd_agent.SetAgentRequest): - The request object. The request message for - [Agents.SetAgent][google.cloud.dialogflow.v2beta1.Agents.SetAgent]. - 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: - ~.gcd_agent.Agent: - A Dialogflow agent is a virtual agent that handles - conversations with your end-users. It is a natural - language understanding module that understands the - nuances of human language. Dialogflow translates - end-user text or audio during a conversation to - structured data that your apps and services can - understand. You design and build a Dialogflow agent to - handle the types of conversations required for your - system. - - For more information about agents, see the `Agent - guide `__. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'post', - 'uri': '/v2beta1/{agent.parent=projects/*}/agent', - 'body': 'agent', - }, -{ - 'method': 'post', - 'uri': '/v2beta1/{agent.parent=projects/*/locations/*}/agent', - 'body': 'agent', - }, - ] - request, metadata = self._interceptor.pre_set_agent(request, metadata) - pb_request = gcd_agent.SetAgentRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request['body'], - including_default_value_fields=False, - use_integers_for_enums=True - ) - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - including_default_value_fields=False, - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = gcd_agent.Agent() - pb_resp = gcd_agent.Agent.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_set_agent(resp) - return resp - - class _TrainAgent(AgentsRestStub): - def __hash__(self): - return hash("TrainAgent") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: agent.TrainAgentRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> operations_pb2.Operation: - r"""Call the train agent method over HTTP. - - Args: - request (~.agent.TrainAgentRequest): - The request object. The request message for - [Agents.TrainAgent][google.cloud.dialogflow.v2beta1.Agents.TrainAgent]. - 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: - ~.operations_pb2.Operation: - This resource represents a - long-running operation that is the - result of a network API call. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'post', - 'uri': '/v2beta1/{parent=projects/*}/agent:train', - 'body': '*', - }, -{ - 'method': 'post', - 'uri': '/v2beta1/{parent=projects/*/locations/*}/agent:train', - 'body': '*', - }, - ] - request, metadata = self._interceptor.pre_train_agent(request, metadata) - pb_request = agent.TrainAgentRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request['body'], - including_default_value_fields=False, - use_integers_for_enums=True - ) - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - including_default_value_fields=False, - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = operations_pb2.Operation() - json_format.Parse(response.content, resp, ignore_unknown_fields=True) - resp = self._interceptor.post_train_agent(resp) - return resp - - @property - def delete_agent(self) -> Callable[ - [agent.DeleteAgentRequest], - empty_pb2.Empty]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._DeleteAgent(self._session, self._host, self._interceptor) # type: ignore - - @property - def export_agent(self) -> Callable[ - [agent.ExportAgentRequest], - operations_pb2.Operation]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._ExportAgent(self._session, self._host, self._interceptor) # type: ignore - - @property - def get_agent(self) -> Callable[ - [agent.GetAgentRequest], - agent.Agent]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._GetAgent(self._session, self._host, self._interceptor) # type: ignore - - @property - def get_validation_result(self) -> Callable[ - [agent.GetValidationResultRequest], - validation_result.ValidationResult]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._GetValidationResult(self._session, self._host, self._interceptor) # type: ignore - - @property - def import_agent(self) -> Callable[ - [agent.ImportAgentRequest], - operations_pb2.Operation]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._ImportAgent(self._session, self._host, self._interceptor) # type: ignore - - @property - def restore_agent(self) -> Callable[ - [agent.RestoreAgentRequest], - operations_pb2.Operation]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._RestoreAgent(self._session, self._host, self._interceptor) # type: ignore - - @property - def search_agents(self) -> Callable[ - [agent.SearchAgentsRequest], - agent.SearchAgentsResponse]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._SearchAgents(self._session, self._host, self._interceptor) # type: ignore - - @property - def set_agent(self) -> Callable[ - [gcd_agent.SetAgentRequest], - gcd_agent.Agent]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._SetAgent(self._session, self._host, self._interceptor) # type: ignore - - @property - def train_agent(self) -> Callable[ - [agent.TrainAgentRequest], - operations_pb2.Operation]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._TrainAgent(self._session, self._host, self._interceptor) # type: ignore - - @property - def get_location(self): - return self._GetLocation(self._session, self._host, self._interceptor) # type: ignore - - class _GetLocation(AgentsRestStub): - def __call__(self, - request: locations_pb2.GetLocationRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> locations_pb2.Location: - - r"""Call the get location method over HTTP. - - Args: - request (locations_pb2.GetLocationRequest): - The request object for GetLocation method. - 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: - locations_pb2.Location: Response from GetLocation method. - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v2beta1/{name=projects/*/locations/*}', - }, - ] - - request, metadata = self._interceptor.pre_get_location(request, metadata) - request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode( - http_options, **request_kwargs) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json.dumps(transcoded_request['query_params'])) - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - resp = locations_pb2.Location() - resp = json_format.Parse(response.content.decode("utf-8"), resp) - resp = self._interceptor.post_get_location(resp) - return resp - - @property - def list_locations(self): - return self._ListLocations(self._session, self._host, self._interceptor) # type: ignore - - class _ListLocations(AgentsRestStub): - def __call__(self, - request: locations_pb2.ListLocationsRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> locations_pb2.ListLocationsResponse: - - r"""Call the list locations method over HTTP. - - Args: - request (locations_pb2.ListLocationsRequest): - The request object for ListLocations method. - 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: - locations_pb2.ListLocationsResponse: Response from ListLocations method. - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v2beta1/{name=projects/*}/locations', - }, - ] - - request, metadata = self._interceptor.pre_list_locations(request, metadata) - request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode( - http_options, **request_kwargs) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json.dumps(transcoded_request['query_params'])) - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - resp = locations_pb2.ListLocationsResponse() - resp = json_format.Parse(response.content.decode("utf-8"), resp) - resp = self._interceptor.post_list_locations(resp) - return resp - - @property - def cancel_operation(self): - return self._CancelOperation(self._session, self._host, self._interceptor) # type: ignore - - class _CancelOperation(AgentsRestStub): - def __call__(self, - request: operations_pb2.CancelOperationRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> None: - - r"""Call the cancel operation method over HTTP. - - Args: - request (operations_pb2.CancelOperationRequest): - The request object for CancelOperation method. - 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. - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'post', - 'uri': '/v2beta1/{name=projects/*/operations/*}:cancel', - }, -{ - 'method': 'post', - 'uri': '/v2beta1/{name=projects/*/locations/*/operations/*}:cancel', - }, - ] - - request, metadata = self._interceptor.pre_cancel_operation(request, metadata) - request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode( - http_options, **request_kwargs) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json.dumps(transcoded_request['query_params'])) - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - return self._interceptor.post_cancel_operation(None) - - @property - def get_operation(self): - return self._GetOperation(self._session, self._host, self._interceptor) # type: ignore - - class _GetOperation(AgentsRestStub): - def __call__(self, - request: operations_pb2.GetOperationRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> operations_pb2.Operation: - - r"""Call the get operation method over HTTP. - - Args: - request (operations_pb2.GetOperationRequest): - The request object for GetOperation method. - 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: - operations_pb2.Operation: Response from GetOperation method. - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v2beta1/{name=projects/*/operations/*}', - }, -{ - 'method': 'get', - 'uri': '/v2beta1/{name=projects/*/locations/*/operations/*}', - }, - ] - - request, metadata = self._interceptor.pre_get_operation(request, metadata) - request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode( - http_options, **request_kwargs) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json.dumps(transcoded_request['query_params'])) - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - resp = operations_pb2.Operation() - resp = json_format.Parse(response.content.decode("utf-8"), resp) - resp = self._interceptor.post_get_operation(resp) - return resp - - @property - def list_operations(self): - return self._ListOperations(self._session, self._host, self._interceptor) # type: ignore - - class _ListOperations(AgentsRestStub): - def __call__(self, - request: operations_pb2.ListOperationsRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> operations_pb2.ListOperationsResponse: - - r"""Call the list operations method over HTTP. - - Args: - request (operations_pb2.ListOperationsRequest): - The request object for ListOperations method. - 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: - operations_pb2.ListOperationsResponse: Response from ListOperations method. - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v2beta1/{name=projects/*}/operations', - }, -{ - 'method': 'get', - 'uri': '/v2beta1/{name=projects/*/locations/*}/operations', - }, - ] - - request, metadata = self._interceptor.pre_list_operations(request, metadata) - request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode( - http_options, **request_kwargs) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json.dumps(transcoded_request['query_params'])) - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - resp = operations_pb2.ListOperationsResponse() - resp = json_format.Parse(response.content.decode("utf-8"), resp) - resp = self._interceptor.post_list_operations(resp) - return resp - - @property - def kind(self) -> str: - return "rest" - - def close(self): - self._session.close() - - -__all__=( - 'AgentsRestTransport', -) diff --git a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/answer_records/__init__.py b/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/answer_records/__init__.py deleted file mode 100644 index cb89fc95a..000000000 --- a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/answer_records/__init__.py +++ /dev/null @@ -1,22 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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 AnswerRecordsClient -from .async_client import AnswerRecordsAsyncClient - -__all__ = ( - 'AnswerRecordsClient', - 'AnswerRecordsAsyncClient', -) diff --git a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/answer_records/async_client.py b/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/answer_records/async_client.py deleted file mode 100644 index 30200f642..000000000 --- a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/answer_records/async_client.py +++ /dev/null @@ -1,830 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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, Mapping, MutableMapping, MutableSequence, Optional, Sequence, Tuple, Type, Union -import warnings - -from google.cloud.dialogflow_v2beta1 import gapic_version as package_version - -from google.api_core.client_options import ClientOptions -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import retry as retries -from google.auth import credentials as ga_credentials # type: ignore -from google.oauth2 import service_account # type: ignore - -try: - OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] -except AttributeError: # pragma: NO COVER - OptionalRetry = Union[retries.Retry, object] # 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.cloud.location import locations_pb2 # type: ignore -from google.longrunning import operations_pb2 -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 - - -class AnswerRecordsAsyncClient: - """Service for managing - [AnswerRecords][google.cloud.dialogflow.v2beta1.AnswerRecord]. - """ - - _client: AnswerRecordsClient - - DEFAULT_ENDPOINT = AnswerRecordsClient.DEFAULT_ENDPOINT - DEFAULT_MTLS_ENDPOINT = AnswerRecordsClient.DEFAULT_MTLS_ENDPOINT - - answer_record_path = staticmethod(AnswerRecordsClient.answer_record_path) - 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) - - @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: - AnswerRecordsAsyncClient: The constructed client. - """ - return AnswerRecordsClient.from_service_account_info.__func__(AnswerRecordsAsyncClient, 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: - AnswerRecordsAsyncClient: The constructed client. - """ - return AnswerRecordsClient.from_service_account_file.__func__(AnswerRecordsAsyncClient, filename, *args, **kwargs) # type: ignore - - from_service_account_json = from_service_account_file - - @classmethod - def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[ClientOptions] = None): - """Return the API endpoint and client cert source for mutual TLS. - - The client cert source is determined in the following order: - (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the - client cert source is None. - (2) if `client_options.client_cert_source` is provided, use the provided one; if the - default client cert source exists, use the default one; otherwise the client cert - source is None. - - The API endpoint is determined in the following order: - (1) if `client_options.api_endpoint` if provided, use the provided one. - (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the - default mTLS endpoint; if the environment variable is "never", use the default API - endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise - use the default API endpoint. - - More details can be found at https://google.aip.dev/auth/4114. - - Args: - client_options (google.api_core.client_options.ClientOptions): Custom options for the - client. Only the `api_endpoint` and `client_cert_source` properties may be used - in this method. - - Returns: - Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the - client cert source to use. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If any errors happen. - """ - return AnswerRecordsClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore - - @property - def transport(self) -> AnswerRecordsTransport: - """Returns the transport used by the client instance. - - Returns: - AnswerRecordsTransport: The transport used by the client instance. - """ - return self._client.transport - - get_transport_class = functools.partial(type(AnswerRecordsClient).get_transport_class, type(AnswerRecordsClient)) - - def __init__(self, *, - credentials: Optional[ga_credentials.Credentials] = None, - transport: Union[str, AnswerRecordsTransport] = "grpc_asyncio", - client_options: Optional[ClientOptions] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the answer records 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, ~.AnswerRecordsTransport]): 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 = AnswerRecordsClient( - credentials=credentials, - transport=transport, - client_options=client_options, - client_info=client_info, - - ) - - async def get_answer_record(self, - request: Optional[Union[answer_record.GetAnswerRecordRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> answer_record.AnswerRecord: - r"""Deprecated. - Retrieves a specific answer record. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import dialogflow_v2beta1 - - async def sample_get_answer_record(): - # Create a client - client = dialogflow_v2beta1.AnswerRecordsAsyncClient() - - # Initialize request argument(s) - request = dialogflow_v2beta1.GetAnswerRecordRequest( - ) - - # Make the request - response = await client.get_answer_record(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.dialogflow_v2beta1.types.GetAnswerRecordRequest, dict]]): - 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. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.dialogflow_v2beta1.types.AnswerRecord: - Answer records are records to manage answer history and feedbacks for - Dialogflow. - - Currently, answer record includes: - - - human agent assistant article suggestion - - human agent assistant faq article - - It doesn't include: - - - DetectIntent intent matching - - DetectIntent knowledge - - Answer records are not related to the conversation - history in the Dialogflow Console. A Record is - generated even when the end-user disables - conversation history in the console. Records are - created when there's a human agent assistant - suggestion generated. - - A typical workflow for customers provide feedback to - an answer is: - - 1. For human agent assistant, customers get - suggestion via ListSuggestions API. Together with - 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. - - """ - warnings.warn("AnswerRecordsAsyncClient.get_answer_record is deprecated", - DeprecationWarning) - - # Create or coerce a protobuf request object. - request = answer_record.GetAnswerRecordRequest(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_answer_record, - 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 list_answer_records(self, - request: Optional[Union[answer_record.ListAnswerRecordsRequest, dict]] = None, - *, - parent: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListAnswerRecordsAsyncPager: - r"""Returns the list of all answer records in the - specified project in reverse chronological order. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import dialogflow_v2beta1 - - async def sample_list_answer_records(): - # Create a client - client = dialogflow_v2beta1.AnswerRecordsAsyncClient() - - # Initialize request argument(s) - request = dialogflow_v2beta1.ListAnswerRecordsRequest( - ) - - # Make the request - page_result = client.list_answer_records(request=request) - - # Handle the response - async for response in page_result: - print(response) - - Args: - request (Optional[Union[google.cloud.dialogflow_v2beta1.types.ListAnswerRecordsRequest, dict]]): - The request object. Request message for - [AnswerRecords.ListAnswerRecords][google.cloud.dialogflow.v2beta1.AnswerRecords.ListAnswerRecords]. - parent (:class:`str`): - Required. The project to list all answer records for in - reverse chronological order. Format: - ``projects//locations/``. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.dialogflow_v2beta1.services.answer_records.pagers.ListAnswerRecordsAsyncPager: - Response message for - [AnswerRecords.ListAnswerRecords][google.cloud.dialogflow.v2beta1.AnswerRecords.ListAnswerRecords]. - - Iterating over this object will yield results and - resolve additional pages automatically. - - """ - # Create or coerce a protobuf request object. - # Quick 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 = 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 - - # 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_answer_records, - 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.ListAnswerRecordsAsyncPager( - method=rpc, - request=request, - response=response, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def update_answer_record(self, - request: Optional[Union[gcd_answer_record.UpdateAnswerRecordRequest, dict]] = None, - *, - answer_record: Optional[gcd_answer_record.AnswerRecord] = None, - update_mask: Optional[field_mask_pb2.FieldMask] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gcd_answer_record.AnswerRecord: - r"""Updates the specified answer record. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import dialogflow_v2beta1 - - async def sample_update_answer_record(): - # Create a client - client = dialogflow_v2beta1.AnswerRecordsAsyncClient() - - # Initialize request argument(s) - request = dialogflow_v2beta1.UpdateAnswerRecordRequest( - ) - - # Make the request - response = await client.update_answer_record(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.dialogflow_v2beta1.types.UpdateAnswerRecordRequest, dict]]): - The request object. Request message for - [AnswerRecords.UpdateAnswerRecord][google.cloud.dialogflow.v2beta1.AnswerRecords.UpdateAnswerRecord]. - answer_record (:class:`google.cloud.dialogflow_v2beta1.types.AnswerRecord`): - Required. Answer record to update. - This corresponds to the ``answer_record`` 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.AnswerRecord: - Answer records are records to manage answer history and feedbacks for - Dialogflow. - - Currently, answer record includes: - - - human agent assistant article suggestion - - human agent assistant faq article - - It doesn't include: - - - DetectIntent intent matching - - DetectIntent knowledge - - Answer records are not related to the conversation - history in the Dialogflow Console. A Record is - generated even when the end-user disables - conversation history in the console. Records are - created when there's a human agent assistant - suggestion generated. - - A typical workflow for customers provide feedback to - an answer is: - - 1. For human agent assistant, customers get - suggestion via ListSuggestions API. Together with - 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. - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([answer_record, 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_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: - 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_answer_record, - 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(( - ("answer_record.name", request.answer_record.name), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def list_operations( - self, - request: Optional[operations_pb2.ListOperationsRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operations_pb2.ListOperationsResponse: - r"""Lists operations that match the specified filter in the request. - - Args: - request (:class:`~.operations_pb2.ListOperationsRequest`): - The request object. Request message for - `ListOperations` method. - 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: - ~.operations_pb2.ListOperationsResponse: - Response message for ``ListOperations`` method. - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = operations_pb2.ListOperationsRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._client._transport.list_operations, - 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 get_operation( - self, - request: Optional[operations_pb2.GetOperationRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operations_pb2.Operation: - r"""Gets the latest state of a long-running operation. - - Args: - request (:class:`~.operations_pb2.GetOperationRequest`): - The request object. Request message for - `GetOperation` method. - 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: - ~.operations_pb2.Operation: - An ``Operation`` object. - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = operations_pb2.GetOperationRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._client._transport.get_operation, - 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 cancel_operation( - self, - request: Optional[operations_pb2.CancelOperationRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> None: - r"""Starts asynchronous cancellation on a long-running operation. - - The server makes a best effort to cancel the operation, but success - is not guaranteed. If the server doesn't support this method, it returns - `google.rpc.Code.UNIMPLEMENTED`. - - Args: - request (:class:`~.operations_pb2.CancelOperationRequest`): - The request object. Request message for - `CancelOperation` method. - 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: - None - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = operations_pb2.CancelOperationRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._client._transport.cancel_operation, - 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_location( - self, - request: Optional[locations_pb2.GetLocationRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> locations_pb2.Location: - r"""Gets information about a location. - - Args: - request (:class:`~.location_pb2.GetLocationRequest`): - The request object. Request message for - `GetLocation` method. - 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: - ~.location_pb2.Location: - Location object. - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = locations_pb2.GetLocationRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._client._transport.get_location, - 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 list_locations( - self, - request: Optional[locations_pb2.ListLocationsRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> locations_pb2.ListLocationsResponse: - r"""Lists information about the supported locations for this service. - - Args: - request (:class:`~.location_pb2.ListLocationsRequest`): - The request object. Request message for - `ListLocations` method. - 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: - ~.location_pb2.ListLocationsResponse: - Response message for ``ListLocations`` method. - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = locations_pb2.ListLocationsRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._client._transport.list_locations, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("name", request.name),)), - ) - - # Send the request. - response = await rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - async def __aenter__(self): - return self - - async def __aexit__(self, exc_type, exc, tb): - await self.transport.close() - -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) - - -__all__ = ( - "AnswerRecordsAsyncClient", -) diff --git a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/answer_records/client.py b/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/answer_records/client.py deleted file mode 100644 index bf9e00f53..000000000 --- a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/answer_records/client.py +++ /dev/null @@ -1,1030 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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 os -import re -from typing import Dict, Mapping, MutableMapping, MutableSequence, Optional, Sequence, Tuple, Type, Union, cast -import warnings - -from google.cloud.dialogflow_v2beta1 import gapic_version as package_version - -from google.api_core import client_options as client_options_lib -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import retry as retries -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 - -try: - OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] -except AttributeError: # pragma: NO COVER - OptionalRetry = Union[retries.Retry, object] # 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.cloud.location import locations_pb2 # type: ignore -from google.longrunning import operations_pb2 -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 -from .transports.rest import AnswerRecordsRestTransport - - -class AnswerRecordsClientMeta(type): - """Metaclass for the AnswerRecords 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[AnswerRecordsTransport]] - _transport_registry["grpc"] = AnswerRecordsGrpcTransport - _transport_registry["grpc_asyncio"] = AnswerRecordsGrpcAsyncIOTransport - _transport_registry["rest"] = AnswerRecordsRestTransport - - def get_transport_class(cls, - label: Optional[str] = None, - ) -> Type[AnswerRecordsTransport]: - """Returns an appropriate transport class. - - Args: - label: The name of the desired transport. If none is - provided, then the first transport in the registry is used. - - Returns: - The transport class to use. - """ - # If a specific transport is requested, return that one. - if label: - return cls._transport_registry[label] - - # No transport is requested; return the default (that is, the first one - # in the dictionary). - return next(iter(cls._transport_registry.values())) - - -class AnswerRecordsClient(metaclass=AnswerRecordsClientMeta): - """Service for managing - [AnswerRecords][google.cloud.dialogflow.v2beta1.AnswerRecord]. - """ - - @staticmethod - def _get_default_mtls_endpoint(api_endpoint): - """Converts api endpoint to mTLS endpoint. - - Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to - "*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively. - Args: - api_endpoint (Optional[str]): the api endpoint to convert. - Returns: - str: converted mTLS api endpoint. - """ - if not api_endpoint: - return api_endpoint - - mtls_endpoint_re = re.compile( - r"(?P[^.]+)(?P\.mtls)?(?P\.sandbox)?(?P\.googleapis\.com)?" - ) - - m = mtls_endpoint_re.match(api_endpoint) - name, mtls, sandbox, googledomain = m.groups() - if mtls or not googledomain: - return api_endpoint - - if sandbox: - return api_endpoint.replace( - "sandbox.googleapis.com", "mtls.sandbox.googleapis.com" - ) - - return api_endpoint.replace(".googleapis.com", ".mtls.googleapis.com") - - DEFAULT_ENDPOINT = "dialogflow.googleapis.com" - DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore - DEFAULT_ENDPOINT - ) - - @classmethod - def from_service_account_info(cls, info: dict, *args, **kwargs): - """Creates an instance of this client using the provided credentials - info. - - Args: - info (dict): The service account private key info. - args: Additional arguments to pass to the constructor. - kwargs: Additional arguments to pass to the constructor. - - Returns: - AnswerRecordsClient: 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: - AnswerRecordsClient: 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) -> AnswerRecordsTransport: - """Returns the transport used by the client instance. - - Returns: - AnswerRecordsTransport: The transport used by the client - instance. - """ - return self._transport - - @staticmethod - def answer_record_path(project: str,answer_record: str,) -> str: - """Returns a fully-qualified answer_record string.""" - return "projects/{project}/answerRecords/{answer_record}".format(project=project, answer_record=answer_record, ) - - @staticmethod - def parse_answer_record_path(path: str) -> Dict[str,str]: - """Parses a answer_record path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/answerRecords/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_billing_account_path(billing_account: str, ) -> str: - """Returns a fully-qualified billing_account string.""" - return "billingAccounts/{billing_account}".format(billing_account=billing_account, ) - - @staticmethod - def parse_common_billing_account_path(path: str) -> Dict[str,str]: - """Parse a billing_account path into its component segments.""" - m = re.match(r"^billingAccounts/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_folder_path(folder: str, ) -> str: - """Returns a fully-qualified folder string.""" - return "folders/{folder}".format(folder=folder, ) - - @staticmethod - def parse_common_folder_path(path: str) -> Dict[str,str]: - """Parse a folder path into its component segments.""" - m = re.match(r"^folders/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_organization_path(organization: str, ) -> str: - """Returns a fully-qualified organization string.""" - return "organizations/{organization}".format(organization=organization, ) - - @staticmethod - def parse_common_organization_path(path: str) -> Dict[str,str]: - """Parse a organization path into its component segments.""" - m = re.match(r"^organizations/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_project_path(project: str, ) -> str: - """Returns a fully-qualified project string.""" - return "projects/{project}".format(project=project, ) - - @staticmethod - def parse_common_project_path(path: str) -> Dict[str,str]: - """Parse a project path into its component segments.""" - m = re.match(r"^projects/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_location_path(project: str, location: str, ) -> str: - """Returns a fully-qualified location string.""" - return "projects/{project}/locations/{location}".format(project=project, location=location, ) - - @staticmethod - def parse_common_location_path(path: str) -> Dict[str,str]: - """Parse a location path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)$", path) - return m.groupdict() if m else {} - - @classmethod - def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[client_options_lib.ClientOptions] = None): - """Return the API endpoint and client cert source for mutual TLS. - - The client cert source is determined in the following order: - (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the - client cert source is None. - (2) if `client_options.client_cert_source` is provided, use the provided one; if the - default client cert source exists, use the default one; otherwise the client cert - source is None. - - The API endpoint is determined in the following order: - (1) if `client_options.api_endpoint` if provided, use the provided one. - (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the - default mTLS endpoint; if the environment variable is "never", use the default API - endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise - use the default API endpoint. - - More details can be found at https://google.aip.dev/auth/4114. - - Args: - client_options (google.api_core.client_options.ClientOptions): Custom options for the - client. Only the `api_endpoint` and `client_cert_source` properties may be used - in this method. - - Returns: - Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the - client cert source to use. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If any errors happen. - """ - if client_options is None: - client_options = client_options_lib.ClientOptions() - use_client_cert = os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false") - use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") - if use_client_cert not in ("true", "false"): - raise ValueError("Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`") - if use_mtls_endpoint not in ("auto", "never", "always"): - raise MutualTLSChannelError("Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`") - - # Figure out the client cert source to use. - client_cert_source = None - if use_client_cert == "true": - if client_options.client_cert_source: - client_cert_source = client_options.client_cert_source - elif mtls.has_default_client_cert_source(): - client_cert_source = mtls.default_client_cert_source() - - # Figure out which api endpoint to use. - if client_options.api_endpoint is not None: - api_endpoint = client_options.api_endpoint - elif use_mtls_endpoint == "always" or (use_mtls_endpoint == "auto" and client_cert_source): - api_endpoint = cls.DEFAULT_MTLS_ENDPOINT - else: - api_endpoint = cls.DEFAULT_ENDPOINT - - return api_endpoint, client_cert_source - - def __init__(self, *, - credentials: Optional[ga_credentials.Credentials] = None, - transport: Optional[Union[str, AnswerRecordsTransport]] = None, - client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the answer records 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, AnswerRecordsTransport]): The - transport to use. If set to None, a transport is chosen - automatically. - client_options (Optional[Union[google.api_core.client_options.ClientOptions, dict]]): 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() - client_options = cast(client_options_lib.ClientOptions, client_options) - - api_endpoint, client_cert_source_func = self.get_mtls_endpoint_and_cert_source(client_options) - - api_key_value = getattr(client_options, "api_key", None) - if api_key_value and credentials: - raise ValueError("client_options.api_key and credentials are mutually exclusive") - - # 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, AnswerRecordsTransport): - # transport is a AnswerRecordsTransport instance. - if credentials or client_options.credentials_file or api_key_value: - 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: - import google.auth._default # type: ignore - - if api_key_value and hasattr(google.auth._default, "get_api_key_credentials"): - credentials = google.auth._default.get_api_key_credentials(api_key_value) - - Transport = type(self).get_transport_class(transport) - self._transport = Transport( - credentials=credentials, - credentials_file=client_options.credentials_file, - host=api_endpoint, - scopes=client_options.scopes, - client_cert_source_for_mtls=client_cert_source_func, - quota_project_id=client_options.quota_project_id, - client_info=client_info, - always_use_jwt_access=True, - api_audience=client_options.api_audience, - ) - - def get_answer_record(self, - request: Optional[Union[answer_record.GetAnswerRecordRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> answer_record.AnswerRecord: - r"""Deprecated. - Retrieves a specific answer record. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import dialogflow_v2beta1 - - def sample_get_answer_record(): - # Create a client - client = dialogflow_v2beta1.AnswerRecordsClient() - - # Initialize request argument(s) - request = dialogflow_v2beta1.GetAnswerRecordRequest( - ) - - # Make the request - response = client.get_answer_record(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.dialogflow_v2beta1.types.GetAnswerRecordRequest, dict]): - 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. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.dialogflow_v2beta1.types.AnswerRecord: - Answer records are records to manage answer history and feedbacks for - Dialogflow. - - Currently, answer record includes: - - - human agent assistant article suggestion - - human agent assistant faq article - - It doesn't include: - - - DetectIntent intent matching - - DetectIntent knowledge - - Answer records are not related to the conversation - history in the Dialogflow Console. A Record is - generated even when the end-user disables - conversation history in the console. Records are - created when there's a human agent assistant - suggestion generated. - - A typical workflow for customers provide feedback to - an answer is: - - 1. For human agent assistant, customers get - suggestion via ListSuggestions API. Together with - 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. - - """ - warnings.warn("AnswerRecordsClient.get_answer_record is deprecated", - DeprecationWarning) - - # 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 - # there are no flattened fields. - if not isinstance(request, answer_record.GetAnswerRecordRequest): - request = answer_record.GetAnswerRecordRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.get_answer_record] - - # 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 list_answer_records(self, - request: Optional[Union[answer_record.ListAnswerRecordsRequest, dict]] = None, - *, - parent: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListAnswerRecordsPager: - r"""Returns the list of all answer records in the - specified project in reverse chronological order. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import dialogflow_v2beta1 - - def sample_list_answer_records(): - # Create a client - client = dialogflow_v2beta1.AnswerRecordsClient() - - # Initialize request argument(s) - request = dialogflow_v2beta1.ListAnswerRecordsRequest( - ) - - # Make the request - page_result = client.list_answer_records(request=request) - - # Handle the response - for response in page_result: - print(response) - - Args: - request (Union[google.cloud.dialogflow_v2beta1.types.ListAnswerRecordsRequest, dict]): - The request object. Request message for - [AnswerRecords.ListAnswerRecords][google.cloud.dialogflow.v2beta1.AnswerRecords.ListAnswerRecords]. - parent (str): - Required. The project to list all answer records for in - reverse chronological order. Format: - ``projects//locations/``. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.dialogflow_v2beta1.services.answer_records.pagers.ListAnswerRecordsPager: - Response message for - [AnswerRecords.ListAnswerRecords][google.cloud.dialogflow.v2beta1.AnswerRecords.ListAnswerRecords]. - - Iterating over this object will yield results and - resolve additional pages automatically. - - """ - # Create or coerce a protobuf request object. - # Quick 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 answer_record.ListAnswerRecordsRequest. - # There's no risk of modifying the input as we've already verified - # 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 - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.list_answer_records] - - # 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.ListAnswerRecordsPager( - method=rpc, - request=request, - response=response, - metadata=metadata, - ) - - # Done; return the response. - return response - - def update_answer_record(self, - request: Optional[Union[gcd_answer_record.UpdateAnswerRecordRequest, dict]] = None, - *, - answer_record: Optional[gcd_answer_record.AnswerRecord] = None, - update_mask: Optional[field_mask_pb2.FieldMask] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gcd_answer_record.AnswerRecord: - r"""Updates the specified answer record. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import dialogflow_v2beta1 - - def sample_update_answer_record(): - # Create a client - client = dialogflow_v2beta1.AnswerRecordsClient() - - # Initialize request argument(s) - request = dialogflow_v2beta1.UpdateAnswerRecordRequest( - ) - - # Make the request - response = client.update_answer_record(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.dialogflow_v2beta1.types.UpdateAnswerRecordRequest, dict]): - The request object. Request message for - [AnswerRecords.UpdateAnswerRecord][google.cloud.dialogflow.v2beta1.AnswerRecords.UpdateAnswerRecord]. - answer_record (google.cloud.dialogflow_v2beta1.types.AnswerRecord): - Required. Answer record to update. - This corresponds to the ``answer_record`` 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.AnswerRecord: - Answer records are records to manage answer history and feedbacks for - Dialogflow. - - Currently, answer record includes: - - - human agent assistant article suggestion - - human agent assistant faq article - - It doesn't include: - - - DetectIntent intent matching - - DetectIntent knowledge - - Answer records are not related to the conversation - history in the Dialogflow Console. A Record is - generated even when the end-user disables - conversation history in the console. Records are - created when there's a human agent assistant - suggestion generated. - - A typical workflow for customers provide feedback to - an answer is: - - 1. For human agent assistant, customers get - suggestion via ListSuggestions API. Together with - 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. - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([answer_record, 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_answer_record.UpdateAnswerRecordRequest. - # There's no risk of modifying the input as we've already verified - # 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: - 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_answer_record] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("answer_record.name", request.answer_record.name), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def __enter__(self) -> "AnswerRecordsClient": - return self - - def __exit__(self, type, value, traceback): - """Releases underlying transport's resources. - - .. warning:: - ONLY use as a context manager if the transport is NOT shared - with other clients! Exiting the with block will CLOSE the transport - and may cause errors in other clients! - """ - self.transport.close() - - def list_operations( - self, - request: Optional[operations_pb2.ListOperationsRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operations_pb2.ListOperationsResponse: - r"""Lists operations that match the specified filter in the request. - - Args: - request (:class:`~.operations_pb2.ListOperationsRequest`): - The request object. Request message for - `ListOperations` method. - 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: - ~.operations_pb2.ListOperationsResponse: - Response message for ``ListOperations`` method. - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = operations_pb2.ListOperationsRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._transport.list_operations, - 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 = rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - def get_operation( - self, - request: Optional[operations_pb2.GetOperationRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operations_pb2.Operation: - r"""Gets the latest state of a long-running operation. - - Args: - request (:class:`~.operations_pb2.GetOperationRequest`): - The request object. Request message for - `GetOperation` method. - 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: - ~.operations_pb2.Operation: - An ``Operation`` object. - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = operations_pb2.GetOperationRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._transport.get_operation, - 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 = rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - def cancel_operation( - self, - request: Optional[operations_pb2.CancelOperationRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> None: - r"""Starts asynchronous cancellation on a long-running operation. - - The server makes a best effort to cancel the operation, but success - is not guaranteed. If the server doesn't support this method, it returns - `google.rpc.Code.UNIMPLEMENTED`. - - Args: - request (:class:`~.operations_pb2.CancelOperationRequest`): - The request object. Request message for - `CancelOperation` method. - 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: - None - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = operations_pb2.CancelOperationRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._transport.cancel_operation, - 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. - rpc(request, retry=retry, timeout=timeout, metadata=metadata,) - - def get_location( - self, - request: Optional[locations_pb2.GetLocationRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> locations_pb2.Location: - r"""Gets information about a location. - - Args: - request (:class:`~.location_pb2.GetLocationRequest`): - The request object. Request message for - `GetLocation` method. - 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: - ~.location_pb2.Location: - Location object. - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = locations_pb2.GetLocationRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._transport.get_location, - 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 = rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - def list_locations( - self, - request: Optional[locations_pb2.ListLocationsRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> locations_pb2.ListLocationsResponse: - r"""Lists information about the supported locations for this service. - - Args: - request (:class:`~.location_pb2.ListLocationsRequest`): - The request object. Request message for - `ListLocations` method. - 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: - ~.location_pb2.ListLocationsResponse: - Response message for ``ListLocations`` method. - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = locations_pb2.ListLocationsRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._transport.list_locations, - 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 = rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) - - -__all__ = ( - "AnswerRecordsClient", -) diff --git a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/answer_records/pagers.py b/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/answer_records/pagers.py deleted file mode 100644 index a63748ca3..000000000 --- a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/answer_records/pagers.py +++ /dev/null @@ -1,139 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from typing import Any, AsyncIterator, Awaitable, Callable, Sequence, Tuple, Optional, Iterator - -from google.cloud.dialogflow_v2beta1.types import answer_record - - -class ListAnswerRecordsPager: - """A pager for iterating through ``list_answer_records`` requests. - - This class thinly wraps an initial - :class:`google.cloud.dialogflow_v2beta1.types.ListAnswerRecordsResponse` object, and - provides an ``__iter__`` method to iterate through its - ``answer_records`` field. - - If there are more pages, the ``__iter__`` method will make additional - ``ListAnswerRecords`` requests and continue to iterate - through the ``answer_records`` field on the - corresponding responses. - - All the usual :class:`google.cloud.dialogflow_v2beta1.types.ListAnswerRecordsResponse` - 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[..., answer_record.ListAnswerRecordsResponse], - request: answer_record.ListAnswerRecordsRequest, - response: answer_record.ListAnswerRecordsResponse, - *, - 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.ListAnswerRecordsRequest): - The initial request object. - response (google.cloud.dialogflow_v2beta1.types.ListAnswerRecordsResponse): - 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 = answer_record.ListAnswerRecordsRequest(request) - self._response = response - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - def pages(self) -> Iterator[answer_record.ListAnswerRecordsResponse]: - yield self._response - while self._response.next_page_token: - self._request.page_token = self._response.next_page_token - self._response = self._method(self._request, metadata=self._metadata) - yield self._response - - def __iter__(self) -> Iterator[answer_record.AnswerRecord]: - for page in self.pages: - yield from page.answer_records - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListAnswerRecordsAsyncPager: - """A pager for iterating through ``list_answer_records`` requests. - - This class thinly wraps an initial - :class:`google.cloud.dialogflow_v2beta1.types.ListAnswerRecordsResponse` object, and - provides an ``__aiter__`` method to iterate through its - ``answer_records`` field. - - If there are more pages, the ``__aiter__`` method will make additional - ``ListAnswerRecords`` requests and continue to iterate - through the ``answer_records`` field on the - corresponding responses. - - All the usual :class:`google.cloud.dialogflow_v2beta1.types.ListAnswerRecordsResponse` - 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[answer_record.ListAnswerRecordsResponse]], - request: answer_record.ListAnswerRecordsRequest, - response: answer_record.ListAnswerRecordsResponse, - *, - metadata: Sequence[Tuple[str, str]] = ()): - """Instantiates the pager. - - Args: - method (Callable): The method that was originally called, and - which instantiated this pager. - request (google.cloud.dialogflow_v2beta1.types.ListAnswerRecordsRequest): - The initial request object. - response (google.cloud.dialogflow_v2beta1.types.ListAnswerRecordsResponse): - 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 = answer_record.ListAnswerRecordsRequest(request) - self._response = response - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - async def pages(self) -> AsyncIterator[answer_record.ListAnswerRecordsResponse]: - yield self._response - while self._response.next_page_token: - self._request.page_token = self._response.next_page_token - self._response = await self._method(self._request, metadata=self._metadata) - yield self._response - def __aiter__(self) -> AsyncIterator[answer_record.AnswerRecord]: - async def async_generator(): - async for page in self.pages: - for response in page.answer_records: - yield response - - return async_generator() - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) diff --git a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/answer_records/transports/__init__.py b/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/answer_records/transports/__init__.py deleted file mode 100644 index 1285a3133..000000000 --- a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/answer_records/transports/__init__.py +++ /dev/null @@ -1,38 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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 AnswerRecordsTransport -from .grpc import AnswerRecordsGrpcTransport -from .grpc_asyncio import AnswerRecordsGrpcAsyncIOTransport -from .rest import AnswerRecordsRestTransport -from .rest import AnswerRecordsRestInterceptor - - -# Compile a registry of transports. -_transport_registry = OrderedDict() # type: Dict[str, Type[AnswerRecordsTransport]] -_transport_registry['grpc'] = AnswerRecordsGrpcTransport -_transport_registry['grpc_asyncio'] = AnswerRecordsGrpcAsyncIOTransport -_transport_registry['rest'] = AnswerRecordsRestTransport - -__all__ = ( - 'AnswerRecordsTransport', - 'AnswerRecordsGrpcTransport', - 'AnswerRecordsGrpcAsyncIOTransport', - 'AnswerRecordsRestTransport', - 'AnswerRecordsRestInterceptor', -) diff --git a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/answer_records/transports/base.py b/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/answer_records/transports/base.py deleted file mode 100644 index de9456951..000000000 --- a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/answer_records/transports/base.py +++ /dev/null @@ -1,223 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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 - -from google.cloud.dialogflow_v2beta1 import gapic_version as package_version - -import google.auth # type: ignore -import google.api_core -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import retry as retries -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 answer_record -from google.cloud.dialogflow_v2beta1.types import answer_record as gcd_answer_record -from google.cloud.location import locations_pb2 # type: ignore -from google.longrunning import operations_pb2 - -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) - - -class AnswerRecordsTransport(abc.ABC): - """Abstract transport class for AnswerRecords.""" - - 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: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - api_audience: Optional[str] = None, - **kwargs, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. - scopes (Optional[Sequence[str]]): A list of scopes. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - """ - - scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} - - # Save the scopes. - self._scopes = scopes - - # If no credentials are provided, then determine the appropriate - # defaults. - if credentials and credentials_file: - raise core_exceptions.DuplicateCredentialArgs("'credentials_file' and 'credentials' are mutually exclusive") - - if credentials_file is not None: - credentials, _ = google.auth.load_credentials_from_file( - credentials_file, - **scopes_kwargs, - quota_project_id=quota_project_id - ) - elif credentials is None: - credentials, _ = google.auth.default(**scopes_kwargs, quota_project_id=quota_project_id) - # Don't apply audience if the credentials file passed from user. - if hasattr(credentials, "with_gdch_audience"): - credentials = credentials.with_gdch_audience(api_audience if api_audience else host) - - # If the credentials are service account credentials, then always try to use self signed JWT. - if always_use_jwt_access and isinstance(credentials, service_account.Credentials) and hasattr(service_account.Credentials, "with_always_use_jwt_access"): - credentials = credentials.with_always_use_jwt_access(True) - - # Save the credentials. - self._credentials = credentials - - # Save the hostname. Default to port 443 (HTTPS) if none is specified. - if ':' not in host: - host += ':443' - self._host = host - - def _prep_wrapped_messages(self, client_info): - # Precompute the wrapped methods. - self._wrapped_methods = { - self.get_answer_record: gapic_v1.method.wrap_method( - self.get_answer_record, - default_timeout=None, - client_info=client_info, - ), - self.list_answer_records: gapic_v1.method.wrap_method( - self.list_answer_records, - default_timeout=None, - client_info=client_info, - ), - self.update_answer_record: gapic_v1.method.wrap_method( - self.update_answer_record, - default_timeout=None, - client_info=client_info, - ), - } - - def close(self): - """Closes resources associated with the transport. - - .. warning:: - Only call this method if the transport is NOT shared - with other clients - this may cause errors in other clients! - """ - raise NotImplementedError() - - @property - def get_answer_record(self) -> Callable[ - [answer_record.GetAnswerRecordRequest], - Union[ - answer_record.AnswerRecord, - Awaitable[answer_record.AnswerRecord] - ]]: - raise NotImplementedError() - - @property - def list_answer_records(self) -> Callable[ - [answer_record.ListAnswerRecordsRequest], - Union[ - answer_record.ListAnswerRecordsResponse, - Awaitable[answer_record.ListAnswerRecordsResponse] - ]]: - raise NotImplementedError() - - @property - def update_answer_record(self) -> Callable[ - [gcd_answer_record.UpdateAnswerRecordRequest], - Union[ - gcd_answer_record.AnswerRecord, - Awaitable[gcd_answer_record.AnswerRecord] - ]]: - raise NotImplementedError() - - @property - def list_operations( - self, - ) -> Callable[ - [operations_pb2.ListOperationsRequest], - Union[operations_pb2.ListOperationsResponse, Awaitable[operations_pb2.ListOperationsResponse]], - ]: - raise NotImplementedError() - - @property - def get_operation( - self, - ) -> Callable[ - [operations_pb2.GetOperationRequest], - Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], - ]: - raise NotImplementedError() - - @property - def cancel_operation( - self, - ) -> Callable[ - [operations_pb2.CancelOperationRequest], - None, - ]: - raise NotImplementedError() - - @property - def get_location(self, - ) -> Callable[ - [locations_pb2.GetLocationRequest], - Union[locations_pb2.Location, Awaitable[locations_pb2.Location]], - ]: - raise NotImplementedError() - - @property - def list_locations(self, - ) -> Callable[ - [locations_pb2.ListLocationsRequest], - Union[locations_pb2.ListLocationsResponse, Awaitable[locations_pb2.ListLocationsResponse]], - ]: - raise NotImplementedError() - - @property - def kind(self) -> str: - raise NotImplementedError() - - -__all__ = ( - 'AnswerRecordsTransport', -) diff --git a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/answer_records/transports/grpc.py b/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/answer_records/transports/grpc.py deleted file mode 100644 index d44800137..000000000 --- a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/answer_records/transports/grpc.py +++ /dev/null @@ -1,412 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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 -from google.api_core import gapic_v1 -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 google.cloud.location import locations_pb2 # type: ignore -from google.longrunning import operations_pb2 -from .base import AnswerRecordsTransport, DEFAULT_CLIENT_INFO - - -class AnswerRecordsGrpcTransport(AnswerRecordsTransport): - """gRPC backend transport for AnswerRecords. - - Service for managing - [AnswerRecords][google.cloud.dialogflow.v2beta1.AnswerRecord]. - - 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: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - channel: Optional[grpc.Channel] = None, - api_mtls_endpoint: Optional[str] = None, - client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, - ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, - client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - api_audience: Optional[str] = None, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - This argument is ignored if ``channel`` is provided. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional(Sequence[str])): A list of scopes. This argument is - ignored if ``channel`` is provided. - channel (Optional[grpc.Channel]): A ``Channel`` instance through - which to make calls. - api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. - If provided, it overrides the ``host`` argument and tries to create - a mutual TLS channel with client SSL credentials from - ``client_cert_source`` or application default SSL credentials. - client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): - Deprecated. A callback to provide client SSL certificate bytes and - private key bytes, both in PEM format. It is ignored if - ``api_mtls_endpoint`` is None. - ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials - for the grpc channel. It is ignored if ``channel`` is provided. - client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): - A callback to provide client certificate bytes and private key bytes, - both in PEM format. It is used to configure a mutual TLS channel. It is - ignored if ``channel`` or ``ssl_channel_credentials`` is provided. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport - creation failed for any reason. - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - self._grpc_channel = None - self._ssl_channel_credentials = ssl_channel_credentials - self._stubs: Dict[str, Callable] = {} - - if api_mtls_endpoint: - warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) - if client_cert_source: - warnings.warn("client_cert_source is deprecated", DeprecationWarning) - - if channel: - # Ignore credentials if a channel was passed. - credentials = False - # If a channel was explicitly provided, set it. - self._grpc_channel = channel - self._ssl_channel_credentials = None - - else: - if api_mtls_endpoint: - host = api_mtls_endpoint - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - self._ssl_channel_credentials = SslCredentials().ssl_credentials - - else: - if client_cert_source_for_mtls and not ssl_channel_credentials: - cert, key = client_cert_source_for_mtls() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - - # The base transport sets the host, credentials and scopes - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes, - quota_project_id=quota_project_id, - client_info=client_info, - always_use_jwt_access=always_use_jwt_access, - api_audience=api_audience, - ) - - if not self._grpc_channel: - self._grpc_channel = type(self).create_channel( - self._host, - # use the credentials which are saved - credentials=self._credentials, - # Set ``credentials_file`` to ``None`` here as - # the credentials that we saved earlier should be used. - credentials_file=None, - 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: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - **kwargs) -> grpc.Channel: - """Create and return a gRPC channel object. - Args: - host (Optional[str]): The host for the channel to use. - credentials (Optional[~.Credentials]): The - authorization credentials to attach to requests. These - credentials identify this application to the service. If - none are specified, the client will attempt to ascertain - the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - kwargs (Optional[dict]): Keyword arguments, which are passed to the - channel creation. - Returns: - grpc.Channel: A gRPC channel object. - - Raises: - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - - return grpc_helpers.create_channel( - host, - credentials=credentials, - credentials_file=credentials_file, - quota_project_id=quota_project_id, - default_scopes=cls.AUTH_SCOPES, - scopes=scopes, - default_host=cls.DEFAULT_HOST, - **kwargs - ) - - @property - def grpc_channel(self) -> grpc.Channel: - """Return the channel designed to connect to this service. - """ - return self._grpc_channel - - @property - def get_answer_record(self) -> Callable[ - [answer_record.GetAnswerRecordRequest], - answer_record.AnswerRecord]: - r"""Return a callable for the get answer record method over gRPC. - - Deprecated. - Retrieves a specific answer record. - - Returns: - Callable[[~.GetAnswerRecordRequest], - ~.AnswerRecord]: - 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_answer_record' not in self._stubs: - self._stubs['get_answer_record'] = self.grpc_channel.unary_unary( - '/google.cloud.dialogflow.v2beta1.AnswerRecords/GetAnswerRecord', - request_serializer=answer_record.GetAnswerRecordRequest.serialize, - response_deserializer=answer_record.AnswerRecord.deserialize, - ) - return self._stubs['get_answer_record'] - - @property - def list_answer_records(self) -> Callable[ - [answer_record.ListAnswerRecordsRequest], - answer_record.ListAnswerRecordsResponse]: - r"""Return a callable for the list answer records method over gRPC. - - Returns the list of all answer records in the - specified project in reverse chronological order. - - Returns: - Callable[[~.ListAnswerRecordsRequest], - ~.ListAnswerRecordsResponse]: - 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_answer_records' not in self._stubs: - self._stubs['list_answer_records'] = self.grpc_channel.unary_unary( - '/google.cloud.dialogflow.v2beta1.AnswerRecords/ListAnswerRecords', - request_serializer=answer_record.ListAnswerRecordsRequest.serialize, - response_deserializer=answer_record.ListAnswerRecordsResponse.deserialize, - ) - return self._stubs['list_answer_records'] - - @property - def update_answer_record(self) -> Callable[ - [gcd_answer_record.UpdateAnswerRecordRequest], - gcd_answer_record.AnswerRecord]: - r"""Return a callable for the update answer record method over gRPC. - - Updates the specified answer record. - - Returns: - Callable[[~.UpdateAnswerRecordRequest], - ~.AnswerRecord]: - 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_answer_record' not in self._stubs: - self._stubs['update_answer_record'] = self.grpc_channel.unary_unary( - '/google.cloud.dialogflow.v2beta1.AnswerRecords/UpdateAnswerRecord', - request_serializer=gcd_answer_record.UpdateAnswerRecordRequest.serialize, - response_deserializer=gcd_answer_record.AnswerRecord.deserialize, - ) - return self._stubs['update_answer_record'] - - def close(self): - self.grpc_channel.close() - - @property - def cancel_operation( - self, - ) -> Callable[[operations_pb2.CancelOperationRequest], None]: - r"""Return a callable for the cancel_operation method over gRPC. - """ - # 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 "cancel_operation" not in self._stubs: - self._stubs["cancel_operation"] = self.grpc_channel.unary_unary( - "/google.longrunning.Operations/CancelOperation", - request_serializer=operations_pb2.CancelOperationRequest.SerializeToString, - response_deserializer=None, - ) - return self._stubs["cancel_operation"] - - @property - def get_operation( - self, - ) -> Callable[[operations_pb2.GetOperationRequest], operations_pb2.Operation]: - r"""Return a callable for the get_operation method over gRPC. - """ - # 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_operation" not in self._stubs: - self._stubs["get_operation"] = self.grpc_channel.unary_unary( - "/google.longrunning.Operations/GetOperation", - request_serializer=operations_pb2.GetOperationRequest.SerializeToString, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs["get_operation"] - - @property - def list_operations( - self, - ) -> Callable[[operations_pb2.ListOperationsRequest], operations_pb2.ListOperationsResponse]: - r"""Return a callable for the list_operations method over gRPC. - """ - # 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_operations" not in self._stubs: - self._stubs["list_operations"] = self.grpc_channel.unary_unary( - "/google.longrunning.Operations/ListOperations", - request_serializer=operations_pb2.ListOperationsRequest.SerializeToString, - response_deserializer=operations_pb2.ListOperationsResponse.FromString, - ) - return self._stubs["list_operations"] - - @property - def list_locations( - self, - ) -> Callable[[locations_pb2.ListLocationsRequest], locations_pb2.ListLocationsResponse]: - r"""Return a callable for the list locations method over gRPC. - """ - # 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_locations" not in self._stubs: - self._stubs["list_locations"] = self.grpc_channel.unary_unary( - "/google.cloud.location.Locations/ListLocations", - request_serializer=locations_pb2.ListLocationsRequest.SerializeToString, - response_deserializer=locations_pb2.ListLocationsResponse.FromString, - ) - return self._stubs["list_locations"] - - @property - def get_location( - self, - ) -> Callable[[locations_pb2.GetLocationRequest], locations_pb2.Location]: - r"""Return a callable for the list locations method over gRPC. - """ - # 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_location" not in self._stubs: - self._stubs["get_location"] = self.grpc_channel.unary_unary( - "/google.cloud.location.Locations/GetLocation", - request_serializer=locations_pb2.GetLocationRequest.SerializeToString, - response_deserializer=locations_pb2.Location.FromString, - ) - return self._stubs["get_location"] - - @property - def kind(self) -> str: - return "grpc" - - -__all__ = ( - 'AnswerRecordsGrpcTransport', -) diff --git a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/answer_records/transports/grpc_asyncio.py b/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/answer_records/transports/grpc_asyncio.py deleted file mode 100644 index 48d5b5ee2..000000000 --- a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/answer_records/transports/grpc_asyncio.py +++ /dev/null @@ -1,411 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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 -from google.api_core import grpc_helpers_async -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore - -import grpc # type: ignore -from grpc.experimental import aio # type: ignore - -from google.cloud.dialogflow_v2beta1.types import answer_record -from google.cloud.dialogflow_v2beta1.types import answer_record as gcd_answer_record -from google.cloud.location import locations_pb2 # type: ignore -from google.longrunning import operations_pb2 -from .base import AnswerRecordsTransport, DEFAULT_CLIENT_INFO -from .grpc import AnswerRecordsGrpcTransport - - -class AnswerRecordsGrpcAsyncIOTransport(AnswerRecordsTransport): - """gRPC AsyncIO backend transport for AnswerRecords. - - Service for managing - [AnswerRecords][google.cloud.dialogflow.v2beta1.AnswerRecord]. - - 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: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - **kwargs) -> aio.Channel: - """Create and return a gRPC AsyncIO channel object. - Args: - host (Optional[str]): The host for the channel to use. - credentials (Optional[~.Credentials]): The - authorization credentials to attach to requests. These - credentials identify this application to the service. If - none are specified, the client will attempt to ascertain - the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - kwargs (Optional[dict]): Keyword arguments, which are passed to the - channel creation. - Returns: - aio.Channel: A gRPC AsyncIO channel object. - """ - - return grpc_helpers_async.create_channel( - host, - credentials=credentials, - credentials_file=credentials_file, - quota_project_id=quota_project_id, - default_scopes=cls.AUTH_SCOPES, - scopes=scopes, - default_host=cls.DEFAULT_HOST, - **kwargs - ) - - def __init__(self, *, - host: str = 'dialogflow.googleapis.com', - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - channel: Optional[aio.Channel] = None, - api_mtls_endpoint: Optional[str] = None, - client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, - ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, - client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - api_audience: Optional[str] = None, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - This argument is ignored if ``channel`` is provided. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - channel (Optional[aio.Channel]): A ``Channel`` instance through - which to make calls. - api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. - If provided, it overrides the ``host`` argument and tries to create - a mutual TLS channel with client SSL credentials from - ``client_cert_source`` or application default SSL credentials. - client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): - Deprecated. A callback to provide client SSL certificate bytes and - private key bytes, both in PEM format. It is ignored if - ``api_mtls_endpoint`` is None. - ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials - for the grpc channel. It is ignored if ``channel`` is provided. - client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): - A callback to provide client certificate bytes and private key bytes, - both in PEM format. It is used to configure a mutual TLS channel. It is - ignored if ``channel`` or ``ssl_channel_credentials`` is provided. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - - Raises: - google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport - creation failed for any reason. - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - self._grpc_channel = None - self._ssl_channel_credentials = ssl_channel_credentials - self._stubs: Dict[str, Callable] = {} - - if api_mtls_endpoint: - warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) - if client_cert_source: - warnings.warn("client_cert_source is deprecated", DeprecationWarning) - - if channel: - # Ignore credentials if a channel was passed. - credentials = False - # If a channel was explicitly provided, set it. - self._grpc_channel = channel - self._ssl_channel_credentials = None - else: - if api_mtls_endpoint: - host = api_mtls_endpoint - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - self._ssl_channel_credentials = SslCredentials().ssl_credentials - - else: - if client_cert_source_for_mtls and not ssl_channel_credentials: - cert, key = client_cert_source_for_mtls() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - - # The base transport sets the host, credentials and scopes - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes, - quota_project_id=quota_project_id, - client_info=client_info, - always_use_jwt_access=always_use_jwt_access, - api_audience=api_audience, - ) - - if not self._grpc_channel: - self._grpc_channel = type(self).create_channel( - self._host, - # use the credentials which are saved - credentials=self._credentials, - # Set ``credentials_file`` to ``None`` here as - # the credentials that we saved earlier should be used. - credentials_file=None, - 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_answer_record(self) -> Callable[ - [answer_record.GetAnswerRecordRequest], - Awaitable[answer_record.AnswerRecord]]: - r"""Return a callable for the get answer record method over gRPC. - - Deprecated. - Retrieves a specific answer record. - - Returns: - Callable[[~.GetAnswerRecordRequest], - Awaitable[~.AnswerRecord]]: - 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_answer_record' not in self._stubs: - self._stubs['get_answer_record'] = self.grpc_channel.unary_unary( - '/google.cloud.dialogflow.v2beta1.AnswerRecords/GetAnswerRecord', - request_serializer=answer_record.GetAnswerRecordRequest.serialize, - response_deserializer=answer_record.AnswerRecord.deserialize, - ) - return self._stubs['get_answer_record'] - - @property - def list_answer_records(self) -> Callable[ - [answer_record.ListAnswerRecordsRequest], - Awaitable[answer_record.ListAnswerRecordsResponse]]: - r"""Return a callable for the list answer records method over gRPC. - - Returns the list of all answer records in the - specified project in reverse chronological order. - - Returns: - Callable[[~.ListAnswerRecordsRequest], - Awaitable[~.ListAnswerRecordsResponse]]: - 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_answer_records' not in self._stubs: - self._stubs['list_answer_records'] = self.grpc_channel.unary_unary( - '/google.cloud.dialogflow.v2beta1.AnswerRecords/ListAnswerRecords', - request_serializer=answer_record.ListAnswerRecordsRequest.serialize, - response_deserializer=answer_record.ListAnswerRecordsResponse.deserialize, - ) - return self._stubs['list_answer_records'] - - @property - def update_answer_record(self) -> Callable[ - [gcd_answer_record.UpdateAnswerRecordRequest], - Awaitable[gcd_answer_record.AnswerRecord]]: - r"""Return a callable for the update answer record method over gRPC. - - Updates the specified answer record. - - Returns: - Callable[[~.UpdateAnswerRecordRequest], - Awaitable[~.AnswerRecord]]: - 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_answer_record' not in self._stubs: - self._stubs['update_answer_record'] = self.grpc_channel.unary_unary( - '/google.cloud.dialogflow.v2beta1.AnswerRecords/UpdateAnswerRecord', - request_serializer=gcd_answer_record.UpdateAnswerRecordRequest.serialize, - response_deserializer=gcd_answer_record.AnswerRecord.deserialize, - ) - return self._stubs['update_answer_record'] - - def close(self): - return self.grpc_channel.close() - - @property - def cancel_operation( - self, - ) -> Callable[[operations_pb2.CancelOperationRequest], None]: - r"""Return a callable for the cancel_operation method over gRPC. - """ - # 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 "cancel_operation" not in self._stubs: - self._stubs["cancel_operation"] = self.grpc_channel.unary_unary( - "/google.longrunning.Operations/CancelOperation", - request_serializer=operations_pb2.CancelOperationRequest.SerializeToString, - response_deserializer=None, - ) - return self._stubs["cancel_operation"] - - @property - def get_operation( - self, - ) -> Callable[[operations_pb2.GetOperationRequest], operations_pb2.Operation]: - r"""Return a callable for the get_operation method over gRPC. - """ - # 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_operation" not in self._stubs: - self._stubs["get_operation"] = self.grpc_channel.unary_unary( - "/google.longrunning.Operations/GetOperation", - request_serializer=operations_pb2.GetOperationRequest.SerializeToString, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs["get_operation"] - - @property - def list_operations( - self, - ) -> Callable[[operations_pb2.ListOperationsRequest], operations_pb2.ListOperationsResponse]: - r"""Return a callable for the list_operations method over gRPC. - """ - # 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_operations" not in self._stubs: - self._stubs["list_operations"] = self.grpc_channel.unary_unary( - "/google.longrunning.Operations/ListOperations", - request_serializer=operations_pb2.ListOperationsRequest.SerializeToString, - response_deserializer=operations_pb2.ListOperationsResponse.FromString, - ) - return self._stubs["list_operations"] - - @property - def list_locations( - self, - ) -> Callable[[locations_pb2.ListLocationsRequest], locations_pb2.ListLocationsResponse]: - r"""Return a callable for the list locations method over gRPC. - """ - # 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_locations" not in self._stubs: - self._stubs["list_locations"] = self.grpc_channel.unary_unary( - "/google.cloud.location.Locations/ListLocations", - request_serializer=locations_pb2.ListLocationsRequest.SerializeToString, - response_deserializer=locations_pb2.ListLocationsResponse.FromString, - ) - return self._stubs["list_locations"] - - @property - def get_location( - self, - ) -> Callable[[locations_pb2.GetLocationRequest], locations_pb2.Location]: - r"""Return a callable for the list locations method over gRPC. - """ - # 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_location" not in self._stubs: - self._stubs["get_location"] = self.grpc_channel.unary_unary( - "/google.cloud.location.Locations/GetLocation", - request_serializer=locations_pb2.GetLocationRequest.SerializeToString, - response_deserializer=locations_pb2.Location.FromString, - ) - return self._stubs["get_location"] - - -__all__ = ( - 'AnswerRecordsGrpcAsyncIOTransport', -) diff --git a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/answer_records/transports/rest.py b/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/answer_records/transports/rest.py deleted file mode 100644 index 22dfbc853..000000000 --- a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/answer_records/transports/rest.py +++ /dev/null @@ -1,1017 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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 google.auth.transport.requests import AuthorizedSession # type: ignore -import json # type: ignore -import grpc # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore -from google.auth import credentials as ga_credentials # type: ignore -from google.api_core import exceptions as core_exceptions -from google.api_core import retry as retries -from google.api_core import rest_helpers -from google.api_core import rest_streaming -from google.api_core import path_template -from google.api_core import gapic_v1 - -from google.protobuf import json_format -from google.cloud.location import locations_pb2 # type: ignore -from google.longrunning import operations_pb2 -from requests import __version__ as requests_version -import dataclasses -import re -from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union -import warnings - -try: - OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] -except AttributeError: # pragma: NO COVER - OptionalRetry = Union[retries.Retry, object] # 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 as BASE_DEFAULT_CLIENT_INFO - - -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=BASE_DEFAULT_CLIENT_INFO.gapic_version, - grpc_version=None, - rest_version=requests_version, -) - - -class AnswerRecordsRestInterceptor: - """Interceptor for AnswerRecords. - - Interceptors are used to manipulate requests, request metadata, and responses - in arbitrary ways. - Example use cases include: - * Logging - * Verifying requests according to service or custom semantics - * Stripping extraneous information from responses - - These use cases and more can be enabled by injecting an - instance of a custom subclass when constructing the AnswerRecordsRestTransport. - - .. code-block:: python - class MyCustomAnswerRecordsInterceptor(AnswerRecordsRestInterceptor): - def pre_get_answer_record(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_get_answer_record(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_list_answer_records(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_list_answer_records(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_update_answer_record(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_update_answer_record(self, response): - logging.log(f"Received response: {response}") - return response - - transport = AnswerRecordsRestTransport(interceptor=MyCustomAnswerRecordsInterceptor()) - client = AnswerRecordsClient(transport=transport) - - - """ - def pre_get_answer_record(self, request: answer_record.GetAnswerRecordRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[answer_record.GetAnswerRecordRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for get_answer_record - - Override in a subclass to manipulate the request or metadata - before they are sent to the AnswerRecords server. - """ - return request, metadata - - def post_get_answer_record(self, response: answer_record.AnswerRecord) -> answer_record.AnswerRecord: - """Post-rpc interceptor for get_answer_record - - Override in a subclass to manipulate the response - after it is returned by the AnswerRecords server but before - it is returned to user code. - """ - return response - def pre_list_answer_records(self, request: answer_record.ListAnswerRecordsRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[answer_record.ListAnswerRecordsRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for list_answer_records - - Override in a subclass to manipulate the request or metadata - before they are sent to the AnswerRecords server. - """ - return request, metadata - - def post_list_answer_records(self, response: answer_record.ListAnswerRecordsResponse) -> answer_record.ListAnswerRecordsResponse: - """Post-rpc interceptor for list_answer_records - - Override in a subclass to manipulate the response - after it is returned by the AnswerRecords server but before - it is returned to user code. - """ - return response - def pre_update_answer_record(self, request: gcd_answer_record.UpdateAnswerRecordRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[gcd_answer_record.UpdateAnswerRecordRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for update_answer_record - - Override in a subclass to manipulate the request or metadata - before they are sent to the AnswerRecords server. - """ - return request, metadata - - def post_update_answer_record(self, response: gcd_answer_record.AnswerRecord) -> gcd_answer_record.AnswerRecord: - """Post-rpc interceptor for update_answer_record - - Override in a subclass to manipulate the response - after it is returned by the AnswerRecords server but before - it is returned to user code. - """ - return response - - def pre_get_location( - self, request: locations_pb2.GetLocationRequest, metadata: Sequence[Tuple[str, str]] - ) -> Tuple[locations_pb2.GetLocationRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for get_location - - Override in a subclass to manipulate the request or metadata - before they are sent to the AnswerRecords server. - """ - return request, metadata - - def post_get_location( - self, response: locations_pb2.Location - ) -> locations_pb2.Location: - """Post-rpc interceptor for get_location - - Override in a subclass to manipulate the response - after it is returned by the AnswerRecords server but before - it is returned to user code. - """ - return response - def pre_list_locations( - self, request: locations_pb2.ListLocationsRequest, metadata: Sequence[Tuple[str, str]] - ) -> Tuple[locations_pb2.ListLocationsRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for list_locations - - Override in a subclass to manipulate the request or metadata - before they are sent to the AnswerRecords server. - """ - return request, metadata - - def post_list_locations( - self, response: locations_pb2.ListLocationsResponse - ) -> locations_pb2.ListLocationsResponse: - """Post-rpc interceptor for list_locations - - Override in a subclass to manipulate the response - after it is returned by the AnswerRecords server but before - it is returned to user code. - """ - return response - def pre_cancel_operation( - self, request: operations_pb2.CancelOperationRequest, metadata: Sequence[Tuple[str, str]] - ) -> Tuple[operations_pb2.CancelOperationRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for cancel_operation - - Override in a subclass to manipulate the request or metadata - before they are sent to the AnswerRecords server. - """ - return request, metadata - - def post_cancel_operation( - self, response: None - ) -> None: - """Post-rpc interceptor for cancel_operation - - Override in a subclass to manipulate the response - after it is returned by the AnswerRecords server but before - it is returned to user code. - """ - return response - def pre_get_operation( - self, request: operations_pb2.GetOperationRequest, metadata: Sequence[Tuple[str, str]] - ) -> Tuple[operations_pb2.GetOperationRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for get_operation - - Override in a subclass to manipulate the request or metadata - before they are sent to the AnswerRecords server. - """ - return request, metadata - - def post_get_operation( - self, response: operations_pb2.Operation - ) -> operations_pb2.Operation: - """Post-rpc interceptor for get_operation - - Override in a subclass to manipulate the response - after it is returned by the AnswerRecords server but before - it is returned to user code. - """ - return response - def pre_list_operations( - self, request: operations_pb2.ListOperationsRequest, metadata: Sequence[Tuple[str, str]] - ) -> Tuple[operations_pb2.ListOperationsRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for list_operations - - Override in a subclass to manipulate the request or metadata - before they are sent to the AnswerRecords server. - """ - return request, metadata - - def post_list_operations( - self, response: operations_pb2.ListOperationsResponse - ) -> operations_pb2.ListOperationsResponse: - """Post-rpc interceptor for list_operations - - Override in a subclass to manipulate the response - after it is returned by the AnswerRecords server but before - it is returned to user code. - """ - return response - - -@dataclasses.dataclass -class AnswerRecordsRestStub: - _session: AuthorizedSession - _host: str - _interceptor: AnswerRecordsRestInterceptor - - -class AnswerRecordsRestTransport(AnswerRecordsTransport): - """REST backend transport for AnswerRecords. - - Service for managing - [AnswerRecords][google.cloud.dialogflow.v2beta1.AnswerRecord]. - - 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 JSON representations of protocol buffers over HTTP/1.1 - - """ - - def __init__(self, *, - host: str = 'dialogflow.googleapis.com', - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - client_cert_source_for_mtls: Optional[Callable[[ - ], Tuple[bytes, bytes]]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - url_scheme: str = 'https', - interceptor: Optional[AnswerRecordsRestInterceptor] = None, - api_audience: Optional[str] = None, - ) -> 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 ignored if ``channel`` is provided. - scopes (Optional(Sequence[str])): A list of scopes. This argument is - ignored if ``channel`` is provided. - client_cert_source_for_mtls (Callable[[], Tuple[bytes, bytes]]): Client - certificate to configure mutual TLS HTTP channel. It is ignored - if ``channel`` is provided. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you are developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - url_scheme: the protocol scheme for the API endpoint. Normally - "https", but for testing or local servers, - "http" can be specified. - """ - # Run the base constructor - # TODO(yon-mg): resolve other ctor params i.e. scopes, quota, etc. - # TODO: When custom host (api_endpoint) is set, `scopes` must *also* be set on the - # credentials object - maybe_url_match = re.match("^(?Phttp(?:s)?://)?(?P.*)$", host) - if maybe_url_match is None: - raise ValueError(f"Unexpected hostname structure: {host}") # pragma: NO COVER - - url_match_items = maybe_url_match.groupdict() - - host = f"{url_scheme}://{host}" if not url_match_items["scheme"] else host - - super().__init__( - host=host, - credentials=credentials, - client_info=client_info, - always_use_jwt_access=always_use_jwt_access, - api_audience=api_audience - ) - self._session = AuthorizedSession( - self._credentials, default_host=self.DEFAULT_HOST) - if client_cert_source_for_mtls: - self._session.configure_mtls_channel(client_cert_source_for_mtls) - self._interceptor = interceptor or AnswerRecordsRestInterceptor() - self._prep_wrapped_messages(client_info) - - class _GetAnswerRecord(AnswerRecordsRestStub): - def __hash__(self): - return hash("GetAnswerRecord") - - def __call__(self, - request: answer_record.GetAnswerRecordRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> answer_record.AnswerRecord: - r"""Call the get answer record method over HTTP. - - Args: - request (~.answer_record.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. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.answer_record.AnswerRecord: - Answer records are records to manage answer history and - feedbacks for Dialogflow. - - Currently, answer record includes: - - - human agent assistant article suggestion - - human agent assistant faq article - - It doesn't include: - - - ``DetectIntent`` intent matching - - ``DetectIntent`` knowledge - - Answer records are not related to the conversation - history in the Dialogflow Console. A Record is generated - even when the end-user disables conversation history in - the console. Records are created when there's a human - agent assistant suggestion generated. - - A typical workflow for customers provide feedback to an - answer is: - - 1. For human agent assistant, customers get suggestion - via ListSuggestions API. Together with 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. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v2beta1/{name=projects/*/answerRecords/*}', - }, -{ - 'method': 'get', - 'uri': '/v2beta1/{name=projects/*/locations/*/answerRecords/*}', - }, - ] - request, metadata = self._interceptor.pre_get_answer_record(request, metadata) - pb_request = answer_record.GetAnswerRecordRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - including_default_value_fields=False, - use_integers_for_enums=True, - )) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = answer_record.AnswerRecord() - pb_resp = answer_record.AnswerRecord.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_get_answer_record(resp) - return resp - - class _ListAnswerRecords(AnswerRecordsRestStub): - def __hash__(self): - return hash("ListAnswerRecords") - - def __call__(self, - request: answer_record.ListAnswerRecordsRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> answer_record.ListAnswerRecordsResponse: - r"""Call the list answer records method over HTTP. - - Args: - request (~.answer_record.ListAnswerRecordsRequest): - The request object. Request message for - [AnswerRecords.ListAnswerRecords][google.cloud.dialogflow.v2beta1.AnswerRecords.ListAnswerRecords]. - 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: - ~.answer_record.ListAnswerRecordsResponse: - Response message for - [AnswerRecords.ListAnswerRecords][google.cloud.dialogflow.v2beta1.AnswerRecords.ListAnswerRecords]. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v2beta1/{parent=projects/*}/answerRecords', - }, -{ - 'method': 'get', - 'uri': '/v2beta1/{parent=projects/*/locations/*}/answerRecords', - }, - ] - request, metadata = self._interceptor.pre_list_answer_records(request, metadata) - pb_request = answer_record.ListAnswerRecordsRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - including_default_value_fields=False, - use_integers_for_enums=True, - )) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = answer_record.ListAnswerRecordsResponse() - pb_resp = answer_record.ListAnswerRecordsResponse.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_list_answer_records(resp) - return resp - - class _UpdateAnswerRecord(AnswerRecordsRestStub): - def __hash__(self): - return hash("UpdateAnswerRecord") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: gcd_answer_record.UpdateAnswerRecordRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> gcd_answer_record.AnswerRecord: - r"""Call the update answer record method over HTTP. - - Args: - request (~.gcd_answer_record.UpdateAnswerRecordRequest): - The request object. Request message for - [AnswerRecords.UpdateAnswerRecord][google.cloud.dialogflow.v2beta1.AnswerRecords.UpdateAnswerRecord]. - 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: - ~.gcd_answer_record.AnswerRecord: - Answer records are records to manage answer history and - feedbacks for Dialogflow. - - Currently, answer record includes: - - - human agent assistant article suggestion - - human agent assistant faq article - - It doesn't include: - - - ``DetectIntent`` intent matching - - ``DetectIntent`` knowledge - - Answer records are not related to the conversation - history in the Dialogflow Console. A Record is generated - even when the end-user disables conversation history in - the console. Records are created when there's a human - agent assistant suggestion generated. - - A typical workflow for customers provide feedback to an - answer is: - - 1. For human agent assistant, customers get suggestion - via ListSuggestions API. Together with 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. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'patch', - 'uri': '/v2beta1/{answer_record.name=projects/*/answerRecords/*}', - 'body': 'answer_record', - }, -{ - 'method': 'patch', - 'uri': '/v2beta1/{answer_record.name=projects/*/locations/*/answerRecords/*}', - 'body': 'answer_record', - }, - ] - request, metadata = self._interceptor.pre_update_answer_record(request, metadata) - pb_request = gcd_answer_record.UpdateAnswerRecordRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request['body'], - including_default_value_fields=False, - use_integers_for_enums=True - ) - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - including_default_value_fields=False, - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = gcd_answer_record.AnswerRecord() - pb_resp = gcd_answer_record.AnswerRecord.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_update_answer_record(resp) - return resp - - @property - def get_answer_record(self) -> Callable[ - [answer_record.GetAnswerRecordRequest], - answer_record.AnswerRecord]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._GetAnswerRecord(self._session, self._host, self._interceptor) # type: ignore - - @property - def list_answer_records(self) -> Callable[ - [answer_record.ListAnswerRecordsRequest], - answer_record.ListAnswerRecordsResponse]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._ListAnswerRecords(self._session, self._host, self._interceptor) # type: ignore - - @property - def update_answer_record(self) -> Callable[ - [gcd_answer_record.UpdateAnswerRecordRequest], - gcd_answer_record.AnswerRecord]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._UpdateAnswerRecord(self._session, self._host, self._interceptor) # type: ignore - - @property - def get_location(self): - return self._GetLocation(self._session, self._host, self._interceptor) # type: ignore - - class _GetLocation(AnswerRecordsRestStub): - def __call__(self, - request: locations_pb2.GetLocationRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> locations_pb2.Location: - - r"""Call the get location method over HTTP. - - Args: - request (locations_pb2.GetLocationRequest): - The request object for GetLocation method. - 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: - locations_pb2.Location: Response from GetLocation method. - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v2beta1/{name=projects/*/locations/*}', - }, - ] - - request, metadata = self._interceptor.pre_get_location(request, metadata) - request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode( - http_options, **request_kwargs) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json.dumps(transcoded_request['query_params'])) - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - resp = locations_pb2.Location() - resp = json_format.Parse(response.content.decode("utf-8"), resp) - resp = self._interceptor.post_get_location(resp) - return resp - - @property - def list_locations(self): - return self._ListLocations(self._session, self._host, self._interceptor) # type: ignore - - class _ListLocations(AnswerRecordsRestStub): - def __call__(self, - request: locations_pb2.ListLocationsRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> locations_pb2.ListLocationsResponse: - - r"""Call the list locations method over HTTP. - - Args: - request (locations_pb2.ListLocationsRequest): - The request object for ListLocations method. - 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: - locations_pb2.ListLocationsResponse: Response from ListLocations method. - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v2beta1/{name=projects/*}/locations', - }, - ] - - request, metadata = self._interceptor.pre_list_locations(request, metadata) - request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode( - http_options, **request_kwargs) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json.dumps(transcoded_request['query_params'])) - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - resp = locations_pb2.ListLocationsResponse() - resp = json_format.Parse(response.content.decode("utf-8"), resp) - resp = self._interceptor.post_list_locations(resp) - return resp - - @property - def cancel_operation(self): - return self._CancelOperation(self._session, self._host, self._interceptor) # type: ignore - - class _CancelOperation(AnswerRecordsRestStub): - def __call__(self, - request: operations_pb2.CancelOperationRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> None: - - r"""Call the cancel operation method over HTTP. - - Args: - request (operations_pb2.CancelOperationRequest): - The request object for CancelOperation method. - 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. - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'post', - 'uri': '/v2beta1/{name=projects/*/operations/*}:cancel', - }, -{ - 'method': 'post', - 'uri': '/v2beta1/{name=projects/*/locations/*/operations/*}:cancel', - }, - ] - - request, metadata = self._interceptor.pre_cancel_operation(request, metadata) - request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode( - http_options, **request_kwargs) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json.dumps(transcoded_request['query_params'])) - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - return self._interceptor.post_cancel_operation(None) - - @property - def get_operation(self): - return self._GetOperation(self._session, self._host, self._interceptor) # type: ignore - - class _GetOperation(AnswerRecordsRestStub): - def __call__(self, - request: operations_pb2.GetOperationRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> operations_pb2.Operation: - - r"""Call the get operation method over HTTP. - - Args: - request (operations_pb2.GetOperationRequest): - The request object for GetOperation method. - 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: - operations_pb2.Operation: Response from GetOperation method. - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v2beta1/{name=projects/*/operations/*}', - }, -{ - 'method': 'get', - 'uri': '/v2beta1/{name=projects/*/locations/*/operations/*}', - }, - ] - - request, metadata = self._interceptor.pre_get_operation(request, metadata) - request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode( - http_options, **request_kwargs) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json.dumps(transcoded_request['query_params'])) - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - resp = operations_pb2.Operation() - resp = json_format.Parse(response.content.decode("utf-8"), resp) - resp = self._interceptor.post_get_operation(resp) - return resp - - @property - def list_operations(self): - return self._ListOperations(self._session, self._host, self._interceptor) # type: ignore - - class _ListOperations(AnswerRecordsRestStub): - def __call__(self, - request: operations_pb2.ListOperationsRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> operations_pb2.ListOperationsResponse: - - r"""Call the list operations method over HTTP. - - Args: - request (operations_pb2.ListOperationsRequest): - The request object for ListOperations method. - 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: - operations_pb2.ListOperationsResponse: Response from ListOperations method. - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v2beta1/{name=projects/*}/operations', - }, -{ - 'method': 'get', - 'uri': '/v2beta1/{name=projects/*/locations/*}/operations', - }, - ] - - request, metadata = self._interceptor.pre_list_operations(request, metadata) - request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode( - http_options, **request_kwargs) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json.dumps(transcoded_request['query_params'])) - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - resp = operations_pb2.ListOperationsResponse() - resp = json_format.Parse(response.content.decode("utf-8"), resp) - resp = self._interceptor.post_list_operations(resp) - return resp - - @property - def kind(self) -> str: - return "rest" - - def close(self): - self._session.close() - - -__all__=( - 'AnswerRecordsRestTransport', -) diff --git a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/contexts/__init__.py b/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/contexts/__init__.py deleted file mode 100644 index 3d4b75847..000000000 --- a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/contexts/__init__.py +++ /dev/null @@ -1,22 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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 ContextsClient -from .async_client import ContextsAsyncClient - -__all__ = ( - 'ContextsClient', - 'ContextsAsyncClient', -) diff --git a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/contexts/async_client.py b/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/contexts/async_client.py deleted file mode 100644 index 48ff69434..000000000 --- a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/contexts/async_client.py +++ /dev/null @@ -1,1172 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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, Mapping, MutableMapping, MutableSequence, Optional, Sequence, Tuple, Type, Union - -from google.cloud.dialogflow_v2beta1 import gapic_version as package_version - -from google.api_core.client_options import ClientOptions -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import retry as retries -from google.auth import credentials as ga_credentials # type: ignore -from google.oauth2 import service_account # type: ignore - -try: - OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] -except AttributeError: # pragma: NO COVER - OptionalRetry = Union[retries.Retry, object] # 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.cloud.location import locations_pb2 # type: ignore -from google.longrunning import operations_pb2 -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 - - -class ContextsAsyncClient: - """Service for managing - [Contexts][google.cloud.dialogflow.v2beta1.Context]. - """ - - _client: ContextsClient - - DEFAULT_ENDPOINT = ContextsClient.DEFAULT_ENDPOINT - DEFAULT_MTLS_ENDPOINT = ContextsClient.DEFAULT_MTLS_ENDPOINT - - 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) - - @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: - ContextsAsyncClient: The constructed client. - """ - return ContextsClient.from_service_account_info.__func__(ContextsAsyncClient, 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: - ContextsAsyncClient: The constructed client. - """ - return ContextsClient.from_service_account_file.__func__(ContextsAsyncClient, filename, *args, **kwargs) # type: ignore - - from_service_account_json = from_service_account_file - - @classmethod - def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[ClientOptions] = None): - """Return the API endpoint and client cert source for mutual TLS. - - The client cert source is determined in the following order: - (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the - client cert source is None. - (2) if `client_options.client_cert_source` is provided, use the provided one; if the - default client cert source exists, use the default one; otherwise the client cert - source is None. - - The API endpoint is determined in the following order: - (1) if `client_options.api_endpoint` if provided, use the provided one. - (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the - default mTLS endpoint; if the environment variable is "never", use the default API - endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise - use the default API endpoint. - - More details can be found at https://google.aip.dev/auth/4114. - - Args: - client_options (google.api_core.client_options.ClientOptions): Custom options for the - client. Only the `api_endpoint` and `client_cert_source` properties may be used - in this method. - - Returns: - Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the - client cert source to use. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If any errors happen. - """ - return ContextsClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore - - @property - def transport(self) -> ContextsTransport: - """Returns the transport used by the client instance. - - Returns: - ContextsTransport: The transport used by the client instance. - """ - return self._client.transport - - get_transport_class = functools.partial(type(ContextsClient).get_transport_class, type(ContextsClient)) - - def __init__(self, *, - credentials: Optional[ga_credentials.Credentials] = None, - transport: Union[str, ContextsTransport] = "grpc_asyncio", - client_options: Optional[ClientOptions] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the contexts 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, ~.ContextsTransport]): 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 = ContextsClient( - credentials=credentials, - transport=transport, - client_options=client_options, - client_info=client_info, - - ) - - async def list_contexts(self, - request: Optional[Union[context.ListContextsRequest, dict]] = None, - *, - parent: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListContextsAsyncPager: - r"""Returns the list of all contexts in the specified - session. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import dialogflow_v2beta1 - - async def sample_list_contexts(): - # Create a client - client = dialogflow_v2beta1.ContextsAsyncClient() - - # Initialize request argument(s) - request = dialogflow_v2beta1.ListContextsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_contexts(request=request) - - # Handle the response - async for response in page_result: - print(response) - - Args: - request (Optional[Union[google.cloud.dialogflow_v2beta1.types.ListContextsRequest, dict]]): - The request object. The request message for - [Contexts.ListContexts][google.cloud.dialogflow.v2beta1.Contexts.ListContexts]. - parent (:class:`str`): - Required. The session to list all contexts from. - Supported formats: - - - \`projects//agent/sessions/, - - ``projects//locations//agent/sessions/``, - - ``projects//agent/environments//users//sessions/``, - - ``projects//locations//agent/environments//users//sessions/``, - - If ``Location ID`` is not specified we assume default - 'us' location. If ``Environment ID`` is not specified, - we assume default 'draft' environment. If ``User ID`` is - not specified, we assume default '-' user. - - 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.contexts.pagers.ListContextsAsyncPager: - The response message for - [Contexts.ListContexts][google.cloud.dialogflow.v2beta1.Contexts.ListContexts]. - - Iterating over this object will yield results and - resolve additional pages automatically. - - """ - # Create or coerce a protobuf request object. - # Quick 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 = context.ListContextsRequest(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_contexts, - 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.ListContextsAsyncPager( - method=rpc, - request=request, - response=response, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def get_context(self, - request: Optional[Union[context.GetContextRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> context.Context: - r"""Retrieves the specified context. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import dialogflow_v2beta1 - - async def sample_get_context(): - # Create a client - client = dialogflow_v2beta1.ContextsAsyncClient() - - # Initialize request argument(s) - request = dialogflow_v2beta1.GetContextRequest( - name="name_value", - ) - - # Make the request - response = await client.get_context(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.dialogflow_v2beta1.types.GetContextRequest, dict]]): - The request object. The request message for - [Contexts.GetContext][google.cloud.dialogflow.v2beta1.Contexts.GetContext]. - name (:class:`str`): - Required. The name of the context. Supported formats: - - - ``projects//agent/sessions//contexts/``, - - ``projects//locations//agent/sessions//contexts/``, - - ``projects//agent/environments//users//sessions//contexts/``, - - ``projects//locations//agent/environments//users//sessions//contexts/``, - - If ``Location ID`` is not specified we assume default - 'us' location. If ``Environment ID`` is not specified, - we assume default 'draft' environment. If ``User ID`` is - not specified, we assume default '-' user. - - 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.Context: - Dialogflow contexts are similar to natural language context. If a person says - to you "they are orange", you need context in order - to understand what "they" is referring to. Similarly, - for Dialogflow to handle an end-user expression like - that, it needs to be provided with context in order - to correctly match an intent. - - Using contexts, you can control the flow of a - conversation. You can configure contexts for an - intent by setting input and output contexts, which - are identified by string names. When an intent is - matched, any configured output contexts for that - intent become active. While any contexts are active, - Dialogflow is more likely to match intents that are - configured with input contexts that correspond to the - currently active contexts. - - For more information about context, see the [Contexts - guide](\ https://cloud.google.com/dialogflow/docs/contexts-overview). - - """ - # Create or coerce a protobuf request object. - # Quick 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 = context.GetContextRequest(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_context, - 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_context(self, - request: Optional[Union[gcd_context.CreateContextRequest, dict]] = None, - *, - parent: Optional[str] = None, - context: Optional[gcd_context.Context] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gcd_context.Context: - r"""Creates a context. - If the specified context already exists, overrides the - context. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import dialogflow_v2beta1 - - async def sample_create_context(): - # Create a client - client = dialogflow_v2beta1.ContextsAsyncClient() - - # Initialize request argument(s) - request = dialogflow_v2beta1.CreateContextRequest( - parent="parent_value", - ) - - # Make the request - response = await client.create_context(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.dialogflow_v2beta1.types.CreateContextRequest, dict]]): - The request object. The request message for - [Contexts.CreateContext][google.cloud.dialogflow.v2beta1.Contexts.CreateContext]. - parent (:class:`str`): - Required. The session to create a context for. Supported - formats: - - - \`projects//agent/sessions/, - - ``projects//locations//agent/sessions/``, - - ``projects//agent/environments//users//sessions/``, - - ``projects//locations//agent/environments//users//sessions/``, - - If ``Location ID`` is not specified we assume default - 'us' location. If ``Environment ID`` is not specified, - we assume default 'draft' environment. If ``User ID`` is - not specified, we assume default '-' user. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - context (:class:`google.cloud.dialogflow_v2beta1.types.Context`): - Required. The context to create. - 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. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.dialogflow_v2beta1.types.Context: - Dialogflow contexts are similar to natural language context. If a person says - to you "they are orange", you need context in order - to understand what "they" is referring to. Similarly, - for Dialogflow to handle an end-user expression like - that, it needs to be provided with context in order - to correctly match an intent. - - Using contexts, you can control the flow of a - conversation. You can configure contexts for an - intent by setting input and output contexts, which - are identified by string names. When an intent is - matched, any configured output contexts for that - intent become active. While any contexts are active, - Dialogflow is more likely to match intents that are - configured with input contexts that correspond to the - currently active contexts. - - For more information about context, see the [Contexts - guide](\ https://cloud.google.com/dialogflow/docs/contexts-overview). - - """ - # Create or coerce a protobuf request object. - # Quick 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, context]) - 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_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: - request.context = context - - # 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_context, - 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_context(self, - request: Optional[Union[gcd_context.UpdateContextRequest, dict]] = None, - *, - context: Optional[gcd_context.Context] = None, - update_mask: Optional[field_mask_pb2.FieldMask] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gcd_context.Context: - r"""Updates the specified context. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import dialogflow_v2beta1 - - async def sample_update_context(): - # Create a client - client = dialogflow_v2beta1.ContextsAsyncClient() - - # Initialize request argument(s) - request = dialogflow_v2beta1.UpdateContextRequest( - ) - - # Make the request - response = await client.update_context(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.dialogflow_v2beta1.types.UpdateContextRequest, dict]]): - The request object. The request message for - [Contexts.UpdateContext][google.cloud.dialogflow.v2beta1.Contexts.UpdateContext]. - context (:class:`google.cloud.dialogflow_v2beta1.types.Context`): - Required. The context to update. - This corresponds to the ``context`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - update_mask (:class:`google.protobuf.field_mask_pb2.FieldMask`): - Optional. 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.Context: - Dialogflow contexts are similar to natural language context. If a person says - to you "they are orange", you need context in order - to understand what "they" is referring to. Similarly, - for Dialogflow to handle an end-user expression like - that, it needs to be provided with context in order - to correctly match an intent. - - Using contexts, you can control the flow of a - conversation. You can configure contexts for an - intent by setting input and output contexts, which - are identified by string names. When an intent is - matched, any configured output contexts for that - intent become active. While any contexts are active, - Dialogflow is more likely to match intents that are - configured with input contexts that correspond to the - currently active contexts. - - For more information about context, see the [Contexts - guide](\ https://cloud.google.com/dialogflow/docs/contexts-overview). - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([context, 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_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: - 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_context, - 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(( - ("context.name", request.context.name), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def delete_context(self, - request: Optional[Union[context.DeleteContextRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> None: - r"""Deletes the specified context. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import dialogflow_v2beta1 - - async def sample_delete_context(): - # Create a client - client = dialogflow_v2beta1.ContextsAsyncClient() - - # Initialize request argument(s) - request = dialogflow_v2beta1.DeleteContextRequest( - name="name_value", - ) - - # Make the request - await client.delete_context(request=request) - - Args: - request (Optional[Union[google.cloud.dialogflow_v2beta1.types.DeleteContextRequest, dict]]): - The request object. The request message for - [Contexts.DeleteContext][google.cloud.dialogflow.v2beta1.Contexts.DeleteContext]. - name (:class:`str`): - Required. The name of the context to delete. Supported - formats: - - - ``projects//agent/sessions//contexts/``, - - ``projects//locations//agent/sessions//contexts/``, - - ``projects//agent/environments//users//sessions//contexts/``, - - ``projects//locations//agent/environments//users//sessions//contexts/``, - - If ``Location ID`` is not specified we assume default - 'us' location. If ``Environment ID`` is not specified, - we assume default 'draft' environment. If ``User ID`` is - not specified, we assume default '-' user. - - 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. - # Quick 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 = context.DeleteContextRequest(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_context, - 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 delete_all_contexts(self, - request: Optional[Union[context.DeleteAllContextsRequest, dict]] = None, - *, - parent: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> None: - r"""Deletes all active contexts in the specified session. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import dialogflow_v2beta1 - - async def sample_delete_all_contexts(): - # Create a client - client = dialogflow_v2beta1.ContextsAsyncClient() - - # Initialize request argument(s) - request = dialogflow_v2beta1.DeleteAllContextsRequest( - parent="parent_value", - ) - - # Make the request - await client.delete_all_contexts(request=request) - - Args: - request (Optional[Union[google.cloud.dialogflow_v2beta1.types.DeleteAllContextsRequest, dict]]): - The request object. The request message for - [Contexts.DeleteAllContexts][google.cloud.dialogflow.v2beta1.Contexts.DeleteAllContexts]. - parent (:class:`str`): - Required. The name of the session to delete all contexts - from. Supported formats: - - - \`projects//agent/sessions/, - - ``projects//locations//agent/sessions/``, - - ``projects//agent/environments//users//sessions/``, - - ``projects//locations//agent/environments//users//sessions/``, - - If ``Location ID`` is not specified we assume default - 'us' location. If ``Environment ID`` is not specified we - assume default 'draft' environment. If ``User ID`` is - not specified, we assume default '-' user. - - 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. - """ - # Create or coerce a protobuf request object. - # Quick 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 = context.DeleteAllContextsRequest(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.delete_all_contexts, - 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. - await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - async def list_operations( - self, - request: Optional[operations_pb2.ListOperationsRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operations_pb2.ListOperationsResponse: - r"""Lists operations that match the specified filter in the request. - - Args: - request (:class:`~.operations_pb2.ListOperationsRequest`): - The request object. Request message for - `ListOperations` method. - 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: - ~.operations_pb2.ListOperationsResponse: - Response message for ``ListOperations`` method. - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = operations_pb2.ListOperationsRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._client._transport.list_operations, - 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 get_operation( - self, - request: Optional[operations_pb2.GetOperationRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operations_pb2.Operation: - r"""Gets the latest state of a long-running operation. - - Args: - request (:class:`~.operations_pb2.GetOperationRequest`): - The request object. Request message for - `GetOperation` method. - 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: - ~.operations_pb2.Operation: - An ``Operation`` object. - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = operations_pb2.GetOperationRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._client._transport.get_operation, - 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 cancel_operation( - self, - request: Optional[operations_pb2.CancelOperationRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> None: - r"""Starts asynchronous cancellation on a long-running operation. - - The server makes a best effort to cancel the operation, but success - is not guaranteed. If the server doesn't support this method, it returns - `google.rpc.Code.UNIMPLEMENTED`. - - Args: - request (:class:`~.operations_pb2.CancelOperationRequest`): - The request object. Request message for - `CancelOperation` method. - 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: - None - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = operations_pb2.CancelOperationRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._client._transport.cancel_operation, - 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_location( - self, - request: Optional[locations_pb2.GetLocationRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> locations_pb2.Location: - r"""Gets information about a location. - - Args: - request (:class:`~.location_pb2.GetLocationRequest`): - The request object. Request message for - `GetLocation` method. - 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: - ~.location_pb2.Location: - Location object. - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = locations_pb2.GetLocationRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._client._transport.get_location, - 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 list_locations( - self, - request: Optional[locations_pb2.ListLocationsRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> locations_pb2.ListLocationsResponse: - r"""Lists information about the supported locations for this service. - - Args: - request (:class:`~.location_pb2.ListLocationsRequest`): - The request object. Request message for - `ListLocations` method. - 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: - ~.location_pb2.ListLocationsResponse: - Response message for ``ListLocations`` method. - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = locations_pb2.ListLocationsRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._client._transport.list_locations, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("name", request.name),)), - ) - - # Send the request. - response = await rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - async def __aenter__(self): - return self - - async def __aexit__(self, exc_type, exc, tb): - await self.transport.close() - -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) - - -__all__ = ( - "ContextsAsyncClient", -) diff --git a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/contexts/client.py b/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/contexts/client.py deleted file mode 100644 index 9b7ea5c99..000000000 --- a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/contexts/client.py +++ /dev/null @@ -1,1371 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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 os -import re -from typing import Dict, Mapping, MutableMapping, MutableSequence, Optional, Sequence, Tuple, Type, Union, cast - -from google.cloud.dialogflow_v2beta1 import gapic_version as package_version - -from google.api_core import client_options as client_options_lib -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import retry as retries -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 - -try: - OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] -except AttributeError: # pragma: NO COVER - OptionalRetry = Union[retries.Retry, object] # 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.cloud.location import locations_pb2 # type: ignore -from google.longrunning import operations_pb2 -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 -from .transports.rest import ContextsRestTransport - - -class ContextsClientMeta(type): - """Metaclass for the Contexts 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[ContextsTransport]] - _transport_registry["grpc"] = ContextsGrpcTransport - _transport_registry["grpc_asyncio"] = ContextsGrpcAsyncIOTransport - _transport_registry["rest"] = ContextsRestTransport - - def get_transport_class(cls, - label: Optional[str] = None, - ) -> Type[ContextsTransport]: - """Returns an appropriate transport class. - - Args: - label: The name of the desired transport. If none is - provided, then the first transport in the registry is used. - - Returns: - The transport class to use. - """ - # If a specific transport is requested, return that one. - if label: - return cls._transport_registry[label] - - # No transport is requested; return the default (that is, the first one - # in the dictionary). - return next(iter(cls._transport_registry.values())) - - -class ContextsClient(metaclass=ContextsClientMeta): - """Service for managing - [Contexts][google.cloud.dialogflow.v2beta1.Context]. - """ - - @staticmethod - def _get_default_mtls_endpoint(api_endpoint): - """Converts api endpoint to mTLS endpoint. - - Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to - "*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively. - Args: - api_endpoint (Optional[str]): the api endpoint to convert. - Returns: - str: converted mTLS api endpoint. - """ - if not api_endpoint: - return api_endpoint - - mtls_endpoint_re = re.compile( - r"(?P[^.]+)(?P\.mtls)?(?P\.sandbox)?(?P\.googleapis\.com)?" - ) - - m = mtls_endpoint_re.match(api_endpoint) - name, mtls, sandbox, googledomain = m.groups() - if mtls or not googledomain: - return api_endpoint - - if sandbox: - return api_endpoint.replace( - "sandbox.googleapis.com", "mtls.sandbox.googleapis.com" - ) - - return api_endpoint.replace(".googleapis.com", ".mtls.googleapis.com") - - DEFAULT_ENDPOINT = "dialogflow.googleapis.com" - DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore - DEFAULT_ENDPOINT - ) - - @classmethod - def from_service_account_info(cls, info: dict, *args, **kwargs): - """Creates an instance of this client using the provided credentials - info. - - Args: - info (dict): The service account private key info. - args: Additional arguments to pass to the constructor. - kwargs: Additional arguments to pass to the constructor. - - Returns: - ContextsClient: 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: - ContextsClient: 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) -> ContextsTransport: - """Returns the transport used by the client instance. - - Returns: - ContextsTransport: The transport used by the client - instance. - """ - return self._transport - - @staticmethod - def context_path(project: str,session: str,context: str,) -> str: - """Returns a fully-qualified context string.""" - return "projects/{project}/agent/sessions/{session}/contexts/{context}".format(project=project, session=session, context=context, ) - - @staticmethod - def parse_context_path(path: str) -> Dict[str,str]: - """Parses a context path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/agent/sessions/(?P.+?)/contexts/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_billing_account_path(billing_account: str, ) -> str: - """Returns a fully-qualified billing_account string.""" - return "billingAccounts/{billing_account}".format(billing_account=billing_account, ) - - @staticmethod - def parse_common_billing_account_path(path: str) -> Dict[str,str]: - """Parse a billing_account path into its component segments.""" - m = re.match(r"^billingAccounts/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_folder_path(folder: str, ) -> str: - """Returns a fully-qualified folder string.""" - return "folders/{folder}".format(folder=folder, ) - - @staticmethod - def parse_common_folder_path(path: str) -> Dict[str,str]: - """Parse a folder path into its component segments.""" - m = re.match(r"^folders/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_organization_path(organization: str, ) -> str: - """Returns a fully-qualified organization string.""" - return "organizations/{organization}".format(organization=organization, ) - - @staticmethod - def parse_common_organization_path(path: str) -> Dict[str,str]: - """Parse a organization path into its component segments.""" - m = re.match(r"^organizations/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_project_path(project: str, ) -> str: - """Returns a fully-qualified project string.""" - return "projects/{project}".format(project=project, ) - - @staticmethod - def parse_common_project_path(path: str) -> Dict[str,str]: - """Parse a project path into its component segments.""" - m = re.match(r"^projects/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_location_path(project: str, location: str, ) -> str: - """Returns a fully-qualified location string.""" - return "projects/{project}/locations/{location}".format(project=project, location=location, ) - - @staticmethod - def parse_common_location_path(path: str) -> Dict[str,str]: - """Parse a location path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)$", path) - return m.groupdict() if m else {} - - @classmethod - def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[client_options_lib.ClientOptions] = None): - """Return the API endpoint and client cert source for mutual TLS. - - The client cert source is determined in the following order: - (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the - client cert source is None. - (2) if `client_options.client_cert_source` is provided, use the provided one; if the - default client cert source exists, use the default one; otherwise the client cert - source is None. - - The API endpoint is determined in the following order: - (1) if `client_options.api_endpoint` if provided, use the provided one. - (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the - default mTLS endpoint; if the environment variable is "never", use the default API - endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise - use the default API endpoint. - - More details can be found at https://google.aip.dev/auth/4114. - - Args: - client_options (google.api_core.client_options.ClientOptions): Custom options for the - client. Only the `api_endpoint` and `client_cert_source` properties may be used - in this method. - - Returns: - Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the - client cert source to use. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If any errors happen. - """ - if client_options is None: - client_options = client_options_lib.ClientOptions() - use_client_cert = os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false") - use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") - if use_client_cert not in ("true", "false"): - raise ValueError("Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`") - if use_mtls_endpoint not in ("auto", "never", "always"): - raise MutualTLSChannelError("Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`") - - # Figure out the client cert source to use. - client_cert_source = None - if use_client_cert == "true": - if client_options.client_cert_source: - client_cert_source = client_options.client_cert_source - elif mtls.has_default_client_cert_source(): - client_cert_source = mtls.default_client_cert_source() - - # Figure out which api endpoint to use. - if client_options.api_endpoint is not None: - api_endpoint = client_options.api_endpoint - elif use_mtls_endpoint == "always" or (use_mtls_endpoint == "auto" and client_cert_source): - api_endpoint = cls.DEFAULT_MTLS_ENDPOINT - else: - api_endpoint = cls.DEFAULT_ENDPOINT - - return api_endpoint, client_cert_source - - def __init__(self, *, - credentials: Optional[ga_credentials.Credentials] = None, - transport: Optional[Union[str, ContextsTransport]] = None, - client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the contexts 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, ContextsTransport]): The - transport to use. If set to None, a transport is chosen - automatically. - client_options (Optional[Union[google.api_core.client_options.ClientOptions, dict]]): 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() - client_options = cast(client_options_lib.ClientOptions, client_options) - - api_endpoint, client_cert_source_func = self.get_mtls_endpoint_and_cert_source(client_options) - - api_key_value = getattr(client_options, "api_key", None) - if api_key_value and credentials: - raise ValueError("client_options.api_key and credentials are mutually exclusive") - - # 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, ContextsTransport): - # transport is a ContextsTransport instance. - if credentials or client_options.credentials_file or api_key_value: - 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: - import google.auth._default # type: ignore - - if api_key_value and hasattr(google.auth._default, "get_api_key_credentials"): - credentials = google.auth._default.get_api_key_credentials(api_key_value) - - Transport = type(self).get_transport_class(transport) - self._transport = Transport( - credentials=credentials, - credentials_file=client_options.credentials_file, - host=api_endpoint, - scopes=client_options.scopes, - client_cert_source_for_mtls=client_cert_source_func, - quota_project_id=client_options.quota_project_id, - client_info=client_info, - always_use_jwt_access=True, - api_audience=client_options.api_audience, - ) - - def list_contexts(self, - request: Optional[Union[context.ListContextsRequest, dict]] = None, - *, - parent: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListContextsPager: - r"""Returns the list of all contexts in the specified - session. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import dialogflow_v2beta1 - - def sample_list_contexts(): - # Create a client - client = dialogflow_v2beta1.ContextsClient() - - # Initialize request argument(s) - request = dialogflow_v2beta1.ListContextsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_contexts(request=request) - - # Handle the response - for response in page_result: - print(response) - - Args: - request (Union[google.cloud.dialogflow_v2beta1.types.ListContextsRequest, dict]): - The request object. The request message for - [Contexts.ListContexts][google.cloud.dialogflow.v2beta1.Contexts.ListContexts]. - parent (str): - Required. The session to list all contexts from. - Supported formats: - - - \`projects//agent/sessions/, - - ``projects//locations//agent/sessions/``, - - ``projects//agent/environments//users//sessions/``, - - ``projects//locations//agent/environments//users//sessions/``, - - If ``Location ID`` is not specified we assume default - 'us' location. If ``Environment ID`` is not specified, - we assume default 'draft' environment. If ``User ID`` is - not specified, we assume default '-' user. - - 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.contexts.pagers.ListContextsPager: - The response message for - [Contexts.ListContexts][google.cloud.dialogflow.v2beta1.Contexts.ListContexts]. - - Iterating over this object will yield results and - resolve additional pages automatically. - - """ - # Create or coerce a protobuf request object. - # Quick 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 context.ListContextsRequest. - # There's no risk of modifying the input as we've already verified - # 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 - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.list_contexts] - - # 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.ListContextsPager( - method=rpc, - request=request, - response=response, - metadata=metadata, - ) - - # Done; return the response. - return response - - def get_context(self, - request: Optional[Union[context.GetContextRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> context.Context: - r"""Retrieves the specified context. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import dialogflow_v2beta1 - - def sample_get_context(): - # Create a client - client = dialogflow_v2beta1.ContextsClient() - - # Initialize request argument(s) - request = dialogflow_v2beta1.GetContextRequest( - name="name_value", - ) - - # Make the request - response = client.get_context(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.dialogflow_v2beta1.types.GetContextRequest, dict]): - The request object. The request message for - [Contexts.GetContext][google.cloud.dialogflow.v2beta1.Contexts.GetContext]. - name (str): - Required. The name of the context. Supported formats: - - - ``projects//agent/sessions//contexts/``, - - ``projects//locations//agent/sessions//contexts/``, - - ``projects//agent/environments//users//sessions//contexts/``, - - ``projects//locations//agent/environments//users//sessions//contexts/``, - - If ``Location ID`` is not specified we assume default - 'us' location. If ``Environment ID`` is not specified, - we assume default 'draft' environment. If ``User ID`` is - not specified, we assume default '-' user. - - 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.Context: - Dialogflow contexts are similar to natural language context. If a person says - to you "they are orange", you need context in order - to understand what "they" is referring to. Similarly, - for Dialogflow to handle an end-user expression like - that, it needs to be provided with context in order - to correctly match an intent. - - Using contexts, you can control the flow of a - conversation. You can configure contexts for an - intent by setting input and output contexts, which - are identified by string names. When an intent is - matched, any configured output contexts for that - intent become active. While any contexts are active, - Dialogflow is more likely to match intents that are - configured with input contexts that correspond to the - currently active contexts. - - For more information about context, see the [Contexts - guide](\ https://cloud.google.com/dialogflow/docs/contexts-overview). - - """ - # Create or coerce a protobuf request object. - # Quick 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 context.GetContextRequest. - # There's no risk of modifying the input as we've already verified - # 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 - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.get_context] - - # 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_context(self, - request: Optional[Union[gcd_context.CreateContextRequest, dict]] = None, - *, - parent: Optional[str] = None, - context: Optional[gcd_context.Context] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gcd_context.Context: - r"""Creates a context. - If the specified context already exists, overrides the - context. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import dialogflow_v2beta1 - - def sample_create_context(): - # Create a client - client = dialogflow_v2beta1.ContextsClient() - - # Initialize request argument(s) - request = dialogflow_v2beta1.CreateContextRequest( - parent="parent_value", - ) - - # Make the request - response = client.create_context(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.dialogflow_v2beta1.types.CreateContextRequest, dict]): - The request object. The request message for - [Contexts.CreateContext][google.cloud.dialogflow.v2beta1.Contexts.CreateContext]. - parent (str): - Required. The session to create a context for. Supported - formats: - - - \`projects//agent/sessions/, - - ``projects//locations//agent/sessions/``, - - ``projects//agent/environments//users//sessions/``, - - ``projects//locations//agent/environments//users//sessions/``, - - If ``Location ID`` is not specified we assume default - 'us' location. If ``Environment ID`` is not specified, - we assume default 'draft' environment. If ``User ID`` is - not specified, we assume default '-' user. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - context (google.cloud.dialogflow_v2beta1.types.Context): - Required. The context to create. - 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. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.dialogflow_v2beta1.types.Context: - Dialogflow contexts are similar to natural language context. If a person says - to you "they are orange", you need context in order - to understand what "they" is referring to. Similarly, - for Dialogflow to handle an end-user expression like - that, it needs to be provided with context in order - to correctly match an intent. - - Using contexts, you can control the flow of a - conversation. You can configure contexts for an - intent by setting input and output contexts, which - are identified by string names. When an intent is - matched, any configured output contexts for that - intent become active. While any contexts are active, - Dialogflow is more likely to match intents that are - configured with input contexts that correspond to the - currently active contexts. - - For more information about context, see the [Contexts - guide](\ https://cloud.google.com/dialogflow/docs/contexts-overview). - - """ - # Create or coerce a protobuf request object. - # Quick 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, context]) - 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_context.CreateContextRequest. - # There's no risk of modifying the input as we've already verified - # 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: - request.context = context - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.create_context] - - # 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_context(self, - request: Optional[Union[gcd_context.UpdateContextRequest, dict]] = None, - *, - context: Optional[gcd_context.Context] = None, - update_mask: Optional[field_mask_pb2.FieldMask] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gcd_context.Context: - r"""Updates the specified context. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import dialogflow_v2beta1 - - def sample_update_context(): - # Create a client - client = dialogflow_v2beta1.ContextsClient() - - # Initialize request argument(s) - request = dialogflow_v2beta1.UpdateContextRequest( - ) - - # Make the request - response = client.update_context(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.dialogflow_v2beta1.types.UpdateContextRequest, dict]): - The request object. The request message for - [Contexts.UpdateContext][google.cloud.dialogflow.v2beta1.Contexts.UpdateContext]. - context (google.cloud.dialogflow_v2beta1.types.Context): - Required. The context to update. - This corresponds to the ``context`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - update_mask (google.protobuf.field_mask_pb2.FieldMask): - Optional. 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.Context: - Dialogflow contexts are similar to natural language context. If a person says - to you "they are orange", you need context in order - to understand what "they" is referring to. Similarly, - for Dialogflow to handle an end-user expression like - that, it needs to be provided with context in order - to correctly match an intent. - - Using contexts, you can control the flow of a - conversation. You can configure contexts for an - intent by setting input and output contexts, which - are identified by string names. When an intent is - matched, any configured output contexts for that - intent become active. While any contexts are active, - Dialogflow is more likely to match intents that are - configured with input contexts that correspond to the - currently active contexts. - - For more information about context, see the [Contexts - guide](\ https://cloud.google.com/dialogflow/docs/contexts-overview). - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([context, 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_context.UpdateContextRequest. - # There's no risk of modifying the input as we've already verified - # 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: - 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_context] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("context.name", request.context.name), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def delete_context(self, - request: Optional[Union[context.DeleteContextRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> None: - r"""Deletes the specified context. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import dialogflow_v2beta1 - - def sample_delete_context(): - # Create a client - client = dialogflow_v2beta1.ContextsClient() - - # Initialize request argument(s) - request = dialogflow_v2beta1.DeleteContextRequest( - name="name_value", - ) - - # Make the request - client.delete_context(request=request) - - Args: - request (Union[google.cloud.dialogflow_v2beta1.types.DeleteContextRequest, dict]): - The request object. The request message for - [Contexts.DeleteContext][google.cloud.dialogflow.v2beta1.Contexts.DeleteContext]. - name (str): - Required. The name of the context to delete. Supported - formats: - - - ``projects//agent/sessions//contexts/``, - - ``projects//locations//agent/sessions//contexts/``, - - ``projects//agent/environments//users//sessions//contexts/``, - - ``projects//locations//agent/environments//users//sessions//contexts/``, - - If ``Location ID`` is not specified we assume default - 'us' location. If ``Environment ID`` is not specified, - we assume default 'draft' environment. If ``User ID`` is - not specified, we assume default '-' user. - - 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. - # Quick 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 context.DeleteContextRequest. - # There's no risk of modifying the input as we've already verified - # 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 - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.delete_context] - - # 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 delete_all_contexts(self, - request: Optional[Union[context.DeleteAllContextsRequest, dict]] = None, - *, - parent: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> None: - r"""Deletes all active contexts in the specified session. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import dialogflow_v2beta1 - - def sample_delete_all_contexts(): - # Create a client - client = dialogflow_v2beta1.ContextsClient() - - # Initialize request argument(s) - request = dialogflow_v2beta1.DeleteAllContextsRequest( - parent="parent_value", - ) - - # Make the request - client.delete_all_contexts(request=request) - - Args: - request (Union[google.cloud.dialogflow_v2beta1.types.DeleteAllContextsRequest, dict]): - The request object. The request message for - [Contexts.DeleteAllContexts][google.cloud.dialogflow.v2beta1.Contexts.DeleteAllContexts]. - parent (str): - Required. The name of the session to delete all contexts - from. Supported formats: - - - \`projects//agent/sessions/, - - ``projects//locations//agent/sessions/``, - - ``projects//agent/environments//users//sessions/``, - - ``projects//locations//agent/environments//users//sessions/``, - - If ``Location ID`` is not specified we assume default - 'us' location. If ``Environment ID`` is not specified we - assume default 'draft' environment. If ``User ID`` is - not specified, we assume default '-' user. - - 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. - """ - # Create or coerce a protobuf request object. - # Quick 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 context.DeleteAllContextsRequest. - # There's no risk of modifying the input as we've already verified - # 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 - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.delete_all_contexts] - - # 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. - rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - def __enter__(self) -> "ContextsClient": - return self - - def __exit__(self, type, value, traceback): - """Releases underlying transport's resources. - - .. warning:: - ONLY use as a context manager if the transport is NOT shared - with other clients! Exiting the with block will CLOSE the transport - and may cause errors in other clients! - """ - self.transport.close() - - def list_operations( - self, - request: Optional[operations_pb2.ListOperationsRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operations_pb2.ListOperationsResponse: - r"""Lists operations that match the specified filter in the request. - - Args: - request (:class:`~.operations_pb2.ListOperationsRequest`): - The request object. Request message for - `ListOperations` method. - 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: - ~.operations_pb2.ListOperationsResponse: - Response message for ``ListOperations`` method. - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = operations_pb2.ListOperationsRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._transport.list_operations, - 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 = rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - def get_operation( - self, - request: Optional[operations_pb2.GetOperationRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operations_pb2.Operation: - r"""Gets the latest state of a long-running operation. - - Args: - request (:class:`~.operations_pb2.GetOperationRequest`): - The request object. Request message for - `GetOperation` method. - 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: - ~.operations_pb2.Operation: - An ``Operation`` object. - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = operations_pb2.GetOperationRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._transport.get_operation, - 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 = rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - def cancel_operation( - self, - request: Optional[operations_pb2.CancelOperationRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> None: - r"""Starts asynchronous cancellation on a long-running operation. - - The server makes a best effort to cancel the operation, but success - is not guaranteed. If the server doesn't support this method, it returns - `google.rpc.Code.UNIMPLEMENTED`. - - Args: - request (:class:`~.operations_pb2.CancelOperationRequest`): - The request object. Request message for - `CancelOperation` method. - 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: - None - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = operations_pb2.CancelOperationRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._transport.cancel_operation, - 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. - rpc(request, retry=retry, timeout=timeout, metadata=metadata,) - - def get_location( - self, - request: Optional[locations_pb2.GetLocationRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> locations_pb2.Location: - r"""Gets information about a location. - - Args: - request (:class:`~.location_pb2.GetLocationRequest`): - The request object. Request message for - `GetLocation` method. - 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: - ~.location_pb2.Location: - Location object. - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = locations_pb2.GetLocationRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._transport.get_location, - 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 = rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - def list_locations( - self, - request: Optional[locations_pb2.ListLocationsRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> locations_pb2.ListLocationsResponse: - r"""Lists information about the supported locations for this service. - - Args: - request (:class:`~.location_pb2.ListLocationsRequest`): - The request object. Request message for - `ListLocations` method. - 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: - ~.location_pb2.ListLocationsResponse: - Response message for ``ListLocations`` method. - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = locations_pb2.ListLocationsRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._transport.list_locations, - 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 = rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) - - -__all__ = ( - "ContextsClient", -) diff --git a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/contexts/pagers.py b/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/contexts/pagers.py deleted file mode 100644 index 7c481511a..000000000 --- a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/contexts/pagers.py +++ /dev/null @@ -1,139 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from typing import Any, AsyncIterator, Awaitable, Callable, Sequence, Tuple, Optional, Iterator - -from google.cloud.dialogflow_v2beta1.types import context - - -class ListContextsPager: - """A pager for iterating through ``list_contexts`` requests. - - This class thinly wraps an initial - :class:`google.cloud.dialogflow_v2beta1.types.ListContextsResponse` object, and - provides an ``__iter__`` method to iterate through its - ``contexts`` field. - - If there are more pages, the ``__iter__`` method will make additional - ``ListContexts`` requests and continue to iterate - through the ``contexts`` field on the - corresponding responses. - - All the usual :class:`google.cloud.dialogflow_v2beta1.types.ListContextsResponse` - 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[..., context.ListContextsResponse], - request: context.ListContextsRequest, - response: context.ListContextsResponse, - *, - 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.ListContextsRequest): - The initial request object. - response (google.cloud.dialogflow_v2beta1.types.ListContextsResponse): - 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 = context.ListContextsRequest(request) - self._response = response - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - def pages(self) -> Iterator[context.ListContextsResponse]: - yield self._response - while self._response.next_page_token: - self._request.page_token = self._response.next_page_token - self._response = self._method(self._request, metadata=self._metadata) - yield self._response - - def __iter__(self) -> Iterator[context.Context]: - for page in self.pages: - yield from page.contexts - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListContextsAsyncPager: - """A pager for iterating through ``list_contexts`` requests. - - This class thinly wraps an initial - :class:`google.cloud.dialogflow_v2beta1.types.ListContextsResponse` object, and - provides an ``__aiter__`` method to iterate through its - ``contexts`` field. - - If there are more pages, the ``__aiter__`` method will make additional - ``ListContexts`` requests and continue to iterate - through the ``contexts`` field on the - corresponding responses. - - All the usual :class:`google.cloud.dialogflow_v2beta1.types.ListContextsResponse` - 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[context.ListContextsResponse]], - request: context.ListContextsRequest, - response: context.ListContextsResponse, - *, - metadata: Sequence[Tuple[str, str]] = ()): - """Instantiates the pager. - - Args: - method (Callable): The method that was originally called, and - which instantiated this pager. - request (google.cloud.dialogflow_v2beta1.types.ListContextsRequest): - The initial request object. - response (google.cloud.dialogflow_v2beta1.types.ListContextsResponse): - 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 = context.ListContextsRequest(request) - self._response = response - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - async def pages(self) -> AsyncIterator[context.ListContextsResponse]: - yield self._response - while self._response.next_page_token: - self._request.page_token = self._response.next_page_token - self._response = await self._method(self._request, metadata=self._metadata) - yield self._response - def __aiter__(self) -> AsyncIterator[context.Context]: - async def async_generator(): - async for page in self.pages: - for response in page.contexts: - yield response - - return async_generator() - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) diff --git a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/contexts/transports/__init__.py b/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/contexts/transports/__init__.py deleted file mode 100644 index f6acdd0a1..000000000 --- a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/contexts/transports/__init__.py +++ /dev/null @@ -1,38 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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 ContextsTransport -from .grpc import ContextsGrpcTransport -from .grpc_asyncio import ContextsGrpcAsyncIOTransport -from .rest import ContextsRestTransport -from .rest import ContextsRestInterceptor - - -# Compile a registry of transports. -_transport_registry = OrderedDict() # type: Dict[str, Type[ContextsTransport]] -_transport_registry['grpc'] = ContextsGrpcTransport -_transport_registry['grpc_asyncio'] = ContextsGrpcAsyncIOTransport -_transport_registry['rest'] = ContextsRestTransport - -__all__ = ( - 'ContextsTransport', - 'ContextsGrpcTransport', - 'ContextsGrpcAsyncIOTransport', - 'ContextsRestTransport', - 'ContextsRestInterceptor', -) diff --git a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/contexts/transports/base.py b/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/contexts/transports/base.py deleted file mode 100644 index ff9ede218..000000000 --- a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/contexts/transports/base.py +++ /dev/null @@ -1,266 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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 - -from google.cloud.dialogflow_v2beta1 import gapic_version as package_version - -import google.auth # type: ignore -import google.api_core -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import retry as retries -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 context -from google.cloud.dialogflow_v2beta1.types import context as gcd_context -from google.cloud.location import locations_pb2 # type: ignore -from google.longrunning import operations_pb2 -from google.protobuf import empty_pb2 # type: ignore - -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) - - -class ContextsTransport(abc.ABC): - """Abstract transport class for Contexts.""" - - 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: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - api_audience: Optional[str] = None, - **kwargs, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. - scopes (Optional[Sequence[str]]): A list of scopes. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - """ - - scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} - - # Save the scopes. - self._scopes = scopes - - # If no credentials are provided, then determine the appropriate - # defaults. - if credentials and credentials_file: - raise core_exceptions.DuplicateCredentialArgs("'credentials_file' and 'credentials' are mutually exclusive") - - if credentials_file is not None: - credentials, _ = google.auth.load_credentials_from_file( - credentials_file, - **scopes_kwargs, - quota_project_id=quota_project_id - ) - elif credentials is None: - credentials, _ = google.auth.default(**scopes_kwargs, quota_project_id=quota_project_id) - # Don't apply audience if the credentials file passed from user. - if hasattr(credentials, "with_gdch_audience"): - credentials = credentials.with_gdch_audience(api_audience if api_audience else host) - - # If the credentials are service account credentials, then always try to use self signed JWT. - if always_use_jwt_access and isinstance(credentials, service_account.Credentials) and hasattr(service_account.Credentials, "with_always_use_jwt_access"): - credentials = credentials.with_always_use_jwt_access(True) - - # Save the credentials. - self._credentials = credentials - - # Save the hostname. Default to port 443 (HTTPS) if none is specified. - if ':' not in host: - host += ':443' - self._host = host - - def _prep_wrapped_messages(self, client_info): - # Precompute the wrapped methods. - self._wrapped_methods = { - self.list_contexts: gapic_v1.method.wrap_method( - self.list_contexts, - default_timeout=None, - client_info=client_info, - ), - self.get_context: gapic_v1.method.wrap_method( - self.get_context, - default_timeout=None, - client_info=client_info, - ), - self.create_context: gapic_v1.method.wrap_method( - self.create_context, - default_timeout=None, - client_info=client_info, - ), - self.update_context: gapic_v1.method.wrap_method( - self.update_context, - default_timeout=None, - client_info=client_info, - ), - self.delete_context: gapic_v1.method.wrap_method( - self.delete_context, - default_timeout=None, - client_info=client_info, - ), - self.delete_all_contexts: gapic_v1.method.wrap_method( - self.delete_all_contexts, - default_timeout=None, - client_info=client_info, - ), - } - - def close(self): - """Closes resources associated with the transport. - - .. warning:: - Only call this method if the transport is NOT shared - with other clients - this may cause errors in other clients! - """ - raise NotImplementedError() - - @property - def list_contexts(self) -> Callable[ - [context.ListContextsRequest], - Union[ - context.ListContextsResponse, - Awaitable[context.ListContextsResponse] - ]]: - raise NotImplementedError() - - @property - def get_context(self) -> Callable[ - [context.GetContextRequest], - Union[ - context.Context, - Awaitable[context.Context] - ]]: - raise NotImplementedError() - - @property - def create_context(self) -> Callable[ - [gcd_context.CreateContextRequest], - Union[ - gcd_context.Context, - Awaitable[gcd_context.Context] - ]]: - raise NotImplementedError() - - @property - def update_context(self) -> Callable[ - [gcd_context.UpdateContextRequest], - Union[ - gcd_context.Context, - Awaitable[gcd_context.Context] - ]]: - raise NotImplementedError() - - @property - def delete_context(self) -> Callable[ - [context.DeleteContextRequest], - Union[ - empty_pb2.Empty, - Awaitable[empty_pb2.Empty] - ]]: - raise NotImplementedError() - - @property - def delete_all_contexts(self) -> Callable[ - [context.DeleteAllContextsRequest], - Union[ - empty_pb2.Empty, - Awaitable[empty_pb2.Empty] - ]]: - raise NotImplementedError() - - @property - def list_operations( - self, - ) -> Callable[ - [operations_pb2.ListOperationsRequest], - Union[operations_pb2.ListOperationsResponse, Awaitable[operations_pb2.ListOperationsResponse]], - ]: - raise NotImplementedError() - - @property - def get_operation( - self, - ) -> Callable[ - [operations_pb2.GetOperationRequest], - Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], - ]: - raise NotImplementedError() - - @property - def cancel_operation( - self, - ) -> Callable[ - [operations_pb2.CancelOperationRequest], - None, - ]: - raise NotImplementedError() - - @property - def get_location(self, - ) -> Callable[ - [locations_pb2.GetLocationRequest], - Union[locations_pb2.Location, Awaitable[locations_pb2.Location]], - ]: - raise NotImplementedError() - - @property - def list_locations(self, - ) -> Callable[ - [locations_pb2.ListLocationsRequest], - Union[locations_pb2.ListLocationsResponse, Awaitable[locations_pb2.ListLocationsResponse]], - ]: - raise NotImplementedError() - - @property - def kind(self) -> str: - raise NotImplementedError() - - -__all__ = ( - 'ContextsTransport', -) diff --git a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/contexts/transports/grpc.py b/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/contexts/transports/grpc.py deleted file mode 100644 index e6fdfc803..000000000 --- a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/contexts/transports/grpc.py +++ /dev/null @@ -1,492 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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 -from google.api_core import gapic_v1 -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.cloud.location import locations_pb2 # type: ignore -from google.longrunning import operations_pb2 -from google.protobuf import empty_pb2 # type: ignore -from .base import ContextsTransport, DEFAULT_CLIENT_INFO - - -class ContextsGrpcTransport(ContextsTransport): - """gRPC backend transport for Contexts. - - Service for managing - [Contexts][google.cloud.dialogflow.v2beta1.Context]. - - 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: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - channel: Optional[grpc.Channel] = None, - api_mtls_endpoint: Optional[str] = None, - client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, - ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, - client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - api_audience: Optional[str] = None, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - This argument is ignored if ``channel`` is provided. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional(Sequence[str])): A list of scopes. This argument is - ignored if ``channel`` is provided. - channel (Optional[grpc.Channel]): A ``Channel`` instance through - which to make calls. - api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. - If provided, it overrides the ``host`` argument and tries to create - a mutual TLS channel with client SSL credentials from - ``client_cert_source`` or application default SSL credentials. - client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): - Deprecated. A callback to provide client SSL certificate bytes and - private key bytes, both in PEM format. It is ignored if - ``api_mtls_endpoint`` is None. - ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials - for the grpc channel. It is ignored if ``channel`` is provided. - client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): - A callback to provide client certificate bytes and private key bytes, - both in PEM format. It is used to configure a mutual TLS channel. It is - ignored if ``channel`` or ``ssl_channel_credentials`` is provided. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport - creation failed for any reason. - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - self._grpc_channel = None - self._ssl_channel_credentials = ssl_channel_credentials - self._stubs: Dict[str, Callable] = {} - - if api_mtls_endpoint: - warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) - if client_cert_source: - warnings.warn("client_cert_source is deprecated", DeprecationWarning) - - if channel: - # Ignore credentials if a channel was passed. - credentials = False - # If a channel was explicitly provided, set it. - self._grpc_channel = channel - self._ssl_channel_credentials = None - - else: - if api_mtls_endpoint: - host = api_mtls_endpoint - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - self._ssl_channel_credentials = SslCredentials().ssl_credentials - - else: - if client_cert_source_for_mtls and not ssl_channel_credentials: - cert, key = client_cert_source_for_mtls() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - - # The base transport sets the host, credentials and scopes - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes, - quota_project_id=quota_project_id, - client_info=client_info, - always_use_jwt_access=always_use_jwt_access, - api_audience=api_audience, - ) - - if not self._grpc_channel: - self._grpc_channel = type(self).create_channel( - self._host, - # use the credentials which are saved - credentials=self._credentials, - # Set ``credentials_file`` to ``None`` here as - # the credentials that we saved earlier should be used. - credentials_file=None, - 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: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - **kwargs) -> grpc.Channel: - """Create and return a gRPC channel object. - Args: - host (Optional[str]): The host for the channel to use. - credentials (Optional[~.Credentials]): The - authorization credentials to attach to requests. These - credentials identify this application to the service. If - none are specified, the client will attempt to ascertain - the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - kwargs (Optional[dict]): Keyword arguments, which are passed to the - channel creation. - Returns: - grpc.Channel: A gRPC channel object. - - Raises: - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - - return grpc_helpers.create_channel( - host, - credentials=credentials, - credentials_file=credentials_file, - quota_project_id=quota_project_id, - default_scopes=cls.AUTH_SCOPES, - scopes=scopes, - default_host=cls.DEFAULT_HOST, - **kwargs - ) - - @property - def grpc_channel(self) -> grpc.Channel: - """Return the channel designed to connect to this service. - """ - return self._grpc_channel - - @property - def list_contexts(self) -> Callable[ - [context.ListContextsRequest], - context.ListContextsResponse]: - r"""Return a callable for the list contexts method over gRPC. - - Returns the list of all contexts in the specified - session. - - Returns: - Callable[[~.ListContextsRequest], - ~.ListContextsResponse]: - 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_contexts' not in self._stubs: - self._stubs['list_contexts'] = self.grpc_channel.unary_unary( - '/google.cloud.dialogflow.v2beta1.Contexts/ListContexts', - request_serializer=context.ListContextsRequest.serialize, - response_deserializer=context.ListContextsResponse.deserialize, - ) - return self._stubs['list_contexts'] - - @property - def get_context(self) -> Callable[ - [context.GetContextRequest], - context.Context]: - r"""Return a callable for the get context method over gRPC. - - Retrieves the specified context. - - Returns: - Callable[[~.GetContextRequest], - ~.Context]: - 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_context' not in self._stubs: - self._stubs['get_context'] = self.grpc_channel.unary_unary( - '/google.cloud.dialogflow.v2beta1.Contexts/GetContext', - request_serializer=context.GetContextRequest.serialize, - response_deserializer=context.Context.deserialize, - ) - return self._stubs['get_context'] - - @property - def create_context(self) -> Callable[ - [gcd_context.CreateContextRequest], - gcd_context.Context]: - r"""Return a callable for the create context method over gRPC. - - Creates a context. - If the specified context already exists, overrides the - context. - - Returns: - Callable[[~.CreateContextRequest], - ~.Context]: - 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_context' not in self._stubs: - self._stubs['create_context'] = self.grpc_channel.unary_unary( - '/google.cloud.dialogflow.v2beta1.Contexts/CreateContext', - request_serializer=gcd_context.CreateContextRequest.serialize, - response_deserializer=gcd_context.Context.deserialize, - ) - return self._stubs['create_context'] - - @property - def update_context(self) -> Callable[ - [gcd_context.UpdateContextRequest], - gcd_context.Context]: - r"""Return a callable for the update context method over gRPC. - - Updates the specified context. - - Returns: - Callable[[~.UpdateContextRequest], - ~.Context]: - 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_context' not in self._stubs: - self._stubs['update_context'] = self.grpc_channel.unary_unary( - '/google.cloud.dialogflow.v2beta1.Contexts/UpdateContext', - request_serializer=gcd_context.UpdateContextRequest.serialize, - response_deserializer=gcd_context.Context.deserialize, - ) - return self._stubs['update_context'] - - @property - 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. - - Returns: - Callable[[~.DeleteContextRequest], - ~.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_context' not in self._stubs: - self._stubs['delete_context'] = self.grpc_channel.unary_unary( - '/google.cloud.dialogflow.v2beta1.Contexts/DeleteContext', - request_serializer=context.DeleteContextRequest.serialize, - response_deserializer=empty_pb2.Empty.FromString, - ) - return self._stubs['delete_context'] - - @property - def delete_all_contexts(self) -> 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. - - Returns: - Callable[[~.DeleteAllContextsRequest], - ~.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_all_contexts' not in self._stubs: - self._stubs['delete_all_contexts'] = self.grpc_channel.unary_unary( - '/google.cloud.dialogflow.v2beta1.Contexts/DeleteAllContexts', - request_serializer=context.DeleteAllContextsRequest.serialize, - response_deserializer=empty_pb2.Empty.FromString, - ) - return self._stubs['delete_all_contexts'] - - def close(self): - self.grpc_channel.close() - - @property - def cancel_operation( - self, - ) -> Callable[[operations_pb2.CancelOperationRequest], None]: - r"""Return a callable for the cancel_operation method over gRPC. - """ - # 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 "cancel_operation" not in self._stubs: - self._stubs["cancel_operation"] = self.grpc_channel.unary_unary( - "/google.longrunning.Operations/CancelOperation", - request_serializer=operations_pb2.CancelOperationRequest.SerializeToString, - response_deserializer=None, - ) - return self._stubs["cancel_operation"] - - @property - def get_operation( - self, - ) -> Callable[[operations_pb2.GetOperationRequest], operations_pb2.Operation]: - r"""Return a callable for the get_operation method over gRPC. - """ - # 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_operation" not in self._stubs: - self._stubs["get_operation"] = self.grpc_channel.unary_unary( - "/google.longrunning.Operations/GetOperation", - request_serializer=operations_pb2.GetOperationRequest.SerializeToString, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs["get_operation"] - - @property - def list_operations( - self, - ) -> Callable[[operations_pb2.ListOperationsRequest], operations_pb2.ListOperationsResponse]: - r"""Return a callable for the list_operations method over gRPC. - """ - # 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_operations" not in self._stubs: - self._stubs["list_operations"] = self.grpc_channel.unary_unary( - "/google.longrunning.Operations/ListOperations", - request_serializer=operations_pb2.ListOperationsRequest.SerializeToString, - response_deserializer=operations_pb2.ListOperationsResponse.FromString, - ) - return self._stubs["list_operations"] - - @property - def list_locations( - self, - ) -> Callable[[locations_pb2.ListLocationsRequest], locations_pb2.ListLocationsResponse]: - r"""Return a callable for the list locations method over gRPC. - """ - # 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_locations" not in self._stubs: - self._stubs["list_locations"] = self.grpc_channel.unary_unary( - "/google.cloud.location.Locations/ListLocations", - request_serializer=locations_pb2.ListLocationsRequest.SerializeToString, - response_deserializer=locations_pb2.ListLocationsResponse.FromString, - ) - return self._stubs["list_locations"] - - @property - def get_location( - self, - ) -> Callable[[locations_pb2.GetLocationRequest], locations_pb2.Location]: - r"""Return a callable for the list locations method over gRPC. - """ - # 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_location" not in self._stubs: - self._stubs["get_location"] = self.grpc_channel.unary_unary( - "/google.cloud.location.Locations/GetLocation", - request_serializer=locations_pb2.GetLocationRequest.SerializeToString, - response_deserializer=locations_pb2.Location.FromString, - ) - return self._stubs["get_location"] - - @property - def kind(self) -> str: - return "grpc" - - -__all__ = ( - 'ContextsGrpcTransport', -) diff --git a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/contexts/transports/grpc_asyncio.py b/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/contexts/transports/grpc_asyncio.py deleted file mode 100644 index 08a193c38..000000000 --- a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/contexts/transports/grpc_asyncio.py +++ /dev/null @@ -1,491 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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 -from google.api_core import grpc_helpers_async -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore - -import grpc # type: ignore -from grpc.experimental import aio # type: ignore - -from google.cloud.dialogflow_v2beta1.types import context -from google.cloud.dialogflow_v2beta1.types import context as gcd_context -from google.cloud.location import locations_pb2 # type: ignore -from google.longrunning import operations_pb2 -from google.protobuf import empty_pb2 # type: ignore -from .base import ContextsTransport, DEFAULT_CLIENT_INFO -from .grpc import ContextsGrpcTransport - - -class ContextsGrpcAsyncIOTransport(ContextsTransport): - """gRPC AsyncIO backend transport for Contexts. - - Service for managing - [Contexts][google.cloud.dialogflow.v2beta1.Context]. - - 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: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - **kwargs) -> aio.Channel: - """Create and return a gRPC AsyncIO channel object. - Args: - host (Optional[str]): The host for the channel to use. - credentials (Optional[~.Credentials]): The - authorization credentials to attach to requests. These - credentials identify this application to the service. If - none are specified, the client will attempt to ascertain - the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - kwargs (Optional[dict]): Keyword arguments, which are passed to the - channel creation. - Returns: - aio.Channel: A gRPC AsyncIO channel object. - """ - - return grpc_helpers_async.create_channel( - host, - credentials=credentials, - credentials_file=credentials_file, - quota_project_id=quota_project_id, - default_scopes=cls.AUTH_SCOPES, - scopes=scopes, - default_host=cls.DEFAULT_HOST, - **kwargs - ) - - def __init__(self, *, - host: str = 'dialogflow.googleapis.com', - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - channel: Optional[aio.Channel] = None, - api_mtls_endpoint: Optional[str] = None, - client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, - ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, - client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - api_audience: Optional[str] = None, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - This argument is ignored if ``channel`` is provided. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - channel (Optional[aio.Channel]): A ``Channel`` instance through - which to make calls. - api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. - If provided, it overrides the ``host`` argument and tries to create - a mutual TLS channel with client SSL credentials from - ``client_cert_source`` or application default SSL credentials. - client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): - Deprecated. A callback to provide client SSL certificate bytes and - private key bytes, both in PEM format. It is ignored if - ``api_mtls_endpoint`` is None. - ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials - for the grpc channel. It is ignored if ``channel`` is provided. - client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): - A callback to provide client certificate bytes and private key bytes, - both in PEM format. It is used to configure a mutual TLS channel. It is - ignored if ``channel`` or ``ssl_channel_credentials`` is provided. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - - Raises: - google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport - creation failed for any reason. - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - self._grpc_channel = None - self._ssl_channel_credentials = ssl_channel_credentials - self._stubs: Dict[str, Callable] = {} - - if api_mtls_endpoint: - warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) - if client_cert_source: - warnings.warn("client_cert_source is deprecated", DeprecationWarning) - - if channel: - # Ignore credentials if a channel was passed. - credentials = False - # If a channel was explicitly provided, set it. - self._grpc_channel = channel - self._ssl_channel_credentials = None - else: - if api_mtls_endpoint: - host = api_mtls_endpoint - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - self._ssl_channel_credentials = SslCredentials().ssl_credentials - - else: - if client_cert_source_for_mtls and not ssl_channel_credentials: - cert, key = client_cert_source_for_mtls() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - - # The base transport sets the host, credentials and scopes - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes, - quota_project_id=quota_project_id, - client_info=client_info, - always_use_jwt_access=always_use_jwt_access, - api_audience=api_audience, - ) - - if not self._grpc_channel: - self._grpc_channel = type(self).create_channel( - self._host, - # use the credentials which are saved - credentials=self._credentials, - # Set ``credentials_file`` to ``None`` here as - # the credentials that we saved earlier should be used. - credentials_file=None, - 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_contexts(self) -> Callable[ - [context.ListContextsRequest], - Awaitable[context.ListContextsResponse]]: - r"""Return a callable for the list contexts method over gRPC. - - Returns the list of all contexts in the specified - session. - - Returns: - Callable[[~.ListContextsRequest], - Awaitable[~.ListContextsResponse]]: - 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_contexts' not in self._stubs: - self._stubs['list_contexts'] = self.grpc_channel.unary_unary( - '/google.cloud.dialogflow.v2beta1.Contexts/ListContexts', - request_serializer=context.ListContextsRequest.serialize, - response_deserializer=context.ListContextsResponse.deserialize, - ) - return self._stubs['list_contexts'] - - @property - def get_context(self) -> Callable[ - [context.GetContextRequest], - Awaitable[context.Context]]: - r"""Return a callable for the get context method over gRPC. - - Retrieves the specified context. - - Returns: - Callable[[~.GetContextRequest], - Awaitable[~.Context]]: - 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_context' not in self._stubs: - self._stubs['get_context'] = self.grpc_channel.unary_unary( - '/google.cloud.dialogflow.v2beta1.Contexts/GetContext', - request_serializer=context.GetContextRequest.serialize, - response_deserializer=context.Context.deserialize, - ) - return self._stubs['get_context'] - - @property - def create_context(self) -> Callable[ - [gcd_context.CreateContextRequest], - Awaitable[gcd_context.Context]]: - r"""Return a callable for the create context method over gRPC. - - Creates a context. - If the specified context already exists, overrides the - context. - - Returns: - Callable[[~.CreateContextRequest], - Awaitable[~.Context]]: - 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_context' not in self._stubs: - self._stubs['create_context'] = self.grpc_channel.unary_unary( - '/google.cloud.dialogflow.v2beta1.Contexts/CreateContext', - request_serializer=gcd_context.CreateContextRequest.serialize, - response_deserializer=gcd_context.Context.deserialize, - ) - return self._stubs['create_context'] - - @property - def update_context(self) -> Callable[ - [gcd_context.UpdateContextRequest], - Awaitable[gcd_context.Context]]: - r"""Return a callable for the update context method over gRPC. - - Updates the specified context. - - Returns: - Callable[[~.UpdateContextRequest], - Awaitable[~.Context]]: - 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_context' not in self._stubs: - self._stubs['update_context'] = self.grpc_channel.unary_unary( - '/google.cloud.dialogflow.v2beta1.Contexts/UpdateContext', - request_serializer=gcd_context.UpdateContextRequest.serialize, - response_deserializer=gcd_context.Context.deserialize, - ) - return self._stubs['update_context'] - - @property - def delete_context(self) -> Callable[ - [context.DeleteContextRequest], - Awaitable[empty_pb2.Empty]]: - r"""Return a callable for the delete context method over gRPC. - - Deletes the specified context. - - Returns: - Callable[[~.DeleteContextRequest], - 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_context' not in self._stubs: - self._stubs['delete_context'] = self.grpc_channel.unary_unary( - '/google.cloud.dialogflow.v2beta1.Contexts/DeleteContext', - request_serializer=context.DeleteContextRequest.serialize, - response_deserializer=empty_pb2.Empty.FromString, - ) - return self._stubs['delete_context'] - - @property - def delete_all_contexts(self) -> 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. - - Returns: - Callable[[~.DeleteAllContextsRequest], - 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_all_contexts' not in self._stubs: - self._stubs['delete_all_contexts'] = self.grpc_channel.unary_unary( - '/google.cloud.dialogflow.v2beta1.Contexts/DeleteAllContexts', - request_serializer=context.DeleteAllContextsRequest.serialize, - response_deserializer=empty_pb2.Empty.FromString, - ) - return self._stubs['delete_all_contexts'] - - def close(self): - return self.grpc_channel.close() - - @property - def cancel_operation( - self, - ) -> Callable[[operations_pb2.CancelOperationRequest], None]: - r"""Return a callable for the cancel_operation method over gRPC. - """ - # 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 "cancel_operation" not in self._stubs: - self._stubs["cancel_operation"] = self.grpc_channel.unary_unary( - "/google.longrunning.Operations/CancelOperation", - request_serializer=operations_pb2.CancelOperationRequest.SerializeToString, - response_deserializer=None, - ) - return self._stubs["cancel_operation"] - - @property - def get_operation( - self, - ) -> Callable[[operations_pb2.GetOperationRequest], operations_pb2.Operation]: - r"""Return a callable for the get_operation method over gRPC. - """ - # 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_operation" not in self._stubs: - self._stubs["get_operation"] = self.grpc_channel.unary_unary( - "/google.longrunning.Operations/GetOperation", - request_serializer=operations_pb2.GetOperationRequest.SerializeToString, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs["get_operation"] - - @property - def list_operations( - self, - ) -> Callable[[operations_pb2.ListOperationsRequest], operations_pb2.ListOperationsResponse]: - r"""Return a callable for the list_operations method over gRPC. - """ - # 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_operations" not in self._stubs: - self._stubs["list_operations"] = self.grpc_channel.unary_unary( - "/google.longrunning.Operations/ListOperations", - request_serializer=operations_pb2.ListOperationsRequest.SerializeToString, - response_deserializer=operations_pb2.ListOperationsResponse.FromString, - ) - return self._stubs["list_operations"] - - @property - def list_locations( - self, - ) -> Callable[[locations_pb2.ListLocationsRequest], locations_pb2.ListLocationsResponse]: - r"""Return a callable for the list locations method over gRPC. - """ - # 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_locations" not in self._stubs: - self._stubs["list_locations"] = self.grpc_channel.unary_unary( - "/google.cloud.location.Locations/ListLocations", - request_serializer=locations_pb2.ListLocationsRequest.SerializeToString, - response_deserializer=locations_pb2.ListLocationsResponse.FromString, - ) - return self._stubs["list_locations"] - - @property - def get_location( - self, - ) -> Callable[[locations_pb2.GetLocationRequest], locations_pb2.Location]: - r"""Return a callable for the list locations method over gRPC. - """ - # 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_location" not in self._stubs: - self._stubs["get_location"] = self.grpc_channel.unary_unary( - "/google.cloud.location.Locations/GetLocation", - request_serializer=locations_pb2.GetLocationRequest.SerializeToString, - response_deserializer=locations_pb2.Location.FromString, - ) - return self._stubs["get_location"] - - -__all__ = ( - 'ContextsGrpcAsyncIOTransport', -) diff --git a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/contexts/transports/rest.py b/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/contexts/transports/rest.py deleted file mode 100644 index 76ba7f633..000000000 --- a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/contexts/transports/rest.py +++ /dev/null @@ -1,1388 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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 google.auth.transport.requests import AuthorizedSession # type: ignore -import json # type: ignore -import grpc # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore -from google.auth import credentials as ga_credentials # type: ignore -from google.api_core import exceptions as core_exceptions -from google.api_core import retry as retries -from google.api_core import rest_helpers -from google.api_core import rest_streaming -from google.api_core import path_template -from google.api_core import gapic_v1 - -from google.protobuf import json_format -from google.cloud.location import locations_pb2 # type: ignore -from google.longrunning import operations_pb2 -from requests import __version__ as requests_version -import dataclasses -import re -from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union -import warnings - -try: - OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] -except AttributeError: # pragma: NO COVER - OptionalRetry = Union[retries.Retry, object] # 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 # type: ignore - -from .base import ContextsTransport, DEFAULT_CLIENT_INFO as BASE_DEFAULT_CLIENT_INFO - - -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=BASE_DEFAULT_CLIENT_INFO.gapic_version, - grpc_version=None, - rest_version=requests_version, -) - - -class ContextsRestInterceptor: - """Interceptor for Contexts. - - Interceptors are used to manipulate requests, request metadata, and responses - in arbitrary ways. - Example use cases include: - * Logging - * Verifying requests according to service or custom semantics - * Stripping extraneous information from responses - - These use cases and more can be enabled by injecting an - instance of a custom subclass when constructing the ContextsRestTransport. - - .. code-block:: python - class MyCustomContextsInterceptor(ContextsRestInterceptor): - def pre_create_context(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_create_context(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_delete_all_contexts(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def pre_delete_context(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def pre_get_context(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_get_context(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_list_contexts(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_list_contexts(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_update_context(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_update_context(self, response): - logging.log(f"Received response: {response}") - return response - - transport = ContextsRestTransport(interceptor=MyCustomContextsInterceptor()) - client = ContextsClient(transport=transport) - - - """ - def pre_create_context(self, request: gcd_context.CreateContextRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[gcd_context.CreateContextRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for create_context - - Override in a subclass to manipulate the request or metadata - before they are sent to the Contexts server. - """ - return request, metadata - - def post_create_context(self, response: gcd_context.Context) -> gcd_context.Context: - """Post-rpc interceptor for create_context - - Override in a subclass to manipulate the response - after it is returned by the Contexts server but before - it is returned to user code. - """ - return response - def pre_delete_all_contexts(self, request: context.DeleteAllContextsRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[context.DeleteAllContextsRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for delete_all_contexts - - Override in a subclass to manipulate the request or metadata - before they are sent to the Contexts server. - """ - return request, metadata - - def pre_delete_context(self, request: context.DeleteContextRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[context.DeleteContextRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for delete_context - - Override in a subclass to manipulate the request or metadata - before they are sent to the Contexts server. - """ - return request, metadata - - def pre_get_context(self, request: context.GetContextRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[context.GetContextRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for get_context - - Override in a subclass to manipulate the request or metadata - before they are sent to the Contexts server. - """ - return request, metadata - - def post_get_context(self, response: context.Context) -> context.Context: - """Post-rpc interceptor for get_context - - Override in a subclass to manipulate the response - after it is returned by the Contexts server but before - it is returned to user code. - """ - return response - def pre_list_contexts(self, request: context.ListContextsRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[context.ListContextsRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for list_contexts - - Override in a subclass to manipulate the request or metadata - before they are sent to the Contexts server. - """ - return request, metadata - - def post_list_contexts(self, response: context.ListContextsResponse) -> context.ListContextsResponse: - """Post-rpc interceptor for list_contexts - - Override in a subclass to manipulate the response - after it is returned by the Contexts server but before - it is returned to user code. - """ - return response - def pre_update_context(self, request: gcd_context.UpdateContextRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[gcd_context.UpdateContextRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for update_context - - Override in a subclass to manipulate the request or metadata - before they are sent to the Contexts server. - """ - return request, metadata - - def post_update_context(self, response: gcd_context.Context) -> gcd_context.Context: - """Post-rpc interceptor for update_context - - Override in a subclass to manipulate the response - after it is returned by the Contexts server but before - it is returned to user code. - """ - return response - - def pre_get_location( - self, request: locations_pb2.GetLocationRequest, metadata: Sequence[Tuple[str, str]] - ) -> Tuple[locations_pb2.GetLocationRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for get_location - - Override in a subclass to manipulate the request or metadata - before they are sent to the Contexts server. - """ - return request, metadata - - def post_get_location( - self, response: locations_pb2.Location - ) -> locations_pb2.Location: - """Post-rpc interceptor for get_location - - Override in a subclass to manipulate the response - after it is returned by the Contexts server but before - it is returned to user code. - """ - return response - def pre_list_locations( - self, request: locations_pb2.ListLocationsRequest, metadata: Sequence[Tuple[str, str]] - ) -> Tuple[locations_pb2.ListLocationsRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for list_locations - - Override in a subclass to manipulate the request or metadata - before they are sent to the Contexts server. - """ - return request, metadata - - def post_list_locations( - self, response: locations_pb2.ListLocationsResponse - ) -> locations_pb2.ListLocationsResponse: - """Post-rpc interceptor for list_locations - - Override in a subclass to manipulate the response - after it is returned by the Contexts server but before - it is returned to user code. - """ - return response - def pre_cancel_operation( - self, request: operations_pb2.CancelOperationRequest, metadata: Sequence[Tuple[str, str]] - ) -> Tuple[operations_pb2.CancelOperationRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for cancel_operation - - Override in a subclass to manipulate the request or metadata - before they are sent to the Contexts server. - """ - return request, metadata - - def post_cancel_operation( - self, response: None - ) -> None: - """Post-rpc interceptor for cancel_operation - - Override in a subclass to manipulate the response - after it is returned by the Contexts server but before - it is returned to user code. - """ - return response - def pre_get_operation( - self, request: operations_pb2.GetOperationRequest, metadata: Sequence[Tuple[str, str]] - ) -> Tuple[operations_pb2.GetOperationRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for get_operation - - Override in a subclass to manipulate the request or metadata - before they are sent to the Contexts server. - """ - return request, metadata - - def post_get_operation( - self, response: operations_pb2.Operation - ) -> operations_pb2.Operation: - """Post-rpc interceptor for get_operation - - Override in a subclass to manipulate the response - after it is returned by the Contexts server but before - it is returned to user code. - """ - return response - def pre_list_operations( - self, request: operations_pb2.ListOperationsRequest, metadata: Sequence[Tuple[str, str]] - ) -> Tuple[operations_pb2.ListOperationsRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for list_operations - - Override in a subclass to manipulate the request or metadata - before they are sent to the Contexts server. - """ - return request, metadata - - def post_list_operations( - self, response: operations_pb2.ListOperationsResponse - ) -> operations_pb2.ListOperationsResponse: - """Post-rpc interceptor for list_operations - - Override in a subclass to manipulate the response - after it is returned by the Contexts server but before - it is returned to user code. - """ - return response - - -@dataclasses.dataclass -class ContextsRestStub: - _session: AuthorizedSession - _host: str - _interceptor: ContextsRestInterceptor - - -class ContextsRestTransport(ContextsTransport): - """REST backend transport for Contexts. - - Service for managing - [Contexts][google.cloud.dialogflow.v2beta1.Context]. - - 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 JSON representations of protocol buffers over HTTP/1.1 - - """ - - def __init__(self, *, - host: str = 'dialogflow.googleapis.com', - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - client_cert_source_for_mtls: Optional[Callable[[ - ], Tuple[bytes, bytes]]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - url_scheme: str = 'https', - interceptor: Optional[ContextsRestInterceptor] = None, - api_audience: Optional[str] = None, - ) -> 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 ignored if ``channel`` is provided. - scopes (Optional(Sequence[str])): A list of scopes. This argument is - ignored if ``channel`` is provided. - client_cert_source_for_mtls (Callable[[], Tuple[bytes, bytes]]): Client - certificate to configure mutual TLS HTTP channel. It is ignored - if ``channel`` is provided. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you are developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - url_scheme: the protocol scheme for the API endpoint. Normally - "https", but for testing or local servers, - "http" can be specified. - """ - # Run the base constructor - # TODO(yon-mg): resolve other ctor params i.e. scopes, quota, etc. - # TODO: When custom host (api_endpoint) is set, `scopes` must *also* be set on the - # credentials object - maybe_url_match = re.match("^(?Phttp(?:s)?://)?(?P.*)$", host) - if maybe_url_match is None: - raise ValueError(f"Unexpected hostname structure: {host}") # pragma: NO COVER - - url_match_items = maybe_url_match.groupdict() - - host = f"{url_scheme}://{host}" if not url_match_items["scheme"] else host - - super().__init__( - host=host, - credentials=credentials, - client_info=client_info, - always_use_jwt_access=always_use_jwt_access, - api_audience=api_audience - ) - self._session = AuthorizedSession( - self._credentials, default_host=self.DEFAULT_HOST) - if client_cert_source_for_mtls: - self._session.configure_mtls_channel(client_cert_source_for_mtls) - self._interceptor = interceptor or ContextsRestInterceptor() - self._prep_wrapped_messages(client_info) - - class _CreateContext(ContextsRestStub): - def __hash__(self): - return hash("CreateContext") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: gcd_context.CreateContextRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> gcd_context.Context: - r"""Call the create context method over HTTP. - - Args: - request (~.gcd_context.CreateContextRequest): - The request object. The request message for - [Contexts.CreateContext][google.cloud.dialogflow.v2beta1.Contexts.CreateContext]. - 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: - ~.gcd_context.Context: - Dialogflow contexts are similar to natural language - context. If a person says to you "they are orange", you - need context in order to understand what "they" is - referring to. Similarly, for Dialogflow to handle an - end-user expression like that, it needs to be provided - with context in order to correctly match an intent. - - Using contexts, you can control the flow of a - conversation. You can configure contexts for an intent - by setting input and output contexts, which are - identified by string names. When an intent is matched, - any configured output contexts for that intent become - active. While any contexts are active, Dialogflow is - more likely to match intents that are configured with - input contexts that correspond to the currently active - contexts. - - For more information about context, see the `Contexts - guide `__. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'post', - 'uri': '/v2beta1/{parent=projects/*/agent/sessions/*}/contexts', - 'body': 'context', - }, -{ - 'method': 'post', - 'uri': '/v2beta1/{parent=projects/*/agent/environments/*/users/*/sessions/*}/contexts', - 'body': 'context', - }, -{ - 'method': 'post', - 'uri': '/v2beta1/{parent=projects/*/locations/*/agent/sessions/*}/contexts', - 'body': 'context', - }, -{ - 'method': 'post', - 'uri': '/v2beta1/{parent=projects/*/locations/*/agent/environments/*/users/*/sessions/*}/contexts', - 'body': 'context', - }, - ] - request, metadata = self._interceptor.pre_create_context(request, metadata) - pb_request = gcd_context.CreateContextRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request['body'], - including_default_value_fields=False, - use_integers_for_enums=True - ) - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - including_default_value_fields=False, - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = gcd_context.Context() - pb_resp = gcd_context.Context.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_create_context(resp) - return resp - - class _DeleteAllContexts(ContextsRestStub): - def __hash__(self): - return hash("DeleteAllContexts") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: context.DeleteAllContextsRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ): - r"""Call the delete all contexts method over HTTP. - - Args: - request (~.context.DeleteAllContextsRequest): - The request object. The request message for - [Contexts.DeleteAllContexts][google.cloud.dialogflow.v2beta1.Contexts.DeleteAllContexts]. - 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. - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'delete', - 'uri': '/v2beta1/{parent=projects/*/agent/sessions/*}/contexts', - }, -{ - 'method': 'delete', - 'uri': '/v2beta1/{parent=projects/*/agent/environments/*/users/*/sessions/*}/contexts', - }, -{ - 'method': 'delete', - 'uri': '/v2beta1/{parent=projects/*/locations/*/agent/sessions/*}/contexts', - }, -{ - 'method': 'delete', - 'uri': '/v2beta1/{parent=projects/*/locations/*/agent/environments/*/users/*/sessions/*}/contexts', - }, - ] - request, metadata = self._interceptor.pre_delete_all_contexts(request, metadata) - pb_request = context.DeleteAllContextsRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - including_default_value_fields=False, - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - class _DeleteContext(ContextsRestStub): - def __hash__(self): - return hash("DeleteContext") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: context.DeleteContextRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ): - r"""Call the delete context method over HTTP. - - Args: - request (~.context.DeleteContextRequest): - The request object. The request message for - [Contexts.DeleteContext][google.cloud.dialogflow.v2beta1.Contexts.DeleteContext]. - 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. - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'delete', - 'uri': '/v2beta1/{name=projects/*/agent/sessions/*/contexts/*}', - }, -{ - 'method': 'delete', - 'uri': '/v2beta1/{name=projects/*/agent/environments/*/users/*/sessions/*/contexts/*}', - }, -{ - 'method': 'delete', - 'uri': '/v2beta1/{name=projects/*/locations/*/agent/sessions/*/contexts/*}', - }, -{ - 'method': 'delete', - 'uri': '/v2beta1/{name=projects/*/locations/*/agent/environments/*/users/*/sessions/*/contexts/*}', - }, - ] - request, metadata = self._interceptor.pre_delete_context(request, metadata) - pb_request = context.DeleteContextRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - including_default_value_fields=False, - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - class _GetContext(ContextsRestStub): - def __hash__(self): - return hash("GetContext") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: context.GetContextRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> context.Context: - r"""Call the get context method over HTTP. - - Args: - request (~.context.GetContextRequest): - The request object. The request message for - [Contexts.GetContext][google.cloud.dialogflow.v2beta1.Contexts.GetContext]. - 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: - ~.context.Context: - Dialogflow contexts are similar to natural language - context. If a person says to you "they are orange", you - need context in order to understand what "they" is - referring to. Similarly, for Dialogflow to handle an - end-user expression like that, it needs to be provided - with context in order to correctly match an intent. - - Using contexts, you can control the flow of a - conversation. You can configure contexts for an intent - by setting input and output contexts, which are - identified by string names. When an intent is matched, - any configured output contexts for that intent become - active. While any contexts are active, Dialogflow is - more likely to match intents that are configured with - input contexts that correspond to the currently active - contexts. - - For more information about context, see the `Contexts - guide `__. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v2beta1/{name=projects/*/agent/sessions/*/contexts/*}', - }, -{ - 'method': 'get', - 'uri': '/v2beta1/{name=projects/*/agent/environments/*/users/*/sessions/*/contexts/*}', - }, -{ - 'method': 'get', - 'uri': '/v2beta1/{name=projects/*/locations/*/agent/sessions/*/contexts/*}', - }, -{ - 'method': 'get', - 'uri': '/v2beta1/{name=projects/*/locations/*/agent/environments/*/users/*/sessions/*/contexts/*}', - }, - ] - request, metadata = self._interceptor.pre_get_context(request, metadata) - pb_request = context.GetContextRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - including_default_value_fields=False, - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = context.Context() - pb_resp = context.Context.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_get_context(resp) - return resp - - class _ListContexts(ContextsRestStub): - def __hash__(self): - return hash("ListContexts") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: context.ListContextsRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> context.ListContextsResponse: - r"""Call the list contexts method over HTTP. - - Args: - request (~.context.ListContextsRequest): - The request object. The request message for - [Contexts.ListContexts][google.cloud.dialogflow.v2beta1.Contexts.ListContexts]. - 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: - ~.context.ListContextsResponse: - The response message for - [Contexts.ListContexts][google.cloud.dialogflow.v2beta1.Contexts.ListContexts]. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v2beta1/{parent=projects/*/agent/sessions/*}/contexts', - }, -{ - 'method': 'get', - 'uri': '/v2beta1/{parent=projects/*/agent/environments/*/users/*/sessions/*}/contexts', - }, -{ - 'method': 'get', - 'uri': '/v2beta1/{parent=projects/*/locations/*/agent/sessions/*}/contexts', - }, -{ - 'method': 'get', - 'uri': '/v2beta1/{parent=projects/*/locations/*/agent/environments/*/users/*/sessions/*}/contexts', - }, - ] - request, metadata = self._interceptor.pre_list_contexts(request, metadata) - pb_request = context.ListContextsRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - including_default_value_fields=False, - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = context.ListContextsResponse() - pb_resp = context.ListContextsResponse.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_list_contexts(resp) - return resp - - class _UpdateContext(ContextsRestStub): - def __hash__(self): - return hash("UpdateContext") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: gcd_context.UpdateContextRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> gcd_context.Context: - r"""Call the update context method over HTTP. - - Args: - request (~.gcd_context.UpdateContextRequest): - The request object. The request message for - [Contexts.UpdateContext][google.cloud.dialogflow.v2beta1.Contexts.UpdateContext]. - 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: - ~.gcd_context.Context: - Dialogflow contexts are similar to natural language - context. If a person says to you "they are orange", you - need context in order to understand what "they" is - referring to. Similarly, for Dialogflow to handle an - end-user expression like that, it needs to be provided - with context in order to correctly match an intent. - - Using contexts, you can control the flow of a - conversation. You can configure contexts for an intent - by setting input and output contexts, which are - identified by string names. When an intent is matched, - any configured output contexts for that intent become - active. While any contexts are active, Dialogflow is - more likely to match intents that are configured with - input contexts that correspond to the currently active - contexts. - - For more information about context, see the `Contexts - guide `__. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'patch', - 'uri': '/v2beta1/{context.name=projects/*/agent/sessions/*/contexts/*}', - 'body': 'context', - }, -{ - 'method': 'patch', - 'uri': '/v2beta1/{context.name=projects/*/agent/environments/*/users/*/sessions/*/contexts/*}', - 'body': 'context', - }, -{ - 'method': 'patch', - 'uri': '/v2beta1/{context.name=projects/*/locations/*/agent/sessions/*/contexts/*}', - 'body': 'context', - }, -{ - 'method': 'patch', - 'uri': '/v2beta1/{context.name=projects/*/locations/*/agent/environments/*/users/*/sessions/*/contexts/*}', - 'body': 'context', - }, - ] - request, metadata = self._interceptor.pre_update_context(request, metadata) - pb_request = gcd_context.UpdateContextRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request['body'], - including_default_value_fields=False, - use_integers_for_enums=True - ) - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - including_default_value_fields=False, - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = gcd_context.Context() - pb_resp = gcd_context.Context.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_update_context(resp) - return resp - - @property - def create_context(self) -> Callable[ - [gcd_context.CreateContextRequest], - gcd_context.Context]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._CreateContext(self._session, self._host, self._interceptor) # type: ignore - - @property - def delete_all_contexts(self) -> Callable[ - [context.DeleteAllContextsRequest], - empty_pb2.Empty]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._DeleteAllContexts(self._session, self._host, self._interceptor) # type: ignore - - @property - def delete_context(self) -> Callable[ - [context.DeleteContextRequest], - empty_pb2.Empty]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._DeleteContext(self._session, self._host, self._interceptor) # type: ignore - - @property - def get_context(self) -> Callable[ - [context.GetContextRequest], - context.Context]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._GetContext(self._session, self._host, self._interceptor) # type: ignore - - @property - def list_contexts(self) -> Callable[ - [context.ListContextsRequest], - context.ListContextsResponse]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._ListContexts(self._session, self._host, self._interceptor) # type: ignore - - @property - def update_context(self) -> Callable[ - [gcd_context.UpdateContextRequest], - gcd_context.Context]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._UpdateContext(self._session, self._host, self._interceptor) # type: ignore - - @property - def get_location(self): - return self._GetLocation(self._session, self._host, self._interceptor) # type: ignore - - class _GetLocation(ContextsRestStub): - def __call__(self, - request: locations_pb2.GetLocationRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> locations_pb2.Location: - - r"""Call the get location method over HTTP. - - Args: - request (locations_pb2.GetLocationRequest): - The request object for GetLocation method. - 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: - locations_pb2.Location: Response from GetLocation method. - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v2beta1/{name=projects/*/locations/*}', - }, - ] - - request, metadata = self._interceptor.pre_get_location(request, metadata) - request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode( - http_options, **request_kwargs) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json.dumps(transcoded_request['query_params'])) - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - resp = locations_pb2.Location() - resp = json_format.Parse(response.content.decode("utf-8"), resp) - resp = self._interceptor.post_get_location(resp) - return resp - - @property - def list_locations(self): - return self._ListLocations(self._session, self._host, self._interceptor) # type: ignore - - class _ListLocations(ContextsRestStub): - def __call__(self, - request: locations_pb2.ListLocationsRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> locations_pb2.ListLocationsResponse: - - r"""Call the list locations method over HTTP. - - Args: - request (locations_pb2.ListLocationsRequest): - The request object for ListLocations method. - 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: - locations_pb2.ListLocationsResponse: Response from ListLocations method. - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v2beta1/{name=projects/*}/locations', - }, - ] - - request, metadata = self._interceptor.pre_list_locations(request, metadata) - request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode( - http_options, **request_kwargs) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json.dumps(transcoded_request['query_params'])) - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - resp = locations_pb2.ListLocationsResponse() - resp = json_format.Parse(response.content.decode("utf-8"), resp) - resp = self._interceptor.post_list_locations(resp) - return resp - - @property - def cancel_operation(self): - return self._CancelOperation(self._session, self._host, self._interceptor) # type: ignore - - class _CancelOperation(ContextsRestStub): - def __call__(self, - request: operations_pb2.CancelOperationRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> None: - - r"""Call the cancel operation method over HTTP. - - Args: - request (operations_pb2.CancelOperationRequest): - The request object for CancelOperation method. - 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. - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'post', - 'uri': '/v2beta1/{name=projects/*/operations/*}:cancel', - }, -{ - 'method': 'post', - 'uri': '/v2beta1/{name=projects/*/locations/*/operations/*}:cancel', - }, - ] - - request, metadata = self._interceptor.pre_cancel_operation(request, metadata) - request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode( - http_options, **request_kwargs) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json.dumps(transcoded_request['query_params'])) - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - return self._interceptor.post_cancel_operation(None) - - @property - def get_operation(self): - return self._GetOperation(self._session, self._host, self._interceptor) # type: ignore - - class _GetOperation(ContextsRestStub): - def __call__(self, - request: operations_pb2.GetOperationRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> operations_pb2.Operation: - - r"""Call the get operation method over HTTP. - - Args: - request (operations_pb2.GetOperationRequest): - The request object for GetOperation method. - 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: - operations_pb2.Operation: Response from GetOperation method. - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v2beta1/{name=projects/*/operations/*}', - }, -{ - 'method': 'get', - 'uri': '/v2beta1/{name=projects/*/locations/*/operations/*}', - }, - ] - - request, metadata = self._interceptor.pre_get_operation(request, metadata) - request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode( - http_options, **request_kwargs) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json.dumps(transcoded_request['query_params'])) - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - resp = operations_pb2.Operation() - resp = json_format.Parse(response.content.decode("utf-8"), resp) - resp = self._interceptor.post_get_operation(resp) - return resp - - @property - def list_operations(self): - return self._ListOperations(self._session, self._host, self._interceptor) # type: ignore - - class _ListOperations(ContextsRestStub): - def __call__(self, - request: operations_pb2.ListOperationsRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> operations_pb2.ListOperationsResponse: - - r"""Call the list operations method over HTTP. - - Args: - request (operations_pb2.ListOperationsRequest): - The request object for ListOperations method. - 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: - operations_pb2.ListOperationsResponse: Response from ListOperations method. - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v2beta1/{name=projects/*}/operations', - }, -{ - 'method': 'get', - 'uri': '/v2beta1/{name=projects/*/locations/*}/operations', - }, - ] - - request, metadata = self._interceptor.pre_list_operations(request, metadata) - request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode( - http_options, **request_kwargs) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json.dumps(transcoded_request['query_params'])) - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - resp = operations_pb2.ListOperationsResponse() - resp = json_format.Parse(response.content.decode("utf-8"), resp) - resp = self._interceptor.post_list_operations(resp) - return resp - - @property - def kind(self) -> str: - return "rest" - - def close(self): - self._session.close() - - -__all__=( - 'ContextsRestTransport', -) diff --git a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/conversation_profiles/__init__.py b/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/conversation_profiles/__init__.py deleted file mode 100644 index 2418fe346..000000000 --- a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/conversation_profiles/__init__.py +++ /dev/null @@ -1,22 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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 ConversationProfilesClient -from .async_client import ConversationProfilesAsyncClient - -__all__ = ( - 'ConversationProfilesClient', - 'ConversationProfilesAsyncClient', -) diff --git a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/conversation_profiles/async_client.py b/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/conversation_profiles/async_client.py deleted file mode 100644 index f458b1871..000000000 --- a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/conversation_profiles/async_client.py +++ /dev/null @@ -1,1337 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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, Mapping, MutableMapping, MutableSequence, Optional, Sequence, Tuple, Type, Union - -from google.cloud.dialogflow_v2beta1 import gapic_version as package_version - -from google.api_core.client_options import ClientOptions -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import retry as retries -from google.auth import credentials as ga_credentials # type: ignore -from google.oauth2 import service_account # type: ignore - -try: - OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] -except AttributeError: # pragma: NO COVER - OptionalRetry = Union[retries.Retry, object] # type: ignore - -from google.api_core import operation # type: ignore -from google.api_core import operation_async # type: ignore -from google.cloud.dialogflow_v2beta1.services.conversation_profiles import pagers -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 conversation_profile as gcd_conversation_profile -from google.cloud.dialogflow_v2beta1.types import participant -from google.cloud.location import locations_pb2 # type: ignore -from google.longrunning import operations_pb2 -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 - - -class ConversationProfilesAsyncClient: - """Service for managing - [ConversationProfiles][google.cloud.dialogflow.v2beta1.ConversationProfile]. - """ - - _client: ConversationProfilesClient - - DEFAULT_ENDPOINT = ConversationProfilesClient.DEFAULT_ENDPOINT - DEFAULT_MTLS_ENDPOINT = ConversationProfilesClient.DEFAULT_MTLS_ENDPOINT - - 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) - parse_conversation_profile_path = staticmethod(ConversationProfilesClient.parse_conversation_profile_path) - cx_security_settings_path = staticmethod(ConversationProfilesClient.cx_security_settings_path) - parse_cx_security_settings_path = staticmethod(ConversationProfilesClient.parse_cx_security_settings_path) - document_path = staticmethod(ConversationProfilesClient.document_path) - parse_document_path = staticmethod(ConversationProfilesClient.parse_document_path) - knowledge_base_path = staticmethod(ConversationProfilesClient.knowledge_base_path) - 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) - - @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: - ConversationProfilesAsyncClient: The constructed client. - """ - return ConversationProfilesClient.from_service_account_info.__func__(ConversationProfilesAsyncClient, 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: - ConversationProfilesAsyncClient: The constructed client. - """ - return ConversationProfilesClient.from_service_account_file.__func__(ConversationProfilesAsyncClient, filename, *args, **kwargs) # type: ignore - - from_service_account_json = from_service_account_file - - @classmethod - def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[ClientOptions] = None): - """Return the API endpoint and client cert source for mutual TLS. - - The client cert source is determined in the following order: - (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the - client cert source is None. - (2) if `client_options.client_cert_source` is provided, use the provided one; if the - default client cert source exists, use the default one; otherwise the client cert - source is None. - - The API endpoint is determined in the following order: - (1) if `client_options.api_endpoint` if provided, use the provided one. - (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the - default mTLS endpoint; if the environment variable is "never", use the default API - endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise - use the default API endpoint. - - More details can be found at https://google.aip.dev/auth/4114. - - Args: - client_options (google.api_core.client_options.ClientOptions): Custom options for the - client. Only the `api_endpoint` and `client_cert_source` properties may be used - in this method. - - Returns: - Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the - client cert source to use. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If any errors happen. - """ - return ConversationProfilesClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore - - @property - def transport(self) -> ConversationProfilesTransport: - """Returns the transport used by the client instance. - - Returns: - ConversationProfilesTransport: The transport used by the client instance. - """ - return self._client.transport - - get_transport_class = functools.partial(type(ConversationProfilesClient).get_transport_class, type(ConversationProfilesClient)) - - def __init__(self, *, - credentials: Optional[ga_credentials.Credentials] = None, - transport: Union[str, ConversationProfilesTransport] = "grpc_asyncio", - client_options: Optional[ClientOptions] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the conversation profiles 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, ~.ConversationProfilesTransport]): 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 = ConversationProfilesClient( - credentials=credentials, - transport=transport, - client_options=client_options, - client_info=client_info, - - ) - - async def list_conversation_profiles(self, - request: Optional[Union[conversation_profile.ListConversationProfilesRequest, dict]] = None, - *, - parent: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListConversationProfilesAsyncPager: - r"""Returns the list of all conversation profiles in the - specified project. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import dialogflow_v2beta1 - - async def sample_list_conversation_profiles(): - # Create a client - client = dialogflow_v2beta1.ConversationProfilesAsyncClient() - - # Initialize request argument(s) - request = dialogflow_v2beta1.ListConversationProfilesRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_conversation_profiles(request=request) - - # Handle the response - async for response in page_result: - print(response) - - Args: - request (Optional[Union[google.cloud.dialogflow_v2beta1.types.ListConversationProfilesRequest, dict]]): - The request object. The request message for - [ConversationProfiles.ListConversationProfiles][google.cloud.dialogflow.v2beta1.ConversationProfiles.ListConversationProfiles]. - parent (:class:`str`): - Required. The project to list all conversation profiles - from. Format: - ``projects//locations/``. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.dialogflow_v2beta1.services.conversation_profiles.pagers.ListConversationProfilesAsyncPager: - The response message for - [ConversationProfiles.ListConversationProfiles][google.cloud.dialogflow.v2beta1.ConversationProfiles.ListConversationProfiles]. - - Iterating over this object will yield results and - resolve additional pages automatically. - - """ - # Create or coerce a protobuf request object. - # Quick 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 = 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 - - # 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_conversation_profiles, - 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.ListConversationProfilesAsyncPager( - method=rpc, - request=request, - response=response, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def get_conversation_profile(self, - request: Optional[Union[conversation_profile.GetConversationProfileRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> conversation_profile.ConversationProfile: - r"""Retrieves the specified conversation profile. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import dialogflow_v2beta1 - - async def sample_get_conversation_profile(): - # Create a client - client = dialogflow_v2beta1.ConversationProfilesAsyncClient() - - # Initialize request argument(s) - request = dialogflow_v2beta1.GetConversationProfileRequest( - name="name_value", - ) - - # Make the request - response = await client.get_conversation_profile(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.dialogflow_v2beta1.types.GetConversationProfileRequest, dict]]): - The request object. The request message for - [ConversationProfiles.GetConversationProfile][google.cloud.dialogflow.v2beta1.ConversationProfiles.GetConversationProfile]. - name (:class:`str`): - Required. The resource name of the conversation profile. - Format: - ``projects//locations//conversationProfiles/``. - - 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.ConversationProfile: - Defines the services to connect to - incoming Dialogflow conversations. - - """ - # Create or coerce a protobuf request object. - # Quick 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 = 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 - - # 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_conversation_profile, - 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_conversation_profile(self, - request: Optional[Union[gcd_conversation_profile.CreateConversationProfileRequest, dict]] = None, - *, - parent: Optional[str] = None, - conversation_profile: Optional[gcd_conversation_profile.ConversationProfile] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gcd_conversation_profile.ConversationProfile: - r"""Creates a conversation profile in the specified project. - - [ConversationProfile.CreateTime][] and - [ConversationProfile.UpdateTime][] aren't populated in the - response. You can retrieve them via - [GetConversationProfile][google.cloud.dialogflow.v2beta1.ConversationProfiles.GetConversationProfile] - API. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import dialogflow_v2beta1 - - async def sample_create_conversation_profile(): - # Create a client - client = dialogflow_v2beta1.ConversationProfilesAsyncClient() - - # Initialize request argument(s) - conversation_profile = dialogflow_v2beta1.ConversationProfile() - conversation_profile.display_name = "display_name_value" - - request = dialogflow_v2beta1.CreateConversationProfileRequest( - parent="parent_value", - conversation_profile=conversation_profile, - ) - - # Make the request - response = await client.create_conversation_profile(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.dialogflow_v2beta1.types.CreateConversationProfileRequest, dict]]): - The request object. The request message for - [ConversationProfiles.CreateConversationProfile][google.cloud.dialogflow.v2beta1.ConversationProfiles.CreateConversationProfile]. - parent (:class:`str`): - Required. The project to create a conversation profile - for. Format: - ``projects//locations/``. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - conversation_profile (:class:`google.cloud.dialogflow_v2beta1.types.ConversationProfile`): - Required. The conversation profile to - create. - - 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. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.dialogflow_v2beta1.types.ConversationProfile: - Defines the services to connect to - incoming Dialogflow conversations. - - """ - # Create or coerce a protobuf request object. - # Quick 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, conversation_profile]) - 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_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: - request.conversation_profile = conversation_profile - - # 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_conversation_profile, - 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_conversation_profile(self, - request: Optional[Union[gcd_conversation_profile.UpdateConversationProfileRequest, dict]] = None, - *, - conversation_profile: Optional[gcd_conversation_profile.ConversationProfile] = None, - update_mask: Optional[field_mask_pb2.FieldMask] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gcd_conversation_profile.ConversationProfile: - r"""Updates the specified conversation profile. - - [ConversationProfile.CreateTime][] and - [ConversationProfile.UpdateTime][] aren't populated in the - response. You can retrieve them via - [GetConversationProfile][google.cloud.dialogflow.v2beta1.ConversationProfiles.GetConversationProfile] - API. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import dialogflow_v2beta1 - - async def sample_update_conversation_profile(): - # Create a client - client = dialogflow_v2beta1.ConversationProfilesAsyncClient() - - # Initialize request argument(s) - conversation_profile = dialogflow_v2beta1.ConversationProfile() - conversation_profile.display_name = "display_name_value" - - request = dialogflow_v2beta1.UpdateConversationProfileRequest( - conversation_profile=conversation_profile, - ) - - # Make the request - response = await client.update_conversation_profile(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.dialogflow_v2beta1.types.UpdateConversationProfileRequest, dict]]): - The request object. The request message for - [ConversationProfiles.UpdateConversationProfile][google.cloud.dialogflow.v2beta1.ConversationProfiles.UpdateConversationProfile]. - conversation_profile (:class:`google.cloud.dialogflow_v2beta1.types.ConversationProfile`): - Required. The conversation profile to - update. - - This corresponds to the ``conversation_profile`` 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 to update. - - 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.ConversationProfile: - Defines the services to connect to - incoming Dialogflow conversations. - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([conversation_profile, 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_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: - 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_conversation_profile, - 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(( - ("conversation_profile.name", request.conversation_profile.name), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def delete_conversation_profile(self, - request: Optional[Union[conversation_profile.DeleteConversationProfileRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> None: - r"""Deletes the specified conversation profile. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import dialogflow_v2beta1 - - async def sample_delete_conversation_profile(): - # Create a client - client = dialogflow_v2beta1.ConversationProfilesAsyncClient() - - # Initialize request argument(s) - request = dialogflow_v2beta1.DeleteConversationProfileRequest( - name="name_value", - ) - - # Make the request - await client.delete_conversation_profile(request=request) - - Args: - request (Optional[Union[google.cloud.dialogflow_v2beta1.types.DeleteConversationProfileRequest, dict]]): - The request object. The request message for - [ConversationProfiles.DeleteConversationProfile][google.cloud.dialogflow.v2beta1.ConversationProfiles.DeleteConversationProfile]. - - This operation fails if the conversation profile is - still referenced from a phone number. - name (:class:`str`): - Required. The name of the conversation profile to - delete. Format: - ``projects//locations//conversationProfiles/``. - - 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. - # Quick 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 = 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 - - # 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_conversation_profile, - 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 set_suggestion_feature_config(self, - request: Optional[Union[gcd_conversation_profile.SetSuggestionFeatureConfigRequest, dict]] = None, - *, - conversation_profile: Optional[str] = None, - participant_role: Optional[participant.Participant.Role] = None, - suggestion_feature_config: Optional[gcd_conversation_profile.HumanAgentAssistantConfig.SuggestionFeatureConfig] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation_async.AsyncOperation: - r"""Adds or updates a suggestion feature in a conversation profile. - If the conversation profile contains the type of suggestion - feature for the participant role, it will update it. Otherwise - it will insert the suggestion feature. - - This method is a `long-running - operation `__. - The returned ``Operation`` type has the following - method-specific fields: - - - ``metadata``: - [SetSuggestionFeatureConfigOperationMetadata][google.cloud.dialogflow.v2beta1.SetSuggestionFeatureConfigOperationMetadata] - - ``response``: - [ConversationProfile][google.cloud.dialogflow.v2beta1.ConversationProfile] - - If a long running operation to add or update suggestion feature - config for the same conversation profile, participant role and - suggestion feature type exists, please cancel the existing long - running operation before sending such request, otherwise the - request will be rejected. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import dialogflow_v2beta1 - - async def sample_set_suggestion_feature_config(): - # Create a client - client = dialogflow_v2beta1.ConversationProfilesAsyncClient() - - # Initialize request argument(s) - request = dialogflow_v2beta1.SetSuggestionFeatureConfigRequest( - conversation_profile="conversation_profile_value", - participant_role="END_USER", - ) - - # Make the request - operation = client.set_suggestion_feature_config(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.dialogflow_v2beta1.types.SetSuggestionFeatureConfigRequest, dict]]): - The request object. The request message for - [ConversationProfiles.SetSuggestionFeature][]. - conversation_profile (:class:`str`): - Required. The Conversation Profile to add or update the - suggestion feature config. Format: - ``projects//locations//conversationProfiles/``. - - This corresponds to the ``conversation_profile`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - participant_role (:class:`google.cloud.dialogflow_v2beta1.types.Participant.Role`): - Required. The participant role to add or update the - suggestion feature config. Only HUMAN_AGENT or END_USER - can be used. - - This corresponds to the ``participant_role`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - suggestion_feature_config (:class:`google.cloud.dialogflow_v2beta1.types.HumanAgentAssistantConfig.SuggestionFeatureConfig`): - Required. The suggestion feature - config to add or update. - - This corresponds to the ``suggestion_feature_config`` field - on the ``request`` instance; if ``request`` is provided, this - should not 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.api_core.operation_async.AsyncOperation: - An object representing a long-running operation. - - The result type for the operation will be - :class:`google.cloud.dialogflow_v2beta1.types.ConversationProfile` - Defines the services to connect to incoming Dialogflow - conversations. - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([conversation_profile, participant_role, suggestion_feature_config]) - 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_conversation_profile.SetSuggestionFeatureConfigRequest(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 participant_role is not None: - request.participant_role = participant_role - if suggestion_feature_config is not None: - request.suggestion_feature_config = suggestion_feature_config - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.set_suggestion_feature_config, - 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(( - ("conversation_profile", request.conversation_profile), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Wrap the response in an operation future. - response = operation_async.from_gapic( - response, - self._client._transport.operations_client, - gcd_conversation_profile.ConversationProfile, - metadata_type=gcd_conversation_profile.SetSuggestionFeatureConfigOperationMetadata, - ) - - # Done; return the response. - return response - - async def clear_suggestion_feature_config(self, - request: Optional[Union[gcd_conversation_profile.ClearSuggestionFeatureConfigRequest, dict]] = None, - *, - conversation_profile: Optional[str] = None, - participant_role: Optional[participant.Participant.Role] = None, - suggestion_feature_type: Optional[participant.SuggestionFeature.Type] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation_async.AsyncOperation: - r"""Clears a suggestion feature from a conversation profile for the - given participant role. - - This method is a `long-running - operation `__. - The returned ``Operation`` type has the following - method-specific fields: - - - ``metadata``: - [ClearSuggestionFeatureConfigOperationMetadata][google.cloud.dialogflow.v2beta1.ClearSuggestionFeatureConfigOperationMetadata] - - ``response``: - [ConversationProfile][google.cloud.dialogflow.v2beta1.ConversationProfile] - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import dialogflow_v2beta1 - - async def sample_clear_suggestion_feature_config(): - # Create a client - client = dialogflow_v2beta1.ConversationProfilesAsyncClient() - - # Initialize request argument(s) - request = dialogflow_v2beta1.ClearSuggestionFeatureConfigRequest( - conversation_profile="conversation_profile_value", - participant_role="END_USER", - suggestion_feature_type="CONVERSATION_SUMMARIZATION", - ) - - # Make the request - operation = client.clear_suggestion_feature_config(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.dialogflow_v2beta1.types.ClearSuggestionFeatureConfigRequest, dict]]): - The request object. The request message for - [ConversationProfiles.ClearFeature][]. - conversation_profile (:class:`str`): - Required. The Conversation Profile to add or update the - suggestion feature config. Format: - ``projects//locations//conversationProfiles/``. - - This corresponds to the ``conversation_profile`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - participant_role (:class:`google.cloud.dialogflow_v2beta1.types.Participant.Role`): - Required. The participant role to remove the suggestion - feature config. Only HUMAN_AGENT or END_USER can be - used. - - This corresponds to the ``participant_role`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - suggestion_feature_type (:class:`google.cloud.dialogflow_v2beta1.types.SuggestionFeature.Type`): - Required. The type of the suggestion - feature to remove. - - This corresponds to the ``suggestion_feature_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. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.api_core.operation_async.AsyncOperation: - An object representing a long-running operation. - - The result type for the operation will be - :class:`google.cloud.dialogflow_v2beta1.types.ConversationProfile` - Defines the services to connect to incoming Dialogflow - conversations. - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([conversation_profile, participant_role, suggestion_feature_type]) - 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_conversation_profile.ClearSuggestionFeatureConfigRequest(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 participant_role is not None: - request.participant_role = participant_role - if suggestion_feature_type is not None: - request.suggestion_feature_type = suggestion_feature_type - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.clear_suggestion_feature_config, - 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(( - ("conversation_profile", request.conversation_profile), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Wrap the response in an operation future. - response = operation_async.from_gapic( - response, - self._client._transport.operations_client, - gcd_conversation_profile.ConversationProfile, - metadata_type=gcd_conversation_profile.ClearSuggestionFeatureConfigOperationMetadata, - ) - - # Done; return the response. - return response - - async def list_operations( - self, - request: Optional[operations_pb2.ListOperationsRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operations_pb2.ListOperationsResponse: - r"""Lists operations that match the specified filter in the request. - - Args: - request (:class:`~.operations_pb2.ListOperationsRequest`): - The request object. Request message for - `ListOperations` method. - 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: - ~.operations_pb2.ListOperationsResponse: - Response message for ``ListOperations`` method. - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = operations_pb2.ListOperationsRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._client._transport.list_operations, - 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 get_operation( - self, - request: Optional[operations_pb2.GetOperationRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operations_pb2.Operation: - r"""Gets the latest state of a long-running operation. - - Args: - request (:class:`~.operations_pb2.GetOperationRequest`): - The request object. Request message for - `GetOperation` method. - 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: - ~.operations_pb2.Operation: - An ``Operation`` object. - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = operations_pb2.GetOperationRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._client._transport.get_operation, - 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 cancel_operation( - self, - request: Optional[operations_pb2.CancelOperationRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> None: - r"""Starts asynchronous cancellation on a long-running operation. - - The server makes a best effort to cancel the operation, but success - is not guaranteed. If the server doesn't support this method, it returns - `google.rpc.Code.UNIMPLEMENTED`. - - Args: - request (:class:`~.operations_pb2.CancelOperationRequest`): - The request object. Request message for - `CancelOperation` method. - 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: - None - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = operations_pb2.CancelOperationRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._client._transport.cancel_operation, - 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_location( - self, - request: Optional[locations_pb2.GetLocationRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> locations_pb2.Location: - r"""Gets information about a location. - - Args: - request (:class:`~.location_pb2.GetLocationRequest`): - The request object. Request message for - `GetLocation` method. - 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: - ~.location_pb2.Location: - Location object. - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = locations_pb2.GetLocationRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._client._transport.get_location, - 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 list_locations( - self, - request: Optional[locations_pb2.ListLocationsRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> locations_pb2.ListLocationsResponse: - r"""Lists information about the supported locations for this service. - - Args: - request (:class:`~.location_pb2.ListLocationsRequest`): - The request object. Request message for - `ListLocations` method. - 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: - ~.location_pb2.ListLocationsResponse: - Response message for ``ListLocations`` method. - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = locations_pb2.ListLocationsRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._client._transport.list_locations, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("name", request.name),)), - ) - - # Send the request. - response = await rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - async def __aenter__(self): - return self - - async def __aexit__(self, exc_type, exc, tb): - await self.transport.close() - -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) - - -__all__ = ( - "ConversationProfilesAsyncClient", -) diff --git a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/conversation_profiles/client.py b/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/conversation_profiles/client.py deleted file mode 100644 index c616fc3ab..000000000 --- a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/conversation_profiles/client.py +++ /dev/null @@ -1,1581 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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 os -import re -from typing import Dict, Mapping, MutableMapping, MutableSequence, Optional, Sequence, Tuple, Type, Union, cast - -from google.cloud.dialogflow_v2beta1 import gapic_version as package_version - -from google.api_core import client_options as client_options_lib -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import retry as retries -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 - -try: - OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] -except AttributeError: # pragma: NO COVER - OptionalRetry = Union[retries.Retry, object] # type: ignore - -from google.api_core import operation # type: ignore -from google.api_core import operation_async # type: ignore -from google.cloud.dialogflow_v2beta1.services.conversation_profiles import pagers -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 conversation_profile as gcd_conversation_profile -from google.cloud.dialogflow_v2beta1.types import participant -from google.cloud.location import locations_pb2 # type: ignore -from google.longrunning import operations_pb2 -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 -from .transports.rest import ConversationProfilesRestTransport - - -class ConversationProfilesClientMeta(type): - """Metaclass for the ConversationProfiles 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[ConversationProfilesTransport]] - _transport_registry["grpc"] = ConversationProfilesGrpcTransport - _transport_registry["grpc_asyncio"] = ConversationProfilesGrpcAsyncIOTransport - _transport_registry["rest"] = ConversationProfilesRestTransport - - def get_transport_class(cls, - label: Optional[str] = None, - ) -> Type[ConversationProfilesTransport]: - """Returns an appropriate transport class. - - Args: - label: The name of the desired transport. If none is - provided, then the first transport in the registry is used. - - Returns: - The transport class to use. - """ - # If a specific transport is requested, return that one. - if label: - return cls._transport_registry[label] - - # No transport is requested; return the default (that is, the first one - # in the dictionary). - return next(iter(cls._transport_registry.values())) - - -class ConversationProfilesClient(metaclass=ConversationProfilesClientMeta): - """Service for managing - [ConversationProfiles][google.cloud.dialogflow.v2beta1.ConversationProfile]. - """ - - @staticmethod - def _get_default_mtls_endpoint(api_endpoint): - """Converts api endpoint to mTLS endpoint. - - Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to - "*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively. - Args: - api_endpoint (Optional[str]): the api endpoint to convert. - Returns: - str: converted mTLS api endpoint. - """ - if not api_endpoint: - return api_endpoint - - mtls_endpoint_re = re.compile( - r"(?P[^.]+)(?P\.mtls)?(?P\.sandbox)?(?P\.googleapis\.com)?" - ) - - m = mtls_endpoint_re.match(api_endpoint) - name, mtls, sandbox, googledomain = m.groups() - if mtls or not googledomain: - return api_endpoint - - if sandbox: - return api_endpoint.replace( - "sandbox.googleapis.com", "mtls.sandbox.googleapis.com" - ) - - return api_endpoint.replace(".googleapis.com", ".mtls.googleapis.com") - - DEFAULT_ENDPOINT = "dialogflow.googleapis.com" - DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore - DEFAULT_ENDPOINT - ) - - @classmethod - def from_service_account_info(cls, info: dict, *args, **kwargs): - """Creates an instance of this client using the provided credentials - info. - - Args: - info (dict): The service account private key info. - args: Additional arguments to pass to the constructor. - kwargs: Additional arguments to pass to the constructor. - - Returns: - ConversationProfilesClient: 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: - ConversationProfilesClient: 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) -> ConversationProfilesTransport: - """Returns the transport used by the client instance. - - Returns: - ConversationProfilesTransport: The transport used by the client - instance. - """ - return self._transport - - @staticmethod - def agent_path(project: str,) -> str: - """Returns a fully-qualified agent string.""" - return "projects/{project}/agent".format(project=project, ) - - @staticmethod - def parse_agent_path(path: str) -> Dict[str,str]: - """Parses a agent path into its component segments.""" - 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: - """Returns 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]: - """Parses 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: - """Returns a fully-qualified conversation_profile string.""" - return "projects/{project}/conversationProfiles/{conversation_profile}".format(project=project, conversation_profile=conversation_profile, ) - - @staticmethod - def parse_conversation_profile_path(path: str) -> Dict[str,str]: - """Parses a conversation_profile path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/conversationProfiles/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def cx_security_settings_path(project: str,location: str,security_settings: str,) -> str: - """Returns a fully-qualified cx_security_settings string.""" - return "projects/{project}/locations/{location}/securitySettings/{security_settings}".format(project=project, location=location, security_settings=security_settings, ) - - @staticmethod - def parse_cx_security_settings_path(path: str) -> Dict[str,str]: - """Parses a cx_security_settings path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/securitySettings/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def document_path(project: str,knowledge_base: str,document: str,) -> str: - """Returns a fully-qualified document string.""" - return "projects/{project}/knowledgeBases/{knowledge_base}/documents/{document}".format(project=project, knowledge_base=knowledge_base, document=document, ) - - @staticmethod - def parse_document_path(path: str) -> Dict[str,str]: - """Parses a document path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/knowledgeBases/(?P.+?)/documents/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def knowledge_base_path(project: str,knowledge_base: str,) -> str: - """Returns a fully-qualified knowledge_base string.""" - return "projects/{project}/knowledgeBases/{knowledge_base}".format(project=project, knowledge_base=knowledge_base, ) - - @staticmethod - def parse_knowledge_base_path(path: str) -> Dict[str,str]: - """Parses a knowledge_base path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/knowledgeBases/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_billing_account_path(billing_account: str, ) -> str: - """Returns a fully-qualified billing_account string.""" - return "billingAccounts/{billing_account}".format(billing_account=billing_account, ) - - @staticmethod - def parse_common_billing_account_path(path: str) -> Dict[str,str]: - """Parse a billing_account path into its component segments.""" - m = re.match(r"^billingAccounts/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_folder_path(folder: str, ) -> str: - """Returns a fully-qualified folder string.""" - return "folders/{folder}".format(folder=folder, ) - - @staticmethod - def parse_common_folder_path(path: str) -> Dict[str,str]: - """Parse a folder path into its component segments.""" - m = re.match(r"^folders/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_organization_path(organization: str, ) -> str: - """Returns a fully-qualified organization string.""" - return "organizations/{organization}".format(organization=organization, ) - - @staticmethod - def parse_common_organization_path(path: str) -> Dict[str,str]: - """Parse a organization path into its component segments.""" - m = re.match(r"^organizations/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_project_path(project: str, ) -> str: - """Returns a fully-qualified project string.""" - return "projects/{project}".format(project=project, ) - - @staticmethod - def parse_common_project_path(path: str) -> Dict[str,str]: - """Parse a project path into its component segments.""" - m = re.match(r"^projects/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_location_path(project: str, location: str, ) -> str: - """Returns a fully-qualified location string.""" - return "projects/{project}/locations/{location}".format(project=project, location=location, ) - - @staticmethod - def parse_common_location_path(path: str) -> Dict[str,str]: - """Parse a location path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)$", path) - return m.groupdict() if m else {} - - @classmethod - def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[client_options_lib.ClientOptions] = None): - """Return the API endpoint and client cert source for mutual TLS. - - The client cert source is determined in the following order: - (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the - client cert source is None. - (2) if `client_options.client_cert_source` is provided, use the provided one; if the - default client cert source exists, use the default one; otherwise the client cert - source is None. - - The API endpoint is determined in the following order: - (1) if `client_options.api_endpoint` if provided, use the provided one. - (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the - default mTLS endpoint; if the environment variable is "never", use the default API - endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise - use the default API endpoint. - - More details can be found at https://google.aip.dev/auth/4114. - - Args: - client_options (google.api_core.client_options.ClientOptions): Custom options for the - client. Only the `api_endpoint` and `client_cert_source` properties may be used - in this method. - - Returns: - Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the - client cert source to use. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If any errors happen. - """ - if client_options is None: - client_options = client_options_lib.ClientOptions() - use_client_cert = os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false") - use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") - if use_client_cert not in ("true", "false"): - raise ValueError("Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`") - if use_mtls_endpoint not in ("auto", "never", "always"): - raise MutualTLSChannelError("Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`") - - # Figure out the client cert source to use. - client_cert_source = None - if use_client_cert == "true": - if client_options.client_cert_source: - client_cert_source = client_options.client_cert_source - elif mtls.has_default_client_cert_source(): - client_cert_source = mtls.default_client_cert_source() - - # Figure out which api endpoint to use. - if client_options.api_endpoint is not None: - api_endpoint = client_options.api_endpoint - elif use_mtls_endpoint == "always" or (use_mtls_endpoint == "auto" and client_cert_source): - api_endpoint = cls.DEFAULT_MTLS_ENDPOINT - else: - api_endpoint = cls.DEFAULT_ENDPOINT - - return api_endpoint, client_cert_source - - def __init__(self, *, - credentials: Optional[ga_credentials.Credentials] = None, - transport: Optional[Union[str, ConversationProfilesTransport]] = None, - client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the conversation profiles 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, ConversationProfilesTransport]): The - transport to use. If set to None, a transport is chosen - automatically. - client_options (Optional[Union[google.api_core.client_options.ClientOptions, dict]]): 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() - client_options = cast(client_options_lib.ClientOptions, client_options) - - api_endpoint, client_cert_source_func = self.get_mtls_endpoint_and_cert_source(client_options) - - api_key_value = getattr(client_options, "api_key", None) - if api_key_value and credentials: - raise ValueError("client_options.api_key and credentials are mutually exclusive") - - # 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, ConversationProfilesTransport): - # transport is a ConversationProfilesTransport instance. - if credentials or client_options.credentials_file or api_key_value: - 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: - import google.auth._default # type: ignore - - if api_key_value and hasattr(google.auth._default, "get_api_key_credentials"): - credentials = google.auth._default.get_api_key_credentials(api_key_value) - - Transport = type(self).get_transport_class(transport) - self._transport = Transport( - credentials=credentials, - credentials_file=client_options.credentials_file, - host=api_endpoint, - scopes=client_options.scopes, - client_cert_source_for_mtls=client_cert_source_func, - quota_project_id=client_options.quota_project_id, - client_info=client_info, - always_use_jwt_access=True, - api_audience=client_options.api_audience, - ) - - def list_conversation_profiles(self, - request: Optional[Union[conversation_profile.ListConversationProfilesRequest, dict]] = None, - *, - parent: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListConversationProfilesPager: - r"""Returns the list of all conversation profiles in the - specified project. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import dialogflow_v2beta1 - - def sample_list_conversation_profiles(): - # Create a client - client = dialogflow_v2beta1.ConversationProfilesClient() - - # Initialize request argument(s) - request = dialogflow_v2beta1.ListConversationProfilesRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_conversation_profiles(request=request) - - # Handle the response - for response in page_result: - print(response) - - Args: - request (Union[google.cloud.dialogflow_v2beta1.types.ListConversationProfilesRequest, dict]): - The request object. The request message for - [ConversationProfiles.ListConversationProfiles][google.cloud.dialogflow.v2beta1.ConversationProfiles.ListConversationProfiles]. - parent (str): - Required. The project to list all conversation profiles - from. Format: - ``projects//locations/``. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.dialogflow_v2beta1.services.conversation_profiles.pagers.ListConversationProfilesPager: - The response message for - [ConversationProfiles.ListConversationProfiles][google.cloud.dialogflow.v2beta1.ConversationProfiles.ListConversationProfiles]. - - Iterating over this object will yield results and - resolve additional pages automatically. - - """ - # Create or coerce a protobuf request object. - # Quick 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 conversation_profile.ListConversationProfilesRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(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 - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.list_conversation_profiles] - - # 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.ListConversationProfilesPager( - method=rpc, - request=request, - response=response, - metadata=metadata, - ) - - # Done; return the response. - return response - - def get_conversation_profile(self, - request: Optional[Union[conversation_profile.GetConversationProfileRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> conversation_profile.ConversationProfile: - r"""Retrieves the specified conversation profile. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import dialogflow_v2beta1 - - def sample_get_conversation_profile(): - # Create a client - client = dialogflow_v2beta1.ConversationProfilesClient() - - # Initialize request argument(s) - request = dialogflow_v2beta1.GetConversationProfileRequest( - name="name_value", - ) - - # Make the request - response = client.get_conversation_profile(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.dialogflow_v2beta1.types.GetConversationProfileRequest, dict]): - The request object. The request message for - [ConversationProfiles.GetConversationProfile][google.cloud.dialogflow.v2beta1.ConversationProfiles.GetConversationProfile]. - name (str): - Required. The resource name of the conversation profile. - Format: - ``projects//locations//conversationProfiles/``. - - 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.ConversationProfile: - Defines the services to connect to - incoming Dialogflow conversations. - - """ - # Create or coerce a protobuf request object. - # Quick 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 conversation_profile.GetConversationProfileRequest. - # There's no risk of modifying the input as we've already verified - # 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 - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.get_conversation_profile] - - # 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_conversation_profile(self, - request: Optional[Union[gcd_conversation_profile.CreateConversationProfileRequest, dict]] = None, - *, - parent: Optional[str] = None, - conversation_profile: Optional[gcd_conversation_profile.ConversationProfile] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gcd_conversation_profile.ConversationProfile: - r"""Creates a conversation profile in the specified project. - - [ConversationProfile.CreateTime][] and - [ConversationProfile.UpdateTime][] aren't populated in the - response. You can retrieve them via - [GetConversationProfile][google.cloud.dialogflow.v2beta1.ConversationProfiles.GetConversationProfile] - API. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import dialogflow_v2beta1 - - def sample_create_conversation_profile(): - # Create a client - client = dialogflow_v2beta1.ConversationProfilesClient() - - # Initialize request argument(s) - conversation_profile = dialogflow_v2beta1.ConversationProfile() - conversation_profile.display_name = "display_name_value" - - request = dialogflow_v2beta1.CreateConversationProfileRequest( - parent="parent_value", - conversation_profile=conversation_profile, - ) - - # Make the request - response = client.create_conversation_profile(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.dialogflow_v2beta1.types.CreateConversationProfileRequest, dict]): - The request object. The request message for - [ConversationProfiles.CreateConversationProfile][google.cloud.dialogflow.v2beta1.ConversationProfiles.CreateConversationProfile]. - parent (str): - Required. The project to create a conversation profile - for. Format: - ``projects//locations/``. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - conversation_profile (google.cloud.dialogflow_v2beta1.types.ConversationProfile): - Required. The conversation profile to - create. - - 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. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.dialogflow_v2beta1.types.ConversationProfile: - Defines the services to connect to - incoming Dialogflow conversations. - - """ - # Create or coerce a protobuf request object. - # Quick 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, conversation_profile]) - 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_conversation_profile.CreateConversationProfileRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(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: - request.conversation_profile = conversation_profile - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.create_conversation_profile] - - # 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_conversation_profile(self, - request: Optional[Union[gcd_conversation_profile.UpdateConversationProfileRequest, dict]] = None, - *, - conversation_profile: Optional[gcd_conversation_profile.ConversationProfile] = None, - update_mask: Optional[field_mask_pb2.FieldMask] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gcd_conversation_profile.ConversationProfile: - r"""Updates the specified conversation profile. - - [ConversationProfile.CreateTime][] and - [ConversationProfile.UpdateTime][] aren't populated in the - response. You can retrieve them via - [GetConversationProfile][google.cloud.dialogflow.v2beta1.ConversationProfiles.GetConversationProfile] - API. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import dialogflow_v2beta1 - - def sample_update_conversation_profile(): - # Create a client - client = dialogflow_v2beta1.ConversationProfilesClient() - - # Initialize request argument(s) - conversation_profile = dialogflow_v2beta1.ConversationProfile() - conversation_profile.display_name = "display_name_value" - - request = dialogflow_v2beta1.UpdateConversationProfileRequest( - conversation_profile=conversation_profile, - ) - - # Make the request - response = client.update_conversation_profile(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.dialogflow_v2beta1.types.UpdateConversationProfileRequest, dict]): - The request object. The request message for - [ConversationProfiles.UpdateConversationProfile][google.cloud.dialogflow.v2beta1.ConversationProfiles.UpdateConversationProfile]. - conversation_profile (google.cloud.dialogflow_v2beta1.types.ConversationProfile): - Required. The conversation profile to - update. - - This corresponds to the ``conversation_profile`` 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 to update. - - 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.ConversationProfile: - Defines the services to connect to - incoming Dialogflow conversations. - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([conversation_profile, 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_conversation_profile.UpdateConversationProfileRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(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: - 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_conversation_profile] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("conversation_profile.name", request.conversation_profile.name), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def delete_conversation_profile(self, - request: Optional[Union[conversation_profile.DeleteConversationProfileRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> None: - r"""Deletes the specified conversation profile. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import dialogflow_v2beta1 - - def sample_delete_conversation_profile(): - # Create a client - client = dialogflow_v2beta1.ConversationProfilesClient() - - # Initialize request argument(s) - request = dialogflow_v2beta1.DeleteConversationProfileRequest( - name="name_value", - ) - - # Make the request - client.delete_conversation_profile(request=request) - - Args: - request (Union[google.cloud.dialogflow_v2beta1.types.DeleteConversationProfileRequest, dict]): - The request object. The request message for - [ConversationProfiles.DeleteConversationProfile][google.cloud.dialogflow.v2beta1.ConversationProfiles.DeleteConversationProfile]. - - This operation fails if the conversation profile is - still referenced from a phone number. - name (str): - Required. The name of the conversation profile to - delete. Format: - ``projects//locations//conversationProfiles/``. - - 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. - # Quick 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 conversation_profile.DeleteConversationProfileRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(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 - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.delete_conversation_profile] - - # 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 set_suggestion_feature_config(self, - request: Optional[Union[gcd_conversation_profile.SetSuggestionFeatureConfigRequest, dict]] = None, - *, - conversation_profile: Optional[str] = None, - participant_role: Optional[participant.Participant.Role] = None, - suggestion_feature_config: Optional[gcd_conversation_profile.HumanAgentAssistantConfig.SuggestionFeatureConfig] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation.Operation: - r"""Adds or updates a suggestion feature in a conversation profile. - If the conversation profile contains the type of suggestion - feature for the participant role, it will update it. Otherwise - it will insert the suggestion feature. - - This method is a `long-running - operation `__. - The returned ``Operation`` type has the following - method-specific fields: - - - ``metadata``: - [SetSuggestionFeatureConfigOperationMetadata][google.cloud.dialogflow.v2beta1.SetSuggestionFeatureConfigOperationMetadata] - - ``response``: - [ConversationProfile][google.cloud.dialogflow.v2beta1.ConversationProfile] - - If a long running operation to add or update suggestion feature - config for the same conversation profile, participant role and - suggestion feature type exists, please cancel the existing long - running operation before sending such request, otherwise the - request will be rejected. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import dialogflow_v2beta1 - - def sample_set_suggestion_feature_config(): - # Create a client - client = dialogflow_v2beta1.ConversationProfilesClient() - - # Initialize request argument(s) - request = dialogflow_v2beta1.SetSuggestionFeatureConfigRequest( - conversation_profile="conversation_profile_value", - participant_role="END_USER", - ) - - # Make the request - operation = client.set_suggestion_feature_config(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.dialogflow_v2beta1.types.SetSuggestionFeatureConfigRequest, dict]): - The request object. The request message for - [ConversationProfiles.SetSuggestionFeature][]. - conversation_profile (str): - Required. The Conversation Profile to add or update the - suggestion feature config. Format: - ``projects//locations//conversationProfiles/``. - - This corresponds to the ``conversation_profile`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - participant_role (google.cloud.dialogflow_v2beta1.types.Participant.Role): - Required. The participant role to add or update the - suggestion feature config. Only HUMAN_AGENT or END_USER - can be used. - - This corresponds to the ``participant_role`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - suggestion_feature_config (google.cloud.dialogflow_v2beta1.types.HumanAgentAssistantConfig.SuggestionFeatureConfig): - Required. The suggestion feature - config to add or update. - - This corresponds to the ``suggestion_feature_config`` field - on the ``request`` instance; if ``request`` is provided, this - should not 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.api_core.operation.Operation: - An object representing a long-running operation. - - The result type for the operation will be - :class:`google.cloud.dialogflow_v2beta1.types.ConversationProfile` - Defines the services to connect to incoming Dialogflow - conversations. - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([conversation_profile, participant_role, suggestion_feature_config]) - 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_conversation_profile.SetSuggestionFeatureConfigRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, gcd_conversation_profile.SetSuggestionFeatureConfigRequest): - request = gcd_conversation_profile.SetSuggestionFeatureConfigRequest(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 participant_role is not None: - request.participant_role = participant_role - if suggestion_feature_config is not None: - request.suggestion_feature_config = suggestion_feature_config - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.set_suggestion_feature_config] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("conversation_profile", request.conversation_profile), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Wrap the response in an operation future. - response = operation.from_gapic( - response, - self._transport.operations_client, - gcd_conversation_profile.ConversationProfile, - metadata_type=gcd_conversation_profile.SetSuggestionFeatureConfigOperationMetadata, - ) - - # Done; return the response. - return response - - def clear_suggestion_feature_config(self, - request: Optional[Union[gcd_conversation_profile.ClearSuggestionFeatureConfigRequest, dict]] = None, - *, - conversation_profile: Optional[str] = None, - participant_role: Optional[participant.Participant.Role] = None, - suggestion_feature_type: Optional[participant.SuggestionFeature.Type] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation.Operation: - r"""Clears a suggestion feature from a conversation profile for the - given participant role. - - This method is a `long-running - operation `__. - The returned ``Operation`` type has the following - method-specific fields: - - - ``metadata``: - [ClearSuggestionFeatureConfigOperationMetadata][google.cloud.dialogflow.v2beta1.ClearSuggestionFeatureConfigOperationMetadata] - - ``response``: - [ConversationProfile][google.cloud.dialogflow.v2beta1.ConversationProfile] - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import dialogflow_v2beta1 - - def sample_clear_suggestion_feature_config(): - # Create a client - client = dialogflow_v2beta1.ConversationProfilesClient() - - # Initialize request argument(s) - request = dialogflow_v2beta1.ClearSuggestionFeatureConfigRequest( - conversation_profile="conversation_profile_value", - participant_role="END_USER", - suggestion_feature_type="CONVERSATION_SUMMARIZATION", - ) - - # Make the request - operation = client.clear_suggestion_feature_config(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.dialogflow_v2beta1.types.ClearSuggestionFeatureConfigRequest, dict]): - The request object. The request message for - [ConversationProfiles.ClearFeature][]. - conversation_profile (str): - Required. The Conversation Profile to add or update the - suggestion feature config. Format: - ``projects//locations//conversationProfiles/``. - - This corresponds to the ``conversation_profile`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - participant_role (google.cloud.dialogflow_v2beta1.types.Participant.Role): - Required. The participant role to remove the suggestion - feature config. Only HUMAN_AGENT or END_USER can be - used. - - This corresponds to the ``participant_role`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - suggestion_feature_type (google.cloud.dialogflow_v2beta1.types.SuggestionFeature.Type): - Required. The type of the suggestion - feature to remove. - - This corresponds to the ``suggestion_feature_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. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.api_core.operation.Operation: - An object representing a long-running operation. - - The result type for the operation will be - :class:`google.cloud.dialogflow_v2beta1.types.ConversationProfile` - Defines the services to connect to incoming Dialogflow - conversations. - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([conversation_profile, participant_role, suggestion_feature_type]) - 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_conversation_profile.ClearSuggestionFeatureConfigRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, gcd_conversation_profile.ClearSuggestionFeatureConfigRequest): - request = gcd_conversation_profile.ClearSuggestionFeatureConfigRequest(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 participant_role is not None: - request.participant_role = participant_role - if suggestion_feature_type is not None: - request.suggestion_feature_type = suggestion_feature_type - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.clear_suggestion_feature_config] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("conversation_profile", request.conversation_profile), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Wrap the response in an operation future. - response = operation.from_gapic( - response, - self._transport.operations_client, - gcd_conversation_profile.ConversationProfile, - metadata_type=gcd_conversation_profile.ClearSuggestionFeatureConfigOperationMetadata, - ) - - # Done; return the response. - return response - - def __enter__(self) -> "ConversationProfilesClient": - return self - - def __exit__(self, type, value, traceback): - """Releases underlying transport's resources. - - .. warning:: - ONLY use as a context manager if the transport is NOT shared - with other clients! Exiting the with block will CLOSE the transport - and may cause errors in other clients! - """ - self.transport.close() - - def list_operations( - self, - request: Optional[operations_pb2.ListOperationsRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operations_pb2.ListOperationsResponse: - r"""Lists operations that match the specified filter in the request. - - Args: - request (:class:`~.operations_pb2.ListOperationsRequest`): - The request object. Request message for - `ListOperations` method. - 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: - ~.operations_pb2.ListOperationsResponse: - Response message for ``ListOperations`` method. - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = operations_pb2.ListOperationsRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._transport.list_operations, - 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 = rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - def get_operation( - self, - request: Optional[operations_pb2.GetOperationRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operations_pb2.Operation: - r"""Gets the latest state of a long-running operation. - - Args: - request (:class:`~.operations_pb2.GetOperationRequest`): - The request object. Request message for - `GetOperation` method. - 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: - ~.operations_pb2.Operation: - An ``Operation`` object. - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = operations_pb2.GetOperationRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._transport.get_operation, - 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 = rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - def cancel_operation( - self, - request: Optional[operations_pb2.CancelOperationRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> None: - r"""Starts asynchronous cancellation on a long-running operation. - - The server makes a best effort to cancel the operation, but success - is not guaranteed. If the server doesn't support this method, it returns - `google.rpc.Code.UNIMPLEMENTED`. - - Args: - request (:class:`~.operations_pb2.CancelOperationRequest`): - The request object. Request message for - `CancelOperation` method. - 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: - None - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = operations_pb2.CancelOperationRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._transport.cancel_operation, - 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. - rpc(request, retry=retry, timeout=timeout, metadata=metadata,) - - def get_location( - self, - request: Optional[locations_pb2.GetLocationRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> locations_pb2.Location: - r"""Gets information about a location. - - Args: - request (:class:`~.location_pb2.GetLocationRequest`): - The request object. Request message for - `GetLocation` method. - 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: - ~.location_pb2.Location: - Location object. - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = locations_pb2.GetLocationRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._transport.get_location, - 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 = rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - def list_locations( - self, - request: Optional[locations_pb2.ListLocationsRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> locations_pb2.ListLocationsResponse: - r"""Lists information about the supported locations for this service. - - Args: - request (:class:`~.location_pb2.ListLocationsRequest`): - The request object. Request message for - `ListLocations` method. - 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: - ~.location_pb2.ListLocationsResponse: - Response message for ``ListLocations`` method. - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = locations_pb2.ListLocationsRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._transport.list_locations, - 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 = rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) - - -__all__ = ( - "ConversationProfilesClient", -) diff --git a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/conversation_profiles/pagers.py b/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/conversation_profiles/pagers.py deleted file mode 100644 index 9a51a4cdb..000000000 --- a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/conversation_profiles/pagers.py +++ /dev/null @@ -1,139 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from typing import Any, AsyncIterator, Awaitable, Callable, Sequence, Tuple, Optional, Iterator - -from google.cloud.dialogflow_v2beta1.types import conversation_profile - - -class ListConversationProfilesPager: - """A pager for iterating through ``list_conversation_profiles`` requests. - - This class thinly wraps an initial - :class:`google.cloud.dialogflow_v2beta1.types.ListConversationProfilesResponse` object, and - provides an ``__iter__`` method to iterate through its - ``conversation_profiles`` field. - - If there are more pages, the ``__iter__`` method will make additional - ``ListConversationProfiles`` requests and continue to iterate - through the ``conversation_profiles`` field on the - corresponding responses. - - All the usual :class:`google.cloud.dialogflow_v2beta1.types.ListConversationProfilesResponse` - 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[..., conversation_profile.ListConversationProfilesResponse], - request: conversation_profile.ListConversationProfilesRequest, - response: conversation_profile.ListConversationProfilesResponse, - *, - 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.ListConversationProfilesRequest): - The initial request object. - response (google.cloud.dialogflow_v2beta1.types.ListConversationProfilesResponse): - 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 = conversation_profile.ListConversationProfilesRequest(request) - self._response = response - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - def pages(self) -> Iterator[conversation_profile.ListConversationProfilesResponse]: - yield self._response - while self._response.next_page_token: - self._request.page_token = self._response.next_page_token - self._response = self._method(self._request, metadata=self._metadata) - yield self._response - - def __iter__(self) -> Iterator[conversation_profile.ConversationProfile]: - for page in self.pages: - yield from page.conversation_profiles - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListConversationProfilesAsyncPager: - """A pager for iterating through ``list_conversation_profiles`` requests. - - This class thinly wraps an initial - :class:`google.cloud.dialogflow_v2beta1.types.ListConversationProfilesResponse` object, and - provides an ``__aiter__`` method to iterate through its - ``conversation_profiles`` field. - - If there are more pages, the ``__aiter__`` method will make additional - ``ListConversationProfiles`` requests and continue to iterate - through the ``conversation_profiles`` field on the - corresponding responses. - - All the usual :class:`google.cloud.dialogflow_v2beta1.types.ListConversationProfilesResponse` - 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[conversation_profile.ListConversationProfilesResponse]], - request: conversation_profile.ListConversationProfilesRequest, - response: conversation_profile.ListConversationProfilesResponse, - *, - metadata: Sequence[Tuple[str, str]] = ()): - """Instantiates the pager. - - Args: - method (Callable): The method that was originally called, and - which instantiated this pager. - request (google.cloud.dialogflow_v2beta1.types.ListConversationProfilesRequest): - The initial request object. - response (google.cloud.dialogflow_v2beta1.types.ListConversationProfilesResponse): - 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 = conversation_profile.ListConversationProfilesRequest(request) - self._response = response - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - async def pages(self) -> AsyncIterator[conversation_profile.ListConversationProfilesResponse]: - yield self._response - while self._response.next_page_token: - self._request.page_token = self._response.next_page_token - self._response = await self._method(self._request, metadata=self._metadata) - yield self._response - def __aiter__(self) -> AsyncIterator[conversation_profile.ConversationProfile]: - async def async_generator(): - async for page in self.pages: - for response in page.conversation_profiles: - yield response - - return async_generator() - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) diff --git a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/conversation_profiles/transports/__init__.py b/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/conversation_profiles/transports/__init__.py deleted file mode 100644 index f328b6c64..000000000 --- a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/conversation_profiles/transports/__init__.py +++ /dev/null @@ -1,38 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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 ConversationProfilesTransport -from .grpc import ConversationProfilesGrpcTransport -from .grpc_asyncio import ConversationProfilesGrpcAsyncIOTransport -from .rest import ConversationProfilesRestTransport -from .rest import ConversationProfilesRestInterceptor - - -# Compile a registry of transports. -_transport_registry = OrderedDict() # type: Dict[str, Type[ConversationProfilesTransport]] -_transport_registry['grpc'] = ConversationProfilesGrpcTransport -_transport_registry['grpc_asyncio'] = ConversationProfilesGrpcAsyncIOTransport -_transport_registry['rest'] = ConversationProfilesRestTransport - -__all__ = ( - 'ConversationProfilesTransport', - 'ConversationProfilesGrpcTransport', - 'ConversationProfilesGrpcAsyncIOTransport', - 'ConversationProfilesRestTransport', - 'ConversationProfilesRestInterceptor', -) diff --git a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/conversation_profiles/transports/base.py b/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/conversation_profiles/transports/base.py deleted file mode 100644 index f5082a8c5..000000000 --- a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/conversation_profiles/transports/base.py +++ /dev/null @@ -1,287 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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 - -from google.cloud.dialogflow_v2beta1 import gapic_version as package_version - -import google.auth # type: ignore -import google.api_core -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import retry as retries -from google.api_core import operations_v1 -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 conversation_profile -from google.cloud.dialogflow_v2beta1.types import conversation_profile as gcd_conversation_profile -from google.cloud.location import locations_pb2 # type: ignore -from google.longrunning import operations_pb2 -from google.longrunning import operations_pb2 # type: ignore -from google.protobuf import empty_pb2 # type: ignore - -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) - - -class ConversationProfilesTransport(abc.ABC): - """Abstract transport class for ConversationProfiles.""" - - 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: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - api_audience: Optional[str] = None, - **kwargs, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. - scopes (Optional[Sequence[str]]): A list of scopes. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - """ - - scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} - - # Save the scopes. - self._scopes = scopes - - # If no credentials are provided, then determine the appropriate - # defaults. - if credentials and credentials_file: - raise core_exceptions.DuplicateCredentialArgs("'credentials_file' and 'credentials' are mutually exclusive") - - if credentials_file is not None: - credentials, _ = google.auth.load_credentials_from_file( - credentials_file, - **scopes_kwargs, - quota_project_id=quota_project_id - ) - elif credentials is None: - credentials, _ = google.auth.default(**scopes_kwargs, quota_project_id=quota_project_id) - # Don't apply audience if the credentials file passed from user. - if hasattr(credentials, "with_gdch_audience"): - credentials = credentials.with_gdch_audience(api_audience if api_audience else host) - - # If the credentials are service account credentials, then always try to use self signed JWT. - if always_use_jwt_access and isinstance(credentials, service_account.Credentials) and hasattr(service_account.Credentials, "with_always_use_jwt_access"): - credentials = credentials.with_always_use_jwt_access(True) - - # Save the credentials. - self._credentials = credentials - - # Save the hostname. Default to port 443 (HTTPS) if none is specified. - if ':' not in host: - host += ':443' - self._host = host - - def _prep_wrapped_messages(self, client_info): - # Precompute the wrapped methods. - self._wrapped_methods = { - self.list_conversation_profiles: gapic_v1.method.wrap_method( - self.list_conversation_profiles, - default_timeout=None, - client_info=client_info, - ), - self.get_conversation_profile: gapic_v1.method.wrap_method( - self.get_conversation_profile, - default_timeout=None, - client_info=client_info, - ), - self.create_conversation_profile: gapic_v1.method.wrap_method( - self.create_conversation_profile, - default_timeout=None, - client_info=client_info, - ), - self.update_conversation_profile: gapic_v1.method.wrap_method( - self.update_conversation_profile, - default_timeout=None, - client_info=client_info, - ), - self.delete_conversation_profile: gapic_v1.method.wrap_method( - self.delete_conversation_profile, - default_timeout=None, - client_info=client_info, - ), - self.set_suggestion_feature_config: gapic_v1.method.wrap_method( - self.set_suggestion_feature_config, - default_timeout=None, - client_info=client_info, - ), - self.clear_suggestion_feature_config: gapic_v1.method.wrap_method( - self.clear_suggestion_feature_config, - default_timeout=None, - client_info=client_info, - ), - } - - def close(self): - """Closes resources associated with the transport. - - .. warning:: - Only call this method if the transport is NOT shared - with other clients - this may cause errors in other clients! - """ - raise NotImplementedError() - - @property - def operations_client(self): - """Return the client designed to process long-running operations.""" - raise NotImplementedError() - - @property - def list_conversation_profiles(self) -> Callable[ - [conversation_profile.ListConversationProfilesRequest], - Union[ - conversation_profile.ListConversationProfilesResponse, - Awaitable[conversation_profile.ListConversationProfilesResponse] - ]]: - raise NotImplementedError() - - @property - def get_conversation_profile(self) -> Callable[ - [conversation_profile.GetConversationProfileRequest], - Union[ - conversation_profile.ConversationProfile, - Awaitable[conversation_profile.ConversationProfile] - ]]: - raise NotImplementedError() - - @property - def create_conversation_profile(self) -> Callable[ - [gcd_conversation_profile.CreateConversationProfileRequest], - Union[ - gcd_conversation_profile.ConversationProfile, - Awaitable[gcd_conversation_profile.ConversationProfile] - ]]: - raise NotImplementedError() - - @property - def update_conversation_profile(self) -> Callable[ - [gcd_conversation_profile.UpdateConversationProfileRequest], - Union[ - gcd_conversation_profile.ConversationProfile, - Awaitable[gcd_conversation_profile.ConversationProfile] - ]]: - raise NotImplementedError() - - @property - def delete_conversation_profile(self) -> Callable[ - [conversation_profile.DeleteConversationProfileRequest], - Union[ - empty_pb2.Empty, - Awaitable[empty_pb2.Empty] - ]]: - raise NotImplementedError() - - @property - def set_suggestion_feature_config(self) -> Callable[ - [gcd_conversation_profile.SetSuggestionFeatureConfigRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: - raise NotImplementedError() - - @property - def clear_suggestion_feature_config(self) -> Callable[ - [gcd_conversation_profile.ClearSuggestionFeatureConfigRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: - raise NotImplementedError() - - @property - def list_operations( - self, - ) -> Callable[ - [operations_pb2.ListOperationsRequest], - Union[operations_pb2.ListOperationsResponse, Awaitable[operations_pb2.ListOperationsResponse]], - ]: - raise NotImplementedError() - - @property - def get_operation( - self, - ) -> Callable[ - [operations_pb2.GetOperationRequest], - Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], - ]: - raise NotImplementedError() - - @property - def cancel_operation( - self, - ) -> Callable[ - [operations_pb2.CancelOperationRequest], - None, - ]: - raise NotImplementedError() - - @property - def get_location(self, - ) -> Callable[ - [locations_pb2.GetLocationRequest], - Union[locations_pb2.Location, Awaitable[locations_pb2.Location]], - ]: - raise NotImplementedError() - - @property - def list_locations(self, - ) -> Callable[ - [locations_pb2.ListLocationsRequest], - Union[locations_pb2.ListLocationsResponse, Awaitable[locations_pb2.ListLocationsResponse]], - ]: - raise NotImplementedError() - - @property - def kind(self) -> str: - raise NotImplementedError() - - -__all__ = ( - 'ConversationProfilesTransport', -) diff --git a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/conversation_profiles/transports/grpc.py b/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/conversation_profiles/transports/grpc.py deleted file mode 100644 index f1bd73c87..000000000 --- a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/conversation_profiles/transports/grpc.py +++ /dev/null @@ -1,578 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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 -from google.api_core import operations_v1 -from google.api_core import gapic_v1 -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_profile -from google.cloud.dialogflow_v2beta1.types import conversation_profile as gcd_conversation_profile -from google.cloud.location import locations_pb2 # type: ignore -from google.longrunning import operations_pb2 -from google.longrunning import operations_pb2 # type: ignore -from google.protobuf import empty_pb2 # type: ignore -from .base import ConversationProfilesTransport, DEFAULT_CLIENT_INFO - - -class ConversationProfilesGrpcTransport(ConversationProfilesTransport): - """gRPC backend transport for ConversationProfiles. - - Service for managing - [ConversationProfiles][google.cloud.dialogflow.v2beta1.ConversationProfile]. - - 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: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - channel: Optional[grpc.Channel] = None, - api_mtls_endpoint: Optional[str] = None, - client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, - ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, - client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - api_audience: Optional[str] = None, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - This argument is ignored if ``channel`` is provided. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional(Sequence[str])): A list of scopes. This argument is - ignored if ``channel`` is provided. - channel (Optional[grpc.Channel]): A ``Channel`` instance through - which to make calls. - api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. - If provided, it overrides the ``host`` argument and tries to create - a mutual TLS channel with client SSL credentials from - ``client_cert_source`` or application default SSL credentials. - client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): - Deprecated. A callback to provide client SSL certificate bytes and - private key bytes, both in PEM format. It is ignored if - ``api_mtls_endpoint`` is None. - ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials - for the grpc channel. It is ignored if ``channel`` is provided. - client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): - A callback to provide client certificate bytes and private key bytes, - both in PEM format. It is used to configure a mutual TLS channel. It is - ignored if ``channel`` or ``ssl_channel_credentials`` is provided. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport - creation failed for any reason. - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - self._grpc_channel = None - self._ssl_channel_credentials = ssl_channel_credentials - self._stubs: Dict[str, Callable] = {} - self._operations_client: Optional[operations_v1.OperationsClient] = None - - if api_mtls_endpoint: - warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) - if client_cert_source: - warnings.warn("client_cert_source is deprecated", DeprecationWarning) - - if channel: - # Ignore credentials if a channel was passed. - credentials = False - # If a channel was explicitly provided, set it. - self._grpc_channel = channel - self._ssl_channel_credentials = None - - else: - if api_mtls_endpoint: - host = api_mtls_endpoint - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - self._ssl_channel_credentials = SslCredentials().ssl_credentials - - else: - if client_cert_source_for_mtls and not ssl_channel_credentials: - cert, key = client_cert_source_for_mtls() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - - # The base transport sets the host, credentials and scopes - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes, - quota_project_id=quota_project_id, - client_info=client_info, - always_use_jwt_access=always_use_jwt_access, - api_audience=api_audience, - ) - - if not self._grpc_channel: - self._grpc_channel = type(self).create_channel( - self._host, - # use the credentials which are saved - credentials=self._credentials, - # Set ``credentials_file`` to ``None`` here as - # the credentials that we saved earlier should be used. - credentials_file=None, - 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: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - **kwargs) -> grpc.Channel: - """Create and return a gRPC channel object. - Args: - host (Optional[str]): The host for the channel to use. - credentials (Optional[~.Credentials]): The - authorization credentials to attach to requests. These - credentials identify this application to the service. If - none are specified, the client will attempt to ascertain - the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - kwargs (Optional[dict]): Keyword arguments, which are passed to the - channel creation. - Returns: - grpc.Channel: A gRPC channel object. - - Raises: - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - - return grpc_helpers.create_channel( - host, - credentials=credentials, - credentials_file=credentials_file, - quota_project_id=quota_project_id, - default_scopes=cls.AUTH_SCOPES, - scopes=scopes, - default_host=cls.DEFAULT_HOST, - **kwargs - ) - - @property - def grpc_channel(self) -> grpc.Channel: - """Return the channel designed to connect to this service. - """ - return self._grpc_channel - - @property - def operations_client(self) -> operations_v1.OperationsClient: - """Create the client designed to process long-running operations. - - This property caches on the instance; repeated calls return the same - client. - """ - # Quick check: Only create a new client if we do not already have one. - if self._operations_client is None: - self._operations_client = operations_v1.OperationsClient( - self.grpc_channel - ) - - # Return the client from cache. - return self._operations_client - - @property - def list_conversation_profiles(self) -> Callable[ - [conversation_profile.ListConversationProfilesRequest], - conversation_profile.ListConversationProfilesResponse]: - r"""Return a callable for the list conversation profiles method over gRPC. - - Returns the list of all conversation profiles in the - specified project. - - Returns: - Callable[[~.ListConversationProfilesRequest], - ~.ListConversationProfilesResponse]: - 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_conversation_profiles' not in self._stubs: - self._stubs['list_conversation_profiles'] = self.grpc_channel.unary_unary( - '/google.cloud.dialogflow.v2beta1.ConversationProfiles/ListConversationProfiles', - request_serializer=conversation_profile.ListConversationProfilesRequest.serialize, - response_deserializer=conversation_profile.ListConversationProfilesResponse.deserialize, - ) - return self._stubs['list_conversation_profiles'] - - @property - def get_conversation_profile(self) -> Callable[ - [conversation_profile.GetConversationProfileRequest], - conversation_profile.ConversationProfile]: - r"""Return a callable for the get conversation profile method over gRPC. - - Retrieves the specified conversation profile. - - Returns: - Callable[[~.GetConversationProfileRequest], - ~.ConversationProfile]: - 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_conversation_profile' not in self._stubs: - self._stubs['get_conversation_profile'] = self.grpc_channel.unary_unary( - '/google.cloud.dialogflow.v2beta1.ConversationProfiles/GetConversationProfile', - request_serializer=conversation_profile.GetConversationProfileRequest.serialize, - response_deserializer=conversation_profile.ConversationProfile.deserialize, - ) - return self._stubs['get_conversation_profile'] - - @property - def create_conversation_profile(self) -> Callable[ - [gcd_conversation_profile.CreateConversationProfileRequest], - gcd_conversation_profile.ConversationProfile]: - r"""Return a callable for the create conversation profile method over gRPC. - - Creates a conversation profile in the specified project. - - [ConversationProfile.CreateTime][] and - [ConversationProfile.UpdateTime][] aren't populated in the - response. You can retrieve them via - [GetConversationProfile][google.cloud.dialogflow.v2beta1.ConversationProfiles.GetConversationProfile] - API. - - Returns: - Callable[[~.CreateConversationProfileRequest], - ~.ConversationProfile]: - 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_conversation_profile' not in self._stubs: - self._stubs['create_conversation_profile'] = self.grpc_channel.unary_unary( - '/google.cloud.dialogflow.v2beta1.ConversationProfiles/CreateConversationProfile', - request_serializer=gcd_conversation_profile.CreateConversationProfileRequest.serialize, - response_deserializer=gcd_conversation_profile.ConversationProfile.deserialize, - ) - return self._stubs['create_conversation_profile'] - - @property - def update_conversation_profile(self) -> Callable[ - [gcd_conversation_profile.UpdateConversationProfileRequest], - gcd_conversation_profile.ConversationProfile]: - r"""Return a callable for the update conversation profile method over gRPC. - - Updates the specified conversation profile. - - [ConversationProfile.CreateTime][] and - [ConversationProfile.UpdateTime][] aren't populated in the - response. You can retrieve them via - [GetConversationProfile][google.cloud.dialogflow.v2beta1.ConversationProfiles.GetConversationProfile] - API. - - Returns: - Callable[[~.UpdateConversationProfileRequest], - ~.ConversationProfile]: - 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_conversation_profile' not in self._stubs: - self._stubs['update_conversation_profile'] = self.grpc_channel.unary_unary( - '/google.cloud.dialogflow.v2beta1.ConversationProfiles/UpdateConversationProfile', - request_serializer=gcd_conversation_profile.UpdateConversationProfileRequest.serialize, - response_deserializer=gcd_conversation_profile.ConversationProfile.deserialize, - ) - return self._stubs['update_conversation_profile'] - - @property - def delete_conversation_profile(self) -> Callable[ - [conversation_profile.DeleteConversationProfileRequest], - empty_pb2.Empty]: - r"""Return a callable for the delete conversation profile method over gRPC. - - Deletes the specified conversation profile. - - Returns: - Callable[[~.DeleteConversationProfileRequest], - ~.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_conversation_profile' not in self._stubs: - 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_pb2.Empty.FromString, - ) - return self._stubs['delete_conversation_profile'] - - @property - def set_suggestion_feature_config(self) -> Callable[ - [gcd_conversation_profile.SetSuggestionFeatureConfigRequest], - operations_pb2.Operation]: - r"""Return a callable for the set suggestion feature config method over gRPC. - - Adds or updates a suggestion feature in a conversation profile. - If the conversation profile contains the type of suggestion - feature for the participant role, it will update it. Otherwise - it will insert the suggestion feature. - - This method is a `long-running - operation `__. - The returned ``Operation`` type has the following - method-specific fields: - - - ``metadata``: - [SetSuggestionFeatureConfigOperationMetadata][google.cloud.dialogflow.v2beta1.SetSuggestionFeatureConfigOperationMetadata] - - ``response``: - [ConversationProfile][google.cloud.dialogflow.v2beta1.ConversationProfile] - - If a long running operation to add or update suggestion feature - config for the same conversation profile, participant role and - suggestion feature type exists, please cancel the existing long - running operation before sending such request, otherwise the - request will be rejected. - - Returns: - Callable[[~.SetSuggestionFeatureConfigRequest], - ~.Operation]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'set_suggestion_feature_config' not in self._stubs: - self._stubs['set_suggestion_feature_config'] = self.grpc_channel.unary_unary( - '/google.cloud.dialogflow.v2beta1.ConversationProfiles/SetSuggestionFeatureConfig', - request_serializer=gcd_conversation_profile.SetSuggestionFeatureConfigRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['set_suggestion_feature_config'] - - @property - def clear_suggestion_feature_config(self) -> Callable[ - [gcd_conversation_profile.ClearSuggestionFeatureConfigRequest], - operations_pb2.Operation]: - r"""Return a callable for the clear suggestion feature - config method over gRPC. - - Clears a suggestion feature from a conversation profile for the - given participant role. - - This method is a `long-running - operation `__. - The returned ``Operation`` type has the following - method-specific fields: - - - ``metadata``: - [ClearSuggestionFeatureConfigOperationMetadata][google.cloud.dialogflow.v2beta1.ClearSuggestionFeatureConfigOperationMetadata] - - ``response``: - [ConversationProfile][google.cloud.dialogflow.v2beta1.ConversationProfile] - - Returns: - Callable[[~.ClearSuggestionFeatureConfigRequest], - ~.Operation]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'clear_suggestion_feature_config' not in self._stubs: - self._stubs['clear_suggestion_feature_config'] = self.grpc_channel.unary_unary( - '/google.cloud.dialogflow.v2beta1.ConversationProfiles/ClearSuggestionFeatureConfig', - request_serializer=gcd_conversation_profile.ClearSuggestionFeatureConfigRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['clear_suggestion_feature_config'] - - def close(self): - self.grpc_channel.close() - - @property - def cancel_operation( - self, - ) -> Callable[[operations_pb2.CancelOperationRequest], None]: - r"""Return a callable for the cancel_operation method over gRPC. - """ - # 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 "cancel_operation" not in self._stubs: - self._stubs["cancel_operation"] = self.grpc_channel.unary_unary( - "/google.longrunning.Operations/CancelOperation", - request_serializer=operations_pb2.CancelOperationRequest.SerializeToString, - response_deserializer=None, - ) - return self._stubs["cancel_operation"] - - @property - def get_operation( - self, - ) -> Callable[[operations_pb2.GetOperationRequest], operations_pb2.Operation]: - r"""Return a callable for the get_operation method over gRPC. - """ - # 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_operation" not in self._stubs: - self._stubs["get_operation"] = self.grpc_channel.unary_unary( - "/google.longrunning.Operations/GetOperation", - request_serializer=operations_pb2.GetOperationRequest.SerializeToString, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs["get_operation"] - - @property - def list_operations( - self, - ) -> Callable[[operations_pb2.ListOperationsRequest], operations_pb2.ListOperationsResponse]: - r"""Return a callable for the list_operations method over gRPC. - """ - # 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_operations" not in self._stubs: - self._stubs["list_operations"] = self.grpc_channel.unary_unary( - "/google.longrunning.Operations/ListOperations", - request_serializer=operations_pb2.ListOperationsRequest.SerializeToString, - response_deserializer=operations_pb2.ListOperationsResponse.FromString, - ) - return self._stubs["list_operations"] - - @property - def list_locations( - self, - ) -> Callable[[locations_pb2.ListLocationsRequest], locations_pb2.ListLocationsResponse]: - r"""Return a callable for the list locations method over gRPC. - """ - # 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_locations" not in self._stubs: - self._stubs["list_locations"] = self.grpc_channel.unary_unary( - "/google.cloud.location.Locations/ListLocations", - request_serializer=locations_pb2.ListLocationsRequest.SerializeToString, - response_deserializer=locations_pb2.ListLocationsResponse.FromString, - ) - return self._stubs["list_locations"] - - @property - def get_location( - self, - ) -> Callable[[locations_pb2.GetLocationRequest], locations_pb2.Location]: - r"""Return a callable for the list locations method over gRPC. - """ - # 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_location" not in self._stubs: - self._stubs["get_location"] = self.grpc_channel.unary_unary( - "/google.cloud.location.Locations/GetLocation", - request_serializer=locations_pb2.GetLocationRequest.SerializeToString, - response_deserializer=locations_pb2.Location.FromString, - ) - return self._stubs["get_location"] - - @property - def kind(self) -> str: - return "grpc" - - -__all__ = ( - 'ConversationProfilesGrpcTransport', -) diff --git a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/conversation_profiles/transports/grpc_asyncio.py b/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/conversation_profiles/transports/grpc_asyncio.py deleted file mode 100644 index 70e5f94c2..000000000 --- a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/conversation_profiles/transports/grpc_asyncio.py +++ /dev/null @@ -1,577 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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 -from google.api_core import grpc_helpers_async -from google.api_core import operations_v1 -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore - -import grpc # type: ignore -from grpc.experimental import aio # type: ignore - -from google.cloud.dialogflow_v2beta1.types import conversation_profile -from google.cloud.dialogflow_v2beta1.types import conversation_profile as gcd_conversation_profile -from google.cloud.location import locations_pb2 # type: ignore -from google.longrunning import operations_pb2 -from google.longrunning import operations_pb2 # type: ignore -from google.protobuf import empty_pb2 # type: ignore -from .base import ConversationProfilesTransport, DEFAULT_CLIENT_INFO -from .grpc import ConversationProfilesGrpcTransport - - -class ConversationProfilesGrpcAsyncIOTransport(ConversationProfilesTransport): - """gRPC AsyncIO backend transport for ConversationProfiles. - - Service for managing - [ConversationProfiles][google.cloud.dialogflow.v2beta1.ConversationProfile]. - - 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: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - **kwargs) -> aio.Channel: - """Create and return a gRPC AsyncIO channel object. - Args: - host (Optional[str]): The host for the channel to use. - credentials (Optional[~.Credentials]): The - authorization credentials to attach to requests. These - credentials identify this application to the service. If - none are specified, the client will attempt to ascertain - the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - kwargs (Optional[dict]): Keyword arguments, which are passed to the - channel creation. - Returns: - aio.Channel: A gRPC AsyncIO channel object. - """ - - return grpc_helpers_async.create_channel( - host, - credentials=credentials, - credentials_file=credentials_file, - quota_project_id=quota_project_id, - default_scopes=cls.AUTH_SCOPES, - scopes=scopes, - default_host=cls.DEFAULT_HOST, - **kwargs - ) - - def __init__(self, *, - host: str = 'dialogflow.googleapis.com', - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - channel: Optional[aio.Channel] = None, - api_mtls_endpoint: Optional[str] = None, - client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, - ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, - client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - api_audience: Optional[str] = None, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - This argument is ignored if ``channel`` is provided. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - channel (Optional[aio.Channel]): A ``Channel`` instance through - which to make calls. - api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. - If provided, it overrides the ``host`` argument and tries to create - a mutual TLS channel with client SSL credentials from - ``client_cert_source`` or application default SSL credentials. - client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): - Deprecated. A callback to provide client SSL certificate bytes and - private key bytes, both in PEM format. It is ignored if - ``api_mtls_endpoint`` is None. - ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials - for the grpc channel. It is ignored if ``channel`` is provided. - client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): - A callback to provide client certificate bytes and private key bytes, - both in PEM format. It is used to configure a mutual TLS channel. It is - ignored if ``channel`` or ``ssl_channel_credentials`` is provided. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - - Raises: - google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport - creation failed for any reason. - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - self._grpc_channel = None - self._ssl_channel_credentials = ssl_channel_credentials - self._stubs: Dict[str, Callable] = {} - self._operations_client: Optional[operations_v1.OperationsAsyncClient] = None - - if api_mtls_endpoint: - warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) - if client_cert_source: - warnings.warn("client_cert_source is deprecated", DeprecationWarning) - - if channel: - # Ignore credentials if a channel was passed. - credentials = False - # If a channel was explicitly provided, set it. - self._grpc_channel = channel - self._ssl_channel_credentials = None - else: - if api_mtls_endpoint: - host = api_mtls_endpoint - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - self._ssl_channel_credentials = SslCredentials().ssl_credentials - - else: - if client_cert_source_for_mtls and not ssl_channel_credentials: - cert, key = client_cert_source_for_mtls() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - - # The base transport sets the host, credentials and scopes - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes, - quota_project_id=quota_project_id, - client_info=client_info, - always_use_jwt_access=always_use_jwt_access, - api_audience=api_audience, - ) - - if not self._grpc_channel: - self._grpc_channel = type(self).create_channel( - self._host, - # use the credentials which are saved - credentials=self._credentials, - # Set ``credentials_file`` to ``None`` here as - # the credentials that we saved earlier should be used. - credentials_file=None, - 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 operations_client(self) -> operations_v1.OperationsAsyncClient: - """Create the client designed to process long-running operations. - - This property caches on the instance; repeated calls return the same - client. - """ - # Quick check: Only create a new client if we do not already have one. - if self._operations_client is None: - self._operations_client = operations_v1.OperationsAsyncClient( - self.grpc_channel - ) - - # Return the client from cache. - return self._operations_client - - @property - def list_conversation_profiles(self) -> Callable[ - [conversation_profile.ListConversationProfilesRequest], - Awaitable[conversation_profile.ListConversationProfilesResponse]]: - r"""Return a callable for the list conversation profiles method over gRPC. - - Returns the list of all conversation profiles in the - specified project. - - Returns: - Callable[[~.ListConversationProfilesRequest], - Awaitable[~.ListConversationProfilesResponse]]: - 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_conversation_profiles' not in self._stubs: - self._stubs['list_conversation_profiles'] = self.grpc_channel.unary_unary( - '/google.cloud.dialogflow.v2beta1.ConversationProfiles/ListConversationProfiles', - request_serializer=conversation_profile.ListConversationProfilesRequest.serialize, - response_deserializer=conversation_profile.ListConversationProfilesResponse.deserialize, - ) - return self._stubs['list_conversation_profiles'] - - @property - def get_conversation_profile(self) -> Callable[ - [conversation_profile.GetConversationProfileRequest], - Awaitable[conversation_profile.ConversationProfile]]: - r"""Return a callable for the get conversation profile method over gRPC. - - Retrieves the specified conversation profile. - - Returns: - Callable[[~.GetConversationProfileRequest], - Awaitable[~.ConversationProfile]]: - 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_conversation_profile' not in self._stubs: - self._stubs['get_conversation_profile'] = self.grpc_channel.unary_unary( - '/google.cloud.dialogflow.v2beta1.ConversationProfiles/GetConversationProfile', - request_serializer=conversation_profile.GetConversationProfileRequest.serialize, - response_deserializer=conversation_profile.ConversationProfile.deserialize, - ) - return self._stubs['get_conversation_profile'] - - @property - def create_conversation_profile(self) -> Callable[ - [gcd_conversation_profile.CreateConversationProfileRequest], - Awaitable[gcd_conversation_profile.ConversationProfile]]: - r"""Return a callable for the create conversation profile method over gRPC. - - Creates a conversation profile in the specified project. - - [ConversationProfile.CreateTime][] and - [ConversationProfile.UpdateTime][] aren't populated in the - response. You can retrieve them via - [GetConversationProfile][google.cloud.dialogflow.v2beta1.ConversationProfiles.GetConversationProfile] - API. - - Returns: - Callable[[~.CreateConversationProfileRequest], - Awaitable[~.ConversationProfile]]: - 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_conversation_profile' not in self._stubs: - self._stubs['create_conversation_profile'] = self.grpc_channel.unary_unary( - '/google.cloud.dialogflow.v2beta1.ConversationProfiles/CreateConversationProfile', - request_serializer=gcd_conversation_profile.CreateConversationProfileRequest.serialize, - response_deserializer=gcd_conversation_profile.ConversationProfile.deserialize, - ) - return self._stubs['create_conversation_profile'] - - @property - def update_conversation_profile(self) -> Callable[ - [gcd_conversation_profile.UpdateConversationProfileRequest], - Awaitable[gcd_conversation_profile.ConversationProfile]]: - r"""Return a callable for the update conversation profile method over gRPC. - - Updates the specified conversation profile. - - [ConversationProfile.CreateTime][] and - [ConversationProfile.UpdateTime][] aren't populated in the - response. You can retrieve them via - [GetConversationProfile][google.cloud.dialogflow.v2beta1.ConversationProfiles.GetConversationProfile] - API. - - Returns: - Callable[[~.UpdateConversationProfileRequest], - Awaitable[~.ConversationProfile]]: - 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_conversation_profile' not in self._stubs: - self._stubs['update_conversation_profile'] = self.grpc_channel.unary_unary( - '/google.cloud.dialogflow.v2beta1.ConversationProfiles/UpdateConversationProfile', - request_serializer=gcd_conversation_profile.UpdateConversationProfileRequest.serialize, - response_deserializer=gcd_conversation_profile.ConversationProfile.deserialize, - ) - return self._stubs['update_conversation_profile'] - - @property - def delete_conversation_profile(self) -> Callable[ - [conversation_profile.DeleteConversationProfileRequest], - Awaitable[empty_pb2.Empty]]: - r"""Return a callable for the delete conversation profile method over gRPC. - - Deletes the specified conversation profile. - - Returns: - Callable[[~.DeleteConversationProfileRequest], - 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_conversation_profile' not in self._stubs: - 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_pb2.Empty.FromString, - ) - return self._stubs['delete_conversation_profile'] - - @property - def set_suggestion_feature_config(self) -> Callable[ - [gcd_conversation_profile.SetSuggestionFeatureConfigRequest], - Awaitable[operations_pb2.Operation]]: - r"""Return a callable for the set suggestion feature config method over gRPC. - - Adds or updates a suggestion feature in a conversation profile. - If the conversation profile contains the type of suggestion - feature for the participant role, it will update it. Otherwise - it will insert the suggestion feature. - - This method is a `long-running - operation `__. - The returned ``Operation`` type has the following - method-specific fields: - - - ``metadata``: - [SetSuggestionFeatureConfigOperationMetadata][google.cloud.dialogflow.v2beta1.SetSuggestionFeatureConfigOperationMetadata] - - ``response``: - [ConversationProfile][google.cloud.dialogflow.v2beta1.ConversationProfile] - - If a long running operation to add or update suggestion feature - config for the same conversation profile, participant role and - suggestion feature type exists, please cancel the existing long - running operation before sending such request, otherwise the - request will be rejected. - - Returns: - Callable[[~.SetSuggestionFeatureConfigRequest], - Awaitable[~.Operation]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'set_suggestion_feature_config' not in self._stubs: - self._stubs['set_suggestion_feature_config'] = self.grpc_channel.unary_unary( - '/google.cloud.dialogflow.v2beta1.ConversationProfiles/SetSuggestionFeatureConfig', - request_serializer=gcd_conversation_profile.SetSuggestionFeatureConfigRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['set_suggestion_feature_config'] - - @property - def clear_suggestion_feature_config(self) -> Callable[ - [gcd_conversation_profile.ClearSuggestionFeatureConfigRequest], - Awaitable[operations_pb2.Operation]]: - r"""Return a callable for the clear suggestion feature - config method over gRPC. - - Clears a suggestion feature from a conversation profile for the - given participant role. - - This method is a `long-running - operation `__. - The returned ``Operation`` type has the following - method-specific fields: - - - ``metadata``: - [ClearSuggestionFeatureConfigOperationMetadata][google.cloud.dialogflow.v2beta1.ClearSuggestionFeatureConfigOperationMetadata] - - ``response``: - [ConversationProfile][google.cloud.dialogflow.v2beta1.ConversationProfile] - - Returns: - Callable[[~.ClearSuggestionFeatureConfigRequest], - Awaitable[~.Operation]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'clear_suggestion_feature_config' not in self._stubs: - self._stubs['clear_suggestion_feature_config'] = self.grpc_channel.unary_unary( - '/google.cloud.dialogflow.v2beta1.ConversationProfiles/ClearSuggestionFeatureConfig', - request_serializer=gcd_conversation_profile.ClearSuggestionFeatureConfigRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['clear_suggestion_feature_config'] - - def close(self): - return self.grpc_channel.close() - - @property - def cancel_operation( - self, - ) -> Callable[[operations_pb2.CancelOperationRequest], None]: - r"""Return a callable for the cancel_operation method over gRPC. - """ - # 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 "cancel_operation" not in self._stubs: - self._stubs["cancel_operation"] = self.grpc_channel.unary_unary( - "/google.longrunning.Operations/CancelOperation", - request_serializer=operations_pb2.CancelOperationRequest.SerializeToString, - response_deserializer=None, - ) - return self._stubs["cancel_operation"] - - @property - def get_operation( - self, - ) -> Callable[[operations_pb2.GetOperationRequest], operations_pb2.Operation]: - r"""Return a callable for the get_operation method over gRPC. - """ - # 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_operation" not in self._stubs: - self._stubs["get_operation"] = self.grpc_channel.unary_unary( - "/google.longrunning.Operations/GetOperation", - request_serializer=operations_pb2.GetOperationRequest.SerializeToString, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs["get_operation"] - - @property - def list_operations( - self, - ) -> Callable[[operations_pb2.ListOperationsRequest], operations_pb2.ListOperationsResponse]: - r"""Return a callable for the list_operations method over gRPC. - """ - # 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_operations" not in self._stubs: - self._stubs["list_operations"] = self.grpc_channel.unary_unary( - "/google.longrunning.Operations/ListOperations", - request_serializer=operations_pb2.ListOperationsRequest.SerializeToString, - response_deserializer=operations_pb2.ListOperationsResponse.FromString, - ) - return self._stubs["list_operations"] - - @property - def list_locations( - self, - ) -> Callable[[locations_pb2.ListLocationsRequest], locations_pb2.ListLocationsResponse]: - r"""Return a callable for the list locations method over gRPC. - """ - # 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_locations" not in self._stubs: - self._stubs["list_locations"] = self.grpc_channel.unary_unary( - "/google.cloud.location.Locations/ListLocations", - request_serializer=locations_pb2.ListLocationsRequest.SerializeToString, - response_deserializer=locations_pb2.ListLocationsResponse.FromString, - ) - return self._stubs["list_locations"] - - @property - def get_location( - self, - ) -> Callable[[locations_pb2.GetLocationRequest], locations_pb2.Location]: - r"""Return a callable for the list locations method over gRPC. - """ - # 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_location" not in self._stubs: - self._stubs["get_location"] = self.grpc_channel.unary_unary( - "/google.cloud.location.Locations/GetLocation", - request_serializer=locations_pb2.GetLocationRequest.SerializeToString, - response_deserializer=locations_pb2.Location.FromString, - ) - return self._stubs["get_location"] - - -__all__ = ( - 'ConversationProfilesGrpcAsyncIOTransport', -) diff --git a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/conversation_profiles/transports/rest.py b/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/conversation_profiles/transports/rest.py deleted file mode 100644 index 474fdea72..000000000 --- a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/conversation_profiles/transports/rest.py +++ /dev/null @@ -1,1513 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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 google.auth.transport.requests import AuthorizedSession # type: ignore -import json # type: ignore -import grpc # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore -from google.auth import credentials as ga_credentials # type: ignore -from google.api_core import exceptions as core_exceptions -from google.api_core import retry as retries -from google.api_core import rest_helpers -from google.api_core import rest_streaming -from google.api_core import path_template -from google.api_core import gapic_v1 - -from google.protobuf import json_format -from google.api_core import operations_v1 -from google.cloud.location import locations_pb2 # type: ignore -from google.longrunning import operations_pb2 -from requests import __version__ as requests_version -import dataclasses -import re -from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union -import warnings - -try: - OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] -except AttributeError: # pragma: NO COVER - OptionalRetry = Union[retries.Retry, object] # 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.longrunning import operations_pb2 # type: ignore -from google.protobuf import empty_pb2 # type: ignore - -from .base import ConversationProfilesTransport, DEFAULT_CLIENT_INFO as BASE_DEFAULT_CLIENT_INFO - - -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=BASE_DEFAULT_CLIENT_INFO.gapic_version, - grpc_version=None, - rest_version=requests_version, -) - - -class ConversationProfilesRestInterceptor: - """Interceptor for ConversationProfiles. - - Interceptors are used to manipulate requests, request metadata, and responses - in arbitrary ways. - Example use cases include: - * Logging - * Verifying requests according to service or custom semantics - * Stripping extraneous information from responses - - These use cases and more can be enabled by injecting an - instance of a custom subclass when constructing the ConversationProfilesRestTransport. - - .. code-block:: python - class MyCustomConversationProfilesInterceptor(ConversationProfilesRestInterceptor): - def pre_clear_suggestion_feature_config(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_clear_suggestion_feature_config(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_create_conversation_profile(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_create_conversation_profile(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_delete_conversation_profile(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def pre_get_conversation_profile(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_get_conversation_profile(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_list_conversation_profiles(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_list_conversation_profiles(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_set_suggestion_feature_config(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_set_suggestion_feature_config(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_update_conversation_profile(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_update_conversation_profile(self, response): - logging.log(f"Received response: {response}") - return response - - transport = ConversationProfilesRestTransport(interceptor=MyCustomConversationProfilesInterceptor()) - client = ConversationProfilesClient(transport=transport) - - - """ - def pre_clear_suggestion_feature_config(self, request: gcd_conversation_profile.ClearSuggestionFeatureConfigRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[gcd_conversation_profile.ClearSuggestionFeatureConfigRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for clear_suggestion_feature_config - - Override in a subclass to manipulate the request or metadata - before they are sent to the ConversationProfiles server. - """ - return request, metadata - - def post_clear_suggestion_feature_config(self, response: operations_pb2.Operation) -> operations_pb2.Operation: - """Post-rpc interceptor for clear_suggestion_feature_config - - Override in a subclass to manipulate the response - after it is returned by the ConversationProfiles server but before - it is returned to user code. - """ - return response - def pre_create_conversation_profile(self, request: gcd_conversation_profile.CreateConversationProfileRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[gcd_conversation_profile.CreateConversationProfileRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for create_conversation_profile - - Override in a subclass to manipulate the request or metadata - before they are sent to the ConversationProfiles server. - """ - return request, metadata - - def post_create_conversation_profile(self, response: gcd_conversation_profile.ConversationProfile) -> gcd_conversation_profile.ConversationProfile: - """Post-rpc interceptor for create_conversation_profile - - Override in a subclass to manipulate the response - after it is returned by the ConversationProfiles server but before - it is returned to user code. - """ - return response - def pre_delete_conversation_profile(self, request: conversation_profile.DeleteConversationProfileRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[conversation_profile.DeleteConversationProfileRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for delete_conversation_profile - - Override in a subclass to manipulate the request or metadata - before they are sent to the ConversationProfiles server. - """ - return request, metadata - - def pre_get_conversation_profile(self, request: conversation_profile.GetConversationProfileRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[conversation_profile.GetConversationProfileRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for get_conversation_profile - - Override in a subclass to manipulate the request or metadata - before they are sent to the ConversationProfiles server. - """ - return request, metadata - - def post_get_conversation_profile(self, response: conversation_profile.ConversationProfile) -> conversation_profile.ConversationProfile: - """Post-rpc interceptor for get_conversation_profile - - Override in a subclass to manipulate the response - after it is returned by the ConversationProfiles server but before - it is returned to user code. - """ - return response - def pre_list_conversation_profiles(self, request: conversation_profile.ListConversationProfilesRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[conversation_profile.ListConversationProfilesRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for list_conversation_profiles - - Override in a subclass to manipulate the request or metadata - before they are sent to the ConversationProfiles server. - """ - return request, metadata - - def post_list_conversation_profiles(self, response: conversation_profile.ListConversationProfilesResponse) -> conversation_profile.ListConversationProfilesResponse: - """Post-rpc interceptor for list_conversation_profiles - - Override in a subclass to manipulate the response - after it is returned by the ConversationProfiles server but before - it is returned to user code. - """ - return response - def pre_set_suggestion_feature_config(self, request: gcd_conversation_profile.SetSuggestionFeatureConfigRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[gcd_conversation_profile.SetSuggestionFeatureConfigRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for set_suggestion_feature_config - - Override in a subclass to manipulate the request or metadata - before they are sent to the ConversationProfiles server. - """ - return request, metadata - - def post_set_suggestion_feature_config(self, response: operations_pb2.Operation) -> operations_pb2.Operation: - """Post-rpc interceptor for set_suggestion_feature_config - - Override in a subclass to manipulate the response - after it is returned by the ConversationProfiles server but before - it is returned to user code. - """ - return response - def pre_update_conversation_profile(self, request: gcd_conversation_profile.UpdateConversationProfileRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[gcd_conversation_profile.UpdateConversationProfileRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for update_conversation_profile - - Override in a subclass to manipulate the request or metadata - before they are sent to the ConversationProfiles server. - """ - return request, metadata - - def post_update_conversation_profile(self, response: gcd_conversation_profile.ConversationProfile) -> gcd_conversation_profile.ConversationProfile: - """Post-rpc interceptor for update_conversation_profile - - Override in a subclass to manipulate the response - after it is returned by the ConversationProfiles server but before - it is returned to user code. - """ - return response - - def pre_get_location( - self, request: locations_pb2.GetLocationRequest, metadata: Sequence[Tuple[str, str]] - ) -> Tuple[locations_pb2.GetLocationRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for get_location - - Override in a subclass to manipulate the request or metadata - before they are sent to the ConversationProfiles server. - """ - return request, metadata - - def post_get_location( - self, response: locations_pb2.Location - ) -> locations_pb2.Location: - """Post-rpc interceptor for get_location - - Override in a subclass to manipulate the response - after it is returned by the ConversationProfiles server but before - it is returned to user code. - """ - return response - def pre_list_locations( - self, request: locations_pb2.ListLocationsRequest, metadata: Sequence[Tuple[str, str]] - ) -> Tuple[locations_pb2.ListLocationsRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for list_locations - - Override in a subclass to manipulate the request or metadata - before they are sent to the ConversationProfiles server. - """ - return request, metadata - - def post_list_locations( - self, response: locations_pb2.ListLocationsResponse - ) -> locations_pb2.ListLocationsResponse: - """Post-rpc interceptor for list_locations - - Override in a subclass to manipulate the response - after it is returned by the ConversationProfiles server but before - it is returned to user code. - """ - return response - def pre_cancel_operation( - self, request: operations_pb2.CancelOperationRequest, metadata: Sequence[Tuple[str, str]] - ) -> Tuple[operations_pb2.CancelOperationRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for cancel_operation - - Override in a subclass to manipulate the request or metadata - before they are sent to the ConversationProfiles server. - """ - return request, metadata - - def post_cancel_operation( - self, response: None - ) -> None: - """Post-rpc interceptor for cancel_operation - - Override in a subclass to manipulate the response - after it is returned by the ConversationProfiles server but before - it is returned to user code. - """ - return response - def pre_get_operation( - self, request: operations_pb2.GetOperationRequest, metadata: Sequence[Tuple[str, str]] - ) -> Tuple[operations_pb2.GetOperationRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for get_operation - - Override in a subclass to manipulate the request or metadata - before they are sent to the ConversationProfiles server. - """ - return request, metadata - - def post_get_operation( - self, response: operations_pb2.Operation - ) -> operations_pb2.Operation: - """Post-rpc interceptor for get_operation - - Override in a subclass to manipulate the response - after it is returned by the ConversationProfiles server but before - it is returned to user code. - """ - return response - def pre_list_operations( - self, request: operations_pb2.ListOperationsRequest, metadata: Sequence[Tuple[str, str]] - ) -> Tuple[operations_pb2.ListOperationsRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for list_operations - - Override in a subclass to manipulate the request or metadata - before they are sent to the ConversationProfiles server. - """ - return request, metadata - - def post_list_operations( - self, response: operations_pb2.ListOperationsResponse - ) -> operations_pb2.ListOperationsResponse: - """Post-rpc interceptor for list_operations - - Override in a subclass to manipulate the response - after it is returned by the ConversationProfiles server but before - it is returned to user code. - """ - return response - - -@dataclasses.dataclass -class ConversationProfilesRestStub: - _session: AuthorizedSession - _host: str - _interceptor: ConversationProfilesRestInterceptor - - -class ConversationProfilesRestTransport(ConversationProfilesTransport): - """REST backend transport for ConversationProfiles. - - Service for managing - [ConversationProfiles][google.cloud.dialogflow.v2beta1.ConversationProfile]. - - 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 JSON representations of protocol buffers over HTTP/1.1 - - """ - - def __init__(self, *, - host: str = 'dialogflow.googleapis.com', - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - client_cert_source_for_mtls: Optional[Callable[[ - ], Tuple[bytes, bytes]]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - url_scheme: str = 'https', - interceptor: Optional[ConversationProfilesRestInterceptor] = None, - api_audience: Optional[str] = None, - ) -> 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 ignored if ``channel`` is provided. - scopes (Optional(Sequence[str])): A list of scopes. This argument is - ignored if ``channel`` is provided. - client_cert_source_for_mtls (Callable[[], Tuple[bytes, bytes]]): Client - certificate to configure mutual TLS HTTP channel. It is ignored - if ``channel`` is provided. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you are developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - url_scheme: the protocol scheme for the API endpoint. Normally - "https", but for testing or local servers, - "http" can be specified. - """ - # Run the base constructor - # TODO(yon-mg): resolve other ctor params i.e. scopes, quota, etc. - # TODO: When custom host (api_endpoint) is set, `scopes` must *also* be set on the - # credentials object - maybe_url_match = re.match("^(?Phttp(?:s)?://)?(?P.*)$", host) - if maybe_url_match is None: - raise ValueError(f"Unexpected hostname structure: {host}") # pragma: NO COVER - - url_match_items = maybe_url_match.groupdict() - - host = f"{url_scheme}://{host}" if not url_match_items["scheme"] else host - - super().__init__( - host=host, - credentials=credentials, - client_info=client_info, - always_use_jwt_access=always_use_jwt_access, - api_audience=api_audience - ) - self._session = AuthorizedSession( - self._credentials, default_host=self.DEFAULT_HOST) - self._operations_client: Optional[operations_v1.AbstractOperationsClient] = None - if client_cert_source_for_mtls: - self._session.configure_mtls_channel(client_cert_source_for_mtls) - self._interceptor = interceptor or ConversationProfilesRestInterceptor() - self._prep_wrapped_messages(client_info) - - @property - def operations_client(self) -> operations_v1.AbstractOperationsClient: - """Create the client designed to process long-running operations. - - This property caches on the instance; repeated calls return the same - client. - """ - # Only create a new client if we do not already have one. - if self._operations_client is None: - http_options: Dict[str, List[Dict[str, str]]] = { - 'google.longrunning.Operations.CancelOperation': [ - { - 'method': 'post', - 'uri': '/v2beta1/{name=projects/*/operations/*}:cancel', - }, - { - 'method': 'post', - 'uri': '/v2beta1/{name=projects/*/locations/*/operations/*}:cancel', - }, - ], - 'google.longrunning.Operations.GetOperation': [ - { - 'method': 'get', - 'uri': '/v2beta1/{name=projects/*/operations/*}', - }, - { - 'method': 'get', - 'uri': '/v2beta1/{name=projects/*/locations/*/operations/*}', - }, - ], - 'google.longrunning.Operations.ListOperations': [ - { - 'method': 'get', - 'uri': '/v2beta1/{name=projects/*}/operations', - }, - { - 'method': 'get', - 'uri': '/v2beta1/{name=projects/*/locations/*}/operations', - }, - ], - } - - rest_transport = operations_v1.OperationsRestTransport( - host=self._host, - # use the credentials which are saved - credentials=self._credentials, - scopes=self._scopes, - http_options=http_options, - path_prefix="v2beta1") - - self._operations_client = operations_v1.AbstractOperationsClient(transport=rest_transport) - - # Return the client from cache. - return self._operations_client - - class _ClearSuggestionFeatureConfig(ConversationProfilesRestStub): - def __hash__(self): - return hash("ClearSuggestionFeatureConfig") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: gcd_conversation_profile.ClearSuggestionFeatureConfigRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> operations_pb2.Operation: - r"""Call the clear suggestion feature - config method over HTTP. - - Args: - request (~.gcd_conversation_profile.ClearSuggestionFeatureConfigRequest): - The request object. The request message for - [ConversationProfiles.ClearFeature][]. - 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: - ~.operations_pb2.Operation: - This resource represents a - long-running operation that is the - result of a network API call. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'post', - 'uri': '/v2beta1/{conversation_profile=projects/*/conversationProfiles/*}:clearSuggestionFeatureConfig', - 'body': '*', - }, -{ - 'method': 'post', - 'uri': '/v2beta1/{conversation_profile=projects/*/locations/*/conversationProfiles/*}:clearSuggestionFeatureConfig', - 'body': '*', - }, - ] - request, metadata = self._interceptor.pre_clear_suggestion_feature_config(request, metadata) - pb_request = gcd_conversation_profile.ClearSuggestionFeatureConfigRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request['body'], - including_default_value_fields=False, - use_integers_for_enums=True - ) - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - including_default_value_fields=False, - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = operations_pb2.Operation() - json_format.Parse(response.content, resp, ignore_unknown_fields=True) - resp = self._interceptor.post_clear_suggestion_feature_config(resp) - return resp - - class _CreateConversationProfile(ConversationProfilesRestStub): - def __hash__(self): - return hash("CreateConversationProfile") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: gcd_conversation_profile.CreateConversationProfileRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> gcd_conversation_profile.ConversationProfile: - r"""Call the create conversation - profile method over HTTP. - - Args: - request (~.gcd_conversation_profile.CreateConversationProfileRequest): - The request object. The request message for - [ConversationProfiles.CreateConversationProfile][google.cloud.dialogflow.v2beta1.ConversationProfiles.CreateConversationProfile]. - 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: - ~.gcd_conversation_profile.ConversationProfile: - Defines the services to connect to - incoming Dialogflow conversations. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'post', - 'uri': '/v2beta1/{parent=projects/*}/conversationProfiles', - 'body': 'conversation_profile', - }, -{ - 'method': 'post', - 'uri': '/v2beta1/{parent=projects/*/locations/*}/conversationProfiles', - 'body': 'conversation_profile', - }, - ] - request, metadata = self._interceptor.pre_create_conversation_profile(request, metadata) - pb_request = gcd_conversation_profile.CreateConversationProfileRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request['body'], - including_default_value_fields=False, - use_integers_for_enums=True - ) - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - including_default_value_fields=False, - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = gcd_conversation_profile.ConversationProfile() - pb_resp = gcd_conversation_profile.ConversationProfile.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_create_conversation_profile(resp) - return resp - - class _DeleteConversationProfile(ConversationProfilesRestStub): - def __hash__(self): - return hash("DeleteConversationProfile") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: conversation_profile.DeleteConversationProfileRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ): - r"""Call the delete conversation - profile method over HTTP. - - Args: - request (~.conversation_profile.DeleteConversationProfileRequest): - The request object. The request message for - [ConversationProfiles.DeleteConversationProfile][google.cloud.dialogflow.v2beta1.ConversationProfiles.DeleteConversationProfile]. - - This operation fails if the conversation profile is - still referenced from a phone number. - 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. - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'delete', - 'uri': '/v2beta1/{name=projects/*/conversationProfiles/*}', - }, -{ - 'method': 'delete', - 'uri': '/v2beta1/{name=projects/*/locations/*/conversationProfiles/*}', - }, - ] - request, metadata = self._interceptor.pre_delete_conversation_profile(request, metadata) - pb_request = conversation_profile.DeleteConversationProfileRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - including_default_value_fields=False, - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - class _GetConversationProfile(ConversationProfilesRestStub): - def __hash__(self): - return hash("GetConversationProfile") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: conversation_profile.GetConversationProfileRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> conversation_profile.ConversationProfile: - r"""Call the get conversation profile method over HTTP. - - Args: - request (~.conversation_profile.GetConversationProfileRequest): - The request object. The request message for - [ConversationProfiles.GetConversationProfile][google.cloud.dialogflow.v2beta1.ConversationProfiles.GetConversationProfile]. - 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: - ~.conversation_profile.ConversationProfile: - Defines the services to connect to - incoming Dialogflow conversations. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v2beta1/{name=projects/*/conversationProfiles/*}', - }, -{ - 'method': 'get', - 'uri': '/v2beta1/{name=projects/*/locations/*/conversationProfiles/*}', - }, - ] - request, metadata = self._interceptor.pre_get_conversation_profile(request, metadata) - pb_request = conversation_profile.GetConversationProfileRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - including_default_value_fields=False, - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = conversation_profile.ConversationProfile() - pb_resp = conversation_profile.ConversationProfile.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_get_conversation_profile(resp) - return resp - - class _ListConversationProfiles(ConversationProfilesRestStub): - def __hash__(self): - return hash("ListConversationProfiles") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: conversation_profile.ListConversationProfilesRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> conversation_profile.ListConversationProfilesResponse: - r"""Call the list conversation - profiles method over HTTP. - - Args: - request (~.conversation_profile.ListConversationProfilesRequest): - The request object. The request message for - [ConversationProfiles.ListConversationProfiles][google.cloud.dialogflow.v2beta1.ConversationProfiles.ListConversationProfiles]. - 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: - ~.conversation_profile.ListConversationProfilesResponse: - The response message for - [ConversationProfiles.ListConversationProfiles][google.cloud.dialogflow.v2beta1.ConversationProfiles.ListConversationProfiles]. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v2beta1/{parent=projects/*}/conversationProfiles', - }, -{ - 'method': 'get', - 'uri': '/v2beta1/{parent=projects/*/locations/*}/conversationProfiles', - }, - ] - request, metadata = self._interceptor.pre_list_conversation_profiles(request, metadata) - pb_request = conversation_profile.ListConversationProfilesRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - including_default_value_fields=False, - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = conversation_profile.ListConversationProfilesResponse() - pb_resp = conversation_profile.ListConversationProfilesResponse.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_list_conversation_profiles(resp) - return resp - - class _SetSuggestionFeatureConfig(ConversationProfilesRestStub): - def __hash__(self): - return hash("SetSuggestionFeatureConfig") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: gcd_conversation_profile.SetSuggestionFeatureConfigRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> operations_pb2.Operation: - r"""Call the set suggestion feature - config method over HTTP. - - Args: - request (~.gcd_conversation_profile.SetSuggestionFeatureConfigRequest): - The request object. The request message for - [ConversationProfiles.SetSuggestionFeature][]. - 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: - ~.operations_pb2.Operation: - This resource represents a - long-running operation that is the - result of a network API call. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'post', - 'uri': '/v2beta1/{conversation_profile=projects/*/conversationProfiles/*}:setSuggestionFeatureConfig', - 'body': '*', - }, -{ - 'method': 'post', - 'uri': '/v2beta1/{conversation_profile=projects/*/locations/*/conversationProfiles/*}:setSuggestionFeatureConfig', - 'body': '*', - }, - ] - request, metadata = self._interceptor.pre_set_suggestion_feature_config(request, metadata) - pb_request = gcd_conversation_profile.SetSuggestionFeatureConfigRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request['body'], - including_default_value_fields=False, - use_integers_for_enums=True - ) - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - including_default_value_fields=False, - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = operations_pb2.Operation() - json_format.Parse(response.content, resp, ignore_unknown_fields=True) - resp = self._interceptor.post_set_suggestion_feature_config(resp) - return resp - - class _UpdateConversationProfile(ConversationProfilesRestStub): - def __hash__(self): - return hash("UpdateConversationProfile") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - "updateMask" : {}, } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: gcd_conversation_profile.UpdateConversationProfileRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> gcd_conversation_profile.ConversationProfile: - r"""Call the update conversation - profile method over HTTP. - - Args: - request (~.gcd_conversation_profile.UpdateConversationProfileRequest): - The request object. The request message for - [ConversationProfiles.UpdateConversationProfile][google.cloud.dialogflow.v2beta1.ConversationProfiles.UpdateConversationProfile]. - 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: - ~.gcd_conversation_profile.ConversationProfile: - Defines the services to connect to - incoming Dialogflow conversations. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'patch', - 'uri': '/v2beta1/{conversation_profile.name=projects/*/conversationProfiles/*}', - 'body': 'conversation_profile', - }, -{ - 'method': 'patch', - 'uri': '/v2beta1/{conversation_profile.name=projects/*/locations/*/conversationProfiles/*}', - 'body': 'conversation_profile', - }, - ] - request, metadata = self._interceptor.pre_update_conversation_profile(request, metadata) - pb_request = gcd_conversation_profile.UpdateConversationProfileRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request['body'], - including_default_value_fields=False, - use_integers_for_enums=True - ) - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - including_default_value_fields=False, - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = gcd_conversation_profile.ConversationProfile() - pb_resp = gcd_conversation_profile.ConversationProfile.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_update_conversation_profile(resp) - return resp - - @property - def clear_suggestion_feature_config(self) -> Callable[ - [gcd_conversation_profile.ClearSuggestionFeatureConfigRequest], - operations_pb2.Operation]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._ClearSuggestionFeatureConfig(self._session, self._host, self._interceptor) # type: ignore - - @property - def create_conversation_profile(self) -> Callable[ - [gcd_conversation_profile.CreateConversationProfileRequest], - gcd_conversation_profile.ConversationProfile]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._CreateConversationProfile(self._session, self._host, self._interceptor) # type: ignore - - @property - def delete_conversation_profile(self) -> Callable[ - [conversation_profile.DeleteConversationProfileRequest], - empty_pb2.Empty]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._DeleteConversationProfile(self._session, self._host, self._interceptor) # type: ignore - - @property - def get_conversation_profile(self) -> Callable[ - [conversation_profile.GetConversationProfileRequest], - conversation_profile.ConversationProfile]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._GetConversationProfile(self._session, self._host, self._interceptor) # type: ignore - - @property - def list_conversation_profiles(self) -> Callable[ - [conversation_profile.ListConversationProfilesRequest], - conversation_profile.ListConversationProfilesResponse]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._ListConversationProfiles(self._session, self._host, self._interceptor) # type: ignore - - @property - def set_suggestion_feature_config(self) -> Callable[ - [gcd_conversation_profile.SetSuggestionFeatureConfigRequest], - operations_pb2.Operation]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._SetSuggestionFeatureConfig(self._session, self._host, self._interceptor) # type: ignore - - @property - def update_conversation_profile(self) -> Callable[ - [gcd_conversation_profile.UpdateConversationProfileRequest], - gcd_conversation_profile.ConversationProfile]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._UpdateConversationProfile(self._session, self._host, self._interceptor) # type: ignore - - @property - def get_location(self): - return self._GetLocation(self._session, self._host, self._interceptor) # type: ignore - - class _GetLocation(ConversationProfilesRestStub): - def __call__(self, - request: locations_pb2.GetLocationRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> locations_pb2.Location: - - r"""Call the get location method over HTTP. - - Args: - request (locations_pb2.GetLocationRequest): - The request object for GetLocation method. - 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: - locations_pb2.Location: Response from GetLocation method. - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v2beta1/{name=projects/*/locations/*}', - }, - ] - - request, metadata = self._interceptor.pre_get_location(request, metadata) - request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode( - http_options, **request_kwargs) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json.dumps(transcoded_request['query_params'])) - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - resp = locations_pb2.Location() - resp = json_format.Parse(response.content.decode("utf-8"), resp) - resp = self._interceptor.post_get_location(resp) - return resp - - @property - def list_locations(self): - return self._ListLocations(self._session, self._host, self._interceptor) # type: ignore - - class _ListLocations(ConversationProfilesRestStub): - def __call__(self, - request: locations_pb2.ListLocationsRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> locations_pb2.ListLocationsResponse: - - r"""Call the list locations method over HTTP. - - Args: - request (locations_pb2.ListLocationsRequest): - The request object for ListLocations method. - 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: - locations_pb2.ListLocationsResponse: Response from ListLocations method. - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v2beta1/{name=projects/*}/locations', - }, - ] - - request, metadata = self._interceptor.pre_list_locations(request, metadata) - request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode( - http_options, **request_kwargs) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json.dumps(transcoded_request['query_params'])) - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - resp = locations_pb2.ListLocationsResponse() - resp = json_format.Parse(response.content.decode("utf-8"), resp) - resp = self._interceptor.post_list_locations(resp) - return resp - - @property - def cancel_operation(self): - return self._CancelOperation(self._session, self._host, self._interceptor) # type: ignore - - class _CancelOperation(ConversationProfilesRestStub): - def __call__(self, - request: operations_pb2.CancelOperationRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> None: - - r"""Call the cancel operation method over HTTP. - - Args: - request (operations_pb2.CancelOperationRequest): - The request object for CancelOperation method. - 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. - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'post', - 'uri': '/v2beta1/{name=projects/*/operations/*}:cancel', - }, -{ - 'method': 'post', - 'uri': '/v2beta1/{name=projects/*/locations/*/operations/*}:cancel', - }, - ] - - request, metadata = self._interceptor.pre_cancel_operation(request, metadata) - request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode( - http_options, **request_kwargs) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json.dumps(transcoded_request['query_params'])) - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - return self._interceptor.post_cancel_operation(None) - - @property - def get_operation(self): - return self._GetOperation(self._session, self._host, self._interceptor) # type: ignore - - class _GetOperation(ConversationProfilesRestStub): - def __call__(self, - request: operations_pb2.GetOperationRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> operations_pb2.Operation: - - r"""Call the get operation method over HTTP. - - Args: - request (operations_pb2.GetOperationRequest): - The request object for GetOperation method. - 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: - operations_pb2.Operation: Response from GetOperation method. - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v2beta1/{name=projects/*/operations/*}', - }, -{ - 'method': 'get', - 'uri': '/v2beta1/{name=projects/*/locations/*/operations/*}', - }, - ] - - request, metadata = self._interceptor.pre_get_operation(request, metadata) - request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode( - http_options, **request_kwargs) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json.dumps(transcoded_request['query_params'])) - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - resp = operations_pb2.Operation() - resp = json_format.Parse(response.content.decode("utf-8"), resp) - resp = self._interceptor.post_get_operation(resp) - return resp - - @property - def list_operations(self): - return self._ListOperations(self._session, self._host, self._interceptor) # type: ignore - - class _ListOperations(ConversationProfilesRestStub): - def __call__(self, - request: operations_pb2.ListOperationsRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> operations_pb2.ListOperationsResponse: - - r"""Call the list operations method over HTTP. - - Args: - request (operations_pb2.ListOperationsRequest): - The request object for ListOperations method. - 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: - operations_pb2.ListOperationsResponse: Response from ListOperations method. - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v2beta1/{name=projects/*}/operations', - }, -{ - 'method': 'get', - 'uri': '/v2beta1/{name=projects/*/locations/*}/operations', - }, - ] - - request, metadata = self._interceptor.pre_list_operations(request, metadata) - request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode( - http_options, **request_kwargs) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json.dumps(transcoded_request['query_params'])) - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - resp = operations_pb2.ListOperationsResponse() - resp = json_format.Parse(response.content.decode("utf-8"), resp) - resp = self._interceptor.post_list_operations(resp) - return resp - - @property - def kind(self) -> str: - return "rest" - - def close(self): - self._session.close() - - -__all__=( - 'ConversationProfilesRestTransport', -) diff --git a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/conversations/__init__.py b/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/conversations/__init__.py deleted file mode 100644 index 162e3f820..000000000 --- a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/conversations/__init__.py +++ /dev/null @@ -1,22 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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 ConversationsClient -from .async_client import ConversationsAsyncClient - -__all__ = ( - 'ConversationsClient', - 'ConversationsAsyncClient', -) diff --git a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/conversations/async_client.py b/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/conversations/async_client.py deleted file mode 100644 index 453fb9ab5..000000000 --- a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/conversations/async_client.py +++ /dev/null @@ -1,1267 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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, Mapping, MutableMapping, MutableSequence, Optional, Sequence, Tuple, Type, Union - -from google.cloud.dialogflow_v2beta1 import gapic_version as package_version - -from google.api_core.client_options import ClientOptions -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import retry as retries -from google.auth import credentials as ga_credentials # type: ignore -from google.oauth2 import service_account # type: ignore - -try: - OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] -except AttributeError: # pragma: NO COVER - OptionalRetry = Union[retries.Retry, object] # 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.cloud.location import locations_pb2 # type: ignore -from google.longrunning import operations_pb2 -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 - - -class ConversationsAsyncClient: - """Service for managing - [Conversations][google.cloud.dialogflow.v2beta1.Conversation]. - """ - - _client: ConversationsClient - - DEFAULT_ENDPOINT = ConversationsClient.DEFAULT_ENDPOINT - DEFAULT_MTLS_ENDPOINT = ConversationsClient.DEFAULT_MTLS_ENDPOINT - - answer_record_path = staticmethod(ConversationsClient.answer_record_path) - parse_answer_record_path = staticmethod(ConversationsClient.parse_answer_record_path) - conversation_path = staticmethod(ConversationsClient.conversation_path) - parse_conversation_path = staticmethod(ConversationsClient.parse_conversation_path) - conversation_profile_path = staticmethod(ConversationsClient.conversation_profile_path) - parse_conversation_profile_path = staticmethod(ConversationsClient.parse_conversation_profile_path) - 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) - - @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: - ConversationsAsyncClient: The constructed client. - """ - return ConversationsClient.from_service_account_info.__func__(ConversationsAsyncClient, 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: - ConversationsAsyncClient: The constructed client. - """ - return ConversationsClient.from_service_account_file.__func__(ConversationsAsyncClient, filename, *args, **kwargs) # type: ignore - - from_service_account_json = from_service_account_file - - @classmethod - def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[ClientOptions] = None): - """Return the API endpoint and client cert source for mutual TLS. - - The client cert source is determined in the following order: - (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the - client cert source is None. - (2) if `client_options.client_cert_source` is provided, use the provided one; if the - default client cert source exists, use the default one; otherwise the client cert - source is None. - - The API endpoint is determined in the following order: - (1) if `client_options.api_endpoint` if provided, use the provided one. - (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the - default mTLS endpoint; if the environment variable is "never", use the default API - endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise - use the default API endpoint. - - More details can be found at https://google.aip.dev/auth/4114. - - Args: - client_options (google.api_core.client_options.ClientOptions): Custom options for the - client. Only the `api_endpoint` and `client_cert_source` properties may be used - in this method. - - Returns: - Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the - client cert source to use. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If any errors happen. - """ - return ConversationsClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore - - @property - def transport(self) -> ConversationsTransport: - """Returns the transport used by the client instance. - - Returns: - ConversationsTransport: The transport used by the client instance. - """ - return self._client.transport - - get_transport_class = functools.partial(type(ConversationsClient).get_transport_class, type(ConversationsClient)) - - def __init__(self, *, - credentials: Optional[ga_credentials.Credentials] = None, - transport: Union[str, ConversationsTransport] = "grpc_asyncio", - client_options: Optional[ClientOptions] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the conversations 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, ~.ConversationsTransport]): 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 = ConversationsClient( - credentials=credentials, - transport=transport, - client_options=client_options, - client_info=client_info, - - ) - - async def create_conversation(self, - request: Optional[Union[gcd_conversation.CreateConversationRequest, dict]] = None, - *, - parent: Optional[str] = None, - conversation: Optional[gcd_conversation.Conversation] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gcd_conversation.Conversation: - r"""Creates a new conversation. Conversations are auto-completed - after 24 hours. - - Conversation Lifecycle: There are two stages during a - conversation: Automated Agent Stage and Assist Stage. - - For Automated Agent Stage, there will be a dialogflow agent - responding to user queries. - - For Assist Stage, there's no dialogflow agent responding to user - queries. But we will provide suggestions which are generated - from conversation. - - If - [Conversation.conversation_profile][google.cloud.dialogflow.v2beta1.Conversation.conversation_profile] - is configured for a dialogflow agent, conversation will start - from ``Automated Agent Stage``, otherwise, it will start from - ``Assist Stage``. And during ``Automated Agent Stage``, once an - [Intent][google.cloud.dialogflow.v2beta1.Intent] with - [Intent.live_agent_handoff][google.cloud.dialogflow.v2beta1.Intent.live_agent_handoff] - is triggered, conversation will transfer to Assist Stage. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import dialogflow_v2beta1 - - async def sample_create_conversation(): - # Create a client - client = dialogflow_v2beta1.ConversationsAsyncClient() - - # Initialize request argument(s) - conversation = dialogflow_v2beta1.Conversation() - conversation.conversation_profile = "conversation_profile_value" - - request = dialogflow_v2beta1.CreateConversationRequest( - parent="parent_value", - conversation=conversation, - ) - - # Make the request - response = await client.create_conversation(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.dialogflow_v2beta1.types.CreateConversationRequest, dict]]): - The request object. The request message for - [Conversations.CreateConversation][google.cloud.dialogflow.v2beta1.Conversations.CreateConversation]. - parent (:class:`str`): - Required. Resource identifier of the project creating - the conversation. Format: - ``projects//locations/``. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - conversation (:class:`google.cloud.dialogflow_v2beta1.types.Conversation`): - Required. The conversation to create. - 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. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.dialogflow_v2beta1.types.Conversation: - Represents a conversation. - A conversation is an interaction between - an agent, including live agents and - Dialogflow agents, and a support - customer. Conversations can include - phone calls and text-based chat - sessions. - - """ - # Create or coerce a protobuf request object. - # Quick 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, conversation]) - 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_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: - request.conversation = conversation - - # 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_conversation, - 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 list_conversations(self, - request: Optional[Union[conversation.ListConversationsRequest, dict]] = None, - *, - parent: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListConversationsAsyncPager: - r"""Returns the list of all conversations in the - specified project. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import dialogflow_v2beta1 - - async def sample_list_conversations(): - # Create a client - client = dialogflow_v2beta1.ConversationsAsyncClient() - - # Initialize request argument(s) - request = dialogflow_v2beta1.ListConversationsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_conversations(request=request) - - # Handle the response - async for response in page_result: - print(response) - - Args: - request (Optional[Union[google.cloud.dialogflow_v2beta1.types.ListConversationsRequest, dict]]): - The request object. The request message for - [Conversations.ListConversations][google.cloud.dialogflow.v2beta1.Conversations.ListConversations]. - parent (:class:`str`): - Required. The project from which to list all - conversation. Format: - ``projects//locations/``. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.dialogflow_v2beta1.services.conversations.pagers.ListConversationsAsyncPager: - The response message for - [Conversations.ListConversations][google.cloud.dialogflow.v2beta1.Conversations.ListConversations]. - - Iterating over this object will yield results and - resolve additional pages automatically. - - """ - # Create or coerce a protobuf request object. - # Quick 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 = conversation.ListConversationsRequest(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_conversations, - 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.ListConversationsAsyncPager( - method=rpc, - request=request, - response=response, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def get_conversation(self, - request: Optional[Union[conversation.GetConversationRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> conversation.Conversation: - r"""Retrieves the specific conversation. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import dialogflow_v2beta1 - - async def sample_get_conversation(): - # Create a client - client = dialogflow_v2beta1.ConversationsAsyncClient() - - # Initialize request argument(s) - request = dialogflow_v2beta1.GetConversationRequest( - name="name_value", - ) - - # Make the request - response = await client.get_conversation(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.dialogflow_v2beta1.types.GetConversationRequest, dict]]): - The request object. The request message for - [Conversations.GetConversation][google.cloud.dialogflow.v2beta1.Conversations.GetConversation]. - name (:class:`str`): - Required. The name of the conversation. Format: - ``projects//locations//conversations/``. - - 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.Conversation: - Represents a conversation. - A conversation is an interaction between - an agent, including live agents and - Dialogflow agents, and a support - customer. Conversations can include - phone calls and text-based chat - sessions. - - """ - # Create or coerce a protobuf request object. - # Quick 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 = conversation.GetConversationRequest(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_conversation, - 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 complete_conversation(self, - request: Optional[Union[conversation.CompleteConversationRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> conversation.Conversation: - r"""Completes the specified conversation. Finished - conversations are purged from the database after 30 - days. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import dialogflow_v2beta1 - - async def sample_complete_conversation(): - # Create a client - client = dialogflow_v2beta1.ConversationsAsyncClient() - - # Initialize request argument(s) - request = dialogflow_v2beta1.CompleteConversationRequest( - name="name_value", - ) - - # Make the request - response = await client.complete_conversation(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.dialogflow_v2beta1.types.CompleteConversationRequest, dict]]): - The request object. The request message for - [Conversations.CompleteConversation][google.cloud.dialogflow.v2beta1.Conversations.CompleteConversation]. - name (:class:`str`): - Required. Resource identifier of the conversation to - close. Format: - ``projects//locations//conversations/``. - - 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.Conversation: - Represents a conversation. - A conversation is an interaction between - an agent, including live agents and - Dialogflow agents, and a support - customer. Conversations can include - phone calls and text-based chat - sessions. - - """ - # Create or coerce a protobuf request object. - # Quick 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 = conversation.CompleteConversationRequest(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.complete_conversation, - 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 batch_create_messages(self, - request: Optional[Union[conversation.BatchCreateMessagesRequest, dict]] = None, - *, - parent: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> conversation.BatchCreateMessagesResponse: - r"""Batch ingests messages to conversation. Customers can - use this RPC to ingest historical messages to - conversation. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import dialogflow_v2beta1 - - async def sample_batch_create_messages(): - # Create a client - client = dialogflow_v2beta1.ConversationsAsyncClient() - - # Initialize request argument(s) - requests = dialogflow_v2beta1.CreateMessageRequest() - requests.parent = "parent_value" - requests.message.content = "content_value" - - request = dialogflow_v2beta1.BatchCreateMessagesRequest( - parent="parent_value", - requests=requests, - ) - - # Make the request - response = await client.batch_create_messages(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.dialogflow_v2beta1.types.BatchCreateMessagesRequest, dict]]): - The request object. The request message for - [Conversations.BatchCreateMessagesRequest][]. - parent (:class:`str`): - Required. Resource identifier of the conversation to - create message. Format: - ``projects//locations//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. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.dialogflow_v2beta1.types.BatchCreateMessagesResponse: - The request message for - [Conversations.BatchCreateMessagesResponse][]. - - """ - # Create or coerce a protobuf request object. - # Quick 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 = conversation.BatchCreateMessagesRequest(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.batch_create_messages, - 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 list_messages(self, - request: Optional[Union[conversation.ListMessagesRequest, dict]] = None, - *, - parent: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListMessagesAsyncPager: - r"""Lists messages that belong to a given conversation. ``messages`` - are ordered by ``create_time`` in descending order. To fetch - updates without duplication, send request with filter - ``create_time_epoch_microseconds > [first item's create_time of previous request]`` - and empty page_token. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import dialogflow_v2beta1 - - async def sample_list_messages(): - # Create a client - client = dialogflow_v2beta1.ConversationsAsyncClient() - - # Initialize request argument(s) - request = dialogflow_v2beta1.ListMessagesRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_messages(request=request) - - # Handle the response - async for response in page_result: - print(response) - - Args: - request (Optional[Union[google.cloud.dialogflow_v2beta1.types.ListMessagesRequest, dict]]): - The request object. The request message for - [Conversations.ListMessages][google.cloud.dialogflow.v2beta1.Conversations.ListMessages]. - parent (:class:`str`): - Required. The name of the conversation to list messages - for. Format: - ``projects//locations//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. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.dialogflow_v2beta1.services.conversations.pagers.ListMessagesAsyncPager: - The response message for - [Conversations.ListMessages][google.cloud.dialogflow.v2beta1.Conversations.ListMessages]. - - Iterating over this object will yield results and - resolve additional pages automatically. - - """ - # Create or coerce a protobuf request object. - # Quick 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 = conversation.ListMessagesRequest(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_messages, - 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.ListMessagesAsyncPager( - method=rpc, - request=request, - response=response, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def suggest_conversation_summary(self, - request: Optional[Union[gcd_conversation.SuggestConversationSummaryRequest, dict]] = None, - *, - conversation: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gcd_conversation.SuggestConversationSummaryResponse: - r"""Suggest summary for a conversation based on specific - historical messages. The range of the messages to be - used for summary can be specified in the request. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import dialogflow_v2beta1 - - async def sample_suggest_conversation_summary(): - # Create a client - client = dialogflow_v2beta1.ConversationsAsyncClient() - - # Initialize request argument(s) - request = dialogflow_v2beta1.SuggestConversationSummaryRequest( - conversation="conversation_value", - ) - - # Make the request - response = await client.suggest_conversation_summary(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.dialogflow_v2beta1.types.SuggestConversationSummaryRequest, dict]]): - The request object. The request message for - [Conversations.SuggestConversationSummary][google.cloud.dialogflow.v2beta1.Conversations.SuggestConversationSummary]. - conversation (:class:`str`): - Required. The conversation to fetch suggestion for. - Format: - ``projects//locations//conversations/``. - - 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. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.dialogflow_v2beta1.types.SuggestConversationSummaryResponse: - The response message for - [Conversations.SuggestConversationSummary][google.cloud.dialogflow.v2beta1.Conversations.SuggestConversationSummary]. - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([conversation]) - 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_conversation.SuggestConversationSummaryRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if conversation is not None: - request.conversation = conversation - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.suggest_conversation_summary, - 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(( - ("conversation", request.conversation), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def list_operations( - self, - request: Optional[operations_pb2.ListOperationsRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operations_pb2.ListOperationsResponse: - r"""Lists operations that match the specified filter in the request. - - Args: - request (:class:`~.operations_pb2.ListOperationsRequest`): - The request object. Request message for - `ListOperations` method. - 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: - ~.operations_pb2.ListOperationsResponse: - Response message for ``ListOperations`` method. - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = operations_pb2.ListOperationsRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._client._transport.list_operations, - 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 get_operation( - self, - request: Optional[operations_pb2.GetOperationRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operations_pb2.Operation: - r"""Gets the latest state of a long-running operation. - - Args: - request (:class:`~.operations_pb2.GetOperationRequest`): - The request object. Request message for - `GetOperation` method. - 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: - ~.operations_pb2.Operation: - An ``Operation`` object. - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = operations_pb2.GetOperationRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._client._transport.get_operation, - 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 cancel_operation( - self, - request: Optional[operations_pb2.CancelOperationRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> None: - r"""Starts asynchronous cancellation on a long-running operation. - - The server makes a best effort to cancel the operation, but success - is not guaranteed. If the server doesn't support this method, it returns - `google.rpc.Code.UNIMPLEMENTED`. - - Args: - request (:class:`~.operations_pb2.CancelOperationRequest`): - The request object. Request message for - `CancelOperation` method. - 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: - None - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = operations_pb2.CancelOperationRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._client._transport.cancel_operation, - 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_location( - self, - request: Optional[locations_pb2.GetLocationRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> locations_pb2.Location: - r"""Gets information about a location. - - Args: - request (:class:`~.location_pb2.GetLocationRequest`): - The request object. Request message for - `GetLocation` method. - 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: - ~.location_pb2.Location: - Location object. - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = locations_pb2.GetLocationRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._client._transport.get_location, - 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 list_locations( - self, - request: Optional[locations_pb2.ListLocationsRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> locations_pb2.ListLocationsResponse: - r"""Lists information about the supported locations for this service. - - Args: - request (:class:`~.location_pb2.ListLocationsRequest`): - The request object. Request message for - `ListLocations` method. - 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: - ~.location_pb2.ListLocationsResponse: - Response message for ``ListLocations`` method. - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = locations_pb2.ListLocationsRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._client._transport.list_locations, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("name", request.name),)), - ) - - # Send the request. - response = await rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - async def __aenter__(self): - return self - - async def __aexit__(self, exc_type, exc, tb): - await self.transport.close() - -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) - - -__all__ = ( - "ConversationsAsyncClient", -) diff --git a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/conversations/client.py b/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/conversations/client.py deleted file mode 100644 index 4900e2436..000000000 --- a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/conversations/client.py +++ /dev/null @@ -1,1493 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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 os -import re -from typing import Dict, Mapping, MutableMapping, MutableSequence, Optional, Sequence, Tuple, Type, Union, cast - -from google.cloud.dialogflow_v2beta1 import gapic_version as package_version - -from google.api_core import client_options as client_options_lib -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import retry as retries -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 - -try: - OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] -except AttributeError: # pragma: NO COVER - OptionalRetry = Union[retries.Retry, object] # 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.cloud.location import locations_pb2 # type: ignore -from google.longrunning import operations_pb2 -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 -from .transports.rest import ConversationsRestTransport - - -class ConversationsClientMeta(type): - """Metaclass for the Conversations 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[ConversationsTransport]] - _transport_registry["grpc"] = ConversationsGrpcTransport - _transport_registry["grpc_asyncio"] = ConversationsGrpcAsyncIOTransport - _transport_registry["rest"] = ConversationsRestTransport - - def get_transport_class(cls, - label: Optional[str] = None, - ) -> Type[ConversationsTransport]: - """Returns an appropriate transport class. - - Args: - label: The name of the desired transport. If none is - provided, then the first transport in the registry is used. - - Returns: - The transport class to use. - """ - # If a specific transport is requested, return that one. - if label: - return cls._transport_registry[label] - - # No transport is requested; return the default (that is, the first one - # in the dictionary). - return next(iter(cls._transport_registry.values())) - - -class ConversationsClient(metaclass=ConversationsClientMeta): - """Service for managing - [Conversations][google.cloud.dialogflow.v2beta1.Conversation]. - """ - - @staticmethod - def _get_default_mtls_endpoint(api_endpoint): - """Converts api endpoint to mTLS endpoint. - - Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to - "*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively. - Args: - api_endpoint (Optional[str]): the api endpoint to convert. - Returns: - str: converted mTLS api endpoint. - """ - if not api_endpoint: - return api_endpoint - - mtls_endpoint_re = re.compile( - r"(?P[^.]+)(?P\.mtls)?(?P\.sandbox)?(?P\.googleapis\.com)?" - ) - - m = mtls_endpoint_re.match(api_endpoint) - name, mtls, sandbox, googledomain = m.groups() - if mtls or not googledomain: - return api_endpoint - - if sandbox: - return api_endpoint.replace( - "sandbox.googleapis.com", "mtls.sandbox.googleapis.com" - ) - - return api_endpoint.replace(".googleapis.com", ".mtls.googleapis.com") - - DEFAULT_ENDPOINT = "dialogflow.googleapis.com" - DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore - DEFAULT_ENDPOINT - ) - - @classmethod - def from_service_account_info(cls, info: dict, *args, **kwargs): - """Creates an instance of this client using the provided credentials - info. - - Args: - info (dict): The service account private key info. - args: Additional arguments to pass to the constructor. - kwargs: Additional arguments to pass to the constructor. - - Returns: - ConversationsClient: 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: - ConversationsClient: 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) -> ConversationsTransport: - """Returns the transport used by the client instance. - - Returns: - ConversationsTransport: The transport used by the client - instance. - """ - return self._transport - - @staticmethod - def answer_record_path(project: str,answer_record: str,) -> str: - """Returns a fully-qualified answer_record string.""" - return "projects/{project}/answerRecords/{answer_record}".format(project=project, answer_record=answer_record, ) - - @staticmethod - def parse_answer_record_path(path: str) -> Dict[str,str]: - """Parses a answer_record path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/answerRecords/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def conversation_path(project: str,conversation: str,) -> str: - """Returns a fully-qualified conversation string.""" - return "projects/{project}/conversations/{conversation}".format(project=project, conversation=conversation, ) - - @staticmethod - def parse_conversation_path(path: str) -> Dict[str,str]: - """Parses a conversation path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/conversations/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def conversation_profile_path(project: str,conversation_profile: str,) -> str: - """Returns a fully-qualified conversation_profile string.""" - return "projects/{project}/conversationProfiles/{conversation_profile}".format(project=project, conversation_profile=conversation_profile, ) - - @staticmethod - def parse_conversation_profile_path(path: str) -> Dict[str,str]: - """Parses a conversation_profile path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/conversationProfiles/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def message_path(project: str,conversation: str,message: str,) -> str: - """Returns a fully-qualified message string.""" - return "projects/{project}/conversations/{conversation}/messages/{message}".format(project=project, conversation=conversation, message=message, ) - - @staticmethod - def parse_message_path(path: str) -> Dict[str,str]: - """Parses a message path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/conversations/(?P.+?)/messages/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_billing_account_path(billing_account: str, ) -> str: - """Returns a fully-qualified billing_account string.""" - return "billingAccounts/{billing_account}".format(billing_account=billing_account, ) - - @staticmethod - def parse_common_billing_account_path(path: str) -> Dict[str,str]: - """Parse a billing_account path into its component segments.""" - m = re.match(r"^billingAccounts/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_folder_path(folder: str, ) -> str: - """Returns a fully-qualified folder string.""" - return "folders/{folder}".format(folder=folder, ) - - @staticmethod - def parse_common_folder_path(path: str) -> Dict[str,str]: - """Parse a folder path into its component segments.""" - m = re.match(r"^folders/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_organization_path(organization: str, ) -> str: - """Returns a fully-qualified organization string.""" - return "organizations/{organization}".format(organization=organization, ) - - @staticmethod - def parse_common_organization_path(path: str) -> Dict[str,str]: - """Parse a organization path into its component segments.""" - m = re.match(r"^organizations/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_project_path(project: str, ) -> str: - """Returns a fully-qualified project string.""" - return "projects/{project}".format(project=project, ) - - @staticmethod - def parse_common_project_path(path: str) -> Dict[str,str]: - """Parse a project path into its component segments.""" - m = re.match(r"^projects/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_location_path(project: str, location: str, ) -> str: - """Returns a fully-qualified location string.""" - return "projects/{project}/locations/{location}".format(project=project, location=location, ) - - @staticmethod - def parse_common_location_path(path: str) -> Dict[str,str]: - """Parse a location path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)$", path) - return m.groupdict() if m else {} - - @classmethod - def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[client_options_lib.ClientOptions] = None): - """Return the API endpoint and client cert source for mutual TLS. - - The client cert source is determined in the following order: - (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the - client cert source is None. - (2) if `client_options.client_cert_source` is provided, use the provided one; if the - default client cert source exists, use the default one; otherwise the client cert - source is None. - - The API endpoint is determined in the following order: - (1) if `client_options.api_endpoint` if provided, use the provided one. - (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the - default mTLS endpoint; if the environment variable is "never", use the default API - endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise - use the default API endpoint. - - More details can be found at https://google.aip.dev/auth/4114. - - Args: - client_options (google.api_core.client_options.ClientOptions): Custom options for the - client. Only the `api_endpoint` and `client_cert_source` properties may be used - in this method. - - Returns: - Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the - client cert source to use. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If any errors happen. - """ - if client_options is None: - client_options = client_options_lib.ClientOptions() - use_client_cert = os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false") - use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") - if use_client_cert not in ("true", "false"): - raise ValueError("Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`") - if use_mtls_endpoint not in ("auto", "never", "always"): - raise MutualTLSChannelError("Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`") - - # Figure out the client cert source to use. - client_cert_source = None - if use_client_cert == "true": - if client_options.client_cert_source: - client_cert_source = client_options.client_cert_source - elif mtls.has_default_client_cert_source(): - client_cert_source = mtls.default_client_cert_source() - - # Figure out which api endpoint to use. - if client_options.api_endpoint is not None: - api_endpoint = client_options.api_endpoint - elif use_mtls_endpoint == "always" or (use_mtls_endpoint == "auto" and client_cert_source): - api_endpoint = cls.DEFAULT_MTLS_ENDPOINT - else: - api_endpoint = cls.DEFAULT_ENDPOINT - - return api_endpoint, client_cert_source - - def __init__(self, *, - credentials: Optional[ga_credentials.Credentials] = None, - transport: Optional[Union[str, ConversationsTransport]] = None, - client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the conversations 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, ConversationsTransport]): The - transport to use. If set to None, a transport is chosen - automatically. - client_options (Optional[Union[google.api_core.client_options.ClientOptions, dict]]): 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() - client_options = cast(client_options_lib.ClientOptions, client_options) - - api_endpoint, client_cert_source_func = self.get_mtls_endpoint_and_cert_source(client_options) - - api_key_value = getattr(client_options, "api_key", None) - if api_key_value and credentials: - raise ValueError("client_options.api_key and credentials are mutually exclusive") - - # 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, ConversationsTransport): - # transport is a ConversationsTransport instance. - if credentials or client_options.credentials_file or api_key_value: - 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: - import google.auth._default # type: ignore - - if api_key_value and hasattr(google.auth._default, "get_api_key_credentials"): - credentials = google.auth._default.get_api_key_credentials(api_key_value) - - Transport = type(self).get_transport_class(transport) - self._transport = Transport( - credentials=credentials, - credentials_file=client_options.credentials_file, - host=api_endpoint, - scopes=client_options.scopes, - client_cert_source_for_mtls=client_cert_source_func, - quota_project_id=client_options.quota_project_id, - client_info=client_info, - always_use_jwt_access=True, - api_audience=client_options.api_audience, - ) - - def create_conversation(self, - request: Optional[Union[gcd_conversation.CreateConversationRequest, dict]] = None, - *, - parent: Optional[str] = None, - conversation: Optional[gcd_conversation.Conversation] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gcd_conversation.Conversation: - r"""Creates a new conversation. Conversations are auto-completed - after 24 hours. - - Conversation Lifecycle: There are two stages during a - conversation: Automated Agent Stage and Assist Stage. - - For Automated Agent Stage, there will be a dialogflow agent - responding to user queries. - - For Assist Stage, there's no dialogflow agent responding to user - queries. But we will provide suggestions which are generated - from conversation. - - If - [Conversation.conversation_profile][google.cloud.dialogflow.v2beta1.Conversation.conversation_profile] - is configured for a dialogflow agent, conversation will start - from ``Automated Agent Stage``, otherwise, it will start from - ``Assist Stage``. And during ``Automated Agent Stage``, once an - [Intent][google.cloud.dialogflow.v2beta1.Intent] with - [Intent.live_agent_handoff][google.cloud.dialogflow.v2beta1.Intent.live_agent_handoff] - is triggered, conversation will transfer to Assist Stage. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import dialogflow_v2beta1 - - def sample_create_conversation(): - # Create a client - client = dialogflow_v2beta1.ConversationsClient() - - # Initialize request argument(s) - conversation = dialogflow_v2beta1.Conversation() - conversation.conversation_profile = "conversation_profile_value" - - request = dialogflow_v2beta1.CreateConversationRequest( - parent="parent_value", - conversation=conversation, - ) - - # Make the request - response = client.create_conversation(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.dialogflow_v2beta1.types.CreateConversationRequest, dict]): - The request object. The request message for - [Conversations.CreateConversation][google.cloud.dialogflow.v2beta1.Conversations.CreateConversation]. - parent (str): - Required. Resource identifier of the project creating - the conversation. Format: - ``projects//locations/``. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - conversation (google.cloud.dialogflow_v2beta1.types.Conversation): - Required. The conversation to create. - 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. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.dialogflow_v2beta1.types.Conversation: - Represents a conversation. - A conversation is an interaction between - an agent, including live agents and - Dialogflow agents, and a support - customer. Conversations can include - phone calls and text-based chat - sessions. - - """ - # Create or coerce a protobuf request object. - # Quick 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, conversation]) - 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_conversation.CreateConversationRequest. - # There's no risk of modifying the input as we've already verified - # 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: - request.conversation = conversation - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.create_conversation] - - # 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 list_conversations(self, - request: Optional[Union[conversation.ListConversationsRequest, dict]] = None, - *, - parent: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListConversationsPager: - r"""Returns the list of all conversations in the - specified project. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import dialogflow_v2beta1 - - def sample_list_conversations(): - # Create a client - client = dialogflow_v2beta1.ConversationsClient() - - # Initialize request argument(s) - request = dialogflow_v2beta1.ListConversationsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_conversations(request=request) - - # Handle the response - for response in page_result: - print(response) - - Args: - request (Union[google.cloud.dialogflow_v2beta1.types.ListConversationsRequest, dict]): - The request object. The request message for - [Conversations.ListConversations][google.cloud.dialogflow.v2beta1.Conversations.ListConversations]. - parent (str): - Required. The project from which to list all - conversation. Format: - ``projects//locations/``. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.dialogflow_v2beta1.services.conversations.pagers.ListConversationsPager: - The response message for - [Conversations.ListConversations][google.cloud.dialogflow.v2beta1.Conversations.ListConversations]. - - Iterating over this object will yield results and - resolve additional pages automatically. - - """ - # Create or coerce a protobuf request object. - # Quick 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 conversation.ListConversationsRequest. - # There's no risk of modifying the input as we've already verified - # 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 - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.list_conversations] - - # 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.ListConversationsPager( - method=rpc, - request=request, - response=response, - metadata=metadata, - ) - - # Done; return the response. - return response - - def get_conversation(self, - request: Optional[Union[conversation.GetConversationRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> conversation.Conversation: - r"""Retrieves the specific conversation. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import dialogflow_v2beta1 - - def sample_get_conversation(): - # Create a client - client = dialogflow_v2beta1.ConversationsClient() - - # Initialize request argument(s) - request = dialogflow_v2beta1.GetConversationRequest( - name="name_value", - ) - - # Make the request - response = client.get_conversation(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.dialogflow_v2beta1.types.GetConversationRequest, dict]): - The request object. The request message for - [Conversations.GetConversation][google.cloud.dialogflow.v2beta1.Conversations.GetConversation]. - name (str): - Required. The name of the conversation. Format: - ``projects//locations//conversations/``. - - 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.Conversation: - Represents a conversation. - A conversation is an interaction between - an agent, including live agents and - Dialogflow agents, and a support - customer. Conversations can include - phone calls and text-based chat - sessions. - - """ - # Create or coerce a protobuf request object. - # Quick 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 conversation.GetConversationRequest. - # There's no risk of modifying the input as we've already verified - # 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 - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.get_conversation] - - # 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 complete_conversation(self, - request: Optional[Union[conversation.CompleteConversationRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> conversation.Conversation: - r"""Completes the specified conversation. Finished - conversations are purged from the database after 30 - days. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import dialogflow_v2beta1 - - def sample_complete_conversation(): - # Create a client - client = dialogflow_v2beta1.ConversationsClient() - - # Initialize request argument(s) - request = dialogflow_v2beta1.CompleteConversationRequest( - name="name_value", - ) - - # Make the request - response = client.complete_conversation(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.dialogflow_v2beta1.types.CompleteConversationRequest, dict]): - The request object. The request message for - [Conversations.CompleteConversation][google.cloud.dialogflow.v2beta1.Conversations.CompleteConversation]. - name (str): - Required. Resource identifier of the conversation to - close. Format: - ``projects//locations//conversations/``. - - 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.Conversation: - Represents a conversation. - A conversation is an interaction between - an agent, including live agents and - Dialogflow agents, and a support - customer. Conversations can include - phone calls and text-based chat - sessions. - - """ - # Create or coerce a protobuf request object. - # Quick 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 conversation.CompleteConversationRequest. - # There's no risk of modifying the input as we've already verified - # 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 - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.complete_conversation] - - # 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 batch_create_messages(self, - request: Optional[Union[conversation.BatchCreateMessagesRequest, dict]] = None, - *, - parent: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> conversation.BatchCreateMessagesResponse: - r"""Batch ingests messages to conversation. Customers can - use this RPC to ingest historical messages to - conversation. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import dialogflow_v2beta1 - - def sample_batch_create_messages(): - # Create a client - client = dialogflow_v2beta1.ConversationsClient() - - # Initialize request argument(s) - requests = dialogflow_v2beta1.CreateMessageRequest() - requests.parent = "parent_value" - requests.message.content = "content_value" - - request = dialogflow_v2beta1.BatchCreateMessagesRequest( - parent="parent_value", - requests=requests, - ) - - # Make the request - response = client.batch_create_messages(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.dialogflow_v2beta1.types.BatchCreateMessagesRequest, dict]): - The request object. The request message for - [Conversations.BatchCreateMessagesRequest][]. - parent (str): - Required. Resource identifier of the conversation to - create message. Format: - ``projects//locations//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. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.dialogflow_v2beta1.types.BatchCreateMessagesResponse: - The request message for - [Conversations.BatchCreateMessagesResponse][]. - - """ - # Create or coerce a protobuf request object. - # Quick 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 conversation.BatchCreateMessagesRequest. - # There's no risk of modifying the input as we've already verified - # 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 - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.batch_create_messages] - - # 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 list_messages(self, - request: Optional[Union[conversation.ListMessagesRequest, dict]] = None, - *, - parent: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListMessagesPager: - r"""Lists messages that belong to a given conversation. ``messages`` - are ordered by ``create_time`` in descending order. To fetch - updates without duplication, send request with filter - ``create_time_epoch_microseconds > [first item's create_time of previous request]`` - and empty page_token. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import dialogflow_v2beta1 - - def sample_list_messages(): - # Create a client - client = dialogflow_v2beta1.ConversationsClient() - - # Initialize request argument(s) - request = dialogflow_v2beta1.ListMessagesRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_messages(request=request) - - # Handle the response - for response in page_result: - print(response) - - Args: - request (Union[google.cloud.dialogflow_v2beta1.types.ListMessagesRequest, dict]): - The request object. The request message for - [Conversations.ListMessages][google.cloud.dialogflow.v2beta1.Conversations.ListMessages]. - parent (str): - Required. The name of the conversation to list messages - for. Format: - ``projects//locations//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. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.dialogflow_v2beta1.services.conversations.pagers.ListMessagesPager: - The response message for - [Conversations.ListMessages][google.cloud.dialogflow.v2beta1.Conversations.ListMessages]. - - Iterating over this object will yield results and - resolve additional pages automatically. - - """ - # Create or coerce a protobuf request object. - # Quick 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 conversation.ListMessagesRequest. - # There's no risk of modifying the input as we've already verified - # 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 - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.list_messages] - - # 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.ListMessagesPager( - method=rpc, - request=request, - response=response, - metadata=metadata, - ) - - # Done; return the response. - return response - - def suggest_conversation_summary(self, - request: Optional[Union[gcd_conversation.SuggestConversationSummaryRequest, dict]] = None, - *, - conversation: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gcd_conversation.SuggestConversationSummaryResponse: - r"""Suggest summary for a conversation based on specific - historical messages. The range of the messages to be - used for summary can be specified in the request. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import dialogflow_v2beta1 - - def sample_suggest_conversation_summary(): - # Create a client - client = dialogflow_v2beta1.ConversationsClient() - - # Initialize request argument(s) - request = dialogflow_v2beta1.SuggestConversationSummaryRequest( - conversation="conversation_value", - ) - - # Make the request - response = client.suggest_conversation_summary(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.dialogflow_v2beta1.types.SuggestConversationSummaryRequest, dict]): - The request object. The request message for - [Conversations.SuggestConversationSummary][google.cloud.dialogflow.v2beta1.Conversations.SuggestConversationSummary]. - conversation (str): - Required. The conversation to fetch suggestion for. - Format: - ``projects//locations//conversations/``. - - 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. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.dialogflow_v2beta1.types.SuggestConversationSummaryResponse: - The response message for - [Conversations.SuggestConversationSummary][google.cloud.dialogflow.v2beta1.Conversations.SuggestConversationSummary]. - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([conversation]) - 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_conversation.SuggestConversationSummaryRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, gcd_conversation.SuggestConversationSummaryRequest): - request = gcd_conversation.SuggestConversationSummaryRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if conversation is not None: - request.conversation = conversation - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.suggest_conversation_summary] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("conversation", request.conversation), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def __enter__(self) -> "ConversationsClient": - return self - - def __exit__(self, type, value, traceback): - """Releases underlying transport's resources. - - .. warning:: - ONLY use as a context manager if the transport is NOT shared - with other clients! Exiting the with block will CLOSE the transport - and may cause errors in other clients! - """ - self.transport.close() - - def list_operations( - self, - request: Optional[operations_pb2.ListOperationsRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operations_pb2.ListOperationsResponse: - r"""Lists operations that match the specified filter in the request. - - Args: - request (:class:`~.operations_pb2.ListOperationsRequest`): - The request object. Request message for - `ListOperations` method. - 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: - ~.operations_pb2.ListOperationsResponse: - Response message for ``ListOperations`` method. - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = operations_pb2.ListOperationsRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._transport.list_operations, - 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 = rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - def get_operation( - self, - request: Optional[operations_pb2.GetOperationRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operations_pb2.Operation: - r"""Gets the latest state of a long-running operation. - - Args: - request (:class:`~.operations_pb2.GetOperationRequest`): - The request object. Request message for - `GetOperation` method. - 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: - ~.operations_pb2.Operation: - An ``Operation`` object. - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = operations_pb2.GetOperationRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._transport.get_operation, - 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 = rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - def cancel_operation( - self, - request: Optional[operations_pb2.CancelOperationRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> None: - r"""Starts asynchronous cancellation on a long-running operation. - - The server makes a best effort to cancel the operation, but success - is not guaranteed. If the server doesn't support this method, it returns - `google.rpc.Code.UNIMPLEMENTED`. - - Args: - request (:class:`~.operations_pb2.CancelOperationRequest`): - The request object. Request message for - `CancelOperation` method. - 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: - None - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = operations_pb2.CancelOperationRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._transport.cancel_operation, - 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. - rpc(request, retry=retry, timeout=timeout, metadata=metadata,) - - def get_location( - self, - request: Optional[locations_pb2.GetLocationRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> locations_pb2.Location: - r"""Gets information about a location. - - Args: - request (:class:`~.location_pb2.GetLocationRequest`): - The request object. Request message for - `GetLocation` method. - 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: - ~.location_pb2.Location: - Location object. - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = locations_pb2.GetLocationRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._transport.get_location, - 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 = rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - def list_locations( - self, - request: Optional[locations_pb2.ListLocationsRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> locations_pb2.ListLocationsResponse: - r"""Lists information about the supported locations for this service. - - Args: - request (:class:`~.location_pb2.ListLocationsRequest`): - The request object. Request message for - `ListLocations` method. - 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: - ~.location_pb2.ListLocationsResponse: - Response message for ``ListLocations`` method. - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = locations_pb2.ListLocationsRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._transport.list_locations, - 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 = rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) - - -__all__ = ( - "ConversationsClient", -) diff --git a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/conversations/pagers.py b/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/conversations/pagers.py deleted file mode 100644 index 72af827f1..000000000 --- a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/conversations/pagers.py +++ /dev/null @@ -1,261 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from typing import Any, AsyncIterator, Awaitable, Callable, Sequence, Tuple, Optional, Iterator - -from google.cloud.dialogflow_v2beta1.types import conversation -from google.cloud.dialogflow_v2beta1.types import participant - - -class ListConversationsPager: - """A pager for iterating through ``list_conversations`` requests. - - This class thinly wraps an initial - :class:`google.cloud.dialogflow_v2beta1.types.ListConversationsResponse` object, and - provides an ``__iter__`` method to iterate through its - ``conversations`` field. - - If there are more pages, the ``__iter__`` method will make additional - ``ListConversations`` requests and continue to iterate - through the ``conversations`` field on the - corresponding responses. - - All the usual :class:`google.cloud.dialogflow_v2beta1.types.ListConversationsResponse` - 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[..., conversation.ListConversationsResponse], - request: conversation.ListConversationsRequest, - response: conversation.ListConversationsResponse, - *, - 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.ListConversationsRequest): - The initial request object. - response (google.cloud.dialogflow_v2beta1.types.ListConversationsResponse): - 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 = conversation.ListConversationsRequest(request) - self._response = response - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - def pages(self) -> Iterator[conversation.ListConversationsResponse]: - yield self._response - while self._response.next_page_token: - self._request.page_token = self._response.next_page_token - self._response = self._method(self._request, metadata=self._metadata) - yield self._response - - def __iter__(self) -> Iterator[conversation.Conversation]: - for page in self.pages: - yield from page.conversations - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListConversationsAsyncPager: - """A pager for iterating through ``list_conversations`` requests. - - This class thinly wraps an initial - :class:`google.cloud.dialogflow_v2beta1.types.ListConversationsResponse` object, and - provides an ``__aiter__`` method to iterate through its - ``conversations`` field. - - If there are more pages, the ``__aiter__`` method will make additional - ``ListConversations`` requests and continue to iterate - through the ``conversations`` field on the - corresponding responses. - - All the usual :class:`google.cloud.dialogflow_v2beta1.types.ListConversationsResponse` - 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[conversation.ListConversationsResponse]], - request: conversation.ListConversationsRequest, - response: conversation.ListConversationsResponse, - *, - metadata: Sequence[Tuple[str, str]] = ()): - """Instantiates the pager. - - Args: - method (Callable): The method that was originally called, and - which instantiated this pager. - request (google.cloud.dialogflow_v2beta1.types.ListConversationsRequest): - The initial request object. - response (google.cloud.dialogflow_v2beta1.types.ListConversationsResponse): - 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 = conversation.ListConversationsRequest(request) - self._response = response - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - async def pages(self) -> AsyncIterator[conversation.ListConversationsResponse]: - yield self._response - while self._response.next_page_token: - self._request.page_token = self._response.next_page_token - self._response = await self._method(self._request, metadata=self._metadata) - yield self._response - def __aiter__(self) -> AsyncIterator[conversation.Conversation]: - async def async_generator(): - async for page in self.pages: - for response in page.conversations: - yield response - - return async_generator() - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListMessagesPager: - """A pager for iterating through ``list_messages`` requests. - - This class thinly wraps an initial - :class:`google.cloud.dialogflow_v2beta1.types.ListMessagesResponse` object, and - provides an ``__iter__`` method to iterate through its - ``messages`` field. - - If there are more pages, the ``__iter__`` method will make additional - ``ListMessages`` requests and continue to iterate - through the ``messages`` field on the - corresponding responses. - - All the usual :class:`google.cloud.dialogflow_v2beta1.types.ListMessagesResponse` - 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[..., conversation.ListMessagesResponse], - request: conversation.ListMessagesRequest, - response: conversation.ListMessagesResponse, - *, - 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.ListMessagesRequest): - The initial request object. - response (google.cloud.dialogflow_v2beta1.types.ListMessagesResponse): - 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 = conversation.ListMessagesRequest(request) - self._response = response - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - def pages(self) -> Iterator[conversation.ListMessagesResponse]: - yield self._response - while self._response.next_page_token: - self._request.page_token = self._response.next_page_token - self._response = self._method(self._request, metadata=self._metadata) - yield self._response - - def __iter__(self) -> Iterator[participant.Message]: - for page in self.pages: - yield from page.messages - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListMessagesAsyncPager: - """A pager for iterating through ``list_messages`` requests. - - This class thinly wraps an initial - :class:`google.cloud.dialogflow_v2beta1.types.ListMessagesResponse` object, and - provides an ``__aiter__`` method to iterate through its - ``messages`` field. - - If there are more pages, the ``__aiter__`` method will make additional - ``ListMessages`` requests and continue to iterate - through the ``messages`` field on the - corresponding responses. - - All the usual :class:`google.cloud.dialogflow_v2beta1.types.ListMessagesResponse` - 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[conversation.ListMessagesResponse]], - request: conversation.ListMessagesRequest, - response: conversation.ListMessagesResponse, - *, - metadata: Sequence[Tuple[str, str]] = ()): - """Instantiates the pager. - - Args: - method (Callable): The method that was originally called, and - which instantiated this pager. - request (google.cloud.dialogflow_v2beta1.types.ListMessagesRequest): - The initial request object. - response (google.cloud.dialogflow_v2beta1.types.ListMessagesResponse): - 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 = conversation.ListMessagesRequest(request) - self._response = response - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - async def pages(self) -> AsyncIterator[conversation.ListMessagesResponse]: - yield self._response - while self._response.next_page_token: - self._request.page_token = self._response.next_page_token - self._response = await self._method(self._request, metadata=self._metadata) - yield self._response - def __aiter__(self) -> AsyncIterator[participant.Message]: - async def async_generator(): - async for page in self.pages: - for response in page.messages: - yield response - - return async_generator() - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) diff --git a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/conversations/transports/__init__.py b/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/conversations/transports/__init__.py deleted file mode 100644 index c16106880..000000000 --- a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/conversations/transports/__init__.py +++ /dev/null @@ -1,38 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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 ConversationsTransport -from .grpc import ConversationsGrpcTransport -from .grpc_asyncio import ConversationsGrpcAsyncIOTransport -from .rest import ConversationsRestTransport -from .rest import ConversationsRestInterceptor - - -# Compile a registry of transports. -_transport_registry = OrderedDict() # type: Dict[str, Type[ConversationsTransport]] -_transport_registry['grpc'] = ConversationsGrpcTransport -_transport_registry['grpc_asyncio'] = ConversationsGrpcAsyncIOTransport -_transport_registry['rest'] = ConversationsRestTransport - -__all__ = ( - 'ConversationsTransport', - 'ConversationsGrpcTransport', - 'ConversationsGrpcAsyncIOTransport', - 'ConversationsRestTransport', - 'ConversationsRestInterceptor', -) diff --git a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/conversations/transports/base.py b/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/conversations/transports/base.py deleted file mode 100644 index 8fc1b4f8c..000000000 --- a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/conversations/transports/base.py +++ /dev/null @@ -1,279 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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 - -from google.cloud.dialogflow_v2beta1 import gapic_version as package_version - -import google.auth # type: ignore -import google.api_core -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import retry as retries -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 conversation -from google.cloud.dialogflow_v2beta1.types import conversation as gcd_conversation -from google.cloud.location import locations_pb2 # type: ignore -from google.longrunning import operations_pb2 - -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) - - -class ConversationsTransport(abc.ABC): - """Abstract transport class for Conversations.""" - - 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: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - api_audience: Optional[str] = None, - **kwargs, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. - scopes (Optional[Sequence[str]]): A list of scopes. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - """ - - scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} - - # Save the scopes. - self._scopes = scopes - - # If no credentials are provided, then determine the appropriate - # defaults. - if credentials and credentials_file: - raise core_exceptions.DuplicateCredentialArgs("'credentials_file' and 'credentials' are mutually exclusive") - - if credentials_file is not None: - credentials, _ = google.auth.load_credentials_from_file( - credentials_file, - **scopes_kwargs, - quota_project_id=quota_project_id - ) - elif credentials is None: - credentials, _ = google.auth.default(**scopes_kwargs, quota_project_id=quota_project_id) - # Don't apply audience if the credentials file passed from user. - if hasattr(credentials, "with_gdch_audience"): - credentials = credentials.with_gdch_audience(api_audience if api_audience else host) - - # If the credentials are service account credentials, then always try to use self signed JWT. - if always_use_jwt_access and isinstance(credentials, service_account.Credentials) and hasattr(service_account.Credentials, "with_always_use_jwt_access"): - credentials = credentials.with_always_use_jwt_access(True) - - # Save the credentials. - self._credentials = credentials - - # Save the hostname. Default to port 443 (HTTPS) if none is specified. - if ':' not in host: - host += ':443' - self._host = host - - def _prep_wrapped_messages(self, client_info): - # Precompute the wrapped methods. - self._wrapped_methods = { - self.create_conversation: gapic_v1.method.wrap_method( - self.create_conversation, - default_timeout=None, - client_info=client_info, - ), - self.list_conversations: gapic_v1.method.wrap_method( - self.list_conversations, - default_timeout=None, - client_info=client_info, - ), - self.get_conversation: gapic_v1.method.wrap_method( - self.get_conversation, - default_timeout=None, - client_info=client_info, - ), - self.complete_conversation: gapic_v1.method.wrap_method( - self.complete_conversation, - default_timeout=None, - client_info=client_info, - ), - self.batch_create_messages: gapic_v1.method.wrap_method( - self.batch_create_messages, - default_timeout=None, - client_info=client_info, - ), - self.list_messages: gapic_v1.method.wrap_method( - self.list_messages, - default_timeout=None, - client_info=client_info, - ), - self.suggest_conversation_summary: gapic_v1.method.wrap_method( - self.suggest_conversation_summary, - default_timeout=None, - client_info=client_info, - ), - } - - def close(self): - """Closes resources associated with the transport. - - .. warning:: - Only call this method if the transport is NOT shared - with other clients - this may cause errors in other clients! - """ - raise NotImplementedError() - - @property - def create_conversation(self) -> Callable[ - [gcd_conversation.CreateConversationRequest], - Union[ - gcd_conversation.Conversation, - Awaitable[gcd_conversation.Conversation] - ]]: - raise NotImplementedError() - - @property - def list_conversations(self) -> Callable[ - [conversation.ListConversationsRequest], - Union[ - conversation.ListConversationsResponse, - Awaitable[conversation.ListConversationsResponse] - ]]: - raise NotImplementedError() - - @property - def get_conversation(self) -> Callable[ - [conversation.GetConversationRequest], - Union[ - conversation.Conversation, - Awaitable[conversation.Conversation] - ]]: - raise NotImplementedError() - - @property - def complete_conversation(self) -> Callable[ - [conversation.CompleteConversationRequest], - Union[ - conversation.Conversation, - Awaitable[conversation.Conversation] - ]]: - raise NotImplementedError() - - @property - def batch_create_messages(self) -> Callable[ - [conversation.BatchCreateMessagesRequest], - Union[ - conversation.BatchCreateMessagesResponse, - Awaitable[conversation.BatchCreateMessagesResponse] - ]]: - raise NotImplementedError() - - @property - def list_messages(self) -> Callable[ - [conversation.ListMessagesRequest], - Union[ - conversation.ListMessagesResponse, - Awaitable[conversation.ListMessagesResponse] - ]]: - raise NotImplementedError() - - @property - def suggest_conversation_summary(self) -> Callable[ - [gcd_conversation.SuggestConversationSummaryRequest], - Union[ - gcd_conversation.SuggestConversationSummaryResponse, - Awaitable[gcd_conversation.SuggestConversationSummaryResponse] - ]]: - raise NotImplementedError() - - @property - def list_operations( - self, - ) -> Callable[ - [operations_pb2.ListOperationsRequest], - Union[operations_pb2.ListOperationsResponse, Awaitable[operations_pb2.ListOperationsResponse]], - ]: - raise NotImplementedError() - - @property - def get_operation( - self, - ) -> Callable[ - [operations_pb2.GetOperationRequest], - Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], - ]: - raise NotImplementedError() - - @property - def cancel_operation( - self, - ) -> Callable[ - [operations_pb2.CancelOperationRequest], - None, - ]: - raise NotImplementedError() - - @property - def get_location(self, - ) -> Callable[ - [locations_pb2.GetLocationRequest], - Union[locations_pb2.Location, Awaitable[locations_pb2.Location]], - ]: - raise NotImplementedError() - - @property - def list_locations(self, - ) -> Callable[ - [locations_pb2.ListLocationsRequest], - Union[locations_pb2.ListLocationsResponse, Awaitable[locations_pb2.ListLocationsResponse]], - ]: - raise NotImplementedError() - - @property - def kind(self) -> str: - raise NotImplementedError() - - -__all__ = ( - 'ConversationsTransport', -) diff --git a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/conversations/transports/grpc.py b/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/conversations/transports/grpc.py deleted file mode 100644 index 560cfaac6..000000000 --- a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/conversations/transports/grpc.py +++ /dev/null @@ -1,545 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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 -from google.api_core import gapic_v1 -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 google.cloud.location import locations_pb2 # type: ignore -from google.longrunning import operations_pb2 -from .base import ConversationsTransport, DEFAULT_CLIENT_INFO - - -class ConversationsGrpcTransport(ConversationsTransport): - """gRPC backend transport for Conversations. - - Service for managing - [Conversations][google.cloud.dialogflow.v2beta1.Conversation]. - - 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: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - channel: Optional[grpc.Channel] = None, - api_mtls_endpoint: Optional[str] = None, - client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, - ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, - client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - api_audience: Optional[str] = None, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - This argument is ignored if ``channel`` is provided. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional(Sequence[str])): A list of scopes. This argument is - ignored if ``channel`` is provided. - channel (Optional[grpc.Channel]): A ``Channel`` instance through - which to make calls. - api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. - If provided, it overrides the ``host`` argument and tries to create - a mutual TLS channel with client SSL credentials from - ``client_cert_source`` or application default SSL credentials. - client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): - Deprecated. A callback to provide client SSL certificate bytes and - private key bytes, both in PEM format. It is ignored if - ``api_mtls_endpoint`` is None. - ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials - for the grpc channel. It is ignored if ``channel`` is provided. - client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): - A callback to provide client certificate bytes and private key bytes, - both in PEM format. It is used to configure a mutual TLS channel. It is - ignored if ``channel`` or ``ssl_channel_credentials`` is provided. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport - creation failed for any reason. - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - self._grpc_channel = None - self._ssl_channel_credentials = ssl_channel_credentials - self._stubs: Dict[str, Callable] = {} - - if api_mtls_endpoint: - warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) - if client_cert_source: - warnings.warn("client_cert_source is deprecated", DeprecationWarning) - - if channel: - # Ignore credentials if a channel was passed. - credentials = False - # If a channel was explicitly provided, set it. - self._grpc_channel = channel - self._ssl_channel_credentials = None - - else: - if api_mtls_endpoint: - host = api_mtls_endpoint - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - self._ssl_channel_credentials = SslCredentials().ssl_credentials - - else: - if client_cert_source_for_mtls and not ssl_channel_credentials: - cert, key = client_cert_source_for_mtls() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - - # The base transport sets the host, credentials and scopes - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes, - quota_project_id=quota_project_id, - client_info=client_info, - always_use_jwt_access=always_use_jwt_access, - api_audience=api_audience, - ) - - if not self._grpc_channel: - self._grpc_channel = type(self).create_channel( - self._host, - # use the credentials which are saved - credentials=self._credentials, - # Set ``credentials_file`` to ``None`` here as - # the credentials that we saved earlier should be used. - credentials_file=None, - 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: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - **kwargs) -> grpc.Channel: - """Create and return a gRPC channel object. - Args: - host (Optional[str]): The host for the channel to use. - credentials (Optional[~.Credentials]): The - authorization credentials to attach to requests. These - credentials identify this application to the service. If - none are specified, the client will attempt to ascertain - the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - kwargs (Optional[dict]): Keyword arguments, which are passed to the - channel creation. - Returns: - grpc.Channel: A gRPC channel object. - - Raises: - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - - return grpc_helpers.create_channel( - host, - credentials=credentials, - credentials_file=credentials_file, - quota_project_id=quota_project_id, - default_scopes=cls.AUTH_SCOPES, - scopes=scopes, - default_host=cls.DEFAULT_HOST, - **kwargs - ) - - @property - def grpc_channel(self) -> grpc.Channel: - """Return the channel designed to connect to this service. - """ - return self._grpc_channel - - @property - def create_conversation(self) -> Callable[ - [gcd_conversation.CreateConversationRequest], - gcd_conversation.Conversation]: - r"""Return a callable for the create conversation method over gRPC. - - Creates a new conversation. Conversations are auto-completed - after 24 hours. - - Conversation Lifecycle: There are two stages during a - conversation: Automated Agent Stage and Assist Stage. - - For Automated Agent Stage, there will be a dialogflow agent - responding to user queries. - - For Assist Stage, there's no dialogflow agent responding to user - queries. But we will provide suggestions which are generated - from conversation. - - If - [Conversation.conversation_profile][google.cloud.dialogflow.v2beta1.Conversation.conversation_profile] - is configured for a dialogflow agent, conversation will start - from ``Automated Agent Stage``, otherwise, it will start from - ``Assist Stage``. And during ``Automated Agent Stage``, once an - [Intent][google.cloud.dialogflow.v2beta1.Intent] with - [Intent.live_agent_handoff][google.cloud.dialogflow.v2beta1.Intent.live_agent_handoff] - is triggered, conversation will transfer to Assist Stage. - - Returns: - Callable[[~.CreateConversationRequest], - ~.Conversation]: - 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_conversation' not in self._stubs: - self._stubs['create_conversation'] = self.grpc_channel.unary_unary( - '/google.cloud.dialogflow.v2beta1.Conversations/CreateConversation', - request_serializer=gcd_conversation.CreateConversationRequest.serialize, - response_deserializer=gcd_conversation.Conversation.deserialize, - ) - return self._stubs['create_conversation'] - - @property - def list_conversations(self) -> Callable[ - [conversation.ListConversationsRequest], - conversation.ListConversationsResponse]: - r"""Return a callable for the list conversations method over gRPC. - - Returns the list of all conversations in the - specified project. - - Returns: - Callable[[~.ListConversationsRequest], - ~.ListConversationsResponse]: - 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_conversations' not in self._stubs: - self._stubs['list_conversations'] = self.grpc_channel.unary_unary( - '/google.cloud.dialogflow.v2beta1.Conversations/ListConversations', - request_serializer=conversation.ListConversationsRequest.serialize, - response_deserializer=conversation.ListConversationsResponse.deserialize, - ) - return self._stubs['list_conversations'] - - @property - def get_conversation(self) -> Callable[ - [conversation.GetConversationRequest], - conversation.Conversation]: - r"""Return a callable for the get conversation method over gRPC. - - Retrieves the specific conversation. - - Returns: - Callable[[~.GetConversationRequest], - ~.Conversation]: - 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_conversation' not in self._stubs: - self._stubs['get_conversation'] = self.grpc_channel.unary_unary( - '/google.cloud.dialogflow.v2beta1.Conversations/GetConversation', - request_serializer=conversation.GetConversationRequest.serialize, - response_deserializer=conversation.Conversation.deserialize, - ) - return self._stubs['get_conversation'] - - @property - def complete_conversation(self) -> Callable[ - [conversation.CompleteConversationRequest], - conversation.Conversation]: - r"""Return a callable for the complete conversation method over gRPC. - - Completes the specified conversation. Finished - conversations are purged from the database after 30 - days. - - Returns: - Callable[[~.CompleteConversationRequest], - ~.Conversation]: - 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 'complete_conversation' not in self._stubs: - self._stubs['complete_conversation'] = self.grpc_channel.unary_unary( - '/google.cloud.dialogflow.v2beta1.Conversations/CompleteConversation', - request_serializer=conversation.CompleteConversationRequest.serialize, - response_deserializer=conversation.Conversation.deserialize, - ) - return self._stubs['complete_conversation'] - - @property - def batch_create_messages(self) -> Callable[ - [conversation.BatchCreateMessagesRequest], - conversation.BatchCreateMessagesResponse]: - r"""Return a callable for the batch create messages method over gRPC. - - Batch ingests messages to conversation. Customers can - use this RPC to ingest historical messages to - conversation. - - Returns: - Callable[[~.BatchCreateMessagesRequest], - ~.BatchCreateMessagesResponse]: - 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 'batch_create_messages' not in self._stubs: - self._stubs['batch_create_messages'] = self.grpc_channel.unary_unary( - '/google.cloud.dialogflow.v2beta1.Conversations/BatchCreateMessages', - request_serializer=conversation.BatchCreateMessagesRequest.serialize, - response_deserializer=conversation.BatchCreateMessagesResponse.deserialize, - ) - return self._stubs['batch_create_messages'] - - @property - def list_messages(self) -> Callable[ - [conversation.ListMessagesRequest], - conversation.ListMessagesResponse]: - r"""Return a callable for the list messages method over gRPC. - - Lists messages that belong to a given conversation. ``messages`` - are ordered by ``create_time`` in descending order. To fetch - updates without duplication, send request with filter - ``create_time_epoch_microseconds > [first item's create_time of previous request]`` - and empty page_token. - - Returns: - Callable[[~.ListMessagesRequest], - ~.ListMessagesResponse]: - 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_messages' not in self._stubs: - self._stubs['list_messages'] = self.grpc_channel.unary_unary( - '/google.cloud.dialogflow.v2beta1.Conversations/ListMessages', - request_serializer=conversation.ListMessagesRequest.serialize, - response_deserializer=conversation.ListMessagesResponse.deserialize, - ) - return self._stubs['list_messages'] - - @property - def suggest_conversation_summary(self) -> Callable[ - [gcd_conversation.SuggestConversationSummaryRequest], - gcd_conversation.SuggestConversationSummaryResponse]: - r"""Return a callable for the suggest conversation summary method over gRPC. - - Suggest summary for a conversation based on specific - historical messages. The range of the messages to be - used for summary can be specified in the request. - - Returns: - Callable[[~.SuggestConversationSummaryRequest], - ~.SuggestConversationSummaryResponse]: - 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 'suggest_conversation_summary' not in self._stubs: - self._stubs['suggest_conversation_summary'] = self.grpc_channel.unary_unary( - '/google.cloud.dialogflow.v2beta1.Conversations/SuggestConversationSummary', - request_serializer=gcd_conversation.SuggestConversationSummaryRequest.serialize, - response_deserializer=gcd_conversation.SuggestConversationSummaryResponse.deserialize, - ) - return self._stubs['suggest_conversation_summary'] - - def close(self): - self.grpc_channel.close() - - @property - def cancel_operation( - self, - ) -> Callable[[operations_pb2.CancelOperationRequest], None]: - r"""Return a callable for the cancel_operation method over gRPC. - """ - # 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 "cancel_operation" not in self._stubs: - self._stubs["cancel_operation"] = self.grpc_channel.unary_unary( - "/google.longrunning.Operations/CancelOperation", - request_serializer=operations_pb2.CancelOperationRequest.SerializeToString, - response_deserializer=None, - ) - return self._stubs["cancel_operation"] - - @property - def get_operation( - self, - ) -> Callable[[operations_pb2.GetOperationRequest], operations_pb2.Operation]: - r"""Return a callable for the get_operation method over gRPC. - """ - # 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_operation" not in self._stubs: - self._stubs["get_operation"] = self.grpc_channel.unary_unary( - "/google.longrunning.Operations/GetOperation", - request_serializer=operations_pb2.GetOperationRequest.SerializeToString, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs["get_operation"] - - @property - def list_operations( - self, - ) -> Callable[[operations_pb2.ListOperationsRequest], operations_pb2.ListOperationsResponse]: - r"""Return a callable for the list_operations method over gRPC. - """ - # 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_operations" not in self._stubs: - self._stubs["list_operations"] = self.grpc_channel.unary_unary( - "/google.longrunning.Operations/ListOperations", - request_serializer=operations_pb2.ListOperationsRequest.SerializeToString, - response_deserializer=operations_pb2.ListOperationsResponse.FromString, - ) - return self._stubs["list_operations"] - - @property - def list_locations( - self, - ) -> Callable[[locations_pb2.ListLocationsRequest], locations_pb2.ListLocationsResponse]: - r"""Return a callable for the list locations method over gRPC. - """ - # 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_locations" not in self._stubs: - self._stubs["list_locations"] = self.grpc_channel.unary_unary( - "/google.cloud.location.Locations/ListLocations", - request_serializer=locations_pb2.ListLocationsRequest.SerializeToString, - response_deserializer=locations_pb2.ListLocationsResponse.FromString, - ) - return self._stubs["list_locations"] - - @property - def get_location( - self, - ) -> Callable[[locations_pb2.GetLocationRequest], locations_pb2.Location]: - r"""Return a callable for the list locations method over gRPC. - """ - # 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_location" not in self._stubs: - self._stubs["get_location"] = self.grpc_channel.unary_unary( - "/google.cloud.location.Locations/GetLocation", - request_serializer=locations_pb2.GetLocationRequest.SerializeToString, - response_deserializer=locations_pb2.Location.FromString, - ) - return self._stubs["get_location"] - - @property - def kind(self) -> str: - return "grpc" - - -__all__ = ( - 'ConversationsGrpcTransport', -) diff --git a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/conversations/transports/grpc_asyncio.py b/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/conversations/transports/grpc_asyncio.py deleted file mode 100644 index cf2d58a07..000000000 --- a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/conversations/transports/grpc_asyncio.py +++ /dev/null @@ -1,544 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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 -from google.api_core import grpc_helpers_async -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore - -import grpc # type: ignore -from grpc.experimental import aio # type: ignore - -from google.cloud.dialogflow_v2beta1.types import conversation -from google.cloud.dialogflow_v2beta1.types import conversation as gcd_conversation -from google.cloud.location import locations_pb2 # type: ignore -from google.longrunning import operations_pb2 -from .base import ConversationsTransport, DEFAULT_CLIENT_INFO -from .grpc import ConversationsGrpcTransport - - -class ConversationsGrpcAsyncIOTransport(ConversationsTransport): - """gRPC AsyncIO backend transport for Conversations. - - Service for managing - [Conversations][google.cloud.dialogflow.v2beta1.Conversation]. - - 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: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - **kwargs) -> aio.Channel: - """Create and return a gRPC AsyncIO channel object. - Args: - host (Optional[str]): The host for the channel to use. - credentials (Optional[~.Credentials]): The - authorization credentials to attach to requests. These - credentials identify this application to the service. If - none are specified, the client will attempt to ascertain - the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - kwargs (Optional[dict]): Keyword arguments, which are passed to the - channel creation. - Returns: - aio.Channel: A gRPC AsyncIO channel object. - """ - - return grpc_helpers_async.create_channel( - host, - credentials=credentials, - credentials_file=credentials_file, - quota_project_id=quota_project_id, - default_scopes=cls.AUTH_SCOPES, - scopes=scopes, - default_host=cls.DEFAULT_HOST, - **kwargs - ) - - def __init__(self, *, - host: str = 'dialogflow.googleapis.com', - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - channel: Optional[aio.Channel] = None, - api_mtls_endpoint: Optional[str] = None, - client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, - ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, - client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - api_audience: Optional[str] = None, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - This argument is ignored if ``channel`` is provided. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - channel (Optional[aio.Channel]): A ``Channel`` instance through - which to make calls. - api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. - If provided, it overrides the ``host`` argument and tries to create - a mutual TLS channel with client SSL credentials from - ``client_cert_source`` or application default SSL credentials. - client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): - Deprecated. A callback to provide client SSL certificate bytes and - private key bytes, both in PEM format. It is ignored if - ``api_mtls_endpoint`` is None. - ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials - for the grpc channel. It is ignored if ``channel`` is provided. - client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): - A callback to provide client certificate bytes and private key bytes, - both in PEM format. It is used to configure a mutual TLS channel. It is - ignored if ``channel`` or ``ssl_channel_credentials`` is provided. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - - Raises: - google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport - creation failed for any reason. - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - self._grpc_channel = None - self._ssl_channel_credentials = ssl_channel_credentials - self._stubs: Dict[str, Callable] = {} - - if api_mtls_endpoint: - warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) - if client_cert_source: - warnings.warn("client_cert_source is deprecated", DeprecationWarning) - - if channel: - # Ignore credentials if a channel was passed. - credentials = False - # If a channel was explicitly provided, set it. - self._grpc_channel = channel - self._ssl_channel_credentials = None - else: - if api_mtls_endpoint: - host = api_mtls_endpoint - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - self._ssl_channel_credentials = SslCredentials().ssl_credentials - - else: - if client_cert_source_for_mtls and not ssl_channel_credentials: - cert, key = client_cert_source_for_mtls() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - - # The base transport sets the host, credentials and scopes - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes, - quota_project_id=quota_project_id, - client_info=client_info, - always_use_jwt_access=always_use_jwt_access, - api_audience=api_audience, - ) - - if not self._grpc_channel: - self._grpc_channel = type(self).create_channel( - self._host, - # use the credentials which are saved - credentials=self._credentials, - # Set ``credentials_file`` to ``None`` here as - # the credentials that we saved earlier should be used. - credentials_file=None, - 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 create_conversation(self) -> Callable[ - [gcd_conversation.CreateConversationRequest], - Awaitable[gcd_conversation.Conversation]]: - r"""Return a callable for the create conversation method over gRPC. - - Creates a new conversation. Conversations are auto-completed - after 24 hours. - - Conversation Lifecycle: There are two stages during a - conversation: Automated Agent Stage and Assist Stage. - - For Automated Agent Stage, there will be a dialogflow agent - responding to user queries. - - For Assist Stage, there's no dialogflow agent responding to user - queries. But we will provide suggestions which are generated - from conversation. - - If - [Conversation.conversation_profile][google.cloud.dialogflow.v2beta1.Conversation.conversation_profile] - is configured for a dialogflow agent, conversation will start - from ``Automated Agent Stage``, otherwise, it will start from - ``Assist Stage``. And during ``Automated Agent Stage``, once an - [Intent][google.cloud.dialogflow.v2beta1.Intent] with - [Intent.live_agent_handoff][google.cloud.dialogflow.v2beta1.Intent.live_agent_handoff] - is triggered, conversation will transfer to Assist Stage. - - Returns: - Callable[[~.CreateConversationRequest], - Awaitable[~.Conversation]]: - 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_conversation' not in self._stubs: - self._stubs['create_conversation'] = self.grpc_channel.unary_unary( - '/google.cloud.dialogflow.v2beta1.Conversations/CreateConversation', - request_serializer=gcd_conversation.CreateConversationRequest.serialize, - response_deserializer=gcd_conversation.Conversation.deserialize, - ) - return self._stubs['create_conversation'] - - @property - def list_conversations(self) -> Callable[ - [conversation.ListConversationsRequest], - Awaitable[conversation.ListConversationsResponse]]: - r"""Return a callable for the list conversations method over gRPC. - - Returns the list of all conversations in the - specified project. - - Returns: - Callable[[~.ListConversationsRequest], - Awaitable[~.ListConversationsResponse]]: - 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_conversations' not in self._stubs: - self._stubs['list_conversations'] = self.grpc_channel.unary_unary( - '/google.cloud.dialogflow.v2beta1.Conversations/ListConversations', - request_serializer=conversation.ListConversationsRequest.serialize, - response_deserializer=conversation.ListConversationsResponse.deserialize, - ) - return self._stubs['list_conversations'] - - @property - def get_conversation(self) -> Callable[ - [conversation.GetConversationRequest], - Awaitable[conversation.Conversation]]: - r"""Return a callable for the get conversation method over gRPC. - - Retrieves the specific conversation. - - Returns: - Callable[[~.GetConversationRequest], - Awaitable[~.Conversation]]: - 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_conversation' not in self._stubs: - self._stubs['get_conversation'] = self.grpc_channel.unary_unary( - '/google.cloud.dialogflow.v2beta1.Conversations/GetConversation', - request_serializer=conversation.GetConversationRequest.serialize, - response_deserializer=conversation.Conversation.deserialize, - ) - return self._stubs['get_conversation'] - - @property - def complete_conversation(self) -> Callable[ - [conversation.CompleteConversationRequest], - Awaitable[conversation.Conversation]]: - r"""Return a callable for the complete conversation method over gRPC. - - Completes the specified conversation. Finished - conversations are purged from the database after 30 - days. - - Returns: - Callable[[~.CompleteConversationRequest], - Awaitable[~.Conversation]]: - 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 'complete_conversation' not in self._stubs: - self._stubs['complete_conversation'] = self.grpc_channel.unary_unary( - '/google.cloud.dialogflow.v2beta1.Conversations/CompleteConversation', - request_serializer=conversation.CompleteConversationRequest.serialize, - response_deserializer=conversation.Conversation.deserialize, - ) - return self._stubs['complete_conversation'] - - @property - def batch_create_messages(self) -> Callable[ - [conversation.BatchCreateMessagesRequest], - Awaitable[conversation.BatchCreateMessagesResponse]]: - r"""Return a callable for the batch create messages method over gRPC. - - Batch ingests messages to conversation. Customers can - use this RPC to ingest historical messages to - conversation. - - Returns: - Callable[[~.BatchCreateMessagesRequest], - Awaitable[~.BatchCreateMessagesResponse]]: - 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 'batch_create_messages' not in self._stubs: - self._stubs['batch_create_messages'] = self.grpc_channel.unary_unary( - '/google.cloud.dialogflow.v2beta1.Conversations/BatchCreateMessages', - request_serializer=conversation.BatchCreateMessagesRequest.serialize, - response_deserializer=conversation.BatchCreateMessagesResponse.deserialize, - ) - return self._stubs['batch_create_messages'] - - @property - def list_messages(self) -> Callable[ - [conversation.ListMessagesRequest], - Awaitable[conversation.ListMessagesResponse]]: - r"""Return a callable for the list messages method over gRPC. - - Lists messages that belong to a given conversation. ``messages`` - are ordered by ``create_time`` in descending order. To fetch - updates without duplication, send request with filter - ``create_time_epoch_microseconds > [first item's create_time of previous request]`` - and empty page_token. - - Returns: - Callable[[~.ListMessagesRequest], - Awaitable[~.ListMessagesResponse]]: - 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_messages' not in self._stubs: - self._stubs['list_messages'] = self.grpc_channel.unary_unary( - '/google.cloud.dialogflow.v2beta1.Conversations/ListMessages', - request_serializer=conversation.ListMessagesRequest.serialize, - response_deserializer=conversation.ListMessagesResponse.deserialize, - ) - return self._stubs['list_messages'] - - @property - def suggest_conversation_summary(self) -> Callable[ - [gcd_conversation.SuggestConversationSummaryRequest], - Awaitable[gcd_conversation.SuggestConversationSummaryResponse]]: - r"""Return a callable for the suggest conversation summary method over gRPC. - - Suggest summary for a conversation based on specific - historical messages. The range of the messages to be - used for summary can be specified in the request. - - Returns: - Callable[[~.SuggestConversationSummaryRequest], - Awaitable[~.SuggestConversationSummaryResponse]]: - 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 'suggest_conversation_summary' not in self._stubs: - self._stubs['suggest_conversation_summary'] = self.grpc_channel.unary_unary( - '/google.cloud.dialogflow.v2beta1.Conversations/SuggestConversationSummary', - request_serializer=gcd_conversation.SuggestConversationSummaryRequest.serialize, - response_deserializer=gcd_conversation.SuggestConversationSummaryResponse.deserialize, - ) - return self._stubs['suggest_conversation_summary'] - - def close(self): - return self.grpc_channel.close() - - @property - def cancel_operation( - self, - ) -> Callable[[operations_pb2.CancelOperationRequest], None]: - r"""Return a callable for the cancel_operation method over gRPC. - """ - # 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 "cancel_operation" not in self._stubs: - self._stubs["cancel_operation"] = self.grpc_channel.unary_unary( - "/google.longrunning.Operations/CancelOperation", - request_serializer=operations_pb2.CancelOperationRequest.SerializeToString, - response_deserializer=None, - ) - return self._stubs["cancel_operation"] - - @property - def get_operation( - self, - ) -> Callable[[operations_pb2.GetOperationRequest], operations_pb2.Operation]: - r"""Return a callable for the get_operation method over gRPC. - """ - # 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_operation" not in self._stubs: - self._stubs["get_operation"] = self.grpc_channel.unary_unary( - "/google.longrunning.Operations/GetOperation", - request_serializer=operations_pb2.GetOperationRequest.SerializeToString, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs["get_operation"] - - @property - def list_operations( - self, - ) -> Callable[[operations_pb2.ListOperationsRequest], operations_pb2.ListOperationsResponse]: - r"""Return a callable for the list_operations method over gRPC. - """ - # 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_operations" not in self._stubs: - self._stubs["list_operations"] = self.grpc_channel.unary_unary( - "/google.longrunning.Operations/ListOperations", - request_serializer=operations_pb2.ListOperationsRequest.SerializeToString, - response_deserializer=operations_pb2.ListOperationsResponse.FromString, - ) - return self._stubs["list_operations"] - - @property - def list_locations( - self, - ) -> Callable[[locations_pb2.ListLocationsRequest], locations_pb2.ListLocationsResponse]: - r"""Return a callable for the list locations method over gRPC. - """ - # 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_locations" not in self._stubs: - self._stubs["list_locations"] = self.grpc_channel.unary_unary( - "/google.cloud.location.Locations/ListLocations", - request_serializer=locations_pb2.ListLocationsRequest.SerializeToString, - response_deserializer=locations_pb2.ListLocationsResponse.FromString, - ) - return self._stubs["list_locations"] - - @property - def get_location( - self, - ) -> Callable[[locations_pb2.GetLocationRequest], locations_pb2.Location]: - r"""Return a callable for the list locations method over gRPC. - """ - # 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_location" not in self._stubs: - self._stubs["get_location"] = self.grpc_channel.unary_unary( - "/google.cloud.location.Locations/GetLocation", - request_serializer=locations_pb2.GetLocationRequest.SerializeToString, - response_deserializer=locations_pb2.Location.FromString, - ) - return self._stubs["get_location"] - - -__all__ = ( - 'ConversationsGrpcAsyncIOTransport', -) diff --git a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/conversations/transports/rest.py b/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/conversations/transports/rest.py deleted file mode 100644 index 0a5512042..000000000 --- a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/conversations/transports/rest.py +++ /dev/null @@ -1,1489 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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 google.auth.transport.requests import AuthorizedSession # type: ignore -import json # type: ignore -import grpc # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore -from google.auth import credentials as ga_credentials # type: ignore -from google.api_core import exceptions as core_exceptions -from google.api_core import retry as retries -from google.api_core import rest_helpers -from google.api_core import rest_streaming -from google.api_core import path_template -from google.api_core import gapic_v1 - -from google.protobuf import json_format -from google.cloud.location import locations_pb2 # type: ignore -from google.longrunning import operations_pb2 -from requests import __version__ as requests_version -import dataclasses -import re -from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union -import warnings - -try: - OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] -except AttributeError: # pragma: NO COVER - OptionalRetry = Union[retries.Retry, object] # 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 as BASE_DEFAULT_CLIENT_INFO - - -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=BASE_DEFAULT_CLIENT_INFO.gapic_version, - grpc_version=None, - rest_version=requests_version, -) - - -class ConversationsRestInterceptor: - """Interceptor for Conversations. - - Interceptors are used to manipulate requests, request metadata, and responses - in arbitrary ways. - Example use cases include: - * Logging - * Verifying requests according to service or custom semantics - * Stripping extraneous information from responses - - These use cases and more can be enabled by injecting an - instance of a custom subclass when constructing the ConversationsRestTransport. - - .. code-block:: python - class MyCustomConversationsInterceptor(ConversationsRestInterceptor): - def pre_batch_create_messages(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_batch_create_messages(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_complete_conversation(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_complete_conversation(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_create_conversation(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_create_conversation(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_get_conversation(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_get_conversation(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_list_conversations(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_list_conversations(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_list_messages(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_list_messages(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_suggest_conversation_summary(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_suggest_conversation_summary(self, response): - logging.log(f"Received response: {response}") - return response - - transport = ConversationsRestTransport(interceptor=MyCustomConversationsInterceptor()) - client = ConversationsClient(transport=transport) - - - """ - def pre_batch_create_messages(self, request: conversation.BatchCreateMessagesRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[conversation.BatchCreateMessagesRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for batch_create_messages - - Override in a subclass to manipulate the request or metadata - before they are sent to the Conversations server. - """ - return request, metadata - - def post_batch_create_messages(self, response: conversation.BatchCreateMessagesResponse) -> conversation.BatchCreateMessagesResponse: - """Post-rpc interceptor for batch_create_messages - - Override in a subclass to manipulate the response - after it is returned by the Conversations server but before - it is returned to user code. - """ - return response - def pre_complete_conversation(self, request: conversation.CompleteConversationRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[conversation.CompleteConversationRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for complete_conversation - - Override in a subclass to manipulate the request or metadata - before they are sent to the Conversations server. - """ - return request, metadata - - def post_complete_conversation(self, response: conversation.Conversation) -> conversation.Conversation: - """Post-rpc interceptor for complete_conversation - - Override in a subclass to manipulate the response - after it is returned by the Conversations server but before - it is returned to user code. - """ - return response - def pre_create_conversation(self, request: gcd_conversation.CreateConversationRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[gcd_conversation.CreateConversationRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for create_conversation - - Override in a subclass to manipulate the request or metadata - before they are sent to the Conversations server. - """ - return request, metadata - - def post_create_conversation(self, response: gcd_conversation.Conversation) -> gcd_conversation.Conversation: - """Post-rpc interceptor for create_conversation - - Override in a subclass to manipulate the response - after it is returned by the Conversations server but before - it is returned to user code. - """ - return response - def pre_get_conversation(self, request: conversation.GetConversationRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[conversation.GetConversationRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for get_conversation - - Override in a subclass to manipulate the request or metadata - before they are sent to the Conversations server. - """ - return request, metadata - - def post_get_conversation(self, response: conversation.Conversation) -> conversation.Conversation: - """Post-rpc interceptor for get_conversation - - Override in a subclass to manipulate the response - after it is returned by the Conversations server but before - it is returned to user code. - """ - return response - def pre_list_conversations(self, request: conversation.ListConversationsRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[conversation.ListConversationsRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for list_conversations - - Override in a subclass to manipulate the request or metadata - before they are sent to the Conversations server. - """ - return request, metadata - - def post_list_conversations(self, response: conversation.ListConversationsResponse) -> conversation.ListConversationsResponse: - """Post-rpc interceptor for list_conversations - - Override in a subclass to manipulate the response - after it is returned by the Conversations server but before - it is returned to user code. - """ - return response - def pre_list_messages(self, request: conversation.ListMessagesRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[conversation.ListMessagesRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for list_messages - - Override in a subclass to manipulate the request or metadata - before they are sent to the Conversations server. - """ - return request, metadata - - def post_list_messages(self, response: conversation.ListMessagesResponse) -> conversation.ListMessagesResponse: - """Post-rpc interceptor for list_messages - - Override in a subclass to manipulate the response - after it is returned by the Conversations server but before - it is returned to user code. - """ - return response - def pre_suggest_conversation_summary(self, request: gcd_conversation.SuggestConversationSummaryRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[gcd_conversation.SuggestConversationSummaryRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for suggest_conversation_summary - - Override in a subclass to manipulate the request or metadata - before they are sent to the Conversations server. - """ - return request, metadata - - def post_suggest_conversation_summary(self, response: gcd_conversation.SuggestConversationSummaryResponse) -> gcd_conversation.SuggestConversationSummaryResponse: - """Post-rpc interceptor for suggest_conversation_summary - - Override in a subclass to manipulate the response - after it is returned by the Conversations server but before - it is returned to user code. - """ - return response - - def pre_get_location( - self, request: locations_pb2.GetLocationRequest, metadata: Sequence[Tuple[str, str]] - ) -> Tuple[locations_pb2.GetLocationRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for get_location - - Override in a subclass to manipulate the request or metadata - before they are sent to the Conversations server. - """ - return request, metadata - - def post_get_location( - self, response: locations_pb2.Location - ) -> locations_pb2.Location: - """Post-rpc interceptor for get_location - - Override in a subclass to manipulate the response - after it is returned by the Conversations server but before - it is returned to user code. - """ - return response - def pre_list_locations( - self, request: locations_pb2.ListLocationsRequest, metadata: Sequence[Tuple[str, str]] - ) -> Tuple[locations_pb2.ListLocationsRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for list_locations - - Override in a subclass to manipulate the request or metadata - before they are sent to the Conversations server. - """ - return request, metadata - - def post_list_locations( - self, response: locations_pb2.ListLocationsResponse - ) -> locations_pb2.ListLocationsResponse: - """Post-rpc interceptor for list_locations - - Override in a subclass to manipulate the response - after it is returned by the Conversations server but before - it is returned to user code. - """ - return response - def pre_cancel_operation( - self, request: operations_pb2.CancelOperationRequest, metadata: Sequence[Tuple[str, str]] - ) -> Tuple[operations_pb2.CancelOperationRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for cancel_operation - - Override in a subclass to manipulate the request or metadata - before they are sent to the Conversations server. - """ - return request, metadata - - def post_cancel_operation( - self, response: None - ) -> None: - """Post-rpc interceptor for cancel_operation - - Override in a subclass to manipulate the response - after it is returned by the Conversations server but before - it is returned to user code. - """ - return response - def pre_get_operation( - self, request: operations_pb2.GetOperationRequest, metadata: Sequence[Tuple[str, str]] - ) -> Tuple[operations_pb2.GetOperationRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for get_operation - - Override in a subclass to manipulate the request or metadata - before they are sent to the Conversations server. - """ - return request, metadata - - def post_get_operation( - self, response: operations_pb2.Operation - ) -> operations_pb2.Operation: - """Post-rpc interceptor for get_operation - - Override in a subclass to manipulate the response - after it is returned by the Conversations server but before - it is returned to user code. - """ - return response - def pre_list_operations( - self, request: operations_pb2.ListOperationsRequest, metadata: Sequence[Tuple[str, str]] - ) -> Tuple[operations_pb2.ListOperationsRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for list_operations - - Override in a subclass to manipulate the request or metadata - before they are sent to the Conversations server. - """ - return request, metadata - - def post_list_operations( - self, response: operations_pb2.ListOperationsResponse - ) -> operations_pb2.ListOperationsResponse: - """Post-rpc interceptor for list_operations - - Override in a subclass to manipulate the response - after it is returned by the Conversations server but before - it is returned to user code. - """ - return response - - -@dataclasses.dataclass -class ConversationsRestStub: - _session: AuthorizedSession - _host: str - _interceptor: ConversationsRestInterceptor - - -class ConversationsRestTransport(ConversationsTransport): - """REST backend transport for Conversations. - - Service for managing - [Conversations][google.cloud.dialogflow.v2beta1.Conversation]. - - 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 JSON representations of protocol buffers over HTTP/1.1 - - """ - - def __init__(self, *, - host: str = 'dialogflow.googleapis.com', - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - client_cert_source_for_mtls: Optional[Callable[[ - ], Tuple[bytes, bytes]]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - url_scheme: str = 'https', - interceptor: Optional[ConversationsRestInterceptor] = None, - api_audience: Optional[str] = None, - ) -> 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 ignored if ``channel`` is provided. - scopes (Optional(Sequence[str])): A list of scopes. This argument is - ignored if ``channel`` is provided. - client_cert_source_for_mtls (Callable[[], Tuple[bytes, bytes]]): Client - certificate to configure mutual TLS HTTP channel. It is ignored - if ``channel`` is provided. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you are developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - url_scheme: the protocol scheme for the API endpoint. Normally - "https", but for testing or local servers, - "http" can be specified. - """ - # Run the base constructor - # TODO(yon-mg): resolve other ctor params i.e. scopes, quota, etc. - # TODO: When custom host (api_endpoint) is set, `scopes` must *also* be set on the - # credentials object - maybe_url_match = re.match("^(?Phttp(?:s)?://)?(?P.*)$", host) - if maybe_url_match is None: - raise ValueError(f"Unexpected hostname structure: {host}") # pragma: NO COVER - - url_match_items = maybe_url_match.groupdict() - - host = f"{url_scheme}://{host}" if not url_match_items["scheme"] else host - - super().__init__( - host=host, - credentials=credentials, - client_info=client_info, - always_use_jwt_access=always_use_jwt_access, - api_audience=api_audience - ) - self._session = AuthorizedSession( - self._credentials, default_host=self.DEFAULT_HOST) - if client_cert_source_for_mtls: - self._session.configure_mtls_channel(client_cert_source_for_mtls) - self._interceptor = interceptor or ConversationsRestInterceptor() - self._prep_wrapped_messages(client_info) - - class _BatchCreateMessages(ConversationsRestStub): - def __hash__(self): - return hash("BatchCreateMessages") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: conversation.BatchCreateMessagesRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> conversation.BatchCreateMessagesResponse: - r"""Call the batch create messages method over HTTP. - - Args: - request (~.conversation.BatchCreateMessagesRequest): - The request object. The request message for - [Conversations.BatchCreateMessagesRequest][]. - 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: - ~.conversation.BatchCreateMessagesResponse: - The request message for - [Conversations.BatchCreateMessagesResponse][]. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'post', - 'uri': '/v2beta1/{parent=projects/*/conversations/*}/messages:batchCreate', - 'body': '*', - }, -{ - 'method': 'post', - 'uri': '/v2beta1/{parent=projects/*/locations/*/conversations/*}/messages:batchCreate', - 'body': '*', - }, - ] - request, metadata = self._interceptor.pre_batch_create_messages(request, metadata) - pb_request = conversation.BatchCreateMessagesRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request['body'], - including_default_value_fields=False, - use_integers_for_enums=True - ) - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - including_default_value_fields=False, - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = conversation.BatchCreateMessagesResponse() - pb_resp = conversation.BatchCreateMessagesResponse.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_batch_create_messages(resp) - return resp - - class _CompleteConversation(ConversationsRestStub): - def __hash__(self): - return hash("CompleteConversation") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: conversation.CompleteConversationRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> conversation.Conversation: - r"""Call the complete conversation method over HTTP. - - Args: - request (~.conversation.CompleteConversationRequest): - The request object. The request message for - [Conversations.CompleteConversation][google.cloud.dialogflow.v2beta1.Conversations.CompleteConversation]. - 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: - ~.conversation.Conversation: - Represents a conversation. - A conversation is an interaction between - an agent, including live agents and - Dialogflow agents, and a support - customer. Conversations can include - phone calls and text-based chat - sessions. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'post', - 'uri': '/v2beta1/{name=projects/*/conversations/*}:complete', - 'body': '*', - }, -{ - 'method': 'post', - 'uri': '/v2beta1/{name=projects/*/locations/*/conversations/*}:complete', - 'body': '*', - }, - ] - request, metadata = self._interceptor.pre_complete_conversation(request, metadata) - pb_request = conversation.CompleteConversationRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request['body'], - including_default_value_fields=False, - use_integers_for_enums=True - ) - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - including_default_value_fields=False, - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = conversation.Conversation() - pb_resp = conversation.Conversation.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_complete_conversation(resp) - return resp - - class _CreateConversation(ConversationsRestStub): - def __hash__(self): - return hash("CreateConversation") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: gcd_conversation.CreateConversationRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> gcd_conversation.Conversation: - r"""Call the create conversation method over HTTP. - - Args: - request (~.gcd_conversation.CreateConversationRequest): - The request object. The request message for - [Conversations.CreateConversation][google.cloud.dialogflow.v2beta1.Conversations.CreateConversation]. - 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: - ~.gcd_conversation.Conversation: - Represents a conversation. - A conversation is an interaction between - an agent, including live agents and - Dialogflow agents, and a support - customer. Conversations can include - phone calls and text-based chat - sessions. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'post', - 'uri': '/v2beta1/{parent=projects/*}/conversations', - 'body': 'conversation', - }, -{ - 'method': 'post', - 'uri': '/v2beta1/{parent=projects/*/locations/*}/conversations', - 'body': 'conversation', - }, - ] - request, metadata = self._interceptor.pre_create_conversation(request, metadata) - pb_request = gcd_conversation.CreateConversationRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request['body'], - including_default_value_fields=False, - use_integers_for_enums=True - ) - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - including_default_value_fields=False, - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = gcd_conversation.Conversation() - pb_resp = gcd_conversation.Conversation.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_create_conversation(resp) - return resp - - class _GetConversation(ConversationsRestStub): - def __hash__(self): - return hash("GetConversation") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: conversation.GetConversationRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> conversation.Conversation: - r"""Call the get conversation method over HTTP. - - Args: - request (~.conversation.GetConversationRequest): - The request object. The request message for - [Conversations.GetConversation][google.cloud.dialogflow.v2beta1.Conversations.GetConversation]. - 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: - ~.conversation.Conversation: - Represents a conversation. - A conversation is an interaction between - an agent, including live agents and - Dialogflow agents, and a support - customer. Conversations can include - phone calls and text-based chat - sessions. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v2beta1/{name=projects/*/conversations/*}', - }, -{ - 'method': 'get', - 'uri': '/v2beta1/{name=projects/*/locations/*/conversations/*}', - }, - ] - request, metadata = self._interceptor.pre_get_conversation(request, metadata) - pb_request = conversation.GetConversationRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - including_default_value_fields=False, - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = conversation.Conversation() - pb_resp = conversation.Conversation.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_get_conversation(resp) - return resp - - class _ListConversations(ConversationsRestStub): - def __hash__(self): - return hash("ListConversations") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: conversation.ListConversationsRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> conversation.ListConversationsResponse: - r"""Call the list conversations method over HTTP. - - Args: - request (~.conversation.ListConversationsRequest): - The request object. The request message for - [Conversations.ListConversations][google.cloud.dialogflow.v2beta1.Conversations.ListConversations]. - 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: - ~.conversation.ListConversationsResponse: - The response message for - [Conversations.ListConversations][google.cloud.dialogflow.v2beta1.Conversations.ListConversations]. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v2beta1/{parent=projects/*}/conversations', - }, -{ - 'method': 'get', - 'uri': '/v2beta1/{parent=projects/*/locations/*}/conversations', - }, - ] - request, metadata = self._interceptor.pre_list_conversations(request, metadata) - pb_request = conversation.ListConversationsRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - including_default_value_fields=False, - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = conversation.ListConversationsResponse() - pb_resp = conversation.ListConversationsResponse.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_list_conversations(resp) - return resp - - class _ListMessages(ConversationsRestStub): - def __hash__(self): - return hash("ListMessages") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: conversation.ListMessagesRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> conversation.ListMessagesResponse: - r"""Call the list messages method over HTTP. - - Args: - request (~.conversation.ListMessagesRequest): - The request object. The request message for - [Conversations.ListMessages][google.cloud.dialogflow.v2beta1.Conversations.ListMessages]. - 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: - ~.conversation.ListMessagesResponse: - The response message for - [Conversations.ListMessages][google.cloud.dialogflow.v2beta1.Conversations.ListMessages]. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v2beta1/{parent=projects/*/conversations/*}/messages', - }, -{ - 'method': 'get', - 'uri': '/v2beta1/{parent=projects/*/locations/*/conversations/*}/messages', - }, - ] - request, metadata = self._interceptor.pre_list_messages(request, metadata) - pb_request = conversation.ListMessagesRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - including_default_value_fields=False, - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = conversation.ListMessagesResponse() - pb_resp = conversation.ListMessagesResponse.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_list_messages(resp) - return resp - - class _SuggestConversationSummary(ConversationsRestStub): - def __hash__(self): - return hash("SuggestConversationSummary") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: gcd_conversation.SuggestConversationSummaryRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> gcd_conversation.SuggestConversationSummaryResponse: - r"""Call the suggest conversation - summary method over HTTP. - - Args: - request (~.gcd_conversation.SuggestConversationSummaryRequest): - The request object. The request message for - [Conversations.SuggestConversationSummary][google.cloud.dialogflow.v2beta1.Conversations.SuggestConversationSummary]. - 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: - ~.gcd_conversation.SuggestConversationSummaryResponse: - The response message for - [Conversations.SuggestConversationSummary][google.cloud.dialogflow.v2beta1.Conversations.SuggestConversationSummary]. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'post', - 'uri': '/v2beta1/{conversation=projects/*/conversations/*}/suggestions:suggestConversationSummary', - 'body': '*', - }, -{ - 'method': 'post', - 'uri': '/v2beta1/{conversation=projects/*/locations/*/conversations/*}/suggestions:suggestConversationSummary', - 'body': '*', - }, - ] - request, metadata = self._interceptor.pre_suggest_conversation_summary(request, metadata) - pb_request = gcd_conversation.SuggestConversationSummaryRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request['body'], - including_default_value_fields=False, - use_integers_for_enums=True - ) - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - including_default_value_fields=False, - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = gcd_conversation.SuggestConversationSummaryResponse() - pb_resp = gcd_conversation.SuggestConversationSummaryResponse.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_suggest_conversation_summary(resp) - return resp - - @property - def batch_create_messages(self) -> Callable[ - [conversation.BatchCreateMessagesRequest], - conversation.BatchCreateMessagesResponse]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._BatchCreateMessages(self._session, self._host, self._interceptor) # type: ignore - - @property - def complete_conversation(self) -> Callable[ - [conversation.CompleteConversationRequest], - conversation.Conversation]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._CompleteConversation(self._session, self._host, self._interceptor) # type: ignore - - @property - def create_conversation(self) -> Callable[ - [gcd_conversation.CreateConversationRequest], - gcd_conversation.Conversation]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._CreateConversation(self._session, self._host, self._interceptor) # type: ignore - - @property - def get_conversation(self) -> Callable[ - [conversation.GetConversationRequest], - conversation.Conversation]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._GetConversation(self._session, self._host, self._interceptor) # type: ignore - - @property - def list_conversations(self) -> Callable[ - [conversation.ListConversationsRequest], - conversation.ListConversationsResponse]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._ListConversations(self._session, self._host, self._interceptor) # type: ignore - - @property - def list_messages(self) -> Callable[ - [conversation.ListMessagesRequest], - conversation.ListMessagesResponse]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._ListMessages(self._session, self._host, self._interceptor) # type: ignore - - @property - def suggest_conversation_summary(self) -> Callable[ - [gcd_conversation.SuggestConversationSummaryRequest], - gcd_conversation.SuggestConversationSummaryResponse]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._SuggestConversationSummary(self._session, self._host, self._interceptor) # type: ignore - - @property - def get_location(self): - return self._GetLocation(self._session, self._host, self._interceptor) # type: ignore - - class _GetLocation(ConversationsRestStub): - def __call__(self, - request: locations_pb2.GetLocationRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> locations_pb2.Location: - - r"""Call the get location method over HTTP. - - Args: - request (locations_pb2.GetLocationRequest): - The request object for GetLocation method. - 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: - locations_pb2.Location: Response from GetLocation method. - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v2beta1/{name=projects/*/locations/*}', - }, - ] - - request, metadata = self._interceptor.pre_get_location(request, metadata) - request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode( - http_options, **request_kwargs) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json.dumps(transcoded_request['query_params'])) - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - resp = locations_pb2.Location() - resp = json_format.Parse(response.content.decode("utf-8"), resp) - resp = self._interceptor.post_get_location(resp) - return resp - - @property - def list_locations(self): - return self._ListLocations(self._session, self._host, self._interceptor) # type: ignore - - class _ListLocations(ConversationsRestStub): - def __call__(self, - request: locations_pb2.ListLocationsRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> locations_pb2.ListLocationsResponse: - - r"""Call the list locations method over HTTP. - - Args: - request (locations_pb2.ListLocationsRequest): - The request object for ListLocations method. - 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: - locations_pb2.ListLocationsResponse: Response from ListLocations method. - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v2beta1/{name=projects/*}/locations', - }, - ] - - request, metadata = self._interceptor.pre_list_locations(request, metadata) - request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode( - http_options, **request_kwargs) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json.dumps(transcoded_request['query_params'])) - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - resp = locations_pb2.ListLocationsResponse() - resp = json_format.Parse(response.content.decode("utf-8"), resp) - resp = self._interceptor.post_list_locations(resp) - return resp - - @property - def cancel_operation(self): - return self._CancelOperation(self._session, self._host, self._interceptor) # type: ignore - - class _CancelOperation(ConversationsRestStub): - def __call__(self, - request: operations_pb2.CancelOperationRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> None: - - r"""Call the cancel operation method over HTTP. - - Args: - request (operations_pb2.CancelOperationRequest): - The request object for CancelOperation method. - 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. - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'post', - 'uri': '/v2beta1/{name=projects/*/operations/*}:cancel', - }, -{ - 'method': 'post', - 'uri': '/v2beta1/{name=projects/*/locations/*/operations/*}:cancel', - }, - ] - - request, metadata = self._interceptor.pre_cancel_operation(request, metadata) - request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode( - http_options, **request_kwargs) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json.dumps(transcoded_request['query_params'])) - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - return self._interceptor.post_cancel_operation(None) - - @property - def get_operation(self): - return self._GetOperation(self._session, self._host, self._interceptor) # type: ignore - - class _GetOperation(ConversationsRestStub): - def __call__(self, - request: operations_pb2.GetOperationRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> operations_pb2.Operation: - - r"""Call the get operation method over HTTP. - - Args: - request (operations_pb2.GetOperationRequest): - The request object for GetOperation method. - 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: - operations_pb2.Operation: Response from GetOperation method. - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v2beta1/{name=projects/*/operations/*}', - }, -{ - 'method': 'get', - 'uri': '/v2beta1/{name=projects/*/locations/*/operations/*}', - }, - ] - - request, metadata = self._interceptor.pre_get_operation(request, metadata) - request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode( - http_options, **request_kwargs) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json.dumps(transcoded_request['query_params'])) - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - resp = operations_pb2.Operation() - resp = json_format.Parse(response.content.decode("utf-8"), resp) - resp = self._interceptor.post_get_operation(resp) - return resp - - @property - def list_operations(self): - return self._ListOperations(self._session, self._host, self._interceptor) # type: ignore - - class _ListOperations(ConversationsRestStub): - def __call__(self, - request: operations_pb2.ListOperationsRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> operations_pb2.ListOperationsResponse: - - r"""Call the list operations method over HTTP. - - Args: - request (operations_pb2.ListOperationsRequest): - The request object for ListOperations method. - 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: - operations_pb2.ListOperationsResponse: Response from ListOperations method. - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v2beta1/{name=projects/*}/operations', - }, -{ - 'method': 'get', - 'uri': '/v2beta1/{name=projects/*/locations/*}/operations', - }, - ] - - request, metadata = self._interceptor.pre_list_operations(request, metadata) - request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode( - http_options, **request_kwargs) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json.dumps(transcoded_request['query_params'])) - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - resp = operations_pb2.ListOperationsResponse() - resp = json_format.Parse(response.content.decode("utf-8"), resp) - resp = self._interceptor.post_list_operations(resp) - return resp - - @property - def kind(self) -> str: - return "rest" - - def close(self): - self._session.close() - - -__all__=( - 'ConversationsRestTransport', -) diff --git a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/documents/__init__.py b/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/documents/__init__.py deleted file mode 100644 index b54da36c3..000000000 --- a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/documents/__init__.py +++ /dev/null @@ -1,22 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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 DocumentsClient -from .async_client import DocumentsAsyncClient - -__all__ = ( - 'DocumentsClient', - 'DocumentsAsyncClient', -) diff --git a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/documents/async_client.py b/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/documents/async_client.py deleted file mode 100644 index 845ae8e38..000000000 --- a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/documents/async_client.py +++ /dev/null @@ -1,1399 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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, Mapping, MutableMapping, MutableSequence, Optional, Sequence, Tuple, Type, Union - -from google.cloud.dialogflow_v2beta1 import gapic_version as package_version - -from google.api_core.client_options import ClientOptions -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import retry as retries -from google.auth import credentials as ga_credentials # type: ignore -from google.oauth2 import service_account # type: ignore - -try: - OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] -except AttributeError: # pragma: NO COVER - OptionalRetry = Union[retries.Retry, object] # type: ignore - -from google.api_core import operation # type: ignore -from google.api_core import operation_async # type: ignore -from google.cloud.dialogflow_v2beta1.services.documents import pagers -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.cloud.location import locations_pb2 # type: ignore -from google.longrunning import operations_pb2 -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 - - -class DocumentsAsyncClient: - """Service for managing knowledge - [Documents][google.cloud.dialogflow.v2beta1.Document]. - """ - - _client: DocumentsClient - - DEFAULT_ENDPOINT = DocumentsClient.DEFAULT_ENDPOINT - DEFAULT_MTLS_ENDPOINT = DocumentsClient.DEFAULT_MTLS_ENDPOINT - - 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) - - @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: - DocumentsAsyncClient: The constructed client. - """ - return DocumentsClient.from_service_account_info.__func__(DocumentsAsyncClient, 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: - DocumentsAsyncClient: The constructed client. - """ - return DocumentsClient.from_service_account_file.__func__(DocumentsAsyncClient, filename, *args, **kwargs) # type: ignore - - from_service_account_json = from_service_account_file - - @classmethod - def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[ClientOptions] = None): - """Return the API endpoint and client cert source for mutual TLS. - - The client cert source is determined in the following order: - (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the - client cert source is None. - (2) if `client_options.client_cert_source` is provided, use the provided one; if the - default client cert source exists, use the default one; otherwise the client cert - source is None. - - The API endpoint is determined in the following order: - (1) if `client_options.api_endpoint` if provided, use the provided one. - (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the - default mTLS endpoint; if the environment variable is "never", use the default API - endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise - use the default API endpoint. - - More details can be found at https://google.aip.dev/auth/4114. - - Args: - client_options (google.api_core.client_options.ClientOptions): Custom options for the - client. Only the `api_endpoint` and `client_cert_source` properties may be used - in this method. - - Returns: - Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the - client cert source to use. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If any errors happen. - """ - return DocumentsClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore - - @property - def transport(self) -> DocumentsTransport: - """Returns the transport used by the client instance. - - Returns: - DocumentsTransport: The transport used by the client instance. - """ - return self._client.transport - - get_transport_class = functools.partial(type(DocumentsClient).get_transport_class, type(DocumentsClient)) - - def __init__(self, *, - credentials: Optional[ga_credentials.Credentials] = None, - transport: Union[str, DocumentsTransport] = "grpc_asyncio", - client_options: Optional[ClientOptions] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the documents 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, ~.DocumentsTransport]): 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 = DocumentsClient( - credentials=credentials, - transport=transport, - client_options=client_options, - client_info=client_info, - - ) - - async def list_documents(self, - request: Optional[Union[document.ListDocumentsRequest, dict]] = None, - *, - parent: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListDocumentsAsyncPager: - r"""Returns the list of all documents of the knowledge base. - - Note: The ``projects.agent.knowledgeBases.documents`` resource - is deprecated; only use ``projects.knowledgeBases.documents``. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import dialogflow_v2beta1 - - async def sample_list_documents(): - # Create a client - client = dialogflow_v2beta1.DocumentsAsyncClient() - - # Initialize request argument(s) - request = dialogflow_v2beta1.ListDocumentsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_documents(request=request) - - # Handle the response - async for response in page_result: - print(response) - - Args: - request (Optional[Union[google.cloud.dialogflow_v2beta1.types.ListDocumentsRequest, dict]]): - The request object. Request message for - [Documents.ListDocuments][google.cloud.dialogflow.v2beta1.Documents.ListDocuments]. - parent (:class:`str`): - Required. The knowledge base to list all documents for. - Format: - ``projects//locations//knowledgeBases/``. - - 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.documents.pagers.ListDocumentsAsyncPager: - Response message for - [Documents.ListDocuments][google.cloud.dialogflow.v2beta1.Documents.ListDocuments]. - - Iterating over this object will yield results and - resolve additional pages automatically. - - """ - # Create or coerce a protobuf request object. - # Quick 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 = document.ListDocumentsRequest(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_documents, - 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.ListDocumentsAsyncPager( - method=rpc, - request=request, - response=response, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def get_document(self, - request: Optional[Union[document.GetDocumentRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> document.Document: - r"""Retrieves the specified document. - - Note: The ``projects.agent.knowledgeBases.documents`` resource - is deprecated; only use ``projects.knowledgeBases.documents``. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import dialogflow_v2beta1 - - async def sample_get_document(): - # Create a client - client = dialogflow_v2beta1.DocumentsAsyncClient() - - # Initialize request argument(s) - request = dialogflow_v2beta1.GetDocumentRequest( - name="name_value", - ) - - # Make the request - response = await client.get_document(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.dialogflow_v2beta1.types.GetDocumentRequest, dict]]): - The request object. Request message for - [Documents.GetDocument][google.cloud.dialogflow.v2beta1.Documents.GetDocument]. - name (:class:`str`): - Required. The name of the document to retrieve. Format - ``projects//locations//knowledgeBases//documents/``. - - 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.Document: - A knowledge document to be used by a - [KnowledgeBase][google.cloud.dialogflow.v2beta1.KnowledgeBase]. - - For more information, see the [knowledge base - guide](\ https://cloud.google.com/dialogflow/docs/how/knowledge-bases). - - Note: The projects.agent.knowledgeBases.documents - resource is deprecated; only use - projects.knowledgeBases.documents. - - """ - # Create or coerce a protobuf request object. - # Quick 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 = document.GetDocumentRequest(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_document, - 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_document(self, - request: Optional[Union[gcd_document.CreateDocumentRequest, dict]] = None, - *, - parent: Optional[str] = None, - document: Optional[gcd_document.Document] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation_async.AsyncOperation: - r"""Creates a new document. - - This method is a `long-running - operation `__. - The returned ``Operation`` type has the following - method-specific fields: - - - ``metadata``: - [KnowledgeOperationMetadata][google.cloud.dialogflow.v2beta1.KnowledgeOperationMetadata] - - ``response``: - [Document][google.cloud.dialogflow.v2beta1.Document] - - Note: The ``projects.agent.knowledgeBases.documents`` resource - is deprecated; only use ``projects.knowledgeBases.documents``. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import dialogflow_v2beta1 - - async def sample_create_document(): - # Create a client - client = dialogflow_v2beta1.DocumentsAsyncClient() - - # Initialize request argument(s) - document = dialogflow_v2beta1.Document() - document.content_uri = "content_uri_value" - document.display_name = "display_name_value" - document.mime_type = "mime_type_value" - document.knowledge_types = ['SMART_REPLY'] - - request = dialogflow_v2beta1.CreateDocumentRequest( - parent="parent_value", - document=document, - ) - - # Make the request - operation = client.create_document(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.dialogflow_v2beta1.types.CreateDocumentRequest, dict]]): - The request object. Request message for - [Documents.CreateDocument][google.cloud.dialogflow.v2beta1.Documents.CreateDocument]. - parent (:class:`str`): - Required. The knowledge base to create a document for. - Format: - ``projects//locations//knowledgeBases/``. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - document (:class:`google.cloud.dialogflow_v2beta1.types.Document`): - Required. The document to create. - 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. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.api_core.operation_async.AsyncOperation: - An object representing a long-running operation. - - The result type for the operation will be :class:`google.cloud.dialogflow_v2beta1.types.Document` A knowledge document to be used by a - [KnowledgeBase][google.cloud.dialogflow.v2beta1.KnowledgeBase]. - - For more information, see the [knowledge base - guide](\ https://cloud.google.com/dialogflow/docs/how/knowledge-bases). - - Note: The projects.agent.knowledgeBases.documents - resource is deprecated; only use - projects.knowledgeBases.documents. - - """ - # Create or coerce a protobuf request object. - # Quick 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, document]) - 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_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: - request.document = document - - # 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_document, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Wrap the response in an operation future. - response = operation_async.from_gapic( - response, - self._client._transport.operations_client, - gcd_document.Document, - metadata_type=gcd_document.KnowledgeOperationMetadata, - ) - - # Done; return the response. - return response - - async def import_documents(self, - request: Optional[Union[document.ImportDocumentsRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation_async.AsyncOperation: - r"""Create documents by importing data from external sources. - Dialogflow supports up to 350 documents in each request. If you - try to import more, Dialogflow will return an error. - - This method is a `long-running - operation `__. - The returned ``Operation`` type has the following - method-specific fields: - - - ``metadata``: - [KnowledgeOperationMetadata][google.cloud.dialogflow.v2beta1.KnowledgeOperationMetadata] - - ``response``: - [ImportDocumentsResponse][google.cloud.dialogflow.v2beta1.ImportDocumentsResponse] - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import dialogflow_v2beta1 - - async def sample_import_documents(): - # Create a client - client = dialogflow_v2beta1.DocumentsAsyncClient() - - # Initialize request argument(s) - gcs_source = dialogflow_v2beta1.GcsSources() - gcs_source.uris = ['uris_value1', 'uris_value2'] - - document_template = dialogflow_v2beta1.ImportDocumentTemplate() - document_template.mime_type = "mime_type_value" - document_template.knowledge_types = ['SMART_REPLY'] - - request = dialogflow_v2beta1.ImportDocumentsRequest( - gcs_source=gcs_source, - parent="parent_value", - document_template=document_template, - ) - - # Make the request - operation = client.import_documents(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.dialogflow_v2beta1.types.ImportDocumentsRequest, dict]]): - 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. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.api_core.operation_async.AsyncOperation: - An object representing a long-running operation. - - The result type for the operation will be :class:`google.cloud.dialogflow_v2beta1.types.ImportDocumentsResponse` Response message for - [Documents.ImportDocuments][google.cloud.dialogflow.v2beta1.Documents.ImportDocuments]. - - """ - # Create or coerce a protobuf request object. - request = document.ImportDocumentsRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.import_documents, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Wrap the response in an operation future. - response = operation_async.from_gapic( - response, - self._client._transport.operations_client, - document.ImportDocumentsResponse, - metadata_type=document.KnowledgeOperationMetadata, - ) - - # Done; return the response. - return response - - async def delete_document(self, - request: Optional[Union[document.DeleteDocumentRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation_async.AsyncOperation: - r"""Deletes the specified document. - - This method is a `long-running - operation `__. - The returned ``Operation`` type has the following - method-specific fields: - - - ``metadata``: - [KnowledgeOperationMetadata][google.cloud.dialogflow.v2beta1.KnowledgeOperationMetadata] - - ``response``: An `Empty - message `__ - - Note: The ``projects.agent.knowledgeBases.documents`` resource - is deprecated; only use ``projects.knowledgeBases.documents``. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import dialogflow_v2beta1 - - async def sample_delete_document(): - # Create a client - client = dialogflow_v2beta1.DocumentsAsyncClient() - - # Initialize request argument(s) - request = dialogflow_v2beta1.DeleteDocumentRequest( - name="name_value", - ) - - # Make the request - operation = client.delete_document(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.dialogflow_v2beta1.types.DeleteDocumentRequest, dict]]): - The request object. Request message for - [Documents.DeleteDocument][google.cloud.dialogflow.v2beta1.Documents.DeleteDocument]. - name (:class:`str`): - Required. The name of the document to delete. Format: - ``projects//locations//knowledgeBases//documents/``. - - 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.api_core.operation_async.AsyncOperation: - An object representing a long-running operation. - - The result type for the operation will be :class:`google.protobuf.empty_pb2.Empty` A generic empty message that you can re-use to avoid defining duplicated - empty messages in your APIs. A typical example is to - use it as the request or the response type of an API - method. For instance: - - service Foo { - rpc Bar(google.protobuf.Empty) returns - (google.protobuf.Empty); - - } - - """ - # Create or coerce a protobuf request object. - # Quick 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 = document.DeleteDocumentRequest(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_document, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Wrap the response in an operation future. - response = operation_async.from_gapic( - response, - self._client._transport.operations_client, - empty_pb2.Empty, - metadata_type=document.KnowledgeOperationMetadata, - ) - - # Done; return the response. - return response - - async def update_document(self, - request: Optional[Union[gcd_document.UpdateDocumentRequest, dict]] = None, - *, - document: Optional[gcd_document.Document] = None, - update_mask: Optional[field_mask_pb2.FieldMask] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation_async.AsyncOperation: - r"""Updates the specified document. - - This method is a `long-running - operation `__. - The returned ``Operation`` type has the following - method-specific fields: - - - ``metadata``: - [KnowledgeOperationMetadata][google.cloud.dialogflow.v2beta1.KnowledgeOperationMetadata] - - ``response``: - [Document][google.cloud.dialogflow.v2beta1.Document] - - Note: The ``projects.agent.knowledgeBases.documents`` resource - is deprecated; only use ``projects.knowledgeBases.documents``. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import dialogflow_v2beta1 - - async def sample_update_document(): - # Create a client - client = dialogflow_v2beta1.DocumentsAsyncClient() - - # Initialize request argument(s) - document = dialogflow_v2beta1.Document() - document.content_uri = "content_uri_value" - document.display_name = "display_name_value" - document.mime_type = "mime_type_value" - document.knowledge_types = ['SMART_REPLY'] - - request = dialogflow_v2beta1.UpdateDocumentRequest( - document=document, - ) - - # Make the request - operation = client.update_document(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.dialogflow_v2beta1.types.UpdateDocumentRequest, dict]]): - The request object. Request message for - [Documents.UpdateDocument][google.cloud.dialogflow.v2beta1.Documents.UpdateDocument]. - document (:class:`google.cloud.dialogflow_v2beta1.types.Document`): - Required. The document to update. - This corresponds to the ``document`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - update_mask (:class:`google.protobuf.field_mask_pb2.FieldMask`): - Optional. Not specified means ``update all``. Currently, - only ``display_name`` can be updated, an InvalidArgument - will be returned for attempting to update other fields. - - 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.api_core.operation_async.AsyncOperation: - An object representing a long-running operation. - - The result type for the operation will be :class:`google.cloud.dialogflow_v2beta1.types.Document` A knowledge document to be used by a - [KnowledgeBase][google.cloud.dialogflow.v2beta1.KnowledgeBase]. - - For more information, see the [knowledge base - guide](\ https://cloud.google.com/dialogflow/docs/how/knowledge-bases). - - Note: The projects.agent.knowledgeBases.documents - resource is deprecated; only use - projects.knowledgeBases.documents. - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([document, 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_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: - 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_document, - 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(( - ("document.name", request.document.name), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Wrap the response in an operation future. - response = operation_async.from_gapic( - response, - self._client._transport.operations_client, - gcd_document.Document, - metadata_type=gcd_document.KnowledgeOperationMetadata, - ) - - # Done; return the response. - return response - - async def reload_document(self, - request: Optional[Union[document.ReloadDocumentRequest, dict]] = None, - *, - name: Optional[str] = None, - gcs_source: Optional[gcs.GcsSource] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation_async.AsyncOperation: - r"""Reloads the specified document from its specified source, - content_uri or content. The previously loaded content of the - document will be deleted. Note: Even when the content of the - document has not changed, there still may be side effects - because of internal implementation changes. Note: If the - document source is Google Cloud Storage URI, its metadata will - be replaced with the custom metadata from Google Cloud Storage - if the ``import_gcs_custom_metadata`` field is set to true in - the request. - - This method is a `long-running - operation `__. - The returned ``Operation`` type has the following - method-specific fields: - - - ``metadata``: - [KnowledgeOperationMetadata][google.cloud.dialogflow.v2beta1.KnowledgeOperationMetadata] - - ``response``: - [Document][google.cloud.dialogflow.v2beta1.Document] - - Note: The ``projects.agent.knowledgeBases.documents`` resource - is deprecated; only use ``projects.knowledgeBases.documents``. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import dialogflow_v2beta1 - - async def sample_reload_document(): - # Create a client - client = dialogflow_v2beta1.DocumentsAsyncClient() - - # Initialize request argument(s) - request = dialogflow_v2beta1.ReloadDocumentRequest( - name="name_value", - ) - - # Make the request - operation = client.reload_document(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.dialogflow_v2beta1.types.ReloadDocumentRequest, dict]]): - The request object. Request message for - [Documents.ReloadDocument][google.cloud.dialogflow.v2beta1.Documents.ReloadDocument]. - name (:class:`str`): - Required. The name of the document to reload. Format: - ``projects//locations//knowledgeBases//documents/`` - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - gcs_source (:class:`google.cloud.dialogflow_v2beta1.types.GcsSource`): - The path for a Cloud Storage source - file for reloading document content. If - not provided, the Document's existing - source will be reloaded. - - 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. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.api_core.operation_async.AsyncOperation: - An object representing a long-running operation. - - The result type for the operation will be :class:`google.cloud.dialogflow_v2beta1.types.Document` A knowledge document to be used by a - [KnowledgeBase][google.cloud.dialogflow.v2beta1.KnowledgeBase]. - - For more information, see the [knowledge base - guide](\ https://cloud.google.com/dialogflow/docs/how/knowledge-bases). - - Note: The projects.agent.knowledgeBases.documents - resource is deprecated; only use - projects.knowledgeBases.documents. - - """ - # Create or coerce a protobuf request object. - # Quick 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, gcs_source]) - 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 = 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: - request.gcs_source = gcs_source - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.reload_document, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Wrap the response in an operation future. - response = operation_async.from_gapic( - response, - self._client._transport.operations_client, - document.Document, - metadata_type=document.KnowledgeOperationMetadata, - ) - - # Done; return the response. - return response - - async def list_operations( - self, - request: Optional[operations_pb2.ListOperationsRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operations_pb2.ListOperationsResponse: - r"""Lists operations that match the specified filter in the request. - - Args: - request (:class:`~.operations_pb2.ListOperationsRequest`): - The request object. Request message for - `ListOperations` method. - 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: - ~.operations_pb2.ListOperationsResponse: - Response message for ``ListOperations`` method. - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = operations_pb2.ListOperationsRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._client._transport.list_operations, - 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 get_operation( - self, - request: Optional[operations_pb2.GetOperationRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operations_pb2.Operation: - r"""Gets the latest state of a long-running operation. - - Args: - request (:class:`~.operations_pb2.GetOperationRequest`): - The request object. Request message for - `GetOperation` method. - 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: - ~.operations_pb2.Operation: - An ``Operation`` object. - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = operations_pb2.GetOperationRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._client._transport.get_operation, - 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 cancel_operation( - self, - request: Optional[operations_pb2.CancelOperationRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> None: - r"""Starts asynchronous cancellation on a long-running operation. - - The server makes a best effort to cancel the operation, but success - is not guaranteed. If the server doesn't support this method, it returns - `google.rpc.Code.UNIMPLEMENTED`. - - Args: - request (:class:`~.operations_pb2.CancelOperationRequest`): - The request object. Request message for - `CancelOperation` method. - 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: - None - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = operations_pb2.CancelOperationRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._client._transport.cancel_operation, - 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_location( - self, - request: Optional[locations_pb2.GetLocationRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> locations_pb2.Location: - r"""Gets information about a location. - - Args: - request (:class:`~.location_pb2.GetLocationRequest`): - The request object. Request message for - `GetLocation` method. - 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: - ~.location_pb2.Location: - Location object. - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = locations_pb2.GetLocationRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._client._transport.get_location, - 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 list_locations( - self, - request: Optional[locations_pb2.ListLocationsRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> locations_pb2.ListLocationsResponse: - r"""Lists information about the supported locations for this service. - - Args: - request (:class:`~.location_pb2.ListLocationsRequest`): - The request object. Request message for - `ListLocations` method. - 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: - ~.location_pb2.ListLocationsResponse: - Response message for ``ListLocations`` method. - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = locations_pb2.ListLocationsRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._client._transport.list_locations, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("name", request.name),)), - ) - - # Send the request. - response = await rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - async def __aenter__(self): - return self - - async def __aexit__(self, exc_type, exc, tb): - await self.transport.close() - -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) - - -__all__ = ( - "DocumentsAsyncClient", -) diff --git a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/documents/client.py b/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/documents/client.py deleted file mode 100644 index 24d780592..000000000 --- a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/documents/client.py +++ /dev/null @@ -1,1599 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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 os -import re -from typing import Dict, Mapping, MutableMapping, MutableSequence, Optional, Sequence, Tuple, Type, Union, cast - -from google.cloud.dialogflow_v2beta1 import gapic_version as package_version - -from google.api_core import client_options as client_options_lib -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import retry as retries -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 - -try: - OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] -except AttributeError: # pragma: NO COVER - OptionalRetry = Union[retries.Retry, object] # type: ignore - -from google.api_core import operation # type: ignore -from google.api_core import operation_async # type: ignore -from google.cloud.dialogflow_v2beta1.services.documents import pagers -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.cloud.location import locations_pb2 # type: ignore -from google.longrunning import operations_pb2 -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 -from .transports.rest import DocumentsRestTransport - - -class DocumentsClientMeta(type): - """Metaclass for the Documents 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[DocumentsTransport]] - _transport_registry["grpc"] = DocumentsGrpcTransport - _transport_registry["grpc_asyncio"] = DocumentsGrpcAsyncIOTransport - _transport_registry["rest"] = DocumentsRestTransport - - def get_transport_class(cls, - label: Optional[str] = None, - ) -> Type[DocumentsTransport]: - """Returns an appropriate transport class. - - Args: - label: The name of the desired transport. If none is - provided, then the first transport in the registry is used. - - Returns: - The transport class to use. - """ - # If a specific transport is requested, return that one. - if label: - return cls._transport_registry[label] - - # No transport is requested; return the default (that is, the first one - # in the dictionary). - return next(iter(cls._transport_registry.values())) - - -class DocumentsClient(metaclass=DocumentsClientMeta): - """Service for managing knowledge - [Documents][google.cloud.dialogflow.v2beta1.Document]. - """ - - @staticmethod - def _get_default_mtls_endpoint(api_endpoint): - """Converts api endpoint to mTLS endpoint. - - Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to - "*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively. - Args: - api_endpoint (Optional[str]): the api endpoint to convert. - Returns: - str: converted mTLS api endpoint. - """ - if not api_endpoint: - return api_endpoint - - mtls_endpoint_re = re.compile( - r"(?P[^.]+)(?P\.mtls)?(?P\.sandbox)?(?P\.googleapis\.com)?" - ) - - m = mtls_endpoint_re.match(api_endpoint) - name, mtls, sandbox, googledomain = m.groups() - if mtls or not googledomain: - return api_endpoint - - if sandbox: - return api_endpoint.replace( - "sandbox.googleapis.com", "mtls.sandbox.googleapis.com" - ) - - return api_endpoint.replace(".googleapis.com", ".mtls.googleapis.com") - - DEFAULT_ENDPOINT = "dialogflow.googleapis.com" - DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore - DEFAULT_ENDPOINT - ) - - @classmethod - def from_service_account_info(cls, info: dict, *args, **kwargs): - """Creates an instance of this client using the provided credentials - info. - - Args: - info (dict): The service account private key info. - args: Additional arguments to pass to the constructor. - kwargs: Additional arguments to pass to the constructor. - - Returns: - DocumentsClient: 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: - DocumentsClient: 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) -> DocumentsTransport: - """Returns the transport used by the client instance. - - Returns: - DocumentsTransport: The transport used by the client - instance. - """ - return self._transport - - @staticmethod - def document_path(project: str,knowledge_base: str,document: str,) -> str: - """Returns a fully-qualified document string.""" - return "projects/{project}/knowledgeBases/{knowledge_base}/documents/{document}".format(project=project, knowledge_base=knowledge_base, document=document, ) - - @staticmethod - def parse_document_path(path: str) -> Dict[str,str]: - """Parses a document path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/knowledgeBases/(?P.+?)/documents/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_billing_account_path(billing_account: str, ) -> str: - """Returns a fully-qualified billing_account string.""" - return "billingAccounts/{billing_account}".format(billing_account=billing_account, ) - - @staticmethod - def parse_common_billing_account_path(path: str) -> Dict[str,str]: - """Parse a billing_account path into its component segments.""" - m = re.match(r"^billingAccounts/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_folder_path(folder: str, ) -> str: - """Returns a fully-qualified folder string.""" - return "folders/{folder}".format(folder=folder, ) - - @staticmethod - def parse_common_folder_path(path: str) -> Dict[str,str]: - """Parse a folder path into its component segments.""" - m = re.match(r"^folders/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_organization_path(organization: str, ) -> str: - """Returns a fully-qualified organization string.""" - return "organizations/{organization}".format(organization=organization, ) - - @staticmethod - def parse_common_organization_path(path: str) -> Dict[str,str]: - """Parse a organization path into its component segments.""" - m = re.match(r"^organizations/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_project_path(project: str, ) -> str: - """Returns a fully-qualified project string.""" - return "projects/{project}".format(project=project, ) - - @staticmethod - def parse_common_project_path(path: str) -> Dict[str,str]: - """Parse a project path into its component segments.""" - m = re.match(r"^projects/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_location_path(project: str, location: str, ) -> str: - """Returns a fully-qualified location string.""" - return "projects/{project}/locations/{location}".format(project=project, location=location, ) - - @staticmethod - def parse_common_location_path(path: str) -> Dict[str,str]: - """Parse a location path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)$", path) - return m.groupdict() if m else {} - - @classmethod - def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[client_options_lib.ClientOptions] = None): - """Return the API endpoint and client cert source for mutual TLS. - - The client cert source is determined in the following order: - (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the - client cert source is None. - (2) if `client_options.client_cert_source` is provided, use the provided one; if the - default client cert source exists, use the default one; otherwise the client cert - source is None. - - The API endpoint is determined in the following order: - (1) if `client_options.api_endpoint` if provided, use the provided one. - (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the - default mTLS endpoint; if the environment variable is "never", use the default API - endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise - use the default API endpoint. - - More details can be found at https://google.aip.dev/auth/4114. - - Args: - client_options (google.api_core.client_options.ClientOptions): Custom options for the - client. Only the `api_endpoint` and `client_cert_source` properties may be used - in this method. - - Returns: - Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the - client cert source to use. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If any errors happen. - """ - if client_options is None: - client_options = client_options_lib.ClientOptions() - use_client_cert = os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false") - use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") - if use_client_cert not in ("true", "false"): - raise ValueError("Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`") - if use_mtls_endpoint not in ("auto", "never", "always"): - raise MutualTLSChannelError("Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`") - - # Figure out the client cert source to use. - client_cert_source = None - if use_client_cert == "true": - if client_options.client_cert_source: - client_cert_source = client_options.client_cert_source - elif mtls.has_default_client_cert_source(): - client_cert_source = mtls.default_client_cert_source() - - # Figure out which api endpoint to use. - if client_options.api_endpoint is not None: - api_endpoint = client_options.api_endpoint - elif use_mtls_endpoint == "always" or (use_mtls_endpoint == "auto" and client_cert_source): - api_endpoint = cls.DEFAULT_MTLS_ENDPOINT - else: - api_endpoint = cls.DEFAULT_ENDPOINT - - return api_endpoint, client_cert_source - - def __init__(self, *, - credentials: Optional[ga_credentials.Credentials] = None, - transport: Optional[Union[str, DocumentsTransport]] = None, - client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the documents 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, DocumentsTransport]): The - transport to use. If set to None, a transport is chosen - automatically. - client_options (Optional[Union[google.api_core.client_options.ClientOptions, dict]]): 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() - client_options = cast(client_options_lib.ClientOptions, client_options) - - api_endpoint, client_cert_source_func = self.get_mtls_endpoint_and_cert_source(client_options) - - api_key_value = getattr(client_options, "api_key", None) - if api_key_value and credentials: - raise ValueError("client_options.api_key and credentials are mutually exclusive") - - # 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, DocumentsTransport): - # transport is a DocumentsTransport instance. - if credentials or client_options.credentials_file or api_key_value: - 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: - import google.auth._default # type: ignore - - if api_key_value and hasattr(google.auth._default, "get_api_key_credentials"): - credentials = google.auth._default.get_api_key_credentials(api_key_value) - - Transport = type(self).get_transport_class(transport) - self._transport = Transport( - credentials=credentials, - credentials_file=client_options.credentials_file, - host=api_endpoint, - scopes=client_options.scopes, - client_cert_source_for_mtls=client_cert_source_func, - quota_project_id=client_options.quota_project_id, - client_info=client_info, - always_use_jwt_access=True, - api_audience=client_options.api_audience, - ) - - def list_documents(self, - request: Optional[Union[document.ListDocumentsRequest, dict]] = None, - *, - parent: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListDocumentsPager: - r"""Returns the list of all documents of the knowledge base. - - Note: The ``projects.agent.knowledgeBases.documents`` resource - is deprecated; only use ``projects.knowledgeBases.documents``. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import dialogflow_v2beta1 - - def sample_list_documents(): - # Create a client - client = dialogflow_v2beta1.DocumentsClient() - - # Initialize request argument(s) - request = dialogflow_v2beta1.ListDocumentsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_documents(request=request) - - # Handle the response - for response in page_result: - print(response) - - Args: - request (Union[google.cloud.dialogflow_v2beta1.types.ListDocumentsRequest, dict]): - The request object. Request message for - [Documents.ListDocuments][google.cloud.dialogflow.v2beta1.Documents.ListDocuments]. - parent (str): - Required. The knowledge base to list all documents for. - Format: - ``projects//locations//knowledgeBases/``. - - 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.documents.pagers.ListDocumentsPager: - Response message for - [Documents.ListDocuments][google.cloud.dialogflow.v2beta1.Documents.ListDocuments]. - - Iterating over this object will yield results and - resolve additional pages automatically. - - """ - # Create or coerce a protobuf request object. - # Quick 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 document.ListDocumentsRequest. - # There's no risk of modifying the input as we've already verified - # 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 - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.list_documents] - - # 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.ListDocumentsPager( - method=rpc, - request=request, - response=response, - metadata=metadata, - ) - - # Done; return the response. - return response - - def get_document(self, - request: Optional[Union[document.GetDocumentRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> document.Document: - r"""Retrieves the specified document. - - Note: The ``projects.agent.knowledgeBases.documents`` resource - is deprecated; only use ``projects.knowledgeBases.documents``. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import dialogflow_v2beta1 - - def sample_get_document(): - # Create a client - client = dialogflow_v2beta1.DocumentsClient() - - # Initialize request argument(s) - request = dialogflow_v2beta1.GetDocumentRequest( - name="name_value", - ) - - # Make the request - response = client.get_document(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.dialogflow_v2beta1.types.GetDocumentRequest, dict]): - The request object. Request message for - [Documents.GetDocument][google.cloud.dialogflow.v2beta1.Documents.GetDocument]. - name (str): - Required. The name of the document to retrieve. Format - ``projects//locations//knowledgeBases//documents/``. - - 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.Document: - A knowledge document to be used by a - [KnowledgeBase][google.cloud.dialogflow.v2beta1.KnowledgeBase]. - - For more information, see the [knowledge base - guide](\ https://cloud.google.com/dialogflow/docs/how/knowledge-bases). - - Note: The projects.agent.knowledgeBases.documents - resource is deprecated; only use - projects.knowledgeBases.documents. - - """ - # Create or coerce a protobuf request object. - # Quick 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 document.GetDocumentRequest. - # There's no risk of modifying the input as we've already verified - # 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 - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.get_document] - - # 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_document(self, - request: Optional[Union[gcd_document.CreateDocumentRequest, dict]] = None, - *, - parent: Optional[str] = None, - document: Optional[gcd_document.Document] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation.Operation: - r"""Creates a new document. - - This method is a `long-running - operation `__. - The returned ``Operation`` type has the following - method-specific fields: - - - ``metadata``: - [KnowledgeOperationMetadata][google.cloud.dialogflow.v2beta1.KnowledgeOperationMetadata] - - ``response``: - [Document][google.cloud.dialogflow.v2beta1.Document] - - Note: The ``projects.agent.knowledgeBases.documents`` resource - is deprecated; only use ``projects.knowledgeBases.documents``. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import dialogflow_v2beta1 - - def sample_create_document(): - # Create a client - client = dialogflow_v2beta1.DocumentsClient() - - # Initialize request argument(s) - document = dialogflow_v2beta1.Document() - document.content_uri = "content_uri_value" - document.display_name = "display_name_value" - document.mime_type = "mime_type_value" - document.knowledge_types = ['SMART_REPLY'] - - request = dialogflow_v2beta1.CreateDocumentRequest( - parent="parent_value", - document=document, - ) - - # Make the request - operation = client.create_document(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.dialogflow_v2beta1.types.CreateDocumentRequest, dict]): - The request object. Request message for - [Documents.CreateDocument][google.cloud.dialogflow.v2beta1.Documents.CreateDocument]. - parent (str): - Required. The knowledge base to create a document for. - Format: - ``projects//locations//knowledgeBases/``. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - document (google.cloud.dialogflow_v2beta1.types.Document): - Required. The document to create. - 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. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.api_core.operation.Operation: - An object representing a long-running operation. - - The result type for the operation will be :class:`google.cloud.dialogflow_v2beta1.types.Document` A knowledge document to be used by a - [KnowledgeBase][google.cloud.dialogflow.v2beta1.KnowledgeBase]. - - For more information, see the [knowledge base - guide](\ https://cloud.google.com/dialogflow/docs/how/knowledge-bases). - - Note: The projects.agent.knowledgeBases.documents - resource is deprecated; only use - projects.knowledgeBases.documents. - - """ - # Create or coerce a protobuf request object. - # Quick 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, document]) - 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_document.CreateDocumentRequest. - # There's no risk of modifying the input as we've already verified - # 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: - request.document = document - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.create_document] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Wrap the response in an operation future. - response = operation.from_gapic( - response, - self._transport.operations_client, - gcd_document.Document, - metadata_type=gcd_document.KnowledgeOperationMetadata, - ) - - # Done; return the response. - return response - - def import_documents(self, - request: Optional[Union[document.ImportDocumentsRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation.Operation: - r"""Create documents by importing data from external sources. - Dialogflow supports up to 350 documents in each request. If you - try to import more, Dialogflow will return an error. - - This method is a `long-running - operation `__. - The returned ``Operation`` type has the following - method-specific fields: - - - ``metadata``: - [KnowledgeOperationMetadata][google.cloud.dialogflow.v2beta1.KnowledgeOperationMetadata] - - ``response``: - [ImportDocumentsResponse][google.cloud.dialogflow.v2beta1.ImportDocumentsResponse] - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import dialogflow_v2beta1 - - def sample_import_documents(): - # Create a client - client = dialogflow_v2beta1.DocumentsClient() - - # Initialize request argument(s) - gcs_source = dialogflow_v2beta1.GcsSources() - gcs_source.uris = ['uris_value1', 'uris_value2'] - - document_template = dialogflow_v2beta1.ImportDocumentTemplate() - document_template.mime_type = "mime_type_value" - document_template.knowledge_types = ['SMART_REPLY'] - - request = dialogflow_v2beta1.ImportDocumentsRequest( - gcs_source=gcs_source, - parent="parent_value", - document_template=document_template, - ) - - # Make the request - operation = client.import_documents(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.dialogflow_v2beta1.types.ImportDocumentsRequest, dict]): - 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. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.api_core.operation.Operation: - An object representing a long-running operation. - - The result type for the operation will be :class:`google.cloud.dialogflow_v2beta1.types.ImportDocumentsResponse` Response message for - [Documents.ImportDocuments][google.cloud.dialogflow.v2beta1.Documents.ImportDocuments]. - - """ - # 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 - # there are no flattened fields. - if not isinstance(request, document.ImportDocumentsRequest): - request = document.ImportDocumentsRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.import_documents] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Wrap the response in an operation future. - response = operation.from_gapic( - response, - self._transport.operations_client, - document.ImportDocumentsResponse, - metadata_type=document.KnowledgeOperationMetadata, - ) - - # Done; return the response. - return response - - def delete_document(self, - request: Optional[Union[document.DeleteDocumentRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation.Operation: - r"""Deletes the specified document. - - This method is a `long-running - operation `__. - The returned ``Operation`` type has the following - method-specific fields: - - - ``metadata``: - [KnowledgeOperationMetadata][google.cloud.dialogflow.v2beta1.KnowledgeOperationMetadata] - - ``response``: An `Empty - message `__ - - Note: The ``projects.agent.knowledgeBases.documents`` resource - is deprecated; only use ``projects.knowledgeBases.documents``. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import dialogflow_v2beta1 - - def sample_delete_document(): - # Create a client - client = dialogflow_v2beta1.DocumentsClient() - - # Initialize request argument(s) - request = dialogflow_v2beta1.DeleteDocumentRequest( - name="name_value", - ) - - # Make the request - operation = client.delete_document(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.dialogflow_v2beta1.types.DeleteDocumentRequest, dict]): - The request object. Request message for - [Documents.DeleteDocument][google.cloud.dialogflow.v2beta1.Documents.DeleteDocument]. - name (str): - Required. The name of the document to delete. Format: - ``projects//locations//knowledgeBases//documents/``. - - 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.api_core.operation.Operation: - An object representing a long-running operation. - - The result type for the operation will be :class:`google.protobuf.empty_pb2.Empty` A generic empty message that you can re-use to avoid defining duplicated - empty messages in your APIs. A typical example is to - use it as the request or the response type of an API - method. For instance: - - service Foo { - rpc Bar(google.protobuf.Empty) returns - (google.protobuf.Empty); - - } - - """ - # Create or coerce a protobuf request object. - # Quick 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 document.DeleteDocumentRequest. - # There's no risk of modifying the input as we've already verified - # 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 - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.delete_document] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Wrap the response in an operation future. - response = operation.from_gapic( - response, - self._transport.operations_client, - empty_pb2.Empty, - metadata_type=document.KnowledgeOperationMetadata, - ) - - # Done; return the response. - return response - - def update_document(self, - request: Optional[Union[gcd_document.UpdateDocumentRequest, dict]] = None, - *, - document: Optional[gcd_document.Document] = None, - update_mask: Optional[field_mask_pb2.FieldMask] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation.Operation: - r"""Updates the specified document. - - This method is a `long-running - operation `__. - The returned ``Operation`` type has the following - method-specific fields: - - - ``metadata``: - [KnowledgeOperationMetadata][google.cloud.dialogflow.v2beta1.KnowledgeOperationMetadata] - - ``response``: - [Document][google.cloud.dialogflow.v2beta1.Document] - - Note: The ``projects.agent.knowledgeBases.documents`` resource - is deprecated; only use ``projects.knowledgeBases.documents``. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import dialogflow_v2beta1 - - def sample_update_document(): - # Create a client - client = dialogflow_v2beta1.DocumentsClient() - - # Initialize request argument(s) - document = dialogflow_v2beta1.Document() - document.content_uri = "content_uri_value" - document.display_name = "display_name_value" - document.mime_type = "mime_type_value" - document.knowledge_types = ['SMART_REPLY'] - - request = dialogflow_v2beta1.UpdateDocumentRequest( - document=document, - ) - - # Make the request - operation = client.update_document(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.dialogflow_v2beta1.types.UpdateDocumentRequest, dict]): - The request object. Request message for - [Documents.UpdateDocument][google.cloud.dialogflow.v2beta1.Documents.UpdateDocument]. - document (google.cloud.dialogflow_v2beta1.types.Document): - Required. The document to update. - This corresponds to the ``document`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - update_mask (google.protobuf.field_mask_pb2.FieldMask): - Optional. Not specified means ``update all``. Currently, - only ``display_name`` can be updated, an InvalidArgument - will be returned for attempting to update other fields. - - 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.api_core.operation.Operation: - An object representing a long-running operation. - - The result type for the operation will be :class:`google.cloud.dialogflow_v2beta1.types.Document` A knowledge document to be used by a - [KnowledgeBase][google.cloud.dialogflow.v2beta1.KnowledgeBase]. - - For more information, see the [knowledge base - guide](\ https://cloud.google.com/dialogflow/docs/how/knowledge-bases). - - Note: The projects.agent.knowledgeBases.documents - resource is deprecated; only use - projects.knowledgeBases.documents. - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([document, 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_document.UpdateDocumentRequest. - # There's no risk of modifying the input as we've already verified - # 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: - 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_document] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("document.name", request.document.name), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Wrap the response in an operation future. - response = operation.from_gapic( - response, - self._transport.operations_client, - gcd_document.Document, - metadata_type=gcd_document.KnowledgeOperationMetadata, - ) - - # Done; return the response. - return response - - def reload_document(self, - request: Optional[Union[document.ReloadDocumentRequest, dict]] = None, - *, - name: Optional[str] = None, - gcs_source: Optional[gcs.GcsSource] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation.Operation: - r"""Reloads the specified document from its specified source, - content_uri or content. The previously loaded content of the - document will be deleted. Note: Even when the content of the - document has not changed, there still may be side effects - because of internal implementation changes. Note: If the - document source is Google Cloud Storage URI, its metadata will - be replaced with the custom metadata from Google Cloud Storage - if the ``import_gcs_custom_metadata`` field is set to true in - the request. - - This method is a `long-running - operation `__. - The returned ``Operation`` type has the following - method-specific fields: - - - ``metadata``: - [KnowledgeOperationMetadata][google.cloud.dialogflow.v2beta1.KnowledgeOperationMetadata] - - ``response``: - [Document][google.cloud.dialogflow.v2beta1.Document] - - Note: The ``projects.agent.knowledgeBases.documents`` resource - is deprecated; only use ``projects.knowledgeBases.documents``. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import dialogflow_v2beta1 - - def sample_reload_document(): - # Create a client - client = dialogflow_v2beta1.DocumentsClient() - - # Initialize request argument(s) - request = dialogflow_v2beta1.ReloadDocumentRequest( - name="name_value", - ) - - # Make the request - operation = client.reload_document(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.dialogflow_v2beta1.types.ReloadDocumentRequest, dict]): - The request object. Request message for - [Documents.ReloadDocument][google.cloud.dialogflow.v2beta1.Documents.ReloadDocument]. - name (str): - Required. The name of the document to reload. Format: - ``projects//locations//knowledgeBases//documents/`` - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - gcs_source (google.cloud.dialogflow_v2beta1.types.GcsSource): - The path for a Cloud Storage source - file for reloading document content. If - not provided, the Document's existing - source will be reloaded. - - 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. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.api_core.operation.Operation: - An object representing a long-running operation. - - The result type for the operation will be :class:`google.cloud.dialogflow_v2beta1.types.Document` A knowledge document to be used by a - [KnowledgeBase][google.cloud.dialogflow.v2beta1.KnowledgeBase]. - - For more information, see the [knowledge base - guide](\ https://cloud.google.com/dialogflow/docs/how/knowledge-bases). - - Note: The projects.agent.knowledgeBases.documents - resource is deprecated; only use - projects.knowledgeBases.documents. - - """ - # Create or coerce a protobuf request object. - # Quick 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, gcs_source]) - 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 document.ReloadDocumentRequest. - # There's no risk of modifying the input as we've already verified - # 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: - request.gcs_source = gcs_source - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.reload_document] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Wrap the response in an operation future. - response = operation.from_gapic( - response, - self._transport.operations_client, - document.Document, - metadata_type=document.KnowledgeOperationMetadata, - ) - - # Done; return the response. - return response - - def __enter__(self) -> "DocumentsClient": - return self - - def __exit__(self, type, value, traceback): - """Releases underlying transport's resources. - - .. warning:: - ONLY use as a context manager if the transport is NOT shared - with other clients! Exiting the with block will CLOSE the transport - and may cause errors in other clients! - """ - self.transport.close() - - def list_operations( - self, - request: Optional[operations_pb2.ListOperationsRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operations_pb2.ListOperationsResponse: - r"""Lists operations that match the specified filter in the request. - - Args: - request (:class:`~.operations_pb2.ListOperationsRequest`): - The request object. Request message for - `ListOperations` method. - 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: - ~.operations_pb2.ListOperationsResponse: - Response message for ``ListOperations`` method. - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = operations_pb2.ListOperationsRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._transport.list_operations, - 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 = rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - def get_operation( - self, - request: Optional[operations_pb2.GetOperationRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operations_pb2.Operation: - r"""Gets the latest state of a long-running operation. - - Args: - request (:class:`~.operations_pb2.GetOperationRequest`): - The request object. Request message for - `GetOperation` method. - 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: - ~.operations_pb2.Operation: - An ``Operation`` object. - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = operations_pb2.GetOperationRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._transport.get_operation, - 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 = rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - def cancel_operation( - self, - request: Optional[operations_pb2.CancelOperationRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> None: - r"""Starts asynchronous cancellation on a long-running operation. - - The server makes a best effort to cancel the operation, but success - is not guaranteed. If the server doesn't support this method, it returns - `google.rpc.Code.UNIMPLEMENTED`. - - Args: - request (:class:`~.operations_pb2.CancelOperationRequest`): - The request object. Request message for - `CancelOperation` method. - 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: - None - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = operations_pb2.CancelOperationRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._transport.cancel_operation, - 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. - rpc(request, retry=retry, timeout=timeout, metadata=metadata,) - - def get_location( - self, - request: Optional[locations_pb2.GetLocationRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> locations_pb2.Location: - r"""Gets information about a location. - - Args: - request (:class:`~.location_pb2.GetLocationRequest`): - The request object. Request message for - `GetLocation` method. - 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: - ~.location_pb2.Location: - Location object. - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = locations_pb2.GetLocationRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._transport.get_location, - 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 = rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - def list_locations( - self, - request: Optional[locations_pb2.ListLocationsRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> locations_pb2.ListLocationsResponse: - r"""Lists information about the supported locations for this service. - - Args: - request (:class:`~.location_pb2.ListLocationsRequest`): - The request object. Request message for - `ListLocations` method. - 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: - ~.location_pb2.ListLocationsResponse: - Response message for ``ListLocations`` method. - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = locations_pb2.ListLocationsRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._transport.list_locations, - 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 = rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) - - -__all__ = ( - "DocumentsClient", -) diff --git a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/documents/pagers.py b/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/documents/pagers.py deleted file mode 100644 index d15b51f1b..000000000 --- a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/documents/pagers.py +++ /dev/null @@ -1,139 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from typing import Any, AsyncIterator, Awaitable, Callable, Sequence, Tuple, Optional, Iterator - -from google.cloud.dialogflow_v2beta1.types import document - - -class ListDocumentsPager: - """A pager for iterating through ``list_documents`` requests. - - This class thinly wraps an initial - :class:`google.cloud.dialogflow_v2beta1.types.ListDocumentsResponse` object, and - provides an ``__iter__`` method to iterate through its - ``documents`` field. - - If there are more pages, the ``__iter__`` method will make additional - ``ListDocuments`` requests and continue to iterate - through the ``documents`` field on the - corresponding responses. - - All the usual :class:`google.cloud.dialogflow_v2beta1.types.ListDocumentsResponse` - 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[..., document.ListDocumentsResponse], - request: document.ListDocumentsRequest, - response: document.ListDocumentsResponse, - *, - 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.ListDocumentsRequest): - The initial request object. - response (google.cloud.dialogflow_v2beta1.types.ListDocumentsResponse): - 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 = document.ListDocumentsRequest(request) - self._response = response - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - def pages(self) -> Iterator[document.ListDocumentsResponse]: - yield self._response - while self._response.next_page_token: - self._request.page_token = self._response.next_page_token - self._response = self._method(self._request, metadata=self._metadata) - yield self._response - - def __iter__(self) -> Iterator[document.Document]: - for page in self.pages: - yield from page.documents - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListDocumentsAsyncPager: - """A pager for iterating through ``list_documents`` requests. - - This class thinly wraps an initial - :class:`google.cloud.dialogflow_v2beta1.types.ListDocumentsResponse` object, and - provides an ``__aiter__`` method to iterate through its - ``documents`` field. - - If there are more pages, the ``__aiter__`` method will make additional - ``ListDocuments`` requests and continue to iterate - through the ``documents`` field on the - corresponding responses. - - All the usual :class:`google.cloud.dialogflow_v2beta1.types.ListDocumentsResponse` - 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[document.ListDocumentsResponse]], - request: document.ListDocumentsRequest, - response: document.ListDocumentsResponse, - *, - metadata: Sequence[Tuple[str, str]] = ()): - """Instantiates the pager. - - Args: - method (Callable): The method that was originally called, and - which instantiated this pager. - request (google.cloud.dialogflow_v2beta1.types.ListDocumentsRequest): - The initial request object. - response (google.cloud.dialogflow_v2beta1.types.ListDocumentsResponse): - 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 = document.ListDocumentsRequest(request) - self._response = response - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - async def pages(self) -> AsyncIterator[document.ListDocumentsResponse]: - yield self._response - while self._response.next_page_token: - self._request.page_token = self._response.next_page_token - self._response = await self._method(self._request, metadata=self._metadata) - yield self._response - def __aiter__(self) -> AsyncIterator[document.Document]: - async def async_generator(): - async for page in self.pages: - for response in page.documents: - yield response - - return async_generator() - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) diff --git a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/documents/transports/__init__.py b/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/documents/transports/__init__.py deleted file mode 100644 index 4eb72cff2..000000000 --- a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/documents/transports/__init__.py +++ /dev/null @@ -1,38 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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 DocumentsTransport -from .grpc import DocumentsGrpcTransport -from .grpc_asyncio import DocumentsGrpcAsyncIOTransport -from .rest import DocumentsRestTransport -from .rest import DocumentsRestInterceptor - - -# Compile a registry of transports. -_transport_registry = OrderedDict() # type: Dict[str, Type[DocumentsTransport]] -_transport_registry['grpc'] = DocumentsGrpcTransport -_transport_registry['grpc_asyncio'] = DocumentsGrpcAsyncIOTransport -_transport_registry['rest'] = DocumentsRestTransport - -__all__ = ( - 'DocumentsTransport', - 'DocumentsGrpcTransport', - 'DocumentsGrpcAsyncIOTransport', - 'DocumentsRestTransport', - 'DocumentsRestInterceptor', -) diff --git a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/documents/transports/base.py b/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/documents/transports/base.py deleted file mode 100644 index c88c194d9..000000000 --- a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/documents/transports/base.py +++ /dev/null @@ -1,286 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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 - -from google.cloud.dialogflow_v2beta1 import gapic_version as package_version - -import google.auth # type: ignore -import google.api_core -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import retry as retries -from google.api_core import operations_v1 -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 document -from google.cloud.dialogflow_v2beta1.types import document as gcd_document -from google.cloud.location import locations_pb2 # type: ignore -from google.longrunning import operations_pb2 -from google.longrunning import operations_pb2 # type: ignore - -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) - - -class DocumentsTransport(abc.ABC): - """Abstract transport class for Documents.""" - - 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: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - api_audience: Optional[str] = None, - **kwargs, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. - scopes (Optional[Sequence[str]]): A list of scopes. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - """ - - scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} - - # Save the scopes. - self._scopes = scopes - - # If no credentials are provided, then determine the appropriate - # defaults. - if credentials and credentials_file: - raise core_exceptions.DuplicateCredentialArgs("'credentials_file' and 'credentials' are mutually exclusive") - - if credentials_file is not None: - credentials, _ = google.auth.load_credentials_from_file( - credentials_file, - **scopes_kwargs, - quota_project_id=quota_project_id - ) - elif credentials is None: - credentials, _ = google.auth.default(**scopes_kwargs, quota_project_id=quota_project_id) - # Don't apply audience if the credentials file passed from user. - if hasattr(credentials, "with_gdch_audience"): - credentials = credentials.with_gdch_audience(api_audience if api_audience else host) - - # If the credentials are service account credentials, then always try to use self signed JWT. - if always_use_jwt_access and isinstance(credentials, service_account.Credentials) and hasattr(service_account.Credentials, "with_always_use_jwt_access"): - credentials = credentials.with_always_use_jwt_access(True) - - # Save the credentials. - self._credentials = credentials - - # Save the hostname. Default to port 443 (HTTPS) if none is specified. - if ':' not in host: - host += ':443' - self._host = host - - def _prep_wrapped_messages(self, client_info): - # Precompute the wrapped methods. - self._wrapped_methods = { - self.list_documents: gapic_v1.method.wrap_method( - self.list_documents, - default_timeout=None, - client_info=client_info, - ), - self.get_document: gapic_v1.method.wrap_method( - self.get_document, - default_timeout=None, - client_info=client_info, - ), - self.create_document: gapic_v1.method.wrap_method( - self.create_document, - default_timeout=None, - client_info=client_info, - ), - self.import_documents: gapic_v1.method.wrap_method( - self.import_documents, - default_timeout=None, - client_info=client_info, - ), - self.delete_document: gapic_v1.method.wrap_method( - self.delete_document, - default_timeout=None, - client_info=client_info, - ), - self.update_document: gapic_v1.method.wrap_method( - self.update_document, - default_timeout=None, - client_info=client_info, - ), - self.reload_document: gapic_v1.method.wrap_method( - self.reload_document, - default_timeout=None, - client_info=client_info, - ), - } - - def close(self): - """Closes resources associated with the transport. - - .. warning:: - Only call this method if the transport is NOT shared - with other clients - this may cause errors in other clients! - """ - raise NotImplementedError() - - @property - def operations_client(self): - """Return the client designed to process long-running operations.""" - raise NotImplementedError() - - @property - def list_documents(self) -> Callable[ - [document.ListDocumentsRequest], - Union[ - document.ListDocumentsResponse, - Awaitable[document.ListDocumentsResponse] - ]]: - raise NotImplementedError() - - @property - def get_document(self) -> Callable[ - [document.GetDocumentRequest], - Union[ - document.Document, - Awaitable[document.Document] - ]]: - raise NotImplementedError() - - @property - def create_document(self) -> Callable[ - [gcd_document.CreateDocumentRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: - raise NotImplementedError() - - @property - def import_documents(self) -> Callable[ - [document.ImportDocumentsRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: - raise NotImplementedError() - - @property - def delete_document(self) -> Callable[ - [document.DeleteDocumentRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: - raise NotImplementedError() - - @property - def update_document(self) -> Callable[ - [gcd_document.UpdateDocumentRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: - raise NotImplementedError() - - @property - def reload_document(self) -> Callable[ - [document.ReloadDocumentRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: - raise NotImplementedError() - - @property - def list_operations( - self, - ) -> Callable[ - [operations_pb2.ListOperationsRequest], - Union[operations_pb2.ListOperationsResponse, Awaitable[operations_pb2.ListOperationsResponse]], - ]: - raise NotImplementedError() - - @property - def get_operation( - self, - ) -> Callable[ - [operations_pb2.GetOperationRequest], - Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], - ]: - raise NotImplementedError() - - @property - def cancel_operation( - self, - ) -> Callable[ - [operations_pb2.CancelOperationRequest], - None, - ]: - raise NotImplementedError() - - @property - def get_location(self, - ) -> Callable[ - [locations_pb2.GetLocationRequest], - Union[locations_pb2.Location, Awaitable[locations_pb2.Location]], - ]: - raise NotImplementedError() - - @property - def list_locations(self, - ) -> Callable[ - [locations_pb2.ListLocationsRequest], - Union[locations_pb2.ListLocationsResponse, Awaitable[locations_pb2.ListLocationsResponse]], - ]: - raise NotImplementedError() - - @property - def kind(self) -> str: - raise NotImplementedError() - - -__all__ = ( - 'DocumentsTransport', -) diff --git a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/documents/transports/grpc.py b/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/documents/transports/grpc.py deleted file mode 100644 index 3315049d2..000000000 --- a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/documents/transports/grpc.py +++ /dev/null @@ -1,611 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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 -from google.api_core import operations_v1 -from google.api_core import gapic_v1 -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.cloud.location import locations_pb2 # type: ignore -from google.longrunning import operations_pb2 -from google.longrunning import operations_pb2 # type: ignore -from .base import DocumentsTransport, DEFAULT_CLIENT_INFO - - -class DocumentsGrpcTransport(DocumentsTransport): - """gRPC backend transport for Documents. - - Service for managing knowledge - [Documents][google.cloud.dialogflow.v2beta1.Document]. - - 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: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - channel: Optional[grpc.Channel] = None, - api_mtls_endpoint: Optional[str] = None, - client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, - ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, - client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - api_audience: Optional[str] = None, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - This argument is ignored if ``channel`` is provided. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional(Sequence[str])): A list of scopes. This argument is - ignored if ``channel`` is provided. - channel (Optional[grpc.Channel]): A ``Channel`` instance through - which to make calls. - api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. - If provided, it overrides the ``host`` argument and tries to create - a mutual TLS channel with client SSL credentials from - ``client_cert_source`` or application default SSL credentials. - client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): - Deprecated. A callback to provide client SSL certificate bytes and - private key bytes, both in PEM format. It is ignored if - ``api_mtls_endpoint`` is None. - ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials - for the grpc channel. It is ignored if ``channel`` is provided. - client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): - A callback to provide client certificate bytes and private key bytes, - both in PEM format. It is used to configure a mutual TLS channel. It is - ignored if ``channel`` or ``ssl_channel_credentials`` is provided. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport - creation failed for any reason. - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - self._grpc_channel = None - self._ssl_channel_credentials = ssl_channel_credentials - self._stubs: Dict[str, Callable] = {} - self._operations_client: Optional[operations_v1.OperationsClient] = None - - if api_mtls_endpoint: - warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) - if client_cert_source: - warnings.warn("client_cert_source is deprecated", DeprecationWarning) - - if channel: - # Ignore credentials if a channel was passed. - credentials = False - # If a channel was explicitly provided, set it. - self._grpc_channel = channel - self._ssl_channel_credentials = None - - else: - if api_mtls_endpoint: - host = api_mtls_endpoint - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - self._ssl_channel_credentials = SslCredentials().ssl_credentials - - else: - if client_cert_source_for_mtls and not ssl_channel_credentials: - cert, key = client_cert_source_for_mtls() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - - # The base transport sets the host, credentials and scopes - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes, - quota_project_id=quota_project_id, - client_info=client_info, - always_use_jwt_access=always_use_jwt_access, - api_audience=api_audience, - ) - - if not self._grpc_channel: - self._grpc_channel = type(self).create_channel( - self._host, - # use the credentials which are saved - credentials=self._credentials, - # Set ``credentials_file`` to ``None`` here as - # the credentials that we saved earlier should be used. - credentials_file=None, - 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: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - **kwargs) -> grpc.Channel: - """Create and return a gRPC channel object. - Args: - host (Optional[str]): The host for the channel to use. - credentials (Optional[~.Credentials]): The - authorization credentials to attach to requests. These - credentials identify this application to the service. If - none are specified, the client will attempt to ascertain - the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - kwargs (Optional[dict]): Keyword arguments, which are passed to the - channel creation. - Returns: - grpc.Channel: A gRPC channel object. - - Raises: - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - - return grpc_helpers.create_channel( - host, - credentials=credentials, - credentials_file=credentials_file, - quota_project_id=quota_project_id, - default_scopes=cls.AUTH_SCOPES, - scopes=scopes, - default_host=cls.DEFAULT_HOST, - **kwargs - ) - - @property - def grpc_channel(self) -> grpc.Channel: - """Return the channel designed to connect to this service. - """ - return self._grpc_channel - - @property - def operations_client(self) -> operations_v1.OperationsClient: - """Create the client designed to process long-running operations. - - This property caches on the instance; repeated calls return the same - client. - """ - # Quick check: Only create a new client if we do not already have one. - if self._operations_client is None: - self._operations_client = operations_v1.OperationsClient( - self.grpc_channel - ) - - # Return the client from cache. - return self._operations_client - - @property - def list_documents(self) -> Callable[ - [document.ListDocumentsRequest], - document.ListDocumentsResponse]: - r"""Return a callable for the list documents method over gRPC. - - Returns the list of all documents of the knowledge base. - - Note: The ``projects.agent.knowledgeBases.documents`` resource - is deprecated; only use ``projects.knowledgeBases.documents``. - - Returns: - Callable[[~.ListDocumentsRequest], - ~.ListDocumentsResponse]: - 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_documents' not in self._stubs: - self._stubs['list_documents'] = self.grpc_channel.unary_unary( - '/google.cloud.dialogflow.v2beta1.Documents/ListDocuments', - request_serializer=document.ListDocumentsRequest.serialize, - response_deserializer=document.ListDocumentsResponse.deserialize, - ) - return self._stubs['list_documents'] - - @property - def get_document(self) -> Callable[ - [document.GetDocumentRequest], - document.Document]: - r"""Return a callable for the get document method over gRPC. - - Retrieves the specified document. - - Note: The ``projects.agent.knowledgeBases.documents`` resource - is deprecated; only use ``projects.knowledgeBases.documents``. - - Returns: - Callable[[~.GetDocumentRequest], - ~.Document]: - 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_document' not in self._stubs: - self._stubs['get_document'] = self.grpc_channel.unary_unary( - '/google.cloud.dialogflow.v2beta1.Documents/GetDocument', - request_serializer=document.GetDocumentRequest.serialize, - response_deserializer=document.Document.deserialize, - ) - return self._stubs['get_document'] - - @property - def create_document(self) -> Callable[ - [gcd_document.CreateDocumentRequest], - operations_pb2.Operation]: - r"""Return a callable for the create document method over gRPC. - - Creates a new document. - - This method is a `long-running - operation `__. - The returned ``Operation`` type has the following - method-specific fields: - - - ``metadata``: - [KnowledgeOperationMetadata][google.cloud.dialogflow.v2beta1.KnowledgeOperationMetadata] - - ``response``: - [Document][google.cloud.dialogflow.v2beta1.Document] - - Note: The ``projects.agent.knowledgeBases.documents`` resource - is deprecated; only use ``projects.knowledgeBases.documents``. - - Returns: - Callable[[~.CreateDocumentRequest], - ~.Operation]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'create_document' not in self._stubs: - self._stubs['create_document'] = self.grpc_channel.unary_unary( - '/google.cloud.dialogflow.v2beta1.Documents/CreateDocument', - request_serializer=gcd_document.CreateDocumentRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['create_document'] - - @property - def import_documents(self) -> 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. - Dialogflow supports up to 350 documents in each request. If you - try to import more, Dialogflow will return an error. - - This method is a `long-running - operation `__. - The returned ``Operation`` type has the following - method-specific fields: - - - ``metadata``: - [KnowledgeOperationMetadata][google.cloud.dialogflow.v2beta1.KnowledgeOperationMetadata] - - ``response``: - [ImportDocumentsResponse][google.cloud.dialogflow.v2beta1.ImportDocumentsResponse] - - Returns: - Callable[[~.ImportDocumentsRequest], - ~.Operation]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'import_documents' not in self._stubs: - self._stubs['import_documents'] = self.grpc_channel.unary_unary( - '/google.cloud.dialogflow.v2beta1.Documents/ImportDocuments', - request_serializer=document.ImportDocumentsRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['import_documents'] - - @property - def delete_document(self) -> Callable[ - [document.DeleteDocumentRequest], - operations_pb2.Operation]: - r"""Return a callable for the delete document method over gRPC. - - Deletes the specified document. - - This method is a `long-running - operation `__. - The returned ``Operation`` type has the following - method-specific fields: - - - ``metadata``: - [KnowledgeOperationMetadata][google.cloud.dialogflow.v2beta1.KnowledgeOperationMetadata] - - ``response``: An `Empty - message `__ - - Note: The ``projects.agent.knowledgeBases.documents`` resource - is deprecated; only use ``projects.knowledgeBases.documents``. - - Returns: - Callable[[~.DeleteDocumentRequest], - ~.Operation]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'delete_document' not in self._stubs: - self._stubs['delete_document'] = self.grpc_channel.unary_unary( - '/google.cloud.dialogflow.v2beta1.Documents/DeleteDocument', - request_serializer=document.DeleteDocumentRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['delete_document'] - - @property - def update_document(self) -> Callable[ - [gcd_document.UpdateDocumentRequest], - operations_pb2.Operation]: - r"""Return a callable for the update document method over gRPC. - - Updates the specified document. - - This method is a `long-running - operation `__. - The returned ``Operation`` type has the following - method-specific fields: - - - ``metadata``: - [KnowledgeOperationMetadata][google.cloud.dialogflow.v2beta1.KnowledgeOperationMetadata] - - ``response``: - [Document][google.cloud.dialogflow.v2beta1.Document] - - Note: The ``projects.agent.knowledgeBases.documents`` resource - is deprecated; only use ``projects.knowledgeBases.documents``. - - Returns: - Callable[[~.UpdateDocumentRequest], - ~.Operation]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'update_document' not in self._stubs: - self._stubs['update_document'] = self.grpc_channel.unary_unary( - '/google.cloud.dialogflow.v2beta1.Documents/UpdateDocument', - request_serializer=gcd_document.UpdateDocumentRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['update_document'] - - @property - def reload_document(self) -> 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, - content_uri or content. The previously loaded content of the - document will be deleted. Note: Even when the content of the - document has not changed, there still may be side effects - because of internal implementation changes. Note: If the - document source is Google Cloud Storage URI, its metadata will - be replaced with the custom metadata from Google Cloud Storage - if the ``import_gcs_custom_metadata`` field is set to true in - the request. - - This method is a `long-running - operation `__. - The returned ``Operation`` type has the following - method-specific fields: - - - ``metadata``: - [KnowledgeOperationMetadata][google.cloud.dialogflow.v2beta1.KnowledgeOperationMetadata] - - ``response``: - [Document][google.cloud.dialogflow.v2beta1.Document] - - Note: The ``projects.agent.knowledgeBases.documents`` resource - is deprecated; only use ``projects.knowledgeBases.documents``. - - Returns: - Callable[[~.ReloadDocumentRequest], - ~.Operation]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'reload_document' not in self._stubs: - self._stubs['reload_document'] = self.grpc_channel.unary_unary( - '/google.cloud.dialogflow.v2beta1.Documents/ReloadDocument', - request_serializer=document.ReloadDocumentRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['reload_document'] - - def close(self): - self.grpc_channel.close() - - @property - def cancel_operation( - self, - ) -> Callable[[operations_pb2.CancelOperationRequest], None]: - r"""Return a callable for the cancel_operation method over gRPC. - """ - # 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 "cancel_operation" not in self._stubs: - self._stubs["cancel_operation"] = self.grpc_channel.unary_unary( - "/google.longrunning.Operations/CancelOperation", - request_serializer=operations_pb2.CancelOperationRequest.SerializeToString, - response_deserializer=None, - ) - return self._stubs["cancel_operation"] - - @property - def get_operation( - self, - ) -> Callable[[operations_pb2.GetOperationRequest], operations_pb2.Operation]: - r"""Return a callable for the get_operation method over gRPC. - """ - # 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_operation" not in self._stubs: - self._stubs["get_operation"] = self.grpc_channel.unary_unary( - "/google.longrunning.Operations/GetOperation", - request_serializer=operations_pb2.GetOperationRequest.SerializeToString, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs["get_operation"] - - @property - def list_operations( - self, - ) -> Callable[[operations_pb2.ListOperationsRequest], operations_pb2.ListOperationsResponse]: - r"""Return a callable for the list_operations method over gRPC. - """ - # 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_operations" not in self._stubs: - self._stubs["list_operations"] = self.grpc_channel.unary_unary( - "/google.longrunning.Operations/ListOperations", - request_serializer=operations_pb2.ListOperationsRequest.SerializeToString, - response_deserializer=operations_pb2.ListOperationsResponse.FromString, - ) - return self._stubs["list_operations"] - - @property - def list_locations( - self, - ) -> Callable[[locations_pb2.ListLocationsRequest], locations_pb2.ListLocationsResponse]: - r"""Return a callable for the list locations method over gRPC. - """ - # 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_locations" not in self._stubs: - self._stubs["list_locations"] = self.grpc_channel.unary_unary( - "/google.cloud.location.Locations/ListLocations", - request_serializer=locations_pb2.ListLocationsRequest.SerializeToString, - response_deserializer=locations_pb2.ListLocationsResponse.FromString, - ) - return self._stubs["list_locations"] - - @property - def get_location( - self, - ) -> Callable[[locations_pb2.GetLocationRequest], locations_pb2.Location]: - r"""Return a callable for the list locations method over gRPC. - """ - # 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_location" not in self._stubs: - self._stubs["get_location"] = self.grpc_channel.unary_unary( - "/google.cloud.location.Locations/GetLocation", - request_serializer=locations_pb2.GetLocationRequest.SerializeToString, - response_deserializer=locations_pb2.Location.FromString, - ) - return self._stubs["get_location"] - - @property - def kind(self) -> str: - return "grpc" - - -__all__ = ( - 'DocumentsGrpcTransport', -) diff --git a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/documents/transports/grpc_asyncio.py b/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/documents/transports/grpc_asyncio.py deleted file mode 100644 index de8613c9c..000000000 --- a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/documents/transports/grpc_asyncio.py +++ /dev/null @@ -1,610 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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 -from google.api_core import grpc_helpers_async -from google.api_core import operations_v1 -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore - -import grpc # type: ignore -from grpc.experimental import aio # type: ignore - -from google.cloud.dialogflow_v2beta1.types import document -from google.cloud.dialogflow_v2beta1.types import document as gcd_document -from google.cloud.location import locations_pb2 # type: ignore -from google.longrunning import operations_pb2 -from google.longrunning import operations_pb2 # type: ignore -from .base import DocumentsTransport, DEFAULT_CLIENT_INFO -from .grpc import DocumentsGrpcTransport - - -class DocumentsGrpcAsyncIOTransport(DocumentsTransport): - """gRPC AsyncIO backend transport for Documents. - - Service for managing knowledge - [Documents][google.cloud.dialogflow.v2beta1.Document]. - - 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: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - **kwargs) -> aio.Channel: - """Create and return a gRPC AsyncIO channel object. - Args: - host (Optional[str]): The host for the channel to use. - credentials (Optional[~.Credentials]): The - authorization credentials to attach to requests. These - credentials identify this application to the service. If - none are specified, the client will attempt to ascertain - the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - kwargs (Optional[dict]): Keyword arguments, which are passed to the - channel creation. - Returns: - aio.Channel: A gRPC AsyncIO channel object. - """ - - return grpc_helpers_async.create_channel( - host, - credentials=credentials, - credentials_file=credentials_file, - quota_project_id=quota_project_id, - default_scopes=cls.AUTH_SCOPES, - scopes=scopes, - default_host=cls.DEFAULT_HOST, - **kwargs - ) - - def __init__(self, *, - host: str = 'dialogflow.googleapis.com', - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - channel: Optional[aio.Channel] = None, - api_mtls_endpoint: Optional[str] = None, - client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, - ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, - client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - api_audience: Optional[str] = None, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - This argument is ignored if ``channel`` is provided. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - channel (Optional[aio.Channel]): A ``Channel`` instance through - which to make calls. - api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. - If provided, it overrides the ``host`` argument and tries to create - a mutual TLS channel with client SSL credentials from - ``client_cert_source`` or application default SSL credentials. - client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): - Deprecated. A callback to provide client SSL certificate bytes and - private key bytes, both in PEM format. It is ignored if - ``api_mtls_endpoint`` is None. - ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials - for the grpc channel. It is ignored if ``channel`` is provided. - client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): - A callback to provide client certificate bytes and private key bytes, - both in PEM format. It is used to configure a mutual TLS channel. It is - ignored if ``channel`` or ``ssl_channel_credentials`` is provided. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - - Raises: - google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport - creation failed for any reason. - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - self._grpc_channel = None - self._ssl_channel_credentials = ssl_channel_credentials - self._stubs: Dict[str, Callable] = {} - self._operations_client: Optional[operations_v1.OperationsAsyncClient] = None - - if api_mtls_endpoint: - warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) - if client_cert_source: - warnings.warn("client_cert_source is deprecated", DeprecationWarning) - - if channel: - # Ignore credentials if a channel was passed. - credentials = False - # If a channel was explicitly provided, set it. - self._grpc_channel = channel - self._ssl_channel_credentials = None - else: - if api_mtls_endpoint: - host = api_mtls_endpoint - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - self._ssl_channel_credentials = SslCredentials().ssl_credentials - - else: - if client_cert_source_for_mtls and not ssl_channel_credentials: - cert, key = client_cert_source_for_mtls() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - - # The base transport sets the host, credentials and scopes - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes, - quota_project_id=quota_project_id, - client_info=client_info, - always_use_jwt_access=always_use_jwt_access, - api_audience=api_audience, - ) - - if not self._grpc_channel: - self._grpc_channel = type(self).create_channel( - self._host, - # use the credentials which are saved - credentials=self._credentials, - # Set ``credentials_file`` to ``None`` here as - # the credentials that we saved earlier should be used. - credentials_file=None, - 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 operations_client(self) -> operations_v1.OperationsAsyncClient: - """Create the client designed to process long-running operations. - - This property caches on the instance; repeated calls return the same - client. - """ - # Quick check: Only create a new client if we do not already have one. - if self._operations_client is None: - self._operations_client = operations_v1.OperationsAsyncClient( - self.grpc_channel - ) - - # Return the client from cache. - return self._operations_client - - @property - def list_documents(self) -> Callable[ - [document.ListDocumentsRequest], - Awaitable[document.ListDocumentsResponse]]: - r"""Return a callable for the list documents method over gRPC. - - Returns the list of all documents of the knowledge base. - - Note: The ``projects.agent.knowledgeBases.documents`` resource - is deprecated; only use ``projects.knowledgeBases.documents``. - - Returns: - Callable[[~.ListDocumentsRequest], - Awaitable[~.ListDocumentsResponse]]: - 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_documents' not in self._stubs: - self._stubs['list_documents'] = self.grpc_channel.unary_unary( - '/google.cloud.dialogflow.v2beta1.Documents/ListDocuments', - request_serializer=document.ListDocumentsRequest.serialize, - response_deserializer=document.ListDocumentsResponse.deserialize, - ) - return self._stubs['list_documents'] - - @property - def get_document(self) -> Callable[ - [document.GetDocumentRequest], - Awaitable[document.Document]]: - r"""Return a callable for the get document method over gRPC. - - Retrieves the specified document. - - Note: The ``projects.agent.knowledgeBases.documents`` resource - is deprecated; only use ``projects.knowledgeBases.documents``. - - Returns: - Callable[[~.GetDocumentRequest], - Awaitable[~.Document]]: - 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_document' not in self._stubs: - self._stubs['get_document'] = self.grpc_channel.unary_unary( - '/google.cloud.dialogflow.v2beta1.Documents/GetDocument', - request_serializer=document.GetDocumentRequest.serialize, - response_deserializer=document.Document.deserialize, - ) - return self._stubs['get_document'] - - @property - def create_document(self) -> Callable[ - [gcd_document.CreateDocumentRequest], - Awaitable[operations_pb2.Operation]]: - r"""Return a callable for the create document method over gRPC. - - Creates a new document. - - This method is a `long-running - operation `__. - The returned ``Operation`` type has the following - method-specific fields: - - - ``metadata``: - [KnowledgeOperationMetadata][google.cloud.dialogflow.v2beta1.KnowledgeOperationMetadata] - - ``response``: - [Document][google.cloud.dialogflow.v2beta1.Document] - - Note: The ``projects.agent.knowledgeBases.documents`` resource - is deprecated; only use ``projects.knowledgeBases.documents``. - - Returns: - Callable[[~.CreateDocumentRequest], - Awaitable[~.Operation]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'create_document' not in self._stubs: - self._stubs['create_document'] = self.grpc_channel.unary_unary( - '/google.cloud.dialogflow.v2beta1.Documents/CreateDocument', - request_serializer=gcd_document.CreateDocumentRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['create_document'] - - @property - def import_documents(self) -> 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. - Dialogflow supports up to 350 documents in each request. If you - try to import more, Dialogflow will return an error. - - This method is a `long-running - operation `__. - The returned ``Operation`` type has the following - method-specific fields: - - - ``metadata``: - [KnowledgeOperationMetadata][google.cloud.dialogflow.v2beta1.KnowledgeOperationMetadata] - - ``response``: - [ImportDocumentsResponse][google.cloud.dialogflow.v2beta1.ImportDocumentsResponse] - - Returns: - Callable[[~.ImportDocumentsRequest], - Awaitable[~.Operation]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'import_documents' not in self._stubs: - self._stubs['import_documents'] = self.grpc_channel.unary_unary( - '/google.cloud.dialogflow.v2beta1.Documents/ImportDocuments', - request_serializer=document.ImportDocumentsRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['import_documents'] - - @property - def delete_document(self) -> Callable[ - [document.DeleteDocumentRequest], - Awaitable[operations_pb2.Operation]]: - r"""Return a callable for the delete document method over gRPC. - - Deletes the specified document. - - This method is a `long-running - operation `__. - The returned ``Operation`` type has the following - method-specific fields: - - - ``metadata``: - [KnowledgeOperationMetadata][google.cloud.dialogflow.v2beta1.KnowledgeOperationMetadata] - - ``response``: An `Empty - message `__ - - Note: The ``projects.agent.knowledgeBases.documents`` resource - is deprecated; only use ``projects.knowledgeBases.documents``. - - Returns: - Callable[[~.DeleteDocumentRequest], - Awaitable[~.Operation]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'delete_document' not in self._stubs: - self._stubs['delete_document'] = self.grpc_channel.unary_unary( - '/google.cloud.dialogflow.v2beta1.Documents/DeleteDocument', - request_serializer=document.DeleteDocumentRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['delete_document'] - - @property - def update_document(self) -> Callable[ - [gcd_document.UpdateDocumentRequest], - Awaitable[operations_pb2.Operation]]: - r"""Return a callable for the update document method over gRPC. - - Updates the specified document. - - This method is a `long-running - operation `__. - The returned ``Operation`` type has the following - method-specific fields: - - - ``metadata``: - [KnowledgeOperationMetadata][google.cloud.dialogflow.v2beta1.KnowledgeOperationMetadata] - - ``response``: - [Document][google.cloud.dialogflow.v2beta1.Document] - - Note: The ``projects.agent.knowledgeBases.documents`` resource - is deprecated; only use ``projects.knowledgeBases.documents``. - - Returns: - Callable[[~.UpdateDocumentRequest], - Awaitable[~.Operation]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'update_document' not in self._stubs: - self._stubs['update_document'] = self.grpc_channel.unary_unary( - '/google.cloud.dialogflow.v2beta1.Documents/UpdateDocument', - request_serializer=gcd_document.UpdateDocumentRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['update_document'] - - @property - def reload_document(self) -> 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, - content_uri or content. The previously loaded content of the - document will be deleted. Note: Even when the content of the - document has not changed, there still may be side effects - because of internal implementation changes. Note: If the - document source is Google Cloud Storage URI, its metadata will - be replaced with the custom metadata from Google Cloud Storage - if the ``import_gcs_custom_metadata`` field is set to true in - the request. - - This method is a `long-running - operation `__. - The returned ``Operation`` type has the following - method-specific fields: - - - ``metadata``: - [KnowledgeOperationMetadata][google.cloud.dialogflow.v2beta1.KnowledgeOperationMetadata] - - ``response``: - [Document][google.cloud.dialogflow.v2beta1.Document] - - Note: The ``projects.agent.knowledgeBases.documents`` resource - is deprecated; only use ``projects.knowledgeBases.documents``. - - Returns: - Callable[[~.ReloadDocumentRequest], - Awaitable[~.Operation]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'reload_document' not in self._stubs: - self._stubs['reload_document'] = self.grpc_channel.unary_unary( - '/google.cloud.dialogflow.v2beta1.Documents/ReloadDocument', - request_serializer=document.ReloadDocumentRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['reload_document'] - - def close(self): - return self.grpc_channel.close() - - @property - def cancel_operation( - self, - ) -> Callable[[operations_pb2.CancelOperationRequest], None]: - r"""Return a callable for the cancel_operation method over gRPC. - """ - # 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 "cancel_operation" not in self._stubs: - self._stubs["cancel_operation"] = self.grpc_channel.unary_unary( - "/google.longrunning.Operations/CancelOperation", - request_serializer=operations_pb2.CancelOperationRequest.SerializeToString, - response_deserializer=None, - ) - return self._stubs["cancel_operation"] - - @property - def get_operation( - self, - ) -> Callable[[operations_pb2.GetOperationRequest], operations_pb2.Operation]: - r"""Return a callable for the get_operation method over gRPC. - """ - # 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_operation" not in self._stubs: - self._stubs["get_operation"] = self.grpc_channel.unary_unary( - "/google.longrunning.Operations/GetOperation", - request_serializer=operations_pb2.GetOperationRequest.SerializeToString, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs["get_operation"] - - @property - def list_operations( - self, - ) -> Callable[[operations_pb2.ListOperationsRequest], operations_pb2.ListOperationsResponse]: - r"""Return a callable for the list_operations method over gRPC. - """ - # 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_operations" not in self._stubs: - self._stubs["list_operations"] = self.grpc_channel.unary_unary( - "/google.longrunning.Operations/ListOperations", - request_serializer=operations_pb2.ListOperationsRequest.SerializeToString, - response_deserializer=operations_pb2.ListOperationsResponse.FromString, - ) - return self._stubs["list_operations"] - - @property - def list_locations( - self, - ) -> Callable[[locations_pb2.ListLocationsRequest], locations_pb2.ListLocationsResponse]: - r"""Return a callable for the list locations method over gRPC. - """ - # 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_locations" not in self._stubs: - self._stubs["list_locations"] = self.grpc_channel.unary_unary( - "/google.cloud.location.Locations/ListLocations", - request_serializer=locations_pb2.ListLocationsRequest.SerializeToString, - response_deserializer=locations_pb2.ListLocationsResponse.FromString, - ) - return self._stubs["list_locations"] - - @property - def get_location( - self, - ) -> Callable[[locations_pb2.GetLocationRequest], locations_pb2.Location]: - r"""Return a callable for the list locations method over gRPC. - """ - # 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_location" not in self._stubs: - self._stubs["get_location"] = self.grpc_channel.unary_unary( - "/google.cloud.location.Locations/GetLocation", - request_serializer=locations_pb2.GetLocationRequest.SerializeToString, - response_deserializer=locations_pb2.Location.FromString, - ) - return self._stubs["get_location"] - - -__all__ = ( - 'DocumentsGrpcAsyncIOTransport', -) diff --git a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/documents/transports/rest.py b/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/documents/transports/rest.py deleted file mode 100644 index 3d35573fd..000000000 --- a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/documents/transports/rest.py +++ /dev/null @@ -1,1560 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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 google.auth.transport.requests import AuthorizedSession # type: ignore -import json # type: ignore -import grpc # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore -from google.auth import credentials as ga_credentials # type: ignore -from google.api_core import exceptions as core_exceptions -from google.api_core import retry as retries -from google.api_core import rest_helpers -from google.api_core import rest_streaming -from google.api_core import path_template -from google.api_core import gapic_v1 - -from google.protobuf import json_format -from google.api_core import operations_v1 -from google.cloud.location import locations_pb2 # type: ignore -from google.longrunning import operations_pb2 -from requests import __version__ as requests_version -import dataclasses -import re -from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union -import warnings - -try: - OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] -except AttributeError: # pragma: NO COVER - OptionalRetry = Union[retries.Retry, object] # 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 # type: ignore - -from .base import DocumentsTransport, DEFAULT_CLIENT_INFO as BASE_DEFAULT_CLIENT_INFO - - -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=BASE_DEFAULT_CLIENT_INFO.gapic_version, - grpc_version=None, - rest_version=requests_version, -) - - -class DocumentsRestInterceptor: - """Interceptor for Documents. - - Interceptors are used to manipulate requests, request metadata, and responses - in arbitrary ways. - Example use cases include: - * Logging - * Verifying requests according to service or custom semantics - * Stripping extraneous information from responses - - These use cases and more can be enabled by injecting an - instance of a custom subclass when constructing the DocumentsRestTransport. - - .. code-block:: python - class MyCustomDocumentsInterceptor(DocumentsRestInterceptor): - def pre_create_document(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_create_document(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_delete_document(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_delete_document(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_get_document(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_get_document(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_import_documents(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_import_documents(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_list_documents(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_list_documents(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_reload_document(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_reload_document(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_update_document(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_update_document(self, response): - logging.log(f"Received response: {response}") - return response - - transport = DocumentsRestTransport(interceptor=MyCustomDocumentsInterceptor()) - client = DocumentsClient(transport=transport) - - - """ - def pre_create_document(self, request: gcd_document.CreateDocumentRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[gcd_document.CreateDocumentRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for create_document - - Override in a subclass to manipulate the request or metadata - before they are sent to the Documents server. - """ - return request, metadata - - def post_create_document(self, response: operations_pb2.Operation) -> operations_pb2.Operation: - """Post-rpc interceptor for create_document - - Override in a subclass to manipulate the response - after it is returned by the Documents server but before - it is returned to user code. - """ - return response - def pre_delete_document(self, request: document.DeleteDocumentRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[document.DeleteDocumentRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for delete_document - - Override in a subclass to manipulate the request or metadata - before they are sent to the Documents server. - """ - return request, metadata - - def post_delete_document(self, response: operations_pb2.Operation) -> operations_pb2.Operation: - """Post-rpc interceptor for delete_document - - Override in a subclass to manipulate the response - after it is returned by the Documents server but before - it is returned to user code. - """ - return response - def pre_get_document(self, request: document.GetDocumentRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[document.GetDocumentRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for get_document - - Override in a subclass to manipulate the request or metadata - before they are sent to the Documents server. - """ - return request, metadata - - def post_get_document(self, response: document.Document) -> document.Document: - """Post-rpc interceptor for get_document - - Override in a subclass to manipulate the response - after it is returned by the Documents server but before - it is returned to user code. - """ - return response - def pre_import_documents(self, request: document.ImportDocumentsRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[document.ImportDocumentsRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for import_documents - - Override in a subclass to manipulate the request or metadata - before they are sent to the Documents server. - """ - return request, metadata - - def post_import_documents(self, response: operations_pb2.Operation) -> operations_pb2.Operation: - """Post-rpc interceptor for import_documents - - Override in a subclass to manipulate the response - after it is returned by the Documents server but before - it is returned to user code. - """ - return response - def pre_list_documents(self, request: document.ListDocumentsRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[document.ListDocumentsRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for list_documents - - Override in a subclass to manipulate the request or metadata - before they are sent to the Documents server. - """ - return request, metadata - - def post_list_documents(self, response: document.ListDocumentsResponse) -> document.ListDocumentsResponse: - """Post-rpc interceptor for list_documents - - Override in a subclass to manipulate the response - after it is returned by the Documents server but before - it is returned to user code. - """ - return response - def pre_reload_document(self, request: document.ReloadDocumentRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[document.ReloadDocumentRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for reload_document - - Override in a subclass to manipulate the request or metadata - before they are sent to the Documents server. - """ - return request, metadata - - def post_reload_document(self, response: operations_pb2.Operation) -> operations_pb2.Operation: - """Post-rpc interceptor for reload_document - - Override in a subclass to manipulate the response - after it is returned by the Documents server but before - it is returned to user code. - """ - return response - def pre_update_document(self, request: gcd_document.UpdateDocumentRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[gcd_document.UpdateDocumentRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for update_document - - Override in a subclass to manipulate the request or metadata - before they are sent to the Documents server. - """ - return request, metadata - - def post_update_document(self, response: operations_pb2.Operation) -> operations_pb2.Operation: - """Post-rpc interceptor for update_document - - Override in a subclass to manipulate the response - after it is returned by the Documents server but before - it is returned to user code. - """ - return response - - def pre_get_location( - self, request: locations_pb2.GetLocationRequest, metadata: Sequence[Tuple[str, str]] - ) -> Tuple[locations_pb2.GetLocationRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for get_location - - Override in a subclass to manipulate the request or metadata - before they are sent to the Documents server. - """ - return request, metadata - - def post_get_location( - self, response: locations_pb2.Location - ) -> locations_pb2.Location: - """Post-rpc interceptor for get_location - - Override in a subclass to manipulate the response - after it is returned by the Documents server but before - it is returned to user code. - """ - return response - def pre_list_locations( - self, request: locations_pb2.ListLocationsRequest, metadata: Sequence[Tuple[str, str]] - ) -> Tuple[locations_pb2.ListLocationsRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for list_locations - - Override in a subclass to manipulate the request or metadata - before they are sent to the Documents server. - """ - return request, metadata - - def post_list_locations( - self, response: locations_pb2.ListLocationsResponse - ) -> locations_pb2.ListLocationsResponse: - """Post-rpc interceptor for list_locations - - Override in a subclass to manipulate the response - after it is returned by the Documents server but before - it is returned to user code. - """ - return response - def pre_cancel_operation( - self, request: operations_pb2.CancelOperationRequest, metadata: Sequence[Tuple[str, str]] - ) -> Tuple[operations_pb2.CancelOperationRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for cancel_operation - - Override in a subclass to manipulate the request or metadata - before they are sent to the Documents server. - """ - return request, metadata - - def post_cancel_operation( - self, response: None - ) -> None: - """Post-rpc interceptor for cancel_operation - - Override in a subclass to manipulate the response - after it is returned by the Documents server but before - it is returned to user code. - """ - return response - def pre_get_operation( - self, request: operations_pb2.GetOperationRequest, metadata: Sequence[Tuple[str, str]] - ) -> Tuple[operations_pb2.GetOperationRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for get_operation - - Override in a subclass to manipulate the request or metadata - before they are sent to the Documents server. - """ - return request, metadata - - def post_get_operation( - self, response: operations_pb2.Operation - ) -> operations_pb2.Operation: - """Post-rpc interceptor for get_operation - - Override in a subclass to manipulate the response - after it is returned by the Documents server but before - it is returned to user code. - """ - return response - def pre_list_operations( - self, request: operations_pb2.ListOperationsRequest, metadata: Sequence[Tuple[str, str]] - ) -> Tuple[operations_pb2.ListOperationsRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for list_operations - - Override in a subclass to manipulate the request or metadata - before they are sent to the Documents server. - """ - return request, metadata - - def post_list_operations( - self, response: operations_pb2.ListOperationsResponse - ) -> operations_pb2.ListOperationsResponse: - """Post-rpc interceptor for list_operations - - Override in a subclass to manipulate the response - after it is returned by the Documents server but before - it is returned to user code. - """ - return response - - -@dataclasses.dataclass -class DocumentsRestStub: - _session: AuthorizedSession - _host: str - _interceptor: DocumentsRestInterceptor - - -class DocumentsRestTransport(DocumentsTransport): - """REST backend transport for Documents. - - Service for managing knowledge - [Documents][google.cloud.dialogflow.v2beta1.Document]. - - 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 JSON representations of protocol buffers over HTTP/1.1 - - """ - - def __init__(self, *, - host: str = 'dialogflow.googleapis.com', - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - client_cert_source_for_mtls: Optional[Callable[[ - ], Tuple[bytes, bytes]]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - url_scheme: str = 'https', - interceptor: Optional[DocumentsRestInterceptor] = None, - api_audience: Optional[str] = None, - ) -> 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 ignored if ``channel`` is provided. - scopes (Optional(Sequence[str])): A list of scopes. This argument is - ignored if ``channel`` is provided. - client_cert_source_for_mtls (Callable[[], Tuple[bytes, bytes]]): Client - certificate to configure mutual TLS HTTP channel. It is ignored - if ``channel`` is provided. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you are developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - url_scheme: the protocol scheme for the API endpoint. Normally - "https", but for testing or local servers, - "http" can be specified. - """ - # Run the base constructor - # TODO(yon-mg): resolve other ctor params i.e. scopes, quota, etc. - # TODO: When custom host (api_endpoint) is set, `scopes` must *also* be set on the - # credentials object - maybe_url_match = re.match("^(?Phttp(?:s)?://)?(?P.*)$", host) - if maybe_url_match is None: - raise ValueError(f"Unexpected hostname structure: {host}") # pragma: NO COVER - - url_match_items = maybe_url_match.groupdict() - - host = f"{url_scheme}://{host}" if not url_match_items["scheme"] else host - - super().__init__( - host=host, - credentials=credentials, - client_info=client_info, - always_use_jwt_access=always_use_jwt_access, - api_audience=api_audience - ) - self._session = AuthorizedSession( - self._credentials, default_host=self.DEFAULT_HOST) - self._operations_client: Optional[operations_v1.AbstractOperationsClient] = None - if client_cert_source_for_mtls: - self._session.configure_mtls_channel(client_cert_source_for_mtls) - self._interceptor = interceptor or DocumentsRestInterceptor() - self._prep_wrapped_messages(client_info) - - @property - def operations_client(self) -> operations_v1.AbstractOperationsClient: - """Create the client designed to process long-running operations. - - This property caches on the instance; repeated calls return the same - client. - """ - # Only create a new client if we do not already have one. - if self._operations_client is None: - http_options: Dict[str, List[Dict[str, str]]] = { - 'google.longrunning.Operations.CancelOperation': [ - { - 'method': 'post', - 'uri': '/v2beta1/{name=projects/*/operations/*}:cancel', - }, - { - 'method': 'post', - 'uri': '/v2beta1/{name=projects/*/locations/*/operations/*}:cancel', - }, - ], - 'google.longrunning.Operations.GetOperation': [ - { - 'method': 'get', - 'uri': '/v2beta1/{name=projects/*/operations/*}', - }, - { - 'method': 'get', - 'uri': '/v2beta1/{name=projects/*/locations/*/operations/*}', - }, - ], - 'google.longrunning.Operations.ListOperations': [ - { - 'method': 'get', - 'uri': '/v2beta1/{name=projects/*}/operations', - }, - { - 'method': 'get', - 'uri': '/v2beta1/{name=projects/*/locations/*}/operations', - }, - ], - } - - rest_transport = operations_v1.OperationsRestTransport( - host=self._host, - # use the credentials which are saved - credentials=self._credentials, - scopes=self._scopes, - http_options=http_options, - path_prefix="v2beta1") - - self._operations_client = operations_v1.AbstractOperationsClient(transport=rest_transport) - - # Return the client from cache. - return self._operations_client - - class _CreateDocument(DocumentsRestStub): - def __hash__(self): - return hash("CreateDocument") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: gcd_document.CreateDocumentRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> operations_pb2.Operation: - r"""Call the create document method over HTTP. - - Args: - request (~.gcd_document.CreateDocumentRequest): - The request object. Request message for - [Documents.CreateDocument][google.cloud.dialogflow.v2beta1.Documents.CreateDocument]. - 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: - ~.operations_pb2.Operation: - This resource represents a - long-running operation that is the - result of a network API call. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'post', - 'uri': '/v2beta1/{parent=projects/*/knowledgeBases/*}/documents', - 'body': 'document', - }, -{ - 'method': 'post', - 'uri': '/v2beta1/{parent=projects/*/locations/*/knowledgeBases/*}/documents', - 'body': 'document', - }, -{ - 'method': 'post', - 'uri': '/v2beta1/{parent=projects/*/agent/knowledgeBases/*}/documents', - 'body': 'document', - }, - ] - request, metadata = self._interceptor.pre_create_document(request, metadata) - pb_request = gcd_document.CreateDocumentRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request['body'], - including_default_value_fields=False, - use_integers_for_enums=True - ) - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - including_default_value_fields=False, - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = operations_pb2.Operation() - json_format.Parse(response.content, resp, ignore_unknown_fields=True) - resp = self._interceptor.post_create_document(resp) - return resp - - class _DeleteDocument(DocumentsRestStub): - def __hash__(self): - return hash("DeleteDocument") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: document.DeleteDocumentRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> operations_pb2.Operation: - r"""Call the delete document method over HTTP. - - Args: - request (~.document.DeleteDocumentRequest): - The request object. Request message for - [Documents.DeleteDocument][google.cloud.dialogflow.v2beta1.Documents.DeleteDocument]. - 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: - ~.operations_pb2.Operation: - This resource represents a - long-running operation that is the - result of a network API call. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'delete', - 'uri': '/v2beta1/{name=projects/*/knowledgeBases/*/documents/*}', - }, -{ - 'method': 'delete', - 'uri': '/v2beta1/{name=projects/*/locations/*/knowledgeBases/*/documents/*}', - }, -{ - 'method': 'delete', - 'uri': '/v2beta1/{name=projects/*/agent/knowledgeBases/*/documents/*}', - }, - ] - request, metadata = self._interceptor.pre_delete_document(request, metadata) - pb_request = document.DeleteDocumentRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - including_default_value_fields=False, - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = operations_pb2.Operation() - json_format.Parse(response.content, resp, ignore_unknown_fields=True) - resp = self._interceptor.post_delete_document(resp) - return resp - - class _GetDocument(DocumentsRestStub): - def __hash__(self): - return hash("GetDocument") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: document.GetDocumentRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> document.Document: - r"""Call the get document method over HTTP. - - Args: - request (~.document.GetDocumentRequest): - The request object. Request message for - [Documents.GetDocument][google.cloud.dialogflow.v2beta1.Documents.GetDocument]. - 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: - ~.document.Document: - A knowledge document to be used by a - [KnowledgeBase][google.cloud.dialogflow.v2beta1.KnowledgeBase]. - - For more information, see the `knowledge base - guide `__. - - Note: The ``projects.agent.knowledgeBases.documents`` - resource is deprecated; only use - ``projects.knowledgeBases.documents``. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v2beta1/{name=projects/*/knowledgeBases/*/documents/*}', - }, -{ - 'method': 'get', - 'uri': '/v2beta1/{name=projects/*/locations/*/knowledgeBases/*/documents/*}', - }, -{ - 'method': 'get', - 'uri': '/v2beta1/{name=projects/*/agent/knowledgeBases/*/documents/*}', - }, - ] - request, metadata = self._interceptor.pre_get_document(request, metadata) - pb_request = document.GetDocumentRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - including_default_value_fields=False, - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = document.Document() - pb_resp = document.Document.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_get_document(resp) - return resp - - class _ImportDocuments(DocumentsRestStub): - def __hash__(self): - return hash("ImportDocuments") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: document.ImportDocumentsRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> operations_pb2.Operation: - r"""Call the import documents method over HTTP. - - Args: - request (~.document.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. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.operations_pb2.Operation: - This resource represents a - long-running operation that is the - result of a network API call. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'post', - 'uri': '/v2beta1/{parent=projects/*/knowledgeBases/*}/documents:import', - 'body': '*', - }, -{ - 'method': 'post', - 'uri': '/v2beta1/{parent=projects/*/locations/*/knowledgeBases/*}/documents:import', - 'body': '*', - }, - ] - request, metadata = self._interceptor.pre_import_documents(request, metadata) - pb_request = document.ImportDocumentsRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request['body'], - including_default_value_fields=False, - use_integers_for_enums=True - ) - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - including_default_value_fields=False, - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = operations_pb2.Operation() - json_format.Parse(response.content, resp, ignore_unknown_fields=True) - resp = self._interceptor.post_import_documents(resp) - return resp - - class _ListDocuments(DocumentsRestStub): - def __hash__(self): - return hash("ListDocuments") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: document.ListDocumentsRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> document.ListDocumentsResponse: - r"""Call the list documents method over HTTP. - - Args: - request (~.document.ListDocumentsRequest): - The request object. Request message for - [Documents.ListDocuments][google.cloud.dialogflow.v2beta1.Documents.ListDocuments]. - 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: - ~.document.ListDocumentsResponse: - Response message for - [Documents.ListDocuments][google.cloud.dialogflow.v2beta1.Documents.ListDocuments]. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v2beta1/{parent=projects/*/knowledgeBases/*}/documents', - }, -{ - 'method': 'get', - 'uri': '/v2beta1/{parent=projects/*/locations/*/knowledgeBases/*}/documents', - }, -{ - 'method': 'get', - 'uri': '/v2beta1/{parent=projects/*/agent/knowledgeBases/*}/documents', - }, - ] - request, metadata = self._interceptor.pre_list_documents(request, metadata) - pb_request = document.ListDocumentsRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - including_default_value_fields=False, - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = document.ListDocumentsResponse() - pb_resp = document.ListDocumentsResponse.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_list_documents(resp) - return resp - - class _ReloadDocument(DocumentsRestStub): - def __hash__(self): - return hash("ReloadDocument") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: document.ReloadDocumentRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> operations_pb2.Operation: - r"""Call the reload document method over HTTP. - - Args: - request (~.document.ReloadDocumentRequest): - The request object. Request message for - [Documents.ReloadDocument][google.cloud.dialogflow.v2beta1.Documents.ReloadDocument]. - 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: - ~.operations_pb2.Operation: - This resource represents a - long-running operation that is the - result of a network API call. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'post', - 'uri': '/v2beta1/{name=projects/*/knowledgeBases/*/documents/*}:reload', - 'body': '*', - }, -{ - 'method': 'post', - 'uri': '/v2beta1/{name=projects/*/locations/*/knowledgeBases/*/documents/*}:reload', - 'body': '*', - }, -{ - 'method': 'post', - 'uri': '/v2beta1/{name=projects/*/agent/knowledgeBases/*/documents/*}:reload', - 'body': '*', - }, - ] - request, metadata = self._interceptor.pre_reload_document(request, metadata) - pb_request = document.ReloadDocumentRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request['body'], - including_default_value_fields=False, - use_integers_for_enums=True - ) - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - including_default_value_fields=False, - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = operations_pb2.Operation() - json_format.Parse(response.content, resp, ignore_unknown_fields=True) - resp = self._interceptor.post_reload_document(resp) - return resp - - class _UpdateDocument(DocumentsRestStub): - def __hash__(self): - return hash("UpdateDocument") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: gcd_document.UpdateDocumentRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> operations_pb2.Operation: - r"""Call the update document method over HTTP. - - Args: - request (~.gcd_document.UpdateDocumentRequest): - The request object. Request message for - [Documents.UpdateDocument][google.cloud.dialogflow.v2beta1.Documents.UpdateDocument]. - 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: - ~.operations_pb2.Operation: - This resource represents a - long-running operation that is the - result of a network API call. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'patch', - 'uri': '/v2beta1/{document.name=projects/*/knowledgeBases/*/documents/*}', - 'body': 'document', - }, -{ - 'method': 'patch', - 'uri': '/v2beta1/{document.name=projects/*/locations/*/knowledgeBases/*/documents/*}', - 'body': 'document', - }, -{ - 'method': 'patch', - 'uri': '/v2beta1/{document.name=projects/*/agent/knowledgeBases/*/documents/*}', - 'body': 'document', - }, - ] - request, metadata = self._interceptor.pre_update_document(request, metadata) - pb_request = gcd_document.UpdateDocumentRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request['body'], - including_default_value_fields=False, - use_integers_for_enums=True - ) - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - including_default_value_fields=False, - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = operations_pb2.Operation() - json_format.Parse(response.content, resp, ignore_unknown_fields=True) - resp = self._interceptor.post_update_document(resp) - return resp - - @property - def create_document(self) -> Callable[ - [gcd_document.CreateDocumentRequest], - operations_pb2.Operation]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._CreateDocument(self._session, self._host, self._interceptor) # type: ignore - - @property - def delete_document(self) -> Callable[ - [document.DeleteDocumentRequest], - operations_pb2.Operation]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._DeleteDocument(self._session, self._host, self._interceptor) # type: ignore - - @property - def get_document(self) -> Callable[ - [document.GetDocumentRequest], - document.Document]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._GetDocument(self._session, self._host, self._interceptor) # type: ignore - - @property - def import_documents(self) -> Callable[ - [document.ImportDocumentsRequest], - operations_pb2.Operation]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._ImportDocuments(self._session, self._host, self._interceptor) # type: ignore - - @property - def list_documents(self) -> Callable[ - [document.ListDocumentsRequest], - document.ListDocumentsResponse]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._ListDocuments(self._session, self._host, self._interceptor) # type: ignore - - @property - def reload_document(self) -> Callable[ - [document.ReloadDocumentRequest], - operations_pb2.Operation]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._ReloadDocument(self._session, self._host, self._interceptor) # type: ignore - - @property - def update_document(self) -> Callable[ - [gcd_document.UpdateDocumentRequest], - operations_pb2.Operation]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._UpdateDocument(self._session, self._host, self._interceptor) # type: ignore - - @property - def get_location(self): - return self._GetLocation(self._session, self._host, self._interceptor) # type: ignore - - class _GetLocation(DocumentsRestStub): - def __call__(self, - request: locations_pb2.GetLocationRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> locations_pb2.Location: - - r"""Call the get location method over HTTP. - - Args: - request (locations_pb2.GetLocationRequest): - The request object for GetLocation method. - 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: - locations_pb2.Location: Response from GetLocation method. - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v2beta1/{name=projects/*/locations/*}', - }, - ] - - request, metadata = self._interceptor.pre_get_location(request, metadata) - request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode( - http_options, **request_kwargs) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json.dumps(transcoded_request['query_params'])) - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - resp = locations_pb2.Location() - resp = json_format.Parse(response.content.decode("utf-8"), resp) - resp = self._interceptor.post_get_location(resp) - return resp - - @property - def list_locations(self): - return self._ListLocations(self._session, self._host, self._interceptor) # type: ignore - - class _ListLocations(DocumentsRestStub): - def __call__(self, - request: locations_pb2.ListLocationsRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> locations_pb2.ListLocationsResponse: - - r"""Call the list locations method over HTTP. - - Args: - request (locations_pb2.ListLocationsRequest): - The request object for ListLocations method. - 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: - locations_pb2.ListLocationsResponse: Response from ListLocations method. - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v2beta1/{name=projects/*}/locations', - }, - ] - - request, metadata = self._interceptor.pre_list_locations(request, metadata) - request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode( - http_options, **request_kwargs) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json.dumps(transcoded_request['query_params'])) - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - resp = locations_pb2.ListLocationsResponse() - resp = json_format.Parse(response.content.decode("utf-8"), resp) - resp = self._interceptor.post_list_locations(resp) - return resp - - @property - def cancel_operation(self): - return self._CancelOperation(self._session, self._host, self._interceptor) # type: ignore - - class _CancelOperation(DocumentsRestStub): - def __call__(self, - request: operations_pb2.CancelOperationRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> None: - - r"""Call the cancel operation method over HTTP. - - Args: - request (operations_pb2.CancelOperationRequest): - The request object for CancelOperation method. - 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. - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'post', - 'uri': '/v2beta1/{name=projects/*/operations/*}:cancel', - }, -{ - 'method': 'post', - 'uri': '/v2beta1/{name=projects/*/locations/*/operations/*}:cancel', - }, - ] - - request, metadata = self._interceptor.pre_cancel_operation(request, metadata) - request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode( - http_options, **request_kwargs) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json.dumps(transcoded_request['query_params'])) - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - return self._interceptor.post_cancel_operation(None) - - @property - def get_operation(self): - return self._GetOperation(self._session, self._host, self._interceptor) # type: ignore - - class _GetOperation(DocumentsRestStub): - def __call__(self, - request: operations_pb2.GetOperationRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> operations_pb2.Operation: - - r"""Call the get operation method over HTTP. - - Args: - request (operations_pb2.GetOperationRequest): - The request object for GetOperation method. - 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: - operations_pb2.Operation: Response from GetOperation method. - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v2beta1/{name=projects/*/operations/*}', - }, -{ - 'method': 'get', - 'uri': '/v2beta1/{name=projects/*/locations/*/operations/*}', - }, - ] - - request, metadata = self._interceptor.pre_get_operation(request, metadata) - request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode( - http_options, **request_kwargs) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json.dumps(transcoded_request['query_params'])) - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - resp = operations_pb2.Operation() - resp = json_format.Parse(response.content.decode("utf-8"), resp) - resp = self._interceptor.post_get_operation(resp) - return resp - - @property - def list_operations(self): - return self._ListOperations(self._session, self._host, self._interceptor) # type: ignore - - class _ListOperations(DocumentsRestStub): - def __call__(self, - request: operations_pb2.ListOperationsRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> operations_pb2.ListOperationsResponse: - - r"""Call the list operations method over HTTP. - - Args: - request (operations_pb2.ListOperationsRequest): - The request object for ListOperations method. - 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: - operations_pb2.ListOperationsResponse: Response from ListOperations method. - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v2beta1/{name=projects/*}/operations', - }, -{ - 'method': 'get', - 'uri': '/v2beta1/{name=projects/*/locations/*}/operations', - }, - ] - - request, metadata = self._interceptor.pre_list_operations(request, metadata) - request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode( - http_options, **request_kwargs) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json.dumps(transcoded_request['query_params'])) - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - resp = operations_pb2.ListOperationsResponse() - resp = json_format.Parse(response.content.decode("utf-8"), resp) - resp = self._interceptor.post_list_operations(resp) - return resp - - @property - def kind(self) -> str: - return "rest" - - def close(self): - self._session.close() - - -__all__=( - 'DocumentsRestTransport', -) diff --git a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/entity_types/__init__.py b/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/entity_types/__init__.py deleted file mode 100644 index 829926f31..000000000 --- a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/entity_types/__init__.py +++ /dev/null @@ -1,22 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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 EntityTypesClient -from .async_client import EntityTypesAsyncClient - -__all__ = ( - 'EntityTypesClient', - 'EntityTypesAsyncClient', -) diff --git a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/entity_types/async_client.py b/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/entity_types/async_client.py deleted file mode 100644 index da5fc62b3..000000000 --- a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/entity_types/async_client.py +++ /dev/null @@ -1,1869 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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, Mapping, MutableMapping, MutableSequence, Optional, Sequence, Tuple, Type, Union - -from google.cloud.dialogflow_v2beta1 import gapic_version as package_version - -from google.api_core.client_options import ClientOptions -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import retry as retries -from google.auth import credentials as ga_credentials # type: ignore -from google.oauth2 import service_account # type: ignore - -try: - OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] -except AttributeError: # pragma: NO COVER - OptionalRetry = Union[retries.Retry, object] # type: ignore - -from google.api_core import operation # type: ignore -from google.api_core import operation_async # type: ignore -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.cloud.location import locations_pb2 # type: ignore -from google.longrunning import operations_pb2 -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 - - -class EntityTypesAsyncClient: - """Service for managing - [EntityTypes][google.cloud.dialogflow.v2beta1.EntityType]. - """ - - _client: EntityTypesClient - - DEFAULT_ENDPOINT = EntityTypesClient.DEFAULT_ENDPOINT - DEFAULT_MTLS_ENDPOINT = EntityTypesClient.DEFAULT_MTLS_ENDPOINT - - 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) - - @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: - EntityTypesAsyncClient: The constructed client. - """ - return EntityTypesClient.from_service_account_info.__func__(EntityTypesAsyncClient, 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: - EntityTypesAsyncClient: The constructed client. - """ - return EntityTypesClient.from_service_account_file.__func__(EntityTypesAsyncClient, filename, *args, **kwargs) # type: ignore - - from_service_account_json = from_service_account_file - - @classmethod - def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[ClientOptions] = None): - """Return the API endpoint and client cert source for mutual TLS. - - The client cert source is determined in the following order: - (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the - client cert source is None. - (2) if `client_options.client_cert_source` is provided, use the provided one; if the - default client cert source exists, use the default one; otherwise the client cert - source is None. - - The API endpoint is determined in the following order: - (1) if `client_options.api_endpoint` if provided, use the provided one. - (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the - default mTLS endpoint; if the environment variable is "never", use the default API - endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise - use the default API endpoint. - - More details can be found at https://google.aip.dev/auth/4114. - - Args: - client_options (google.api_core.client_options.ClientOptions): Custom options for the - client. Only the `api_endpoint` and `client_cert_source` properties may be used - in this method. - - Returns: - Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the - client cert source to use. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If any errors happen. - """ - return EntityTypesClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore - - @property - def transport(self) -> EntityTypesTransport: - """Returns the transport used by the client instance. - - Returns: - EntityTypesTransport: The transport used by the client instance. - """ - return self._client.transport - - get_transport_class = functools.partial(type(EntityTypesClient).get_transport_class, type(EntityTypesClient)) - - def __init__(self, *, - credentials: Optional[ga_credentials.Credentials] = None, - transport: Union[str, EntityTypesTransport] = "grpc_asyncio", - client_options: Optional[ClientOptions] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the entity types 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, ~.EntityTypesTransport]): 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 = EntityTypesClient( - credentials=credentials, - transport=transport, - client_options=client_options, - client_info=client_info, - - ) - - async def list_entity_types(self, - request: Optional[Union[entity_type.ListEntityTypesRequest, dict]] = None, - *, - parent: Optional[str] = None, - language_code: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListEntityTypesAsyncPager: - r"""Returns the list of all entity types in the specified - agent. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import dialogflow_v2beta1 - - async def sample_list_entity_types(): - # Create a client - client = dialogflow_v2beta1.EntityTypesAsyncClient() - - # Initialize request argument(s) - request = dialogflow_v2beta1.ListEntityTypesRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_entity_types(request=request) - - # Handle the response - async for response in page_result: - print(response) - - Args: - request (Optional[Union[google.cloud.dialogflow_v2beta1.types.ListEntityTypesRequest, dict]]): - The request object. The request message for - [EntityTypes.ListEntityTypes][google.cloud.dialogflow.v2beta1.EntityTypes.ListEntityTypes]. - parent (:class:`str`): - Required. The agent to list all entity types 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. - language_code (:class:`str`): - Optional. The language used to access language-specific - data. If not specified, the agent's default language is - used. For more information, see `Multilingual intent and - entity - data `__. - - 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. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.dialogflow_v2beta1.services.entity_types.pagers.ListEntityTypesAsyncPager: - The response message for - [EntityTypes.ListEntityTypes][google.cloud.dialogflow.v2beta1.EntityTypes.ListEntityTypes]. - - Iterating over this object will yield results and - resolve additional pages automatically. - - """ - # Create or coerce a protobuf request object. - # Quick 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, language_code]) - 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 = 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: - request.language_code = language_code - - # 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_entity_types, - 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.ListEntityTypesAsyncPager( - method=rpc, - request=request, - response=response, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def get_entity_type(self, - request: Optional[Union[entity_type.GetEntityTypeRequest, dict]] = None, - *, - name: Optional[str] = None, - language_code: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> entity_type.EntityType: - r"""Retrieves the specified entity type. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import dialogflow_v2beta1 - - async def sample_get_entity_type(): - # Create a client - client = dialogflow_v2beta1.EntityTypesAsyncClient() - - # Initialize request argument(s) - request = dialogflow_v2beta1.GetEntityTypeRequest( - name="name_value", - ) - - # Make the request - response = await client.get_entity_type(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.dialogflow_v2beta1.types.GetEntityTypeRequest, dict]]): - The request object. The request message for - [EntityTypes.GetEntityType][google.cloud.dialogflow.v2beta1.EntityTypes.GetEntityType]. - name (:class:`str`): - Required. The name of the entity type. Supported - formats: - - - ``projects//agent/entityTypes/`` - - ``projects//locations//agent/entityTypes/`` - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - language_code (:class:`str`): - Optional. The language used to access language-specific - data. If not specified, the agent's default language is - used. For more information, see `Multilingual intent and - entity - data `__. - - 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. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.dialogflow_v2beta1.types.EntityType: - Each intent parameter has a type, called the entity type, which dictates - exactly how data from an end-user expression is - extracted. - - Dialogflow provides predefined system entities that - can match many common types of data. For example, - there are system entities for matching dates, times, - colors, email addresses, and so on. You can also - create your own custom entities for matching custom - data. For example, you could define a vegetable - entity that can match the types of vegetables - available for purchase with a grocery store agent. - - For more information, see the [Entity - guide](\ https://cloud.google.com/dialogflow/docs/entities-overview). - - """ - # Create or coerce a protobuf request object. - # Quick 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, language_code]) - 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 = 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: - request.language_code = language_code - - # 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_entity_type, - 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_entity_type(self, - request: Optional[Union[gcd_entity_type.CreateEntityTypeRequest, dict]] = None, - *, - parent: Optional[str] = None, - entity_type: Optional[gcd_entity_type.EntityType] = None, - language_code: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gcd_entity_type.EntityType: - r"""Creates an entity type in the specified agent. - - Note: You should always train an agent prior to sending it - queries. See the `training - documentation `__. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import dialogflow_v2beta1 - - async def sample_create_entity_type(): - # Create a client - client = dialogflow_v2beta1.EntityTypesAsyncClient() - - # Initialize request argument(s) - entity_type = dialogflow_v2beta1.EntityType() - entity_type.display_name = "display_name_value" - entity_type.kind = "KIND_REGEXP" - - request = dialogflow_v2beta1.CreateEntityTypeRequest( - parent="parent_value", - entity_type=entity_type, - ) - - # Make the request - response = await client.create_entity_type(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.dialogflow_v2beta1.types.CreateEntityTypeRequest, dict]]): - The request object. The request message for - [EntityTypes.CreateEntityType][google.cloud.dialogflow.v2beta1.EntityTypes.CreateEntityType]. - parent (:class:`str`): - Required. The agent to create a entity type 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. - entity_type (:class:`google.cloud.dialogflow_v2beta1.types.EntityType`): - Required. The entity type to create. - This corresponds to the ``entity_type`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - language_code (:class:`str`): - Optional. The language used to access language-specific - data. If not specified, the agent's default language is - used. For more information, see `Multilingual intent and - entity - data `__. - - 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. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.dialogflow_v2beta1.types.EntityType: - Each intent parameter has a type, called the entity type, which dictates - exactly how data from an end-user expression is - extracted. - - Dialogflow provides predefined system entities that - can match many common types of data. For example, - there are system entities for matching dates, times, - colors, email addresses, and so on. You can also - create your own custom entities for matching custom - data. For example, you could define a vegetable - entity that can match the types of vegetables - available for purchase with a grocery store agent. - - For more information, see the [Entity - guide](\ https://cloud.google.com/dialogflow/docs/entities-overview). - - """ - # Create or coerce a protobuf request object. - # Quick 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, entity_type, language_code]) - 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_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: - request.entity_type = entity_type - if language_code is not None: - request.language_code = language_code - - # 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_entity_type, - 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_entity_type(self, - request: Optional[Union[gcd_entity_type.UpdateEntityTypeRequest, dict]] = None, - *, - entity_type: Optional[gcd_entity_type.EntityType] = None, - language_code: Optional[str] = None, - update_mask: Optional[field_mask_pb2.FieldMask] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gcd_entity_type.EntityType: - r"""Updates the specified entity type. - - Note: You should always train an agent prior to sending it - queries. See the `training - documentation `__. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import dialogflow_v2beta1 - - async def sample_update_entity_type(): - # Create a client - client = dialogflow_v2beta1.EntityTypesAsyncClient() - - # Initialize request argument(s) - entity_type = dialogflow_v2beta1.EntityType() - entity_type.display_name = "display_name_value" - entity_type.kind = "KIND_REGEXP" - - request = dialogflow_v2beta1.UpdateEntityTypeRequest( - entity_type=entity_type, - ) - - # Make the request - response = await client.update_entity_type(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.dialogflow_v2beta1.types.UpdateEntityTypeRequest, dict]]): - The request object. The request message for - [EntityTypes.UpdateEntityType][google.cloud.dialogflow.v2beta1.EntityTypes.UpdateEntityType]. - entity_type (:class:`google.cloud.dialogflow_v2beta1.types.EntityType`): - Required. The entity type to update. - This corresponds to the ``entity_type`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - language_code (:class:`str`): - Optional. The language used to access language-specific - data. If not specified, the agent's default language is - used. For more information, see `Multilingual intent and - entity - data `__. - - This corresponds to the ``language_code`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - update_mask (:class:`google.protobuf.field_mask_pb2.FieldMask`): - Optional. 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.EntityType: - Each intent parameter has a type, called the entity type, which dictates - exactly how data from an end-user expression is - extracted. - - Dialogflow provides predefined system entities that - can match many common types of data. For example, - there are system entities for matching dates, times, - colors, email addresses, and so on. You can also - create your own custom entities for matching custom - data. For example, you could define a vegetable - entity that can match the types of vegetables - available for purchase with a grocery store agent. - - For more information, see the [Entity - guide](\ https://cloud.google.com/dialogflow/docs/entities-overview). - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([entity_type, language_code, 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_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: - request.language_code = language_code - 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_entity_type, - 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(( - ("entity_type.name", request.entity_type.name), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def delete_entity_type(self, - request: Optional[Union[entity_type.DeleteEntityTypeRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> None: - r"""Deletes the specified entity type. - - Note: You should always train an agent prior to sending it - queries. See the `training - documentation `__. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import dialogflow_v2beta1 - - async def sample_delete_entity_type(): - # Create a client - client = dialogflow_v2beta1.EntityTypesAsyncClient() - - # Initialize request argument(s) - request = dialogflow_v2beta1.DeleteEntityTypeRequest( - name="name_value", - ) - - # Make the request - await client.delete_entity_type(request=request) - - Args: - request (Optional[Union[google.cloud.dialogflow_v2beta1.types.DeleteEntityTypeRequest, dict]]): - The request object. The request message for - [EntityTypes.DeleteEntityType][google.cloud.dialogflow.v2beta1.EntityTypes.DeleteEntityType]. - name (:class:`str`): - Required. The name of the entity type to delete. - Supported formats: - - - ``projects//agent/entityTypes/`` - - ``projects//locations//agent/entityTypes/`` - - 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. - # Quick 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 = 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 - - # 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_entity_type, - 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 batch_update_entity_types(self, - request: Optional[Union[entity_type.BatchUpdateEntityTypesRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation_async.AsyncOperation: - r"""Updates/Creates multiple entity types in the specified agent. - - This method is a `long-running - operation `__. - The returned ``Operation`` type has the following - method-specific fields: - - - ``metadata``: An empty `Struct - message `__ - - ``response``: - [BatchUpdateEntityTypesResponse][google.cloud.dialogflow.v2beta1.BatchUpdateEntityTypesResponse] - - Note: You should always train an agent prior to sending it - queries. See the `training - documentation `__. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import dialogflow_v2beta1 - - async def sample_batch_update_entity_types(): - # Create a client - client = dialogflow_v2beta1.EntityTypesAsyncClient() - - # Initialize request argument(s) - request = dialogflow_v2beta1.BatchUpdateEntityTypesRequest( - entity_type_batch_uri="entity_type_batch_uri_value", - parent="parent_value", - ) - - # Make the request - operation = client.batch_update_entity_types(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.dialogflow_v2beta1.types.BatchUpdateEntityTypesRequest, dict]]): - 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. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.api_core.operation_async.AsyncOperation: - An object representing a long-running operation. - - The result type for the operation will be :class:`google.cloud.dialogflow_v2beta1.types.BatchUpdateEntityTypesResponse` The response message for - [EntityTypes.BatchUpdateEntityTypes][google.cloud.dialogflow.v2beta1.EntityTypes.BatchUpdateEntityTypes]. - - """ - # Create or coerce a protobuf request object. - request = entity_type.BatchUpdateEntityTypesRequest(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.batch_update_entity_types, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Wrap the response in an operation future. - response = operation_async.from_gapic( - response, - self._client._transport.operations_client, - entity_type.BatchUpdateEntityTypesResponse, - metadata_type=struct_pb2.Struct, - ) - - # Done; return the response. - return response - - async def batch_delete_entity_types(self, - request: Optional[Union[entity_type.BatchDeleteEntityTypesRequest, dict]] = None, - *, - parent: Optional[str] = None, - entity_type_names: Optional[MutableSequence[str]] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation_async.AsyncOperation: - r"""Deletes entity types in the specified agent. - - This method is a `long-running - operation `__. - The returned ``Operation`` type has the following - method-specific fields: - - - ``metadata``: An empty `Struct - message `__ - - ``response``: An `Empty - message `__ - - Note: You should always train an agent prior to sending it - queries. See the `training - documentation `__. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import dialogflow_v2beta1 - - async def sample_batch_delete_entity_types(): - # Create a client - client = dialogflow_v2beta1.EntityTypesAsyncClient() - - # Initialize request argument(s) - request = dialogflow_v2beta1.BatchDeleteEntityTypesRequest( - parent="parent_value", - entity_type_names=['entity_type_names_value1', 'entity_type_names_value2'], - ) - - # Make the request - operation = client.batch_delete_entity_types(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.dialogflow_v2beta1.types.BatchDeleteEntityTypesRequest, dict]]): - The request object. The request message for - [EntityTypes.BatchDeleteEntityTypes][google.cloud.dialogflow.v2beta1.EntityTypes.BatchDeleteEntityTypes]. - parent (:class:`str`): - Required. The name of the agent to delete all entities - types 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. - entity_type_names (:class:`MutableSequence[str]`): - Required. The names entity types to delete. All names - must point to the same agent as ``parent``. - - 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. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.api_core.operation_async.AsyncOperation: - An object representing a long-running operation. - - The result type for the operation will be :class:`google.protobuf.empty_pb2.Empty` A generic empty message that you can re-use to avoid defining duplicated - empty messages in your APIs. A typical example is to - use it as the request or the response type of an API - method. For instance: - - service Foo { - rpc Bar(google.protobuf.Empty) returns - (google.protobuf.Empty); - - } - - """ - # Create or coerce a protobuf request object. - # Quick 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, entity_type_names]) - 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 = 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: - request.entity_type_names.extend(entity_type_names) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.batch_delete_entity_types, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Wrap the response in an operation future. - response = operation_async.from_gapic( - response, - self._client._transport.operations_client, - empty_pb2.Empty, - metadata_type=struct_pb2.Struct, - ) - - # Done; return the response. - return response - - async def batch_create_entities(self, - request: Optional[Union[entity_type.BatchCreateEntitiesRequest, dict]] = None, - *, - parent: Optional[str] = None, - entities: Optional[MutableSequence[entity_type.EntityType.Entity]] = None, - language_code: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation_async.AsyncOperation: - r"""Creates multiple new entities in the specified entity type. - - This method is a `long-running - operation `__. - The returned ``Operation`` type has the following - method-specific fields: - - - ``metadata``: An empty `Struct - message `__ - - ``response``: An `Empty - message `__ - - Note: You should always train an agent prior to sending it - queries. See the `training - documentation `__. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import dialogflow_v2beta1 - - async def sample_batch_create_entities(): - # Create a client - client = dialogflow_v2beta1.EntityTypesAsyncClient() - - # Initialize request argument(s) - entities = dialogflow_v2beta1.Entity() - entities.value = "value_value" - - request = dialogflow_v2beta1.BatchCreateEntitiesRequest( - parent="parent_value", - entities=entities, - ) - - # Make the request - operation = client.batch_create_entities(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.dialogflow_v2beta1.types.BatchCreateEntitiesRequest, dict]]): - The request object. The request message for - [EntityTypes.BatchCreateEntities][google.cloud.dialogflow.v2beta1.EntityTypes.BatchCreateEntities]. - parent (:class:`str`): - Required. The name of the entity type to create entities - in. Supported formats: - - - ``projects//agent/entityTypes/`` - - ``projects//locations//agent/entityTypes/`` - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - entities (:class:`MutableSequence[google.cloud.dialogflow_v2beta1.types.EntityType.Entity]`): - Required. The entities to create. - This corresponds to the ``entities`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - language_code (:class:`str`): - Optional. The language used to access language-specific - data. If not specified, the agent's default language is - used. For more information, see `Multilingual intent and - entity - data `__. - - 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. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.api_core.operation_async.AsyncOperation: - An object representing a long-running operation. - - The result type for the operation will be :class:`google.protobuf.empty_pb2.Empty` A generic empty message that you can re-use to avoid defining duplicated - empty messages in your APIs. A typical example is to - use it as the request or the response type of an API - method. For instance: - - service Foo { - rpc Bar(google.protobuf.Empty) returns - (google.protobuf.Empty); - - } - - """ - # Create or coerce a protobuf request object. - # Quick 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, entities, language_code]) - 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 = 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 language_code is not None: - request.language_code = language_code - if entities: - request.entities.extend(entities) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.batch_create_entities, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Wrap the response in an operation future. - response = operation_async.from_gapic( - response, - self._client._transport.operations_client, - empty_pb2.Empty, - metadata_type=struct_pb2.Struct, - ) - - # Done; return the response. - return response - - async def batch_update_entities(self, - request: Optional[Union[entity_type.BatchUpdateEntitiesRequest, dict]] = None, - *, - parent: Optional[str] = None, - entities: Optional[MutableSequence[entity_type.EntityType.Entity]] = None, - language_code: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation_async.AsyncOperation: - r"""Updates or creates multiple entities in the specified entity - type. This method does not affect entities in the entity type - that aren't explicitly specified in the request. - - Note: You should always train an agent prior to sending it - queries. See the `training - documentation `__. - - This method is a `long-running - operation `__. - The returned ``Operation`` type has the following - method-specific fields: - - - ``metadata``: An empty `Struct - message `__ - - ``response``: An `Empty - message `__ - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import dialogflow_v2beta1 - - async def sample_batch_update_entities(): - # Create a client - client = dialogflow_v2beta1.EntityTypesAsyncClient() - - # Initialize request argument(s) - entities = dialogflow_v2beta1.Entity() - entities.value = "value_value" - - request = dialogflow_v2beta1.BatchUpdateEntitiesRequest( - parent="parent_value", - entities=entities, - ) - - # Make the request - operation = client.batch_update_entities(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.dialogflow_v2beta1.types.BatchUpdateEntitiesRequest, dict]]): - The request object. The request message for - [EntityTypes.BatchUpdateEntities][google.cloud.dialogflow.v2beta1.EntityTypes.BatchUpdateEntities]. - parent (:class:`str`): - Required. The name of the entity type to update or - create entities in. Supported formats: - - - ``projects//agent/entityTypes/`` - - ``projects//locations//agent/entityTypes/`` - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - entities (:class:`MutableSequence[google.cloud.dialogflow_v2beta1.types.EntityType.Entity]`): - Required. The entities to update or - create. - - This corresponds to the ``entities`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - language_code (:class:`str`): - Optional. The language used to access language-specific - data. If not specified, the agent's default language is - used. For more information, see `Multilingual intent and - entity - data `__. - - 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. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.api_core.operation_async.AsyncOperation: - An object representing a long-running operation. - - The result type for the operation will be :class:`google.protobuf.empty_pb2.Empty` A generic empty message that you can re-use to avoid defining duplicated - empty messages in your APIs. A typical example is to - use it as the request or the response type of an API - method. For instance: - - service Foo { - rpc Bar(google.protobuf.Empty) returns - (google.protobuf.Empty); - - } - - """ - # Create or coerce a protobuf request object. - # Quick 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, entities, language_code]) - 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 = 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 language_code is not None: - request.language_code = language_code - if entities: - request.entities.extend(entities) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.batch_update_entities, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Wrap the response in an operation future. - response = operation_async.from_gapic( - response, - self._client._transport.operations_client, - empty_pb2.Empty, - metadata_type=struct_pb2.Struct, - ) - - # Done; return the response. - return response - - async def batch_delete_entities(self, - request: Optional[Union[entity_type.BatchDeleteEntitiesRequest, dict]] = None, - *, - parent: Optional[str] = None, - entity_values: Optional[MutableSequence[str]] = None, - language_code: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation_async.AsyncOperation: - r"""Deletes entities in the specified entity type. - - This method is a `long-running - operation `__. - The returned ``Operation`` type has the following - method-specific fields: - - - ``metadata``: An empty `Struct - message `__ - - ``response``: An `Empty - message `__ - - Note: You should always train an agent prior to sending it - queries. See the `training - documentation `__. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import dialogflow_v2beta1 - - async def sample_batch_delete_entities(): - # Create a client - client = dialogflow_v2beta1.EntityTypesAsyncClient() - - # Initialize request argument(s) - request = dialogflow_v2beta1.BatchDeleteEntitiesRequest( - parent="parent_value", - entity_values=['entity_values_value1', 'entity_values_value2'], - ) - - # Make the request - operation = client.batch_delete_entities(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.dialogflow_v2beta1.types.BatchDeleteEntitiesRequest, dict]]): - The request object. The request message for - [EntityTypes.BatchDeleteEntities][google.cloud.dialogflow.v2beta1.EntityTypes.BatchDeleteEntities]. - parent (:class:`str`): - Required. The name of the entity type to delete entries - for. Supported formats: - - - ``projects//agent/entityTypes/`` - - ``projects//locations//agent/entityTypes/`` - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - entity_values (:class:`MutableSequence[str]`): - Required. The reference ``values`` of the entities to - delete. Note that these are not fully-qualified names, - i.e. they don't start with ``projects/``. - - This corresponds to the ``entity_values`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - language_code (:class:`str`): - Optional. The language used to access language-specific - data. If not specified, the agent's default language is - used. For more information, see `Multilingual intent and - entity - data `__. - - 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. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.api_core.operation_async.AsyncOperation: - An object representing a long-running operation. - - The result type for the operation will be :class:`google.protobuf.empty_pb2.Empty` A generic empty message that you can re-use to avoid defining duplicated - empty messages in your APIs. A typical example is to - use it as the request or the response type of an API - method. For instance: - - service Foo { - rpc Bar(google.protobuf.Empty) returns - (google.protobuf.Empty); - - } - - """ - # Create or coerce a protobuf request object. - # Quick 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, entity_values, language_code]) - 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 = 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 language_code is not None: - request.language_code = language_code - if entity_values: - request.entity_values.extend(entity_values) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.batch_delete_entities, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Wrap the response in an operation future. - response = operation_async.from_gapic( - response, - self._client._transport.operations_client, - empty_pb2.Empty, - metadata_type=struct_pb2.Struct, - ) - - # Done; return the response. - return response - - async def list_operations( - self, - request: Optional[operations_pb2.ListOperationsRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operations_pb2.ListOperationsResponse: - r"""Lists operations that match the specified filter in the request. - - Args: - request (:class:`~.operations_pb2.ListOperationsRequest`): - The request object. Request message for - `ListOperations` method. - 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: - ~.operations_pb2.ListOperationsResponse: - Response message for ``ListOperations`` method. - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = operations_pb2.ListOperationsRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._client._transport.list_operations, - 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 get_operation( - self, - request: Optional[operations_pb2.GetOperationRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operations_pb2.Operation: - r"""Gets the latest state of a long-running operation. - - Args: - request (:class:`~.operations_pb2.GetOperationRequest`): - The request object. Request message for - `GetOperation` method. - 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: - ~.operations_pb2.Operation: - An ``Operation`` object. - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = operations_pb2.GetOperationRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._client._transport.get_operation, - 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 cancel_operation( - self, - request: Optional[operations_pb2.CancelOperationRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> None: - r"""Starts asynchronous cancellation on a long-running operation. - - The server makes a best effort to cancel the operation, but success - is not guaranteed. If the server doesn't support this method, it returns - `google.rpc.Code.UNIMPLEMENTED`. - - Args: - request (:class:`~.operations_pb2.CancelOperationRequest`): - The request object. Request message for - `CancelOperation` method. - 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: - None - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = operations_pb2.CancelOperationRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._client._transport.cancel_operation, - 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_location( - self, - request: Optional[locations_pb2.GetLocationRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> locations_pb2.Location: - r"""Gets information about a location. - - Args: - request (:class:`~.location_pb2.GetLocationRequest`): - The request object. Request message for - `GetLocation` method. - 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: - ~.location_pb2.Location: - Location object. - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = locations_pb2.GetLocationRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._client._transport.get_location, - 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 list_locations( - self, - request: Optional[locations_pb2.ListLocationsRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> locations_pb2.ListLocationsResponse: - r"""Lists information about the supported locations for this service. - - Args: - request (:class:`~.location_pb2.ListLocationsRequest`): - The request object. Request message for - `ListLocations` method. - 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: - ~.location_pb2.ListLocationsResponse: - Response message for ``ListLocations`` method. - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = locations_pb2.ListLocationsRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._client._transport.list_locations, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("name", request.name),)), - ) - - # Send the request. - response = await rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - async def __aenter__(self): - return self - - async def __aexit__(self, exc_type, exc, tb): - await self.transport.close() - -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) - - -__all__ = ( - "EntityTypesAsyncClient", -) diff --git a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/entity_types/client.py b/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/entity_types/client.py deleted file mode 100644 index 1cdfde69c..000000000 --- a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/entity_types/client.py +++ /dev/null @@ -1,2069 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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 os -import re -from typing import Dict, Mapping, MutableMapping, MutableSequence, Optional, Sequence, Tuple, Type, Union, cast - -from google.cloud.dialogflow_v2beta1 import gapic_version as package_version - -from google.api_core import client_options as client_options_lib -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import retry as retries -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 - -try: - OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] -except AttributeError: # pragma: NO COVER - OptionalRetry = Union[retries.Retry, object] # type: ignore - -from google.api_core import operation # type: ignore -from google.api_core import operation_async # type: ignore -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.cloud.location import locations_pb2 # type: ignore -from google.longrunning import operations_pb2 -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 -from .transports.rest import EntityTypesRestTransport - - -class EntityTypesClientMeta(type): - """Metaclass for the EntityTypes 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[EntityTypesTransport]] - _transport_registry["grpc"] = EntityTypesGrpcTransport - _transport_registry["grpc_asyncio"] = EntityTypesGrpcAsyncIOTransport - _transport_registry["rest"] = EntityTypesRestTransport - - def get_transport_class(cls, - label: Optional[str] = None, - ) -> Type[EntityTypesTransport]: - """Returns an appropriate transport class. - - Args: - label: The name of the desired transport. If none is - provided, then the first transport in the registry is used. - - Returns: - The transport class to use. - """ - # If a specific transport is requested, return that one. - if label: - return cls._transport_registry[label] - - # No transport is requested; return the default (that is, the first one - # in the dictionary). - return next(iter(cls._transport_registry.values())) - - -class EntityTypesClient(metaclass=EntityTypesClientMeta): - """Service for managing - [EntityTypes][google.cloud.dialogflow.v2beta1.EntityType]. - """ - - @staticmethod - def _get_default_mtls_endpoint(api_endpoint): - """Converts api endpoint to mTLS endpoint. - - Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to - "*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively. - Args: - api_endpoint (Optional[str]): the api endpoint to convert. - Returns: - str: converted mTLS api endpoint. - """ - if not api_endpoint: - return api_endpoint - - mtls_endpoint_re = re.compile( - r"(?P[^.]+)(?P\.mtls)?(?P\.sandbox)?(?P\.googleapis\.com)?" - ) - - m = mtls_endpoint_re.match(api_endpoint) - name, mtls, sandbox, googledomain = m.groups() - if mtls or not googledomain: - return api_endpoint - - if sandbox: - return api_endpoint.replace( - "sandbox.googleapis.com", "mtls.sandbox.googleapis.com" - ) - - return api_endpoint.replace(".googleapis.com", ".mtls.googleapis.com") - - DEFAULT_ENDPOINT = "dialogflow.googleapis.com" - DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore - DEFAULT_ENDPOINT - ) - - @classmethod - def from_service_account_info(cls, info: dict, *args, **kwargs): - """Creates an instance of this client using the provided credentials - info. - - Args: - info (dict): The service account private key info. - args: Additional arguments to pass to the constructor. - kwargs: Additional arguments to pass to the constructor. - - Returns: - EntityTypesClient: 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: - EntityTypesClient: 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) -> EntityTypesTransport: - """Returns the transport used by the client instance. - - Returns: - EntityTypesTransport: The transport used by the client - instance. - """ - return self._transport - - @staticmethod - def entity_type_path(project: str,entity_type: str,) -> str: - """Returns a fully-qualified entity_type string.""" - return "projects/{project}/agent/entityTypes/{entity_type}".format(project=project, entity_type=entity_type, ) - - @staticmethod - def parse_entity_type_path(path: str) -> Dict[str,str]: - """Parses a entity_type path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/agent/entityTypes/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_billing_account_path(billing_account: str, ) -> str: - """Returns a fully-qualified billing_account string.""" - return "billingAccounts/{billing_account}".format(billing_account=billing_account, ) - - @staticmethod - def parse_common_billing_account_path(path: str) -> Dict[str,str]: - """Parse a billing_account path into its component segments.""" - m = re.match(r"^billingAccounts/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_folder_path(folder: str, ) -> str: - """Returns a fully-qualified folder string.""" - return "folders/{folder}".format(folder=folder, ) - - @staticmethod - def parse_common_folder_path(path: str) -> Dict[str,str]: - """Parse a folder path into its component segments.""" - m = re.match(r"^folders/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_organization_path(organization: str, ) -> str: - """Returns a fully-qualified organization string.""" - return "organizations/{organization}".format(organization=organization, ) - - @staticmethod - def parse_common_organization_path(path: str) -> Dict[str,str]: - """Parse a organization path into its component segments.""" - m = re.match(r"^organizations/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_project_path(project: str, ) -> str: - """Returns a fully-qualified project string.""" - return "projects/{project}".format(project=project, ) - - @staticmethod - def parse_common_project_path(path: str) -> Dict[str,str]: - """Parse a project path into its component segments.""" - m = re.match(r"^projects/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_location_path(project: str, location: str, ) -> str: - """Returns a fully-qualified location string.""" - return "projects/{project}/locations/{location}".format(project=project, location=location, ) - - @staticmethod - def parse_common_location_path(path: str) -> Dict[str,str]: - """Parse a location path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)$", path) - return m.groupdict() if m else {} - - @classmethod - def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[client_options_lib.ClientOptions] = None): - """Return the API endpoint and client cert source for mutual TLS. - - The client cert source is determined in the following order: - (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the - client cert source is None. - (2) if `client_options.client_cert_source` is provided, use the provided one; if the - default client cert source exists, use the default one; otherwise the client cert - source is None. - - The API endpoint is determined in the following order: - (1) if `client_options.api_endpoint` if provided, use the provided one. - (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the - default mTLS endpoint; if the environment variable is "never", use the default API - endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise - use the default API endpoint. - - More details can be found at https://google.aip.dev/auth/4114. - - Args: - client_options (google.api_core.client_options.ClientOptions): Custom options for the - client. Only the `api_endpoint` and `client_cert_source` properties may be used - in this method. - - Returns: - Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the - client cert source to use. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If any errors happen. - """ - if client_options is None: - client_options = client_options_lib.ClientOptions() - use_client_cert = os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false") - use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") - if use_client_cert not in ("true", "false"): - raise ValueError("Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`") - if use_mtls_endpoint not in ("auto", "never", "always"): - raise MutualTLSChannelError("Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`") - - # Figure out the client cert source to use. - client_cert_source = None - if use_client_cert == "true": - if client_options.client_cert_source: - client_cert_source = client_options.client_cert_source - elif mtls.has_default_client_cert_source(): - client_cert_source = mtls.default_client_cert_source() - - # Figure out which api endpoint to use. - if client_options.api_endpoint is not None: - api_endpoint = client_options.api_endpoint - elif use_mtls_endpoint == "always" or (use_mtls_endpoint == "auto" and client_cert_source): - api_endpoint = cls.DEFAULT_MTLS_ENDPOINT - else: - api_endpoint = cls.DEFAULT_ENDPOINT - - return api_endpoint, client_cert_source - - def __init__(self, *, - credentials: Optional[ga_credentials.Credentials] = None, - transport: Optional[Union[str, EntityTypesTransport]] = None, - client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the entity types 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, EntityTypesTransport]): The - transport to use. If set to None, a transport is chosen - automatically. - client_options (Optional[Union[google.api_core.client_options.ClientOptions, dict]]): 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() - client_options = cast(client_options_lib.ClientOptions, client_options) - - api_endpoint, client_cert_source_func = self.get_mtls_endpoint_and_cert_source(client_options) - - api_key_value = getattr(client_options, "api_key", None) - if api_key_value and credentials: - raise ValueError("client_options.api_key and credentials are mutually exclusive") - - # 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, EntityTypesTransport): - # transport is a EntityTypesTransport instance. - if credentials or client_options.credentials_file or api_key_value: - 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: - import google.auth._default # type: ignore - - if api_key_value and hasattr(google.auth._default, "get_api_key_credentials"): - credentials = google.auth._default.get_api_key_credentials(api_key_value) - - Transport = type(self).get_transport_class(transport) - self._transport = Transport( - credentials=credentials, - credentials_file=client_options.credentials_file, - host=api_endpoint, - scopes=client_options.scopes, - client_cert_source_for_mtls=client_cert_source_func, - quota_project_id=client_options.quota_project_id, - client_info=client_info, - always_use_jwt_access=True, - api_audience=client_options.api_audience, - ) - - def list_entity_types(self, - request: Optional[Union[entity_type.ListEntityTypesRequest, dict]] = None, - *, - parent: Optional[str] = None, - language_code: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListEntityTypesPager: - r"""Returns the list of all entity types in the specified - agent. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import dialogflow_v2beta1 - - def sample_list_entity_types(): - # Create a client - client = dialogflow_v2beta1.EntityTypesClient() - - # Initialize request argument(s) - request = dialogflow_v2beta1.ListEntityTypesRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_entity_types(request=request) - - # Handle the response - for response in page_result: - print(response) - - Args: - request (Union[google.cloud.dialogflow_v2beta1.types.ListEntityTypesRequest, dict]): - The request object. The request message for - [EntityTypes.ListEntityTypes][google.cloud.dialogflow.v2beta1.EntityTypes.ListEntityTypes]. - parent (str): - Required. The agent to list all entity types 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. - language_code (str): - Optional. The language used to access language-specific - data. If not specified, the agent's default language is - used. For more information, see `Multilingual intent and - entity - data `__. - - 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. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.dialogflow_v2beta1.services.entity_types.pagers.ListEntityTypesPager: - The response message for - [EntityTypes.ListEntityTypes][google.cloud.dialogflow.v2beta1.EntityTypes.ListEntityTypes]. - - Iterating over this object will yield results and - resolve additional pages automatically. - - """ - # Create or coerce a protobuf request object. - # Quick 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, language_code]) - 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 entity_type.ListEntityTypesRequest. - # There's no risk of modifying the input as we've already verified - # 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: - request.language_code = language_code - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.list_entity_types] - - # 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.ListEntityTypesPager( - method=rpc, - request=request, - response=response, - metadata=metadata, - ) - - # Done; return the response. - return response - - def get_entity_type(self, - request: Optional[Union[entity_type.GetEntityTypeRequest, dict]] = None, - *, - name: Optional[str] = None, - language_code: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> entity_type.EntityType: - r"""Retrieves the specified entity type. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import dialogflow_v2beta1 - - def sample_get_entity_type(): - # Create a client - client = dialogflow_v2beta1.EntityTypesClient() - - # Initialize request argument(s) - request = dialogflow_v2beta1.GetEntityTypeRequest( - name="name_value", - ) - - # Make the request - response = client.get_entity_type(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.dialogflow_v2beta1.types.GetEntityTypeRequest, dict]): - The request object. The request message for - [EntityTypes.GetEntityType][google.cloud.dialogflow.v2beta1.EntityTypes.GetEntityType]. - name (str): - Required. The name of the entity type. Supported - formats: - - - ``projects//agent/entityTypes/`` - - ``projects//locations//agent/entityTypes/`` - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - language_code (str): - Optional. The language used to access language-specific - data. If not specified, the agent's default language is - used. For more information, see `Multilingual intent and - entity - data `__. - - 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. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.dialogflow_v2beta1.types.EntityType: - Each intent parameter has a type, called the entity type, which dictates - exactly how data from an end-user expression is - extracted. - - Dialogflow provides predefined system entities that - can match many common types of data. For example, - there are system entities for matching dates, times, - colors, email addresses, and so on. You can also - create your own custom entities for matching custom - data. For example, you could define a vegetable - entity that can match the types of vegetables - available for purchase with a grocery store agent. - - For more information, see the [Entity - guide](\ https://cloud.google.com/dialogflow/docs/entities-overview). - - """ - # Create or coerce a protobuf request object. - # Quick 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, language_code]) - 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 entity_type.GetEntityTypeRequest. - # There's no risk of modifying the input as we've already verified - # 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: - request.language_code = language_code - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.get_entity_type] - - # 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_entity_type(self, - request: Optional[Union[gcd_entity_type.CreateEntityTypeRequest, dict]] = None, - *, - parent: Optional[str] = None, - entity_type: Optional[gcd_entity_type.EntityType] = None, - language_code: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gcd_entity_type.EntityType: - r"""Creates an entity type in the specified agent. - - Note: You should always train an agent prior to sending it - queries. See the `training - documentation `__. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import dialogflow_v2beta1 - - def sample_create_entity_type(): - # Create a client - client = dialogflow_v2beta1.EntityTypesClient() - - # Initialize request argument(s) - entity_type = dialogflow_v2beta1.EntityType() - entity_type.display_name = "display_name_value" - entity_type.kind = "KIND_REGEXP" - - request = dialogflow_v2beta1.CreateEntityTypeRequest( - parent="parent_value", - entity_type=entity_type, - ) - - # Make the request - response = client.create_entity_type(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.dialogflow_v2beta1.types.CreateEntityTypeRequest, dict]): - The request object. The request message for - [EntityTypes.CreateEntityType][google.cloud.dialogflow.v2beta1.EntityTypes.CreateEntityType]. - parent (str): - Required. The agent to create a entity type 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. - entity_type (google.cloud.dialogflow_v2beta1.types.EntityType): - Required. The entity type to create. - This corresponds to the ``entity_type`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - language_code (str): - Optional. The language used to access language-specific - data. If not specified, the agent's default language is - used. For more information, see `Multilingual intent and - entity - data `__. - - 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. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.dialogflow_v2beta1.types.EntityType: - Each intent parameter has a type, called the entity type, which dictates - exactly how data from an end-user expression is - extracted. - - Dialogflow provides predefined system entities that - can match many common types of data. For example, - there are system entities for matching dates, times, - colors, email addresses, and so on. You can also - create your own custom entities for matching custom - data. For example, you could define a vegetable - entity that can match the types of vegetables - available for purchase with a grocery store agent. - - For more information, see the [Entity - guide](\ https://cloud.google.com/dialogflow/docs/entities-overview). - - """ - # Create or coerce a protobuf request object. - # Quick 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, entity_type, language_code]) - 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_entity_type.CreateEntityTypeRequest. - # There's no risk of modifying the input as we've already verified - # 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: - request.entity_type = entity_type - if language_code is not None: - request.language_code = language_code - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.create_entity_type] - - # 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_entity_type(self, - request: Optional[Union[gcd_entity_type.UpdateEntityTypeRequest, dict]] = None, - *, - entity_type: Optional[gcd_entity_type.EntityType] = None, - language_code: Optional[str] = None, - update_mask: Optional[field_mask_pb2.FieldMask] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gcd_entity_type.EntityType: - r"""Updates the specified entity type. - - Note: You should always train an agent prior to sending it - queries. See the `training - documentation `__. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import dialogflow_v2beta1 - - def sample_update_entity_type(): - # Create a client - client = dialogflow_v2beta1.EntityTypesClient() - - # Initialize request argument(s) - entity_type = dialogflow_v2beta1.EntityType() - entity_type.display_name = "display_name_value" - entity_type.kind = "KIND_REGEXP" - - request = dialogflow_v2beta1.UpdateEntityTypeRequest( - entity_type=entity_type, - ) - - # Make the request - response = client.update_entity_type(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.dialogflow_v2beta1.types.UpdateEntityTypeRequest, dict]): - The request object. The request message for - [EntityTypes.UpdateEntityType][google.cloud.dialogflow.v2beta1.EntityTypes.UpdateEntityType]. - entity_type (google.cloud.dialogflow_v2beta1.types.EntityType): - Required. The entity type to update. - This corresponds to the ``entity_type`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - language_code (str): - Optional. The language used to access language-specific - data. If not specified, the agent's default language is - used. For more information, see `Multilingual intent and - entity - data `__. - - This corresponds to the ``language_code`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - update_mask (google.protobuf.field_mask_pb2.FieldMask): - Optional. 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.EntityType: - Each intent parameter has a type, called the entity type, which dictates - exactly how data from an end-user expression is - extracted. - - Dialogflow provides predefined system entities that - can match many common types of data. For example, - there are system entities for matching dates, times, - colors, email addresses, and so on. You can also - create your own custom entities for matching custom - data. For example, you could define a vegetable - entity that can match the types of vegetables - available for purchase with a grocery store agent. - - For more information, see the [Entity - guide](\ https://cloud.google.com/dialogflow/docs/entities-overview). - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([entity_type, language_code, 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_entity_type.UpdateEntityTypeRequest. - # There's no risk of modifying the input as we've already verified - # 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: - request.language_code = language_code - 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_entity_type] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("entity_type.name", request.entity_type.name), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def delete_entity_type(self, - request: Optional[Union[entity_type.DeleteEntityTypeRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> None: - r"""Deletes the specified entity type. - - Note: You should always train an agent prior to sending it - queries. See the `training - documentation `__. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import dialogflow_v2beta1 - - def sample_delete_entity_type(): - # Create a client - client = dialogflow_v2beta1.EntityTypesClient() - - # Initialize request argument(s) - request = dialogflow_v2beta1.DeleteEntityTypeRequest( - name="name_value", - ) - - # Make the request - client.delete_entity_type(request=request) - - Args: - request (Union[google.cloud.dialogflow_v2beta1.types.DeleteEntityTypeRequest, dict]): - The request object. The request message for - [EntityTypes.DeleteEntityType][google.cloud.dialogflow.v2beta1.EntityTypes.DeleteEntityType]. - name (str): - Required. The name of the entity type to delete. - Supported formats: - - - ``projects//agent/entityTypes/`` - - ``projects//locations//agent/entityTypes/`` - - 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. - # Quick 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 entity_type.DeleteEntityTypeRequest. - # There's no risk of modifying the input as we've already verified - # 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 - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.delete_entity_type] - - # 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 batch_update_entity_types(self, - request: Optional[Union[entity_type.BatchUpdateEntityTypesRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation.Operation: - r"""Updates/Creates multiple entity types in the specified agent. - - This method is a `long-running - operation `__. - The returned ``Operation`` type has the following - method-specific fields: - - - ``metadata``: An empty `Struct - message `__ - - ``response``: - [BatchUpdateEntityTypesResponse][google.cloud.dialogflow.v2beta1.BatchUpdateEntityTypesResponse] - - Note: You should always train an agent prior to sending it - queries. See the `training - documentation `__. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import dialogflow_v2beta1 - - def sample_batch_update_entity_types(): - # Create a client - client = dialogflow_v2beta1.EntityTypesClient() - - # Initialize request argument(s) - request = dialogflow_v2beta1.BatchUpdateEntityTypesRequest( - entity_type_batch_uri="entity_type_batch_uri_value", - parent="parent_value", - ) - - # Make the request - operation = client.batch_update_entity_types(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.dialogflow_v2beta1.types.BatchUpdateEntityTypesRequest, dict]): - 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. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.api_core.operation.Operation: - An object representing a long-running operation. - - The result type for the operation will be :class:`google.cloud.dialogflow_v2beta1.types.BatchUpdateEntityTypesResponse` The response message for - [EntityTypes.BatchUpdateEntityTypes][google.cloud.dialogflow.v2beta1.EntityTypes.BatchUpdateEntityTypes]. - - """ - # 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 - # there are no flattened fields. - if not isinstance(request, entity_type.BatchUpdateEntityTypesRequest): - request = entity_type.BatchUpdateEntityTypesRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.batch_update_entity_types] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Wrap the response in an operation future. - response = operation.from_gapic( - response, - self._transport.operations_client, - entity_type.BatchUpdateEntityTypesResponse, - metadata_type=struct_pb2.Struct, - ) - - # Done; return the response. - return response - - def batch_delete_entity_types(self, - request: Optional[Union[entity_type.BatchDeleteEntityTypesRequest, dict]] = None, - *, - parent: Optional[str] = None, - entity_type_names: Optional[MutableSequence[str]] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation.Operation: - r"""Deletes entity types in the specified agent. - - This method is a `long-running - operation `__. - The returned ``Operation`` type has the following - method-specific fields: - - - ``metadata``: An empty `Struct - message `__ - - ``response``: An `Empty - message `__ - - Note: You should always train an agent prior to sending it - queries. See the `training - documentation `__. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import dialogflow_v2beta1 - - def sample_batch_delete_entity_types(): - # Create a client - client = dialogflow_v2beta1.EntityTypesClient() - - # Initialize request argument(s) - request = dialogflow_v2beta1.BatchDeleteEntityTypesRequest( - parent="parent_value", - entity_type_names=['entity_type_names_value1', 'entity_type_names_value2'], - ) - - # Make the request - operation = client.batch_delete_entity_types(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.dialogflow_v2beta1.types.BatchDeleteEntityTypesRequest, dict]): - The request object. The request message for - [EntityTypes.BatchDeleteEntityTypes][google.cloud.dialogflow.v2beta1.EntityTypes.BatchDeleteEntityTypes]. - parent (str): - Required. The name of the agent to delete all entities - types 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. - entity_type_names (MutableSequence[str]): - Required. The names entity types to delete. All names - must point to the same agent as ``parent``. - - 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. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.api_core.operation.Operation: - An object representing a long-running operation. - - The result type for the operation will be :class:`google.protobuf.empty_pb2.Empty` A generic empty message that you can re-use to avoid defining duplicated - empty messages in your APIs. A typical example is to - use it as the request or the response type of an API - method. For instance: - - service Foo { - rpc Bar(google.protobuf.Empty) returns - (google.protobuf.Empty); - - } - - """ - # Create or coerce a protobuf request object. - # Quick 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, entity_type_names]) - 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 entity_type.BatchDeleteEntityTypesRequest. - # There's no risk of modifying the input as we've already verified - # 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: - request.entity_type_names = entity_type_names - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.batch_delete_entity_types] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Wrap the response in an operation future. - response = operation.from_gapic( - response, - self._transport.operations_client, - empty_pb2.Empty, - metadata_type=struct_pb2.Struct, - ) - - # Done; return the response. - return response - - def batch_create_entities(self, - request: Optional[Union[entity_type.BatchCreateEntitiesRequest, dict]] = None, - *, - parent: Optional[str] = None, - entities: Optional[MutableSequence[entity_type.EntityType.Entity]] = None, - language_code: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation.Operation: - r"""Creates multiple new entities in the specified entity type. - - This method is a `long-running - operation `__. - The returned ``Operation`` type has the following - method-specific fields: - - - ``metadata``: An empty `Struct - message `__ - - ``response``: An `Empty - message `__ - - Note: You should always train an agent prior to sending it - queries. See the `training - documentation `__. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import dialogflow_v2beta1 - - def sample_batch_create_entities(): - # Create a client - client = dialogflow_v2beta1.EntityTypesClient() - - # Initialize request argument(s) - entities = dialogflow_v2beta1.Entity() - entities.value = "value_value" - - request = dialogflow_v2beta1.BatchCreateEntitiesRequest( - parent="parent_value", - entities=entities, - ) - - # Make the request - operation = client.batch_create_entities(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.dialogflow_v2beta1.types.BatchCreateEntitiesRequest, dict]): - The request object. The request message for - [EntityTypes.BatchCreateEntities][google.cloud.dialogflow.v2beta1.EntityTypes.BatchCreateEntities]. - parent (str): - Required. The name of the entity type to create entities - in. Supported formats: - - - ``projects//agent/entityTypes/`` - - ``projects//locations//agent/entityTypes/`` - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - entities (MutableSequence[google.cloud.dialogflow_v2beta1.types.EntityType.Entity]): - Required. The entities to create. - This corresponds to the ``entities`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - language_code (str): - Optional. The language used to access language-specific - data. If not specified, the agent's default language is - used. For more information, see `Multilingual intent and - entity - data `__. - - 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. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.api_core.operation.Operation: - An object representing a long-running operation. - - The result type for the operation will be :class:`google.protobuf.empty_pb2.Empty` A generic empty message that you can re-use to avoid defining duplicated - empty messages in your APIs. A typical example is to - use it as the request or the response type of an API - method. For instance: - - service Foo { - rpc Bar(google.protobuf.Empty) returns - (google.protobuf.Empty); - - } - - """ - # Create or coerce a protobuf request object. - # Quick 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, entities, language_code]) - 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 entity_type.BatchCreateEntitiesRequest. - # There's no risk of modifying the input as we've already verified - # 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: - request.entities = entities - if language_code is not None: - request.language_code = language_code - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.batch_create_entities] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Wrap the response in an operation future. - response = operation.from_gapic( - response, - self._transport.operations_client, - empty_pb2.Empty, - metadata_type=struct_pb2.Struct, - ) - - # Done; return the response. - return response - - def batch_update_entities(self, - request: Optional[Union[entity_type.BatchUpdateEntitiesRequest, dict]] = None, - *, - parent: Optional[str] = None, - entities: Optional[MutableSequence[entity_type.EntityType.Entity]] = None, - language_code: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation.Operation: - r"""Updates or creates multiple entities in the specified entity - type. This method does not affect entities in the entity type - that aren't explicitly specified in the request. - - Note: You should always train an agent prior to sending it - queries. See the `training - documentation `__. - - This method is a `long-running - operation `__. - The returned ``Operation`` type has the following - method-specific fields: - - - ``metadata``: An empty `Struct - message `__ - - ``response``: An `Empty - message `__ - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import dialogflow_v2beta1 - - def sample_batch_update_entities(): - # Create a client - client = dialogflow_v2beta1.EntityTypesClient() - - # Initialize request argument(s) - entities = dialogflow_v2beta1.Entity() - entities.value = "value_value" - - request = dialogflow_v2beta1.BatchUpdateEntitiesRequest( - parent="parent_value", - entities=entities, - ) - - # Make the request - operation = client.batch_update_entities(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.dialogflow_v2beta1.types.BatchUpdateEntitiesRequest, dict]): - The request object. The request message for - [EntityTypes.BatchUpdateEntities][google.cloud.dialogflow.v2beta1.EntityTypes.BatchUpdateEntities]. - parent (str): - Required. The name of the entity type to update or - create entities in. Supported formats: - - - ``projects//agent/entityTypes/`` - - ``projects//locations//agent/entityTypes/`` - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - entities (MutableSequence[google.cloud.dialogflow_v2beta1.types.EntityType.Entity]): - Required. The entities to update or - create. - - This corresponds to the ``entities`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - language_code (str): - Optional. The language used to access language-specific - data. If not specified, the agent's default language is - used. For more information, see `Multilingual intent and - entity - data `__. - - 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. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.api_core.operation.Operation: - An object representing a long-running operation. - - The result type for the operation will be :class:`google.protobuf.empty_pb2.Empty` A generic empty message that you can re-use to avoid defining duplicated - empty messages in your APIs. A typical example is to - use it as the request or the response type of an API - method. For instance: - - service Foo { - rpc Bar(google.protobuf.Empty) returns - (google.protobuf.Empty); - - } - - """ - # Create or coerce a protobuf request object. - # Quick 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, entities, language_code]) - 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 entity_type.BatchUpdateEntitiesRequest. - # There's no risk of modifying the input as we've already verified - # 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: - request.entities = entities - if language_code is not None: - request.language_code = language_code - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.batch_update_entities] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Wrap the response in an operation future. - response = operation.from_gapic( - response, - self._transport.operations_client, - empty_pb2.Empty, - metadata_type=struct_pb2.Struct, - ) - - # Done; return the response. - return response - - def batch_delete_entities(self, - request: Optional[Union[entity_type.BatchDeleteEntitiesRequest, dict]] = None, - *, - parent: Optional[str] = None, - entity_values: Optional[MutableSequence[str]] = None, - language_code: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation.Operation: - r"""Deletes entities in the specified entity type. - - This method is a `long-running - operation `__. - The returned ``Operation`` type has the following - method-specific fields: - - - ``metadata``: An empty `Struct - message `__ - - ``response``: An `Empty - message `__ - - Note: You should always train an agent prior to sending it - queries. See the `training - documentation `__. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import dialogflow_v2beta1 - - def sample_batch_delete_entities(): - # Create a client - client = dialogflow_v2beta1.EntityTypesClient() - - # Initialize request argument(s) - request = dialogflow_v2beta1.BatchDeleteEntitiesRequest( - parent="parent_value", - entity_values=['entity_values_value1', 'entity_values_value2'], - ) - - # Make the request - operation = client.batch_delete_entities(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.dialogflow_v2beta1.types.BatchDeleteEntitiesRequest, dict]): - The request object. The request message for - [EntityTypes.BatchDeleteEntities][google.cloud.dialogflow.v2beta1.EntityTypes.BatchDeleteEntities]. - parent (str): - Required. The name of the entity type to delete entries - for. Supported formats: - - - ``projects//agent/entityTypes/`` - - ``projects//locations//agent/entityTypes/`` - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - entity_values (MutableSequence[str]): - Required. The reference ``values`` of the entities to - delete. Note that these are not fully-qualified names, - i.e. they don't start with ``projects/``. - - This corresponds to the ``entity_values`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - language_code (str): - Optional. The language used to access language-specific - data. If not specified, the agent's default language is - used. For more information, see `Multilingual intent and - entity - data `__. - - 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. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.api_core.operation.Operation: - An object representing a long-running operation. - - The result type for the operation will be :class:`google.protobuf.empty_pb2.Empty` A generic empty message that you can re-use to avoid defining duplicated - empty messages in your APIs. A typical example is to - use it as the request or the response type of an API - method. For instance: - - service Foo { - rpc Bar(google.protobuf.Empty) returns - (google.protobuf.Empty); - - } - - """ - # Create or coerce a protobuf request object. - # Quick 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, entity_values, language_code]) - 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 entity_type.BatchDeleteEntitiesRequest. - # There's no risk of modifying the input as we've already verified - # 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: - request.entity_values = entity_values - if language_code is not None: - request.language_code = language_code - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.batch_delete_entities] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Wrap the response in an operation future. - response = operation.from_gapic( - response, - self._transport.operations_client, - empty_pb2.Empty, - metadata_type=struct_pb2.Struct, - ) - - # Done; return the response. - return response - - def __enter__(self) -> "EntityTypesClient": - return self - - def __exit__(self, type, value, traceback): - """Releases underlying transport's resources. - - .. warning:: - ONLY use as a context manager if the transport is NOT shared - with other clients! Exiting the with block will CLOSE the transport - and may cause errors in other clients! - """ - self.transport.close() - - def list_operations( - self, - request: Optional[operations_pb2.ListOperationsRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operations_pb2.ListOperationsResponse: - r"""Lists operations that match the specified filter in the request. - - Args: - request (:class:`~.operations_pb2.ListOperationsRequest`): - The request object. Request message for - `ListOperations` method. - 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: - ~.operations_pb2.ListOperationsResponse: - Response message for ``ListOperations`` method. - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = operations_pb2.ListOperationsRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._transport.list_operations, - 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 = rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - def get_operation( - self, - request: Optional[operations_pb2.GetOperationRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operations_pb2.Operation: - r"""Gets the latest state of a long-running operation. - - Args: - request (:class:`~.operations_pb2.GetOperationRequest`): - The request object. Request message for - `GetOperation` method. - 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: - ~.operations_pb2.Operation: - An ``Operation`` object. - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = operations_pb2.GetOperationRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._transport.get_operation, - 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 = rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - def cancel_operation( - self, - request: Optional[operations_pb2.CancelOperationRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> None: - r"""Starts asynchronous cancellation on a long-running operation. - - The server makes a best effort to cancel the operation, but success - is not guaranteed. If the server doesn't support this method, it returns - `google.rpc.Code.UNIMPLEMENTED`. - - Args: - request (:class:`~.operations_pb2.CancelOperationRequest`): - The request object. Request message for - `CancelOperation` method. - 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: - None - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = operations_pb2.CancelOperationRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._transport.cancel_operation, - 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. - rpc(request, retry=retry, timeout=timeout, metadata=metadata,) - - def get_location( - self, - request: Optional[locations_pb2.GetLocationRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> locations_pb2.Location: - r"""Gets information about a location. - - Args: - request (:class:`~.location_pb2.GetLocationRequest`): - The request object. Request message for - `GetLocation` method. - 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: - ~.location_pb2.Location: - Location object. - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = locations_pb2.GetLocationRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._transport.get_location, - 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 = rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - def list_locations( - self, - request: Optional[locations_pb2.ListLocationsRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> locations_pb2.ListLocationsResponse: - r"""Lists information about the supported locations for this service. - - Args: - request (:class:`~.location_pb2.ListLocationsRequest`): - The request object. Request message for - `ListLocations` method. - 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: - ~.location_pb2.ListLocationsResponse: - Response message for ``ListLocations`` method. - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = locations_pb2.ListLocationsRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._transport.list_locations, - 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 = rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) - - -__all__ = ( - "EntityTypesClient", -) diff --git a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/entity_types/pagers.py b/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/entity_types/pagers.py deleted file mode 100644 index 15e4b2fb0..000000000 --- a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/entity_types/pagers.py +++ /dev/null @@ -1,139 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from typing import Any, AsyncIterator, Awaitable, Callable, Sequence, Tuple, Optional, Iterator - -from google.cloud.dialogflow_v2beta1.types import entity_type - - -class ListEntityTypesPager: - """A pager for iterating through ``list_entity_types`` requests. - - This class thinly wraps an initial - :class:`google.cloud.dialogflow_v2beta1.types.ListEntityTypesResponse` object, and - provides an ``__iter__`` method to iterate through its - ``entity_types`` field. - - If there are more pages, the ``__iter__`` method will make additional - ``ListEntityTypes`` requests and continue to iterate - through the ``entity_types`` field on the - corresponding responses. - - All the usual :class:`google.cloud.dialogflow_v2beta1.types.ListEntityTypesResponse` - 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[..., entity_type.ListEntityTypesResponse], - request: entity_type.ListEntityTypesRequest, - response: entity_type.ListEntityTypesResponse, - *, - 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.ListEntityTypesRequest): - The initial request object. - response (google.cloud.dialogflow_v2beta1.types.ListEntityTypesResponse): - 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 = entity_type.ListEntityTypesRequest(request) - self._response = response - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - def pages(self) -> Iterator[entity_type.ListEntityTypesResponse]: - yield self._response - while self._response.next_page_token: - self._request.page_token = self._response.next_page_token - self._response = self._method(self._request, metadata=self._metadata) - yield self._response - - def __iter__(self) -> Iterator[entity_type.EntityType]: - for page in self.pages: - yield from page.entity_types - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListEntityTypesAsyncPager: - """A pager for iterating through ``list_entity_types`` requests. - - This class thinly wraps an initial - :class:`google.cloud.dialogflow_v2beta1.types.ListEntityTypesResponse` object, and - provides an ``__aiter__`` method to iterate through its - ``entity_types`` field. - - If there are more pages, the ``__aiter__`` method will make additional - ``ListEntityTypes`` requests and continue to iterate - through the ``entity_types`` field on the - corresponding responses. - - All the usual :class:`google.cloud.dialogflow_v2beta1.types.ListEntityTypesResponse` - 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[entity_type.ListEntityTypesResponse]], - request: entity_type.ListEntityTypesRequest, - response: entity_type.ListEntityTypesResponse, - *, - metadata: Sequence[Tuple[str, str]] = ()): - """Instantiates the pager. - - Args: - method (Callable): The method that was originally called, and - which instantiated this pager. - request (google.cloud.dialogflow_v2beta1.types.ListEntityTypesRequest): - The initial request object. - response (google.cloud.dialogflow_v2beta1.types.ListEntityTypesResponse): - 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 = entity_type.ListEntityTypesRequest(request) - self._response = response - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - async def pages(self) -> AsyncIterator[entity_type.ListEntityTypesResponse]: - yield self._response - while self._response.next_page_token: - self._request.page_token = self._response.next_page_token - self._response = await self._method(self._request, metadata=self._metadata) - yield self._response - def __aiter__(self) -> AsyncIterator[entity_type.EntityType]: - async def async_generator(): - async for page in self.pages: - for response in page.entity_types: - yield response - - return async_generator() - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) diff --git a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/entity_types/transports/__init__.py b/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/entity_types/transports/__init__.py deleted file mode 100644 index 3f9feda31..000000000 --- a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/entity_types/transports/__init__.py +++ /dev/null @@ -1,38 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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 EntityTypesTransport -from .grpc import EntityTypesGrpcTransport -from .grpc_asyncio import EntityTypesGrpcAsyncIOTransport -from .rest import EntityTypesRestTransport -from .rest import EntityTypesRestInterceptor - - -# Compile a registry of transports. -_transport_registry = OrderedDict() # type: Dict[str, Type[EntityTypesTransport]] -_transport_registry['grpc'] = EntityTypesGrpcTransport -_transport_registry['grpc_asyncio'] = EntityTypesGrpcAsyncIOTransport -_transport_registry['rest'] = EntityTypesRestTransport - -__all__ = ( - 'EntityTypesTransport', - 'EntityTypesGrpcTransport', - 'EntityTypesGrpcAsyncIOTransport', - 'EntityTypesRestTransport', - 'EntityTypesRestInterceptor', -) diff --git a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/entity_types/transports/base.py b/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/entity_types/transports/base.py deleted file mode 100644 index 5ce6d37c6..000000000 --- a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/entity_types/transports/base.py +++ /dev/null @@ -1,329 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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 - -from google.cloud.dialogflow_v2beta1 import gapic_version as package_version - -import google.auth # type: ignore -import google.api_core -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import retry as retries -from google.api_core import operations_v1 -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 entity_type -from google.cloud.dialogflow_v2beta1.types import entity_type as gcd_entity_type -from google.cloud.location import locations_pb2 # type: ignore -from google.longrunning import operations_pb2 -from google.longrunning import operations_pb2 # type: ignore -from google.protobuf import empty_pb2 # type: ignore - -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) - - -class EntityTypesTransport(abc.ABC): - """Abstract transport class for EntityTypes.""" - - 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: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - api_audience: Optional[str] = None, - **kwargs, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. - scopes (Optional[Sequence[str]]): A list of scopes. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - """ - - scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} - - # Save the scopes. - self._scopes = scopes - - # If no credentials are provided, then determine the appropriate - # defaults. - if credentials and credentials_file: - raise core_exceptions.DuplicateCredentialArgs("'credentials_file' and 'credentials' are mutually exclusive") - - if credentials_file is not None: - credentials, _ = google.auth.load_credentials_from_file( - credentials_file, - **scopes_kwargs, - quota_project_id=quota_project_id - ) - elif credentials is None: - credentials, _ = google.auth.default(**scopes_kwargs, quota_project_id=quota_project_id) - # Don't apply audience if the credentials file passed from user. - if hasattr(credentials, "with_gdch_audience"): - credentials = credentials.with_gdch_audience(api_audience if api_audience else host) - - # If the credentials are service account credentials, then always try to use self signed JWT. - if always_use_jwt_access and isinstance(credentials, service_account.Credentials) and hasattr(service_account.Credentials, "with_always_use_jwt_access"): - credentials = credentials.with_always_use_jwt_access(True) - - # Save the credentials. - self._credentials = credentials - - # Save the hostname. Default to port 443 (HTTPS) if none is specified. - if ':' not in host: - host += ':443' - self._host = host - - def _prep_wrapped_messages(self, client_info): - # Precompute the wrapped methods. - self._wrapped_methods = { - self.list_entity_types: gapic_v1.method.wrap_method( - self.list_entity_types, - default_timeout=None, - client_info=client_info, - ), - self.get_entity_type: gapic_v1.method.wrap_method( - self.get_entity_type, - default_timeout=None, - client_info=client_info, - ), - self.create_entity_type: gapic_v1.method.wrap_method( - self.create_entity_type, - default_timeout=None, - client_info=client_info, - ), - self.update_entity_type: gapic_v1.method.wrap_method( - self.update_entity_type, - default_timeout=None, - client_info=client_info, - ), - self.delete_entity_type: gapic_v1.method.wrap_method( - self.delete_entity_type, - default_timeout=None, - client_info=client_info, - ), - self.batch_update_entity_types: gapic_v1.method.wrap_method( - self.batch_update_entity_types, - default_timeout=None, - client_info=client_info, - ), - self.batch_delete_entity_types: gapic_v1.method.wrap_method( - self.batch_delete_entity_types, - default_timeout=None, - client_info=client_info, - ), - self.batch_create_entities: gapic_v1.method.wrap_method( - self.batch_create_entities, - default_timeout=None, - client_info=client_info, - ), - self.batch_update_entities: gapic_v1.method.wrap_method( - self.batch_update_entities, - default_timeout=None, - client_info=client_info, - ), - self.batch_delete_entities: gapic_v1.method.wrap_method( - self.batch_delete_entities, - default_timeout=None, - client_info=client_info, - ), - } - - def close(self): - """Closes resources associated with the transport. - - .. warning:: - Only call this method if the transport is NOT shared - with other clients - this may cause errors in other clients! - """ - raise NotImplementedError() - - @property - def operations_client(self): - """Return the client designed to process long-running operations.""" - raise NotImplementedError() - - @property - def list_entity_types(self) -> Callable[ - [entity_type.ListEntityTypesRequest], - Union[ - entity_type.ListEntityTypesResponse, - Awaitable[entity_type.ListEntityTypesResponse] - ]]: - raise NotImplementedError() - - @property - def get_entity_type(self) -> Callable[ - [entity_type.GetEntityTypeRequest], - Union[ - entity_type.EntityType, - Awaitable[entity_type.EntityType] - ]]: - raise NotImplementedError() - - @property - def create_entity_type(self) -> Callable[ - [gcd_entity_type.CreateEntityTypeRequest], - Union[ - gcd_entity_type.EntityType, - Awaitable[gcd_entity_type.EntityType] - ]]: - raise NotImplementedError() - - @property - def update_entity_type(self) -> Callable[ - [gcd_entity_type.UpdateEntityTypeRequest], - Union[ - gcd_entity_type.EntityType, - Awaitable[gcd_entity_type.EntityType] - ]]: - raise NotImplementedError() - - @property - def delete_entity_type(self) -> Callable[ - [entity_type.DeleteEntityTypeRequest], - Union[ - empty_pb2.Empty, - Awaitable[empty_pb2.Empty] - ]]: - raise NotImplementedError() - - @property - def batch_update_entity_types(self) -> Callable[ - [entity_type.BatchUpdateEntityTypesRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: - raise NotImplementedError() - - @property - def batch_delete_entity_types(self) -> Callable[ - [entity_type.BatchDeleteEntityTypesRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: - raise NotImplementedError() - - @property - def batch_create_entities(self) -> Callable[ - [entity_type.BatchCreateEntitiesRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: - raise NotImplementedError() - - @property - def batch_update_entities(self) -> Callable[ - [entity_type.BatchUpdateEntitiesRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: - raise NotImplementedError() - - @property - def batch_delete_entities(self) -> Callable[ - [entity_type.BatchDeleteEntitiesRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: - raise NotImplementedError() - - @property - def list_operations( - self, - ) -> Callable[ - [operations_pb2.ListOperationsRequest], - Union[operations_pb2.ListOperationsResponse, Awaitable[operations_pb2.ListOperationsResponse]], - ]: - raise NotImplementedError() - - @property - def get_operation( - self, - ) -> Callable[ - [operations_pb2.GetOperationRequest], - Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], - ]: - raise NotImplementedError() - - @property - def cancel_operation( - self, - ) -> Callable[ - [operations_pb2.CancelOperationRequest], - None, - ]: - raise NotImplementedError() - - @property - def get_location(self, - ) -> Callable[ - [locations_pb2.GetLocationRequest], - Union[locations_pb2.Location, Awaitable[locations_pb2.Location]], - ]: - raise NotImplementedError() - - @property - def list_locations(self, - ) -> Callable[ - [locations_pb2.ListLocationsRequest], - Union[locations_pb2.ListLocationsResponse, Awaitable[locations_pb2.ListLocationsResponse]], - ]: - raise NotImplementedError() - - @property - def kind(self) -> str: - raise NotImplementedError() - - -__all__ = ( - 'EntityTypesTransport', -) diff --git a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/entity_types/transports/grpc.py b/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/entity_types/transports/grpc.py deleted file mode 100644 index eaacd306b..000000000 --- a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/entity_types/transports/grpc.py +++ /dev/null @@ -1,697 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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 -from google.api_core import operations_v1 -from google.api_core import gapic_v1 -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.cloud.location import locations_pb2 # type: ignore -from google.longrunning import operations_pb2 -from google.longrunning import operations_pb2 # type: ignore -from google.protobuf import empty_pb2 # type: ignore -from .base import EntityTypesTransport, DEFAULT_CLIENT_INFO - - -class EntityTypesGrpcTransport(EntityTypesTransport): - """gRPC backend transport for EntityTypes. - - Service for managing - [EntityTypes][google.cloud.dialogflow.v2beta1.EntityType]. - - 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: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - channel: Optional[grpc.Channel] = None, - api_mtls_endpoint: Optional[str] = None, - client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, - ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, - client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - api_audience: Optional[str] = None, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - This argument is ignored if ``channel`` is provided. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional(Sequence[str])): A list of scopes. This argument is - ignored if ``channel`` is provided. - channel (Optional[grpc.Channel]): A ``Channel`` instance through - which to make calls. - api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. - If provided, it overrides the ``host`` argument and tries to create - a mutual TLS channel with client SSL credentials from - ``client_cert_source`` or application default SSL credentials. - client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): - Deprecated. A callback to provide client SSL certificate bytes and - private key bytes, both in PEM format. It is ignored if - ``api_mtls_endpoint`` is None. - ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials - for the grpc channel. It is ignored if ``channel`` is provided. - client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): - A callback to provide client certificate bytes and private key bytes, - both in PEM format. It is used to configure a mutual TLS channel. It is - ignored if ``channel`` or ``ssl_channel_credentials`` is provided. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport - creation failed for any reason. - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - self._grpc_channel = None - self._ssl_channel_credentials = ssl_channel_credentials - self._stubs: Dict[str, Callable] = {} - self._operations_client: Optional[operations_v1.OperationsClient] = None - - if api_mtls_endpoint: - warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) - if client_cert_source: - warnings.warn("client_cert_source is deprecated", DeprecationWarning) - - if channel: - # Ignore credentials if a channel was passed. - credentials = False - # If a channel was explicitly provided, set it. - self._grpc_channel = channel - self._ssl_channel_credentials = None - - else: - if api_mtls_endpoint: - host = api_mtls_endpoint - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - self._ssl_channel_credentials = SslCredentials().ssl_credentials - - else: - if client_cert_source_for_mtls and not ssl_channel_credentials: - cert, key = client_cert_source_for_mtls() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - - # The base transport sets the host, credentials and scopes - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes, - quota_project_id=quota_project_id, - client_info=client_info, - always_use_jwt_access=always_use_jwt_access, - api_audience=api_audience, - ) - - if not self._grpc_channel: - self._grpc_channel = type(self).create_channel( - self._host, - # use the credentials which are saved - credentials=self._credentials, - # Set ``credentials_file`` to ``None`` here as - # the credentials that we saved earlier should be used. - credentials_file=None, - 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: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - **kwargs) -> grpc.Channel: - """Create and return a gRPC channel object. - Args: - host (Optional[str]): The host for the channel to use. - credentials (Optional[~.Credentials]): The - authorization credentials to attach to requests. These - credentials identify this application to the service. If - none are specified, the client will attempt to ascertain - the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - kwargs (Optional[dict]): Keyword arguments, which are passed to the - channel creation. - Returns: - grpc.Channel: A gRPC channel object. - - Raises: - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - - return grpc_helpers.create_channel( - host, - credentials=credentials, - credentials_file=credentials_file, - quota_project_id=quota_project_id, - default_scopes=cls.AUTH_SCOPES, - scopes=scopes, - default_host=cls.DEFAULT_HOST, - **kwargs - ) - - @property - def grpc_channel(self) -> grpc.Channel: - """Return the channel designed to connect to this service. - """ - return self._grpc_channel - - @property - def operations_client(self) -> operations_v1.OperationsClient: - """Create the client designed to process long-running operations. - - This property caches on the instance; repeated calls return the same - client. - """ - # Quick check: Only create a new client if we do not already have one. - if self._operations_client is None: - self._operations_client = operations_v1.OperationsClient( - self.grpc_channel - ) - - # Return the client from cache. - return self._operations_client - - @property - def list_entity_types(self) -> Callable[ - [entity_type.ListEntityTypesRequest], - entity_type.ListEntityTypesResponse]: - r"""Return a callable for the list entity types method over gRPC. - - Returns the list of all entity types in the specified - agent. - - Returns: - Callable[[~.ListEntityTypesRequest], - ~.ListEntityTypesResponse]: - 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_entity_types' not in self._stubs: - self._stubs['list_entity_types'] = self.grpc_channel.unary_unary( - '/google.cloud.dialogflow.v2beta1.EntityTypes/ListEntityTypes', - request_serializer=entity_type.ListEntityTypesRequest.serialize, - response_deserializer=entity_type.ListEntityTypesResponse.deserialize, - ) - return self._stubs['list_entity_types'] - - @property - def get_entity_type(self) -> Callable[ - [entity_type.GetEntityTypeRequest], - entity_type.EntityType]: - r"""Return a callable for the get entity type method over gRPC. - - Retrieves the specified entity type. - - Returns: - Callable[[~.GetEntityTypeRequest], - ~.EntityType]: - 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_entity_type' not in self._stubs: - self._stubs['get_entity_type'] = self.grpc_channel.unary_unary( - '/google.cloud.dialogflow.v2beta1.EntityTypes/GetEntityType', - request_serializer=entity_type.GetEntityTypeRequest.serialize, - response_deserializer=entity_type.EntityType.deserialize, - ) - return self._stubs['get_entity_type'] - - @property - def create_entity_type(self) -> Callable[ - [gcd_entity_type.CreateEntityTypeRequest], - gcd_entity_type.EntityType]: - r"""Return a callable for the create entity type method over gRPC. - - Creates an entity type in the specified agent. - - Note: You should always train an agent prior to sending it - queries. See the `training - documentation `__. - - Returns: - Callable[[~.CreateEntityTypeRequest], - ~.EntityType]: - 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_entity_type' not in self._stubs: - self._stubs['create_entity_type'] = self.grpc_channel.unary_unary( - '/google.cloud.dialogflow.v2beta1.EntityTypes/CreateEntityType', - request_serializer=gcd_entity_type.CreateEntityTypeRequest.serialize, - response_deserializer=gcd_entity_type.EntityType.deserialize, - ) - return self._stubs['create_entity_type'] - - @property - def update_entity_type(self) -> Callable[ - [gcd_entity_type.UpdateEntityTypeRequest], - gcd_entity_type.EntityType]: - r"""Return a callable for the update entity type method over gRPC. - - Updates the specified entity type. - - Note: You should always train an agent prior to sending it - queries. See the `training - documentation `__. - - Returns: - Callable[[~.UpdateEntityTypeRequest], - ~.EntityType]: - 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_entity_type' not in self._stubs: - self._stubs['update_entity_type'] = self.grpc_channel.unary_unary( - '/google.cloud.dialogflow.v2beta1.EntityTypes/UpdateEntityType', - request_serializer=gcd_entity_type.UpdateEntityTypeRequest.serialize, - response_deserializer=gcd_entity_type.EntityType.deserialize, - ) - return self._stubs['update_entity_type'] - - @property - def delete_entity_type(self) -> Callable[ - [entity_type.DeleteEntityTypeRequest], - empty_pb2.Empty]: - r"""Return a callable for the delete entity type method over gRPC. - - Deletes the specified entity type. - - Note: You should always train an agent prior to sending it - queries. See the `training - documentation `__. - - Returns: - Callable[[~.DeleteEntityTypeRequest], - ~.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_entity_type' not in self._stubs: - 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_pb2.Empty.FromString, - ) - return self._stubs['delete_entity_type'] - - @property - def batch_update_entity_types(self) -> 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. - - This method is a `long-running - operation `__. - The returned ``Operation`` type has the following - method-specific fields: - - - ``metadata``: An empty `Struct - message `__ - - ``response``: - [BatchUpdateEntityTypesResponse][google.cloud.dialogflow.v2beta1.BatchUpdateEntityTypesResponse] - - Note: You should always train an agent prior to sending it - queries. See the `training - documentation `__. - - Returns: - Callable[[~.BatchUpdateEntityTypesRequest], - ~.Operation]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'batch_update_entity_types' not in self._stubs: - 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_pb2.Operation.FromString, - ) - return self._stubs['batch_update_entity_types'] - - @property - def batch_delete_entity_types(self) -> 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. - - This method is a `long-running - operation `__. - The returned ``Operation`` type has the following - method-specific fields: - - - ``metadata``: An empty `Struct - message `__ - - ``response``: An `Empty - message `__ - - Note: You should always train an agent prior to sending it - queries. See the `training - documentation `__. - - Returns: - Callable[[~.BatchDeleteEntityTypesRequest], - ~.Operation]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'batch_delete_entity_types' not in self._stubs: - 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_pb2.Operation.FromString, - ) - return self._stubs['batch_delete_entity_types'] - - @property - def batch_create_entities(self) -> 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. - - This method is a `long-running - operation `__. - The returned ``Operation`` type has the following - method-specific fields: - - - ``metadata``: An empty `Struct - message `__ - - ``response``: An `Empty - message `__ - - Note: You should always train an agent prior to sending it - queries. See the `training - documentation `__. - - Returns: - Callable[[~.BatchCreateEntitiesRequest], - ~.Operation]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'batch_create_entities' not in self._stubs: - 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_pb2.Operation.FromString, - ) - return self._stubs['batch_create_entities'] - - @property - def batch_update_entities(self) -> 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 - type. This method does not affect entities in the entity type - that aren't explicitly specified in the request. - - Note: You should always train an agent prior to sending it - queries. See the `training - documentation `__. - - This method is a `long-running - operation `__. - The returned ``Operation`` type has the following - method-specific fields: - - - ``metadata``: An empty `Struct - message `__ - - ``response``: An `Empty - message `__ - - Returns: - Callable[[~.BatchUpdateEntitiesRequest], - ~.Operation]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'batch_update_entities' not in self._stubs: - 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_pb2.Operation.FromString, - ) - return self._stubs['batch_update_entities'] - - @property - def batch_delete_entities(self) -> 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. - - This method is a `long-running - operation `__. - The returned ``Operation`` type has the following - method-specific fields: - - - ``metadata``: An empty `Struct - message `__ - - ``response``: An `Empty - message `__ - - Note: You should always train an agent prior to sending it - queries. See the `training - documentation `__. - - Returns: - Callable[[~.BatchDeleteEntitiesRequest], - ~.Operation]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'batch_delete_entities' not in self._stubs: - 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_pb2.Operation.FromString, - ) - return self._stubs['batch_delete_entities'] - - def close(self): - self.grpc_channel.close() - - @property - def cancel_operation( - self, - ) -> Callable[[operations_pb2.CancelOperationRequest], None]: - r"""Return a callable for the cancel_operation method over gRPC. - """ - # 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 "cancel_operation" not in self._stubs: - self._stubs["cancel_operation"] = self.grpc_channel.unary_unary( - "/google.longrunning.Operations/CancelOperation", - request_serializer=operations_pb2.CancelOperationRequest.SerializeToString, - response_deserializer=None, - ) - return self._stubs["cancel_operation"] - - @property - def get_operation( - self, - ) -> Callable[[operations_pb2.GetOperationRequest], operations_pb2.Operation]: - r"""Return a callable for the get_operation method over gRPC. - """ - # 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_operation" not in self._stubs: - self._stubs["get_operation"] = self.grpc_channel.unary_unary( - "/google.longrunning.Operations/GetOperation", - request_serializer=operations_pb2.GetOperationRequest.SerializeToString, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs["get_operation"] - - @property - def list_operations( - self, - ) -> Callable[[operations_pb2.ListOperationsRequest], operations_pb2.ListOperationsResponse]: - r"""Return a callable for the list_operations method over gRPC. - """ - # 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_operations" not in self._stubs: - self._stubs["list_operations"] = self.grpc_channel.unary_unary( - "/google.longrunning.Operations/ListOperations", - request_serializer=operations_pb2.ListOperationsRequest.SerializeToString, - response_deserializer=operations_pb2.ListOperationsResponse.FromString, - ) - return self._stubs["list_operations"] - - @property - def list_locations( - self, - ) -> Callable[[locations_pb2.ListLocationsRequest], locations_pb2.ListLocationsResponse]: - r"""Return a callable for the list locations method over gRPC. - """ - # 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_locations" not in self._stubs: - self._stubs["list_locations"] = self.grpc_channel.unary_unary( - "/google.cloud.location.Locations/ListLocations", - request_serializer=locations_pb2.ListLocationsRequest.SerializeToString, - response_deserializer=locations_pb2.ListLocationsResponse.FromString, - ) - return self._stubs["list_locations"] - - @property - def get_location( - self, - ) -> Callable[[locations_pb2.GetLocationRequest], locations_pb2.Location]: - r"""Return a callable for the list locations method over gRPC. - """ - # 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_location" not in self._stubs: - self._stubs["get_location"] = self.grpc_channel.unary_unary( - "/google.cloud.location.Locations/GetLocation", - request_serializer=locations_pb2.GetLocationRequest.SerializeToString, - response_deserializer=locations_pb2.Location.FromString, - ) - return self._stubs["get_location"] - - @property - def kind(self) -> str: - return "grpc" - - -__all__ = ( - 'EntityTypesGrpcTransport', -) diff --git a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/entity_types/transports/grpc_asyncio.py b/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/entity_types/transports/grpc_asyncio.py deleted file mode 100644 index 6a480c371..000000000 --- a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/entity_types/transports/grpc_asyncio.py +++ /dev/null @@ -1,696 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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 -from google.api_core import grpc_helpers_async -from google.api_core import operations_v1 -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore - -import grpc # type: ignore -from grpc.experimental import aio # type: ignore - -from google.cloud.dialogflow_v2beta1.types import entity_type -from google.cloud.dialogflow_v2beta1.types import entity_type as gcd_entity_type -from google.cloud.location import locations_pb2 # type: ignore -from google.longrunning import operations_pb2 -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 - - -class EntityTypesGrpcAsyncIOTransport(EntityTypesTransport): - """gRPC AsyncIO backend transport for EntityTypes. - - Service for managing - [EntityTypes][google.cloud.dialogflow.v2beta1.EntityType]. - - 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: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - **kwargs) -> aio.Channel: - """Create and return a gRPC AsyncIO channel object. - Args: - host (Optional[str]): The host for the channel to use. - credentials (Optional[~.Credentials]): The - authorization credentials to attach to requests. These - credentials identify this application to the service. If - none are specified, the client will attempt to ascertain - the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - kwargs (Optional[dict]): Keyword arguments, which are passed to the - channel creation. - Returns: - aio.Channel: A gRPC AsyncIO channel object. - """ - - return grpc_helpers_async.create_channel( - host, - credentials=credentials, - credentials_file=credentials_file, - quota_project_id=quota_project_id, - default_scopes=cls.AUTH_SCOPES, - scopes=scopes, - default_host=cls.DEFAULT_HOST, - **kwargs - ) - - def __init__(self, *, - host: str = 'dialogflow.googleapis.com', - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - channel: Optional[aio.Channel] = None, - api_mtls_endpoint: Optional[str] = None, - client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, - ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, - client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - api_audience: Optional[str] = None, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - This argument is ignored if ``channel`` is provided. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - channel (Optional[aio.Channel]): A ``Channel`` instance through - which to make calls. - api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. - If provided, it overrides the ``host`` argument and tries to create - a mutual TLS channel with client SSL credentials from - ``client_cert_source`` or application default SSL credentials. - client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): - Deprecated. A callback to provide client SSL certificate bytes and - private key bytes, both in PEM format. It is ignored if - ``api_mtls_endpoint`` is None. - ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials - for the grpc channel. It is ignored if ``channel`` is provided. - client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): - A callback to provide client certificate bytes and private key bytes, - both in PEM format. It is used to configure a mutual TLS channel. It is - ignored if ``channel`` or ``ssl_channel_credentials`` is provided. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - - Raises: - google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport - creation failed for any reason. - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - self._grpc_channel = None - self._ssl_channel_credentials = ssl_channel_credentials - self._stubs: Dict[str, Callable] = {} - self._operations_client: Optional[operations_v1.OperationsAsyncClient] = None - - if api_mtls_endpoint: - warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) - if client_cert_source: - warnings.warn("client_cert_source is deprecated", DeprecationWarning) - - if channel: - # Ignore credentials if a channel was passed. - credentials = False - # If a channel was explicitly provided, set it. - self._grpc_channel = channel - self._ssl_channel_credentials = None - else: - if api_mtls_endpoint: - host = api_mtls_endpoint - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - self._ssl_channel_credentials = SslCredentials().ssl_credentials - - else: - if client_cert_source_for_mtls and not ssl_channel_credentials: - cert, key = client_cert_source_for_mtls() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - - # The base transport sets the host, credentials and scopes - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes, - quota_project_id=quota_project_id, - client_info=client_info, - always_use_jwt_access=always_use_jwt_access, - api_audience=api_audience, - ) - - if not self._grpc_channel: - self._grpc_channel = type(self).create_channel( - self._host, - # use the credentials which are saved - credentials=self._credentials, - # Set ``credentials_file`` to ``None`` here as - # the credentials that we saved earlier should be used. - credentials_file=None, - 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 operations_client(self) -> operations_v1.OperationsAsyncClient: - """Create the client designed to process long-running operations. - - This property caches on the instance; repeated calls return the same - client. - """ - # Quick check: Only create a new client if we do not already have one. - if self._operations_client is None: - self._operations_client = operations_v1.OperationsAsyncClient( - self.grpc_channel - ) - - # Return the client from cache. - return self._operations_client - - @property - def list_entity_types(self) -> Callable[ - [entity_type.ListEntityTypesRequest], - Awaitable[entity_type.ListEntityTypesResponse]]: - r"""Return a callable for the list entity types method over gRPC. - - Returns the list of all entity types in the specified - agent. - - Returns: - Callable[[~.ListEntityTypesRequest], - Awaitable[~.ListEntityTypesResponse]]: - 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_entity_types' not in self._stubs: - self._stubs['list_entity_types'] = self.grpc_channel.unary_unary( - '/google.cloud.dialogflow.v2beta1.EntityTypes/ListEntityTypes', - request_serializer=entity_type.ListEntityTypesRequest.serialize, - response_deserializer=entity_type.ListEntityTypesResponse.deserialize, - ) - return self._stubs['list_entity_types'] - - @property - def get_entity_type(self) -> Callable[ - [entity_type.GetEntityTypeRequest], - Awaitable[entity_type.EntityType]]: - r"""Return a callable for the get entity type method over gRPC. - - Retrieves the specified entity type. - - Returns: - Callable[[~.GetEntityTypeRequest], - Awaitable[~.EntityType]]: - 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_entity_type' not in self._stubs: - self._stubs['get_entity_type'] = self.grpc_channel.unary_unary( - '/google.cloud.dialogflow.v2beta1.EntityTypes/GetEntityType', - request_serializer=entity_type.GetEntityTypeRequest.serialize, - response_deserializer=entity_type.EntityType.deserialize, - ) - return self._stubs['get_entity_type'] - - @property - def create_entity_type(self) -> Callable[ - [gcd_entity_type.CreateEntityTypeRequest], - Awaitable[gcd_entity_type.EntityType]]: - r"""Return a callable for the create entity type method over gRPC. - - Creates an entity type in the specified agent. - - Note: You should always train an agent prior to sending it - queries. See the `training - documentation `__. - - Returns: - Callable[[~.CreateEntityTypeRequest], - Awaitable[~.EntityType]]: - 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_entity_type' not in self._stubs: - self._stubs['create_entity_type'] = self.grpc_channel.unary_unary( - '/google.cloud.dialogflow.v2beta1.EntityTypes/CreateEntityType', - request_serializer=gcd_entity_type.CreateEntityTypeRequest.serialize, - response_deserializer=gcd_entity_type.EntityType.deserialize, - ) - return self._stubs['create_entity_type'] - - @property - def update_entity_type(self) -> Callable[ - [gcd_entity_type.UpdateEntityTypeRequest], - Awaitable[gcd_entity_type.EntityType]]: - r"""Return a callable for the update entity type method over gRPC. - - Updates the specified entity type. - - Note: You should always train an agent prior to sending it - queries. See the `training - documentation `__. - - Returns: - Callable[[~.UpdateEntityTypeRequest], - Awaitable[~.EntityType]]: - 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_entity_type' not in self._stubs: - self._stubs['update_entity_type'] = self.grpc_channel.unary_unary( - '/google.cloud.dialogflow.v2beta1.EntityTypes/UpdateEntityType', - request_serializer=gcd_entity_type.UpdateEntityTypeRequest.serialize, - response_deserializer=gcd_entity_type.EntityType.deserialize, - ) - return self._stubs['update_entity_type'] - - @property - def delete_entity_type(self) -> 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. - - Note: You should always train an agent prior to sending it - queries. See the `training - documentation `__. - - Returns: - Callable[[~.DeleteEntityTypeRequest], - 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_entity_type' not in self._stubs: - 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_pb2.Empty.FromString, - ) - return self._stubs['delete_entity_type'] - - @property - def batch_update_entity_types(self) -> Callable[ - [entity_type.BatchUpdateEntityTypesRequest], - Awaitable[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. - - This method is a `long-running - operation `__. - The returned ``Operation`` type has the following - method-specific fields: - - - ``metadata``: An empty `Struct - message `__ - - ``response``: - [BatchUpdateEntityTypesResponse][google.cloud.dialogflow.v2beta1.BatchUpdateEntityTypesResponse] - - Note: You should always train an agent prior to sending it - queries. See the `training - documentation `__. - - Returns: - Callable[[~.BatchUpdateEntityTypesRequest], - Awaitable[~.Operation]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'batch_update_entity_types' not in self._stubs: - 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_pb2.Operation.FromString, - ) - return self._stubs['batch_update_entity_types'] - - @property - def batch_delete_entity_types(self) -> Callable[ - [entity_type.BatchDeleteEntityTypesRequest], - Awaitable[operations_pb2.Operation]]: - r"""Return a callable for the batch delete entity types method over gRPC. - - Deletes entity types in the specified agent. - - This method is a `long-running - operation `__. - The returned ``Operation`` type has the following - method-specific fields: - - - ``metadata``: An empty `Struct - message `__ - - ``response``: An `Empty - message `__ - - Note: You should always train an agent prior to sending it - queries. See the `training - documentation `__. - - Returns: - Callable[[~.BatchDeleteEntityTypesRequest], - Awaitable[~.Operation]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'batch_delete_entity_types' not in self._stubs: - 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_pb2.Operation.FromString, - ) - return self._stubs['batch_delete_entity_types'] - - @property - def batch_create_entities(self) -> Callable[ - [entity_type.BatchCreateEntitiesRequest], - Awaitable[operations_pb2.Operation]]: - r"""Return a callable for the batch create entities method over gRPC. - - Creates multiple new entities in the specified entity type. - - This method is a `long-running - operation `__. - The returned ``Operation`` type has the following - method-specific fields: - - - ``metadata``: An empty `Struct - message `__ - - ``response``: An `Empty - message `__ - - Note: You should always train an agent prior to sending it - queries. See the `training - documentation `__. - - Returns: - Callable[[~.BatchCreateEntitiesRequest], - Awaitable[~.Operation]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'batch_create_entities' not in self._stubs: - 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_pb2.Operation.FromString, - ) - return self._stubs['batch_create_entities'] - - @property - def batch_update_entities(self) -> Callable[ - [entity_type.BatchUpdateEntitiesRequest], - Awaitable[operations_pb2.Operation]]: - r"""Return a callable for the batch update entities method over gRPC. - - Updates or creates multiple entities in the specified entity - type. This method does not affect entities in the entity type - that aren't explicitly specified in the request. - - Note: You should always train an agent prior to sending it - queries. See the `training - documentation `__. - - This method is a `long-running - operation `__. - The returned ``Operation`` type has the following - method-specific fields: - - - ``metadata``: An empty `Struct - message `__ - - ``response``: An `Empty - message `__ - - Returns: - Callable[[~.BatchUpdateEntitiesRequest], - Awaitable[~.Operation]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'batch_update_entities' not in self._stubs: - 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_pb2.Operation.FromString, - ) - return self._stubs['batch_update_entities'] - - @property - def batch_delete_entities(self) -> Callable[ - [entity_type.BatchDeleteEntitiesRequest], - Awaitable[operations_pb2.Operation]]: - r"""Return a callable for the batch delete entities method over gRPC. - - Deletes entities in the specified entity type. - - This method is a `long-running - operation `__. - The returned ``Operation`` type has the following - method-specific fields: - - - ``metadata``: An empty `Struct - message `__ - - ``response``: An `Empty - message `__ - - Note: You should always train an agent prior to sending it - queries. See the `training - documentation `__. - - Returns: - Callable[[~.BatchDeleteEntitiesRequest], - Awaitable[~.Operation]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'batch_delete_entities' not in self._stubs: - 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_pb2.Operation.FromString, - ) - return self._stubs['batch_delete_entities'] - - def close(self): - return self.grpc_channel.close() - - @property - def cancel_operation( - self, - ) -> Callable[[operations_pb2.CancelOperationRequest], None]: - r"""Return a callable for the cancel_operation method over gRPC. - """ - # 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 "cancel_operation" not in self._stubs: - self._stubs["cancel_operation"] = self.grpc_channel.unary_unary( - "/google.longrunning.Operations/CancelOperation", - request_serializer=operations_pb2.CancelOperationRequest.SerializeToString, - response_deserializer=None, - ) - return self._stubs["cancel_operation"] - - @property - def get_operation( - self, - ) -> Callable[[operations_pb2.GetOperationRequest], operations_pb2.Operation]: - r"""Return a callable for the get_operation method over gRPC. - """ - # 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_operation" not in self._stubs: - self._stubs["get_operation"] = self.grpc_channel.unary_unary( - "/google.longrunning.Operations/GetOperation", - request_serializer=operations_pb2.GetOperationRequest.SerializeToString, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs["get_operation"] - - @property - def list_operations( - self, - ) -> Callable[[operations_pb2.ListOperationsRequest], operations_pb2.ListOperationsResponse]: - r"""Return a callable for the list_operations method over gRPC. - """ - # 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_operations" not in self._stubs: - self._stubs["list_operations"] = self.grpc_channel.unary_unary( - "/google.longrunning.Operations/ListOperations", - request_serializer=operations_pb2.ListOperationsRequest.SerializeToString, - response_deserializer=operations_pb2.ListOperationsResponse.FromString, - ) - return self._stubs["list_operations"] - - @property - def list_locations( - self, - ) -> Callable[[locations_pb2.ListLocationsRequest], locations_pb2.ListLocationsResponse]: - r"""Return a callable for the list locations method over gRPC. - """ - # 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_locations" not in self._stubs: - self._stubs["list_locations"] = self.grpc_channel.unary_unary( - "/google.cloud.location.Locations/ListLocations", - request_serializer=locations_pb2.ListLocationsRequest.SerializeToString, - response_deserializer=locations_pb2.ListLocationsResponse.FromString, - ) - return self._stubs["list_locations"] - - @property - def get_location( - self, - ) -> Callable[[locations_pb2.GetLocationRequest], locations_pb2.Location]: - r"""Return a callable for the list locations method over gRPC. - """ - # 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_location" not in self._stubs: - self._stubs["get_location"] = self.grpc_channel.unary_unary( - "/google.cloud.location.Locations/GetLocation", - request_serializer=locations_pb2.GetLocationRequest.SerializeToString, - response_deserializer=locations_pb2.Location.FromString, - ) - return self._stubs["get_location"] - - -__all__ = ( - 'EntityTypesGrpcAsyncIOTransport', -) diff --git a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/entity_types/transports/rest.py b/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/entity_types/transports/rest.py deleted file mode 100644 index 2b033a0b7..000000000 --- a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/entity_types/transports/rest.py +++ /dev/null @@ -1,1921 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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 google.auth.transport.requests import AuthorizedSession # type: ignore -import json # type: ignore -import grpc # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore -from google.auth import credentials as ga_credentials # type: ignore -from google.api_core import exceptions as core_exceptions -from google.api_core import retry as retries -from google.api_core import rest_helpers -from google.api_core import rest_streaming -from google.api_core import path_template -from google.api_core import gapic_v1 - -from google.protobuf import json_format -from google.api_core import operations_v1 -from google.cloud.location import locations_pb2 # type: ignore -from google.longrunning import operations_pb2 -from requests import __version__ as requests_version -import dataclasses -import re -from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union -import warnings - -try: - OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] -except AttributeError: # pragma: NO COVER - OptionalRetry = Union[retries.Retry, object] # 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 # type: ignore -from google.protobuf import empty_pb2 # type: ignore - -from .base import EntityTypesTransport, DEFAULT_CLIENT_INFO as BASE_DEFAULT_CLIENT_INFO - - -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=BASE_DEFAULT_CLIENT_INFO.gapic_version, - grpc_version=None, - rest_version=requests_version, -) - - -class EntityTypesRestInterceptor: - """Interceptor for EntityTypes. - - Interceptors are used to manipulate requests, request metadata, and responses - in arbitrary ways. - Example use cases include: - * Logging - * Verifying requests according to service or custom semantics - * Stripping extraneous information from responses - - These use cases and more can be enabled by injecting an - instance of a custom subclass when constructing the EntityTypesRestTransport. - - .. code-block:: python - class MyCustomEntityTypesInterceptor(EntityTypesRestInterceptor): - def pre_batch_create_entities(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_batch_create_entities(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_batch_delete_entities(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_batch_delete_entities(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_batch_delete_entity_types(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_batch_delete_entity_types(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_batch_update_entities(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_batch_update_entities(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_batch_update_entity_types(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_batch_update_entity_types(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_create_entity_type(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_create_entity_type(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_delete_entity_type(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def pre_get_entity_type(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_get_entity_type(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_list_entity_types(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_list_entity_types(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_update_entity_type(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_update_entity_type(self, response): - logging.log(f"Received response: {response}") - return response - - transport = EntityTypesRestTransport(interceptor=MyCustomEntityTypesInterceptor()) - client = EntityTypesClient(transport=transport) - - - """ - def pre_batch_create_entities(self, request: entity_type.BatchCreateEntitiesRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[entity_type.BatchCreateEntitiesRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for batch_create_entities - - Override in a subclass to manipulate the request or metadata - before they are sent to the EntityTypes server. - """ - return request, metadata - - def post_batch_create_entities(self, response: operations_pb2.Operation) -> operations_pb2.Operation: - """Post-rpc interceptor for batch_create_entities - - Override in a subclass to manipulate the response - after it is returned by the EntityTypes server but before - it is returned to user code. - """ - return response - def pre_batch_delete_entities(self, request: entity_type.BatchDeleteEntitiesRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[entity_type.BatchDeleteEntitiesRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for batch_delete_entities - - Override in a subclass to manipulate the request or metadata - before they are sent to the EntityTypes server. - """ - return request, metadata - - def post_batch_delete_entities(self, response: operations_pb2.Operation) -> operations_pb2.Operation: - """Post-rpc interceptor for batch_delete_entities - - Override in a subclass to manipulate the response - after it is returned by the EntityTypes server but before - it is returned to user code. - """ - return response - def pre_batch_delete_entity_types(self, request: entity_type.BatchDeleteEntityTypesRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[entity_type.BatchDeleteEntityTypesRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for batch_delete_entity_types - - Override in a subclass to manipulate the request or metadata - before they are sent to the EntityTypes server. - """ - return request, metadata - - def post_batch_delete_entity_types(self, response: operations_pb2.Operation) -> operations_pb2.Operation: - """Post-rpc interceptor for batch_delete_entity_types - - Override in a subclass to manipulate the response - after it is returned by the EntityTypes server but before - it is returned to user code. - """ - return response - def pre_batch_update_entities(self, request: entity_type.BatchUpdateEntitiesRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[entity_type.BatchUpdateEntitiesRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for batch_update_entities - - Override in a subclass to manipulate the request or metadata - before they are sent to the EntityTypes server. - """ - return request, metadata - - def post_batch_update_entities(self, response: operations_pb2.Operation) -> operations_pb2.Operation: - """Post-rpc interceptor for batch_update_entities - - Override in a subclass to manipulate the response - after it is returned by the EntityTypes server but before - it is returned to user code. - """ - return response - def pre_batch_update_entity_types(self, request: entity_type.BatchUpdateEntityTypesRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[entity_type.BatchUpdateEntityTypesRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for batch_update_entity_types - - Override in a subclass to manipulate the request or metadata - before they are sent to the EntityTypes server. - """ - return request, metadata - - def post_batch_update_entity_types(self, response: operations_pb2.Operation) -> operations_pb2.Operation: - """Post-rpc interceptor for batch_update_entity_types - - Override in a subclass to manipulate the response - after it is returned by the EntityTypes server but before - it is returned to user code. - """ - return response - def pre_create_entity_type(self, request: gcd_entity_type.CreateEntityTypeRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[gcd_entity_type.CreateEntityTypeRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for create_entity_type - - Override in a subclass to manipulate the request or metadata - before they are sent to the EntityTypes server. - """ - return request, metadata - - def post_create_entity_type(self, response: gcd_entity_type.EntityType) -> gcd_entity_type.EntityType: - """Post-rpc interceptor for create_entity_type - - Override in a subclass to manipulate the response - after it is returned by the EntityTypes server but before - it is returned to user code. - """ - return response - def pre_delete_entity_type(self, request: entity_type.DeleteEntityTypeRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[entity_type.DeleteEntityTypeRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for delete_entity_type - - Override in a subclass to manipulate the request or metadata - before they are sent to the EntityTypes server. - """ - return request, metadata - - def pre_get_entity_type(self, request: entity_type.GetEntityTypeRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[entity_type.GetEntityTypeRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for get_entity_type - - Override in a subclass to manipulate the request or metadata - before they are sent to the EntityTypes server. - """ - return request, metadata - - def post_get_entity_type(self, response: entity_type.EntityType) -> entity_type.EntityType: - """Post-rpc interceptor for get_entity_type - - Override in a subclass to manipulate the response - after it is returned by the EntityTypes server but before - it is returned to user code. - """ - return response - def pre_list_entity_types(self, request: entity_type.ListEntityTypesRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[entity_type.ListEntityTypesRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for list_entity_types - - Override in a subclass to manipulate the request or metadata - before they are sent to the EntityTypes server. - """ - return request, metadata - - def post_list_entity_types(self, response: entity_type.ListEntityTypesResponse) -> entity_type.ListEntityTypesResponse: - """Post-rpc interceptor for list_entity_types - - Override in a subclass to manipulate the response - after it is returned by the EntityTypes server but before - it is returned to user code. - """ - return response - def pre_update_entity_type(self, request: gcd_entity_type.UpdateEntityTypeRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[gcd_entity_type.UpdateEntityTypeRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for update_entity_type - - Override in a subclass to manipulate the request or metadata - before they are sent to the EntityTypes server. - """ - return request, metadata - - def post_update_entity_type(self, response: gcd_entity_type.EntityType) -> gcd_entity_type.EntityType: - """Post-rpc interceptor for update_entity_type - - Override in a subclass to manipulate the response - after it is returned by the EntityTypes server but before - it is returned to user code. - """ - return response - - def pre_get_location( - self, request: locations_pb2.GetLocationRequest, metadata: Sequence[Tuple[str, str]] - ) -> Tuple[locations_pb2.GetLocationRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for get_location - - Override in a subclass to manipulate the request or metadata - before they are sent to the EntityTypes server. - """ - return request, metadata - - def post_get_location( - self, response: locations_pb2.Location - ) -> locations_pb2.Location: - """Post-rpc interceptor for get_location - - Override in a subclass to manipulate the response - after it is returned by the EntityTypes server but before - it is returned to user code. - """ - return response - def pre_list_locations( - self, request: locations_pb2.ListLocationsRequest, metadata: Sequence[Tuple[str, str]] - ) -> Tuple[locations_pb2.ListLocationsRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for list_locations - - Override in a subclass to manipulate the request or metadata - before they are sent to the EntityTypes server. - """ - return request, metadata - - def post_list_locations( - self, response: locations_pb2.ListLocationsResponse - ) -> locations_pb2.ListLocationsResponse: - """Post-rpc interceptor for list_locations - - Override in a subclass to manipulate the response - after it is returned by the EntityTypes server but before - it is returned to user code. - """ - return response - def pre_cancel_operation( - self, request: operations_pb2.CancelOperationRequest, metadata: Sequence[Tuple[str, str]] - ) -> Tuple[operations_pb2.CancelOperationRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for cancel_operation - - Override in a subclass to manipulate the request or metadata - before they are sent to the EntityTypes server. - """ - return request, metadata - - def post_cancel_operation( - self, response: None - ) -> None: - """Post-rpc interceptor for cancel_operation - - Override in a subclass to manipulate the response - after it is returned by the EntityTypes server but before - it is returned to user code. - """ - return response - def pre_get_operation( - self, request: operations_pb2.GetOperationRequest, metadata: Sequence[Tuple[str, str]] - ) -> Tuple[operations_pb2.GetOperationRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for get_operation - - Override in a subclass to manipulate the request or metadata - before they are sent to the EntityTypes server. - """ - return request, metadata - - def post_get_operation( - self, response: operations_pb2.Operation - ) -> operations_pb2.Operation: - """Post-rpc interceptor for get_operation - - Override in a subclass to manipulate the response - after it is returned by the EntityTypes server but before - it is returned to user code. - """ - return response - def pre_list_operations( - self, request: operations_pb2.ListOperationsRequest, metadata: Sequence[Tuple[str, str]] - ) -> Tuple[operations_pb2.ListOperationsRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for list_operations - - Override in a subclass to manipulate the request or metadata - before they are sent to the EntityTypes server. - """ - return request, metadata - - def post_list_operations( - self, response: operations_pb2.ListOperationsResponse - ) -> operations_pb2.ListOperationsResponse: - """Post-rpc interceptor for list_operations - - Override in a subclass to manipulate the response - after it is returned by the EntityTypes server but before - it is returned to user code. - """ - return response - - -@dataclasses.dataclass -class EntityTypesRestStub: - _session: AuthorizedSession - _host: str - _interceptor: EntityTypesRestInterceptor - - -class EntityTypesRestTransport(EntityTypesTransport): - """REST backend transport for EntityTypes. - - Service for managing - [EntityTypes][google.cloud.dialogflow.v2beta1.EntityType]. - - 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 JSON representations of protocol buffers over HTTP/1.1 - - """ - - def __init__(self, *, - host: str = 'dialogflow.googleapis.com', - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - client_cert_source_for_mtls: Optional[Callable[[ - ], Tuple[bytes, bytes]]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - url_scheme: str = 'https', - interceptor: Optional[EntityTypesRestInterceptor] = None, - api_audience: Optional[str] = None, - ) -> 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 ignored if ``channel`` is provided. - scopes (Optional(Sequence[str])): A list of scopes. This argument is - ignored if ``channel`` is provided. - client_cert_source_for_mtls (Callable[[], Tuple[bytes, bytes]]): Client - certificate to configure mutual TLS HTTP channel. It is ignored - if ``channel`` is provided. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you are developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - url_scheme: the protocol scheme for the API endpoint. Normally - "https", but for testing or local servers, - "http" can be specified. - """ - # Run the base constructor - # TODO(yon-mg): resolve other ctor params i.e. scopes, quota, etc. - # TODO: When custom host (api_endpoint) is set, `scopes` must *also* be set on the - # credentials object - maybe_url_match = re.match("^(?Phttp(?:s)?://)?(?P.*)$", host) - if maybe_url_match is None: - raise ValueError(f"Unexpected hostname structure: {host}") # pragma: NO COVER - - url_match_items = maybe_url_match.groupdict() - - host = f"{url_scheme}://{host}" if not url_match_items["scheme"] else host - - super().__init__( - host=host, - credentials=credentials, - client_info=client_info, - always_use_jwt_access=always_use_jwt_access, - api_audience=api_audience - ) - self._session = AuthorizedSession( - self._credentials, default_host=self.DEFAULT_HOST) - self._operations_client: Optional[operations_v1.AbstractOperationsClient] = None - if client_cert_source_for_mtls: - self._session.configure_mtls_channel(client_cert_source_for_mtls) - self._interceptor = interceptor or EntityTypesRestInterceptor() - self._prep_wrapped_messages(client_info) - - @property - def operations_client(self) -> operations_v1.AbstractOperationsClient: - """Create the client designed to process long-running operations. - - This property caches on the instance; repeated calls return the same - client. - """ - # Only create a new client if we do not already have one. - if self._operations_client is None: - http_options: Dict[str, List[Dict[str, str]]] = { - 'google.longrunning.Operations.CancelOperation': [ - { - 'method': 'post', - 'uri': '/v2beta1/{name=projects/*/operations/*}:cancel', - }, - { - 'method': 'post', - 'uri': '/v2beta1/{name=projects/*/locations/*/operations/*}:cancel', - }, - ], - 'google.longrunning.Operations.GetOperation': [ - { - 'method': 'get', - 'uri': '/v2beta1/{name=projects/*/operations/*}', - }, - { - 'method': 'get', - 'uri': '/v2beta1/{name=projects/*/locations/*/operations/*}', - }, - ], - 'google.longrunning.Operations.ListOperations': [ - { - 'method': 'get', - 'uri': '/v2beta1/{name=projects/*}/operations', - }, - { - 'method': 'get', - 'uri': '/v2beta1/{name=projects/*/locations/*}/operations', - }, - ], - } - - rest_transport = operations_v1.OperationsRestTransport( - host=self._host, - # use the credentials which are saved - credentials=self._credentials, - scopes=self._scopes, - http_options=http_options, - path_prefix="v2beta1") - - self._operations_client = operations_v1.AbstractOperationsClient(transport=rest_transport) - - # Return the client from cache. - return self._operations_client - - class _BatchCreateEntities(EntityTypesRestStub): - def __hash__(self): - return hash("BatchCreateEntities") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: entity_type.BatchCreateEntitiesRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> operations_pb2.Operation: - r"""Call the batch create entities method over HTTP. - - Args: - request (~.entity_type.BatchCreateEntitiesRequest): - The request object. The request message for - [EntityTypes.BatchCreateEntities][google.cloud.dialogflow.v2beta1.EntityTypes.BatchCreateEntities]. - 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: - ~.operations_pb2.Operation: - This resource represents a - long-running operation that is the - result of a network API call. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'post', - 'uri': '/v2beta1/{parent=projects/*/agent/entityTypes/*}/entities:batchCreate', - 'body': '*', - }, -{ - 'method': 'post', - 'uri': '/v2beta1/{parent=projects/*/locations/*/agent/entityTypes/*}/entities:batchCreate', - 'body': '*', - }, - ] - request, metadata = self._interceptor.pre_batch_create_entities(request, metadata) - pb_request = entity_type.BatchCreateEntitiesRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request['body'], - including_default_value_fields=False, - use_integers_for_enums=True - ) - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - including_default_value_fields=False, - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = operations_pb2.Operation() - json_format.Parse(response.content, resp, ignore_unknown_fields=True) - resp = self._interceptor.post_batch_create_entities(resp) - return resp - - class _BatchDeleteEntities(EntityTypesRestStub): - def __hash__(self): - return hash("BatchDeleteEntities") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: entity_type.BatchDeleteEntitiesRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> operations_pb2.Operation: - r"""Call the batch delete entities method over HTTP. - - Args: - request (~.entity_type.BatchDeleteEntitiesRequest): - The request object. The request message for - [EntityTypes.BatchDeleteEntities][google.cloud.dialogflow.v2beta1.EntityTypes.BatchDeleteEntities]. - 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: - ~.operations_pb2.Operation: - This resource represents a - long-running operation that is the - result of a network API call. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'post', - 'uri': '/v2beta1/{parent=projects/*/agent/entityTypes/*}/entities:batchDelete', - 'body': '*', - }, -{ - 'method': 'post', - 'uri': '/v2beta1/{parent=projects/*/locations/*/agent/entityTypes/*}/entities:batchDelete', - 'body': '*', - }, - ] - request, metadata = self._interceptor.pre_batch_delete_entities(request, metadata) - pb_request = entity_type.BatchDeleteEntitiesRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request['body'], - including_default_value_fields=False, - use_integers_for_enums=True - ) - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - including_default_value_fields=False, - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = operations_pb2.Operation() - json_format.Parse(response.content, resp, ignore_unknown_fields=True) - resp = self._interceptor.post_batch_delete_entities(resp) - return resp - - class _BatchDeleteEntityTypes(EntityTypesRestStub): - def __hash__(self): - return hash("BatchDeleteEntityTypes") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: entity_type.BatchDeleteEntityTypesRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> operations_pb2.Operation: - r"""Call the batch delete entity types method over HTTP. - - Args: - request (~.entity_type.BatchDeleteEntityTypesRequest): - The request object. The request message for - [EntityTypes.BatchDeleteEntityTypes][google.cloud.dialogflow.v2beta1.EntityTypes.BatchDeleteEntityTypes]. - 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: - ~.operations_pb2.Operation: - This resource represents a - long-running operation that is the - result of a network API call. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'post', - 'uri': '/v2beta1/{parent=projects/*/agent}/entityTypes:batchDelete', - 'body': '*', - }, -{ - 'method': 'post', - 'uri': '/v2beta1/{parent=projects/*/locations/*/agent}/entityTypes:batchDelete', - 'body': '*', - }, - ] - request, metadata = self._interceptor.pre_batch_delete_entity_types(request, metadata) - pb_request = entity_type.BatchDeleteEntityTypesRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request['body'], - including_default_value_fields=False, - use_integers_for_enums=True - ) - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - including_default_value_fields=False, - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = operations_pb2.Operation() - json_format.Parse(response.content, resp, ignore_unknown_fields=True) - resp = self._interceptor.post_batch_delete_entity_types(resp) - return resp - - class _BatchUpdateEntities(EntityTypesRestStub): - def __hash__(self): - return hash("BatchUpdateEntities") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: entity_type.BatchUpdateEntitiesRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> operations_pb2.Operation: - r"""Call the batch update entities method over HTTP. - - Args: - request (~.entity_type.BatchUpdateEntitiesRequest): - The request object. The request message for - [EntityTypes.BatchUpdateEntities][google.cloud.dialogflow.v2beta1.EntityTypes.BatchUpdateEntities]. - 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: - ~.operations_pb2.Operation: - This resource represents a - long-running operation that is the - result of a network API call. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'post', - 'uri': '/v2beta1/{parent=projects/*/agent/entityTypes/*}/entities:batchUpdate', - 'body': '*', - }, -{ - 'method': 'post', - 'uri': '/v2beta1/{parent=projects/*/locations/*/agent/entityTypes/*}/entities:batchUpdate', - 'body': '*', - }, - ] - request, metadata = self._interceptor.pre_batch_update_entities(request, metadata) - pb_request = entity_type.BatchUpdateEntitiesRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request['body'], - including_default_value_fields=False, - use_integers_for_enums=True - ) - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - including_default_value_fields=False, - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = operations_pb2.Operation() - json_format.Parse(response.content, resp, ignore_unknown_fields=True) - resp = self._interceptor.post_batch_update_entities(resp) - return resp - - class _BatchUpdateEntityTypes(EntityTypesRestStub): - def __hash__(self): - return hash("BatchUpdateEntityTypes") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: entity_type.BatchUpdateEntityTypesRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> operations_pb2.Operation: - r"""Call the batch update entity types method over HTTP. - - Args: - request (~.entity_type.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. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.operations_pb2.Operation: - This resource represents a - long-running operation that is the - result of a network API call. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'post', - 'uri': '/v2beta1/{parent=projects/*/agent}/entityTypes:batchUpdate', - 'body': '*', - }, -{ - 'method': 'post', - 'uri': '/v2beta1/{parent=projects/*/locations/*/agent}/entityTypes:batchUpdate', - 'body': '*', - }, - ] - request, metadata = self._interceptor.pre_batch_update_entity_types(request, metadata) - pb_request = entity_type.BatchUpdateEntityTypesRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request['body'], - including_default_value_fields=False, - use_integers_for_enums=True - ) - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - including_default_value_fields=False, - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = operations_pb2.Operation() - json_format.Parse(response.content, resp, ignore_unknown_fields=True) - resp = self._interceptor.post_batch_update_entity_types(resp) - return resp - - class _CreateEntityType(EntityTypesRestStub): - def __hash__(self): - return hash("CreateEntityType") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: gcd_entity_type.CreateEntityTypeRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> gcd_entity_type.EntityType: - r"""Call the create entity type method over HTTP. - - Args: - request (~.gcd_entity_type.CreateEntityTypeRequest): - The request object. The request message for - [EntityTypes.CreateEntityType][google.cloud.dialogflow.v2beta1.EntityTypes.CreateEntityType]. - 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: - ~.gcd_entity_type.EntityType: - Each intent parameter has a type, called the entity - type, which dictates exactly how data from an end-user - expression is extracted. - - Dialogflow provides predefined system entities that can - match many common types of data. For example, there are - system entities for matching dates, times, colors, email - addresses, and so on. You can also create your own - custom entities for matching custom data. For example, - you could define a vegetable entity that can match the - types of vegetables available for purchase with a - grocery store agent. - - For more information, see the `Entity - guide `__. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'post', - 'uri': '/v2beta1/{parent=projects/*/agent}/entityTypes', - 'body': 'entity_type', - }, -{ - 'method': 'post', - 'uri': '/v2beta1/{parent=projects/*/locations/*/agent}/entityTypes', - 'body': 'entity_type', - }, - ] - request, metadata = self._interceptor.pre_create_entity_type(request, metadata) - pb_request = gcd_entity_type.CreateEntityTypeRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request['body'], - including_default_value_fields=False, - use_integers_for_enums=True - ) - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - including_default_value_fields=False, - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = gcd_entity_type.EntityType() - pb_resp = gcd_entity_type.EntityType.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_create_entity_type(resp) - return resp - - class _DeleteEntityType(EntityTypesRestStub): - def __hash__(self): - return hash("DeleteEntityType") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: entity_type.DeleteEntityTypeRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ): - r"""Call the delete entity type method over HTTP. - - Args: - request (~.entity_type.DeleteEntityTypeRequest): - The request object. The request message for - [EntityTypes.DeleteEntityType][google.cloud.dialogflow.v2beta1.EntityTypes.DeleteEntityType]. - 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. - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'delete', - 'uri': '/v2beta1/{name=projects/*/agent/entityTypes/*}', - }, -{ - 'method': 'delete', - 'uri': '/v2beta1/{name=projects/*/locations/*/agent/entityTypes/*}', - }, - ] - request, metadata = self._interceptor.pre_delete_entity_type(request, metadata) - pb_request = entity_type.DeleteEntityTypeRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - including_default_value_fields=False, - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - class _GetEntityType(EntityTypesRestStub): - def __hash__(self): - return hash("GetEntityType") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: entity_type.GetEntityTypeRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> entity_type.EntityType: - r"""Call the get entity type method over HTTP. - - Args: - request (~.entity_type.GetEntityTypeRequest): - The request object. The request message for - [EntityTypes.GetEntityType][google.cloud.dialogflow.v2beta1.EntityTypes.GetEntityType]. - 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: - ~.entity_type.EntityType: - Each intent parameter has a type, called the entity - type, which dictates exactly how data from an end-user - expression is extracted. - - Dialogflow provides predefined system entities that can - match many common types of data. For example, there are - system entities for matching dates, times, colors, email - addresses, and so on. You can also create your own - custom entities for matching custom data. For example, - you could define a vegetable entity that can match the - types of vegetables available for purchase with a - grocery store agent. - - For more information, see the `Entity - guide `__. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v2beta1/{name=projects/*/agent/entityTypes/*}', - }, -{ - 'method': 'get', - 'uri': '/v2beta1/{name=projects/*/locations/*/agent/entityTypes/*}', - }, - ] - request, metadata = self._interceptor.pre_get_entity_type(request, metadata) - pb_request = entity_type.GetEntityTypeRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - including_default_value_fields=False, - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = entity_type.EntityType() - pb_resp = entity_type.EntityType.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_get_entity_type(resp) - return resp - - class _ListEntityTypes(EntityTypesRestStub): - def __hash__(self): - return hash("ListEntityTypes") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: entity_type.ListEntityTypesRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> entity_type.ListEntityTypesResponse: - r"""Call the list entity types method over HTTP. - - Args: - request (~.entity_type.ListEntityTypesRequest): - The request object. The request message for - [EntityTypes.ListEntityTypes][google.cloud.dialogflow.v2beta1.EntityTypes.ListEntityTypes]. - 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: - ~.entity_type.ListEntityTypesResponse: - The response message for - [EntityTypes.ListEntityTypes][google.cloud.dialogflow.v2beta1.EntityTypes.ListEntityTypes]. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v2beta1/{parent=projects/*/agent}/entityTypes', - }, -{ - 'method': 'get', - 'uri': '/v2beta1/{parent=projects/*/locations/*/agent}/entityTypes', - }, - ] - request, metadata = self._interceptor.pre_list_entity_types(request, metadata) - pb_request = entity_type.ListEntityTypesRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - including_default_value_fields=False, - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = entity_type.ListEntityTypesResponse() - pb_resp = entity_type.ListEntityTypesResponse.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_list_entity_types(resp) - return resp - - class _UpdateEntityType(EntityTypesRestStub): - def __hash__(self): - return hash("UpdateEntityType") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: gcd_entity_type.UpdateEntityTypeRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> gcd_entity_type.EntityType: - r"""Call the update entity type method over HTTP. - - Args: - request (~.gcd_entity_type.UpdateEntityTypeRequest): - The request object. The request message for - [EntityTypes.UpdateEntityType][google.cloud.dialogflow.v2beta1.EntityTypes.UpdateEntityType]. - 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: - ~.gcd_entity_type.EntityType: - Each intent parameter has a type, called the entity - type, which dictates exactly how data from an end-user - expression is extracted. - - Dialogflow provides predefined system entities that can - match many common types of data. For example, there are - system entities for matching dates, times, colors, email - addresses, and so on. You can also create your own - custom entities for matching custom data. For example, - you could define a vegetable entity that can match the - types of vegetables available for purchase with a - grocery store agent. - - For more information, see the `Entity - guide `__. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'patch', - 'uri': '/v2beta1/{entity_type.name=projects/*/agent/entityTypes/*}', - 'body': 'entity_type', - }, -{ - 'method': 'patch', - 'uri': '/v2beta1/{entity_type.name=projects/*/locations/*/agent/entityTypes/*}', - 'body': 'entity_type', - }, - ] - request, metadata = self._interceptor.pre_update_entity_type(request, metadata) - pb_request = gcd_entity_type.UpdateEntityTypeRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request['body'], - including_default_value_fields=False, - use_integers_for_enums=True - ) - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - including_default_value_fields=False, - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = gcd_entity_type.EntityType() - pb_resp = gcd_entity_type.EntityType.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_update_entity_type(resp) - return resp - - @property - def batch_create_entities(self) -> Callable[ - [entity_type.BatchCreateEntitiesRequest], - operations_pb2.Operation]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._BatchCreateEntities(self._session, self._host, self._interceptor) # type: ignore - - @property - def batch_delete_entities(self) -> Callable[ - [entity_type.BatchDeleteEntitiesRequest], - operations_pb2.Operation]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._BatchDeleteEntities(self._session, self._host, self._interceptor) # type: ignore - - @property - def batch_delete_entity_types(self) -> Callable[ - [entity_type.BatchDeleteEntityTypesRequest], - operations_pb2.Operation]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._BatchDeleteEntityTypes(self._session, self._host, self._interceptor) # type: ignore - - @property - def batch_update_entities(self) -> Callable[ - [entity_type.BatchUpdateEntitiesRequest], - operations_pb2.Operation]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._BatchUpdateEntities(self._session, self._host, self._interceptor) # type: ignore - - @property - def batch_update_entity_types(self) -> Callable[ - [entity_type.BatchUpdateEntityTypesRequest], - operations_pb2.Operation]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._BatchUpdateEntityTypes(self._session, self._host, self._interceptor) # type: ignore - - @property - def create_entity_type(self) -> Callable[ - [gcd_entity_type.CreateEntityTypeRequest], - gcd_entity_type.EntityType]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._CreateEntityType(self._session, self._host, self._interceptor) # type: ignore - - @property - def delete_entity_type(self) -> Callable[ - [entity_type.DeleteEntityTypeRequest], - empty_pb2.Empty]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._DeleteEntityType(self._session, self._host, self._interceptor) # type: ignore - - @property - def get_entity_type(self) -> Callable[ - [entity_type.GetEntityTypeRequest], - entity_type.EntityType]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._GetEntityType(self._session, self._host, self._interceptor) # type: ignore - - @property - def list_entity_types(self) -> Callable[ - [entity_type.ListEntityTypesRequest], - entity_type.ListEntityTypesResponse]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._ListEntityTypes(self._session, self._host, self._interceptor) # type: ignore - - @property - def update_entity_type(self) -> Callable[ - [gcd_entity_type.UpdateEntityTypeRequest], - gcd_entity_type.EntityType]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._UpdateEntityType(self._session, self._host, self._interceptor) # type: ignore - - @property - def get_location(self): - return self._GetLocation(self._session, self._host, self._interceptor) # type: ignore - - class _GetLocation(EntityTypesRestStub): - def __call__(self, - request: locations_pb2.GetLocationRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> locations_pb2.Location: - - r"""Call the get location method over HTTP. - - Args: - request (locations_pb2.GetLocationRequest): - The request object for GetLocation method. - 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: - locations_pb2.Location: Response from GetLocation method. - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v2beta1/{name=projects/*/locations/*}', - }, - ] - - request, metadata = self._interceptor.pre_get_location(request, metadata) - request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode( - http_options, **request_kwargs) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json.dumps(transcoded_request['query_params'])) - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - resp = locations_pb2.Location() - resp = json_format.Parse(response.content.decode("utf-8"), resp) - resp = self._interceptor.post_get_location(resp) - return resp - - @property - def list_locations(self): - return self._ListLocations(self._session, self._host, self._interceptor) # type: ignore - - class _ListLocations(EntityTypesRestStub): - def __call__(self, - request: locations_pb2.ListLocationsRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> locations_pb2.ListLocationsResponse: - - r"""Call the list locations method over HTTP. - - Args: - request (locations_pb2.ListLocationsRequest): - The request object for ListLocations method. - 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: - locations_pb2.ListLocationsResponse: Response from ListLocations method. - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v2beta1/{name=projects/*}/locations', - }, - ] - - request, metadata = self._interceptor.pre_list_locations(request, metadata) - request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode( - http_options, **request_kwargs) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json.dumps(transcoded_request['query_params'])) - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - resp = locations_pb2.ListLocationsResponse() - resp = json_format.Parse(response.content.decode("utf-8"), resp) - resp = self._interceptor.post_list_locations(resp) - return resp - - @property - def cancel_operation(self): - return self._CancelOperation(self._session, self._host, self._interceptor) # type: ignore - - class _CancelOperation(EntityTypesRestStub): - def __call__(self, - request: operations_pb2.CancelOperationRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> None: - - r"""Call the cancel operation method over HTTP. - - Args: - request (operations_pb2.CancelOperationRequest): - The request object for CancelOperation method. - 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. - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'post', - 'uri': '/v2beta1/{name=projects/*/operations/*}:cancel', - }, -{ - 'method': 'post', - 'uri': '/v2beta1/{name=projects/*/locations/*/operations/*}:cancel', - }, - ] - - request, metadata = self._interceptor.pre_cancel_operation(request, metadata) - request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode( - http_options, **request_kwargs) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json.dumps(transcoded_request['query_params'])) - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - return self._interceptor.post_cancel_operation(None) - - @property - def get_operation(self): - return self._GetOperation(self._session, self._host, self._interceptor) # type: ignore - - class _GetOperation(EntityTypesRestStub): - def __call__(self, - request: operations_pb2.GetOperationRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> operations_pb2.Operation: - - r"""Call the get operation method over HTTP. - - Args: - request (operations_pb2.GetOperationRequest): - The request object for GetOperation method. - 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: - operations_pb2.Operation: Response from GetOperation method. - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v2beta1/{name=projects/*/operations/*}', - }, -{ - 'method': 'get', - 'uri': '/v2beta1/{name=projects/*/locations/*/operations/*}', - }, - ] - - request, metadata = self._interceptor.pre_get_operation(request, metadata) - request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode( - http_options, **request_kwargs) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json.dumps(transcoded_request['query_params'])) - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - resp = operations_pb2.Operation() - resp = json_format.Parse(response.content.decode("utf-8"), resp) - resp = self._interceptor.post_get_operation(resp) - return resp - - @property - def list_operations(self): - return self._ListOperations(self._session, self._host, self._interceptor) # type: ignore - - class _ListOperations(EntityTypesRestStub): - def __call__(self, - request: operations_pb2.ListOperationsRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> operations_pb2.ListOperationsResponse: - - r"""Call the list operations method over HTTP. - - Args: - request (operations_pb2.ListOperationsRequest): - The request object for ListOperations method. - 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: - operations_pb2.ListOperationsResponse: Response from ListOperations method. - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v2beta1/{name=projects/*}/operations', - }, -{ - 'method': 'get', - 'uri': '/v2beta1/{name=projects/*/locations/*}/operations', - }, - ] - - request, metadata = self._interceptor.pre_list_operations(request, metadata) - request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode( - http_options, **request_kwargs) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json.dumps(transcoded_request['query_params'])) - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - resp = operations_pb2.ListOperationsResponse() - resp = json_format.Parse(response.content.decode("utf-8"), resp) - resp = self._interceptor.post_list_operations(resp) - return resp - - @property - def kind(self) -> str: - return "rest" - - def close(self): - self._session.close() - - -__all__=( - 'EntityTypesRestTransport', -) diff --git a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/environments/__init__.py b/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/environments/__init__.py deleted file mode 100644 index 63bae46ea..000000000 --- a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/environments/__init__.py +++ /dev/null @@ -1,22 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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 EnvironmentsClient -from .async_client import EnvironmentsAsyncClient - -__all__ = ( - 'EnvironmentsClient', - 'EnvironmentsAsyncClient', -) diff --git a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/environments/async_client.py b/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/environments/async_client.py deleted file mode 100644 index efb3b0a31..000000000 --- a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/environments/async_client.py +++ /dev/null @@ -1,1055 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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, Mapping, MutableMapping, MutableSequence, Optional, Sequence, Tuple, Type, Union - -from google.cloud.dialogflow_v2beta1 import gapic_version as package_version - -from google.api_core.client_options import ClientOptions -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import retry as retries -from google.auth import credentials as ga_credentials # type: ignore -from google.oauth2 import service_account # type: ignore - -try: - OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] -except AttributeError: # pragma: NO COVER - OptionalRetry = Union[retries.Retry, object] # 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.cloud.location import locations_pb2 # type: ignore -from google.longrunning import operations_pb2 -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 - - -class EnvironmentsAsyncClient: - """Service for managing - [Environments][google.cloud.dialogflow.v2beta1.Environment]. - """ - - _client: EnvironmentsClient - - DEFAULT_ENDPOINT = EnvironmentsClient.DEFAULT_ENDPOINT - DEFAULT_MTLS_ENDPOINT = EnvironmentsClient.DEFAULT_MTLS_ENDPOINT - - 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) - version_path = staticmethod(EnvironmentsClient.version_path) - parse_version_path = staticmethod(EnvironmentsClient.parse_version_path) - common_billing_account_path = staticmethod(EnvironmentsClient.common_billing_account_path) - parse_common_billing_account_path = staticmethod(EnvironmentsClient.parse_common_billing_account_path) - common_folder_path = staticmethod(EnvironmentsClient.common_folder_path) - parse_common_folder_path = staticmethod(EnvironmentsClient.parse_common_folder_path) - common_organization_path = staticmethod(EnvironmentsClient.common_organization_path) - parse_common_organization_path = staticmethod(EnvironmentsClient.parse_common_organization_path) - common_project_path = staticmethod(EnvironmentsClient.common_project_path) - parse_common_project_path = staticmethod(EnvironmentsClient.parse_common_project_path) - common_location_path = staticmethod(EnvironmentsClient.common_location_path) - parse_common_location_path = staticmethod(EnvironmentsClient.parse_common_location_path) - - @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: - EnvironmentsAsyncClient: The constructed client. - """ - return EnvironmentsClient.from_service_account_info.__func__(EnvironmentsAsyncClient, 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: - EnvironmentsAsyncClient: The constructed client. - """ - return EnvironmentsClient.from_service_account_file.__func__(EnvironmentsAsyncClient, filename, *args, **kwargs) # type: ignore - - from_service_account_json = from_service_account_file - - @classmethod - def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[ClientOptions] = None): - """Return the API endpoint and client cert source for mutual TLS. - - The client cert source is determined in the following order: - (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the - client cert source is None. - (2) if `client_options.client_cert_source` is provided, use the provided one; if the - default client cert source exists, use the default one; otherwise the client cert - source is None. - - The API endpoint is determined in the following order: - (1) if `client_options.api_endpoint` if provided, use the provided one. - (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the - default mTLS endpoint; if the environment variable is "never", use the default API - endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise - use the default API endpoint. - - More details can be found at https://google.aip.dev/auth/4114. - - Args: - client_options (google.api_core.client_options.ClientOptions): Custom options for the - client. Only the `api_endpoint` and `client_cert_source` properties may be used - in this method. - - Returns: - Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the - client cert source to use. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If any errors happen. - """ - return EnvironmentsClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore - - @property - def transport(self) -> EnvironmentsTransport: - """Returns the transport used by the client instance. - - Returns: - EnvironmentsTransport: The transport used by the client instance. - """ - return self._client.transport - - get_transport_class = functools.partial(type(EnvironmentsClient).get_transport_class, type(EnvironmentsClient)) - - def __init__(self, *, - credentials: Optional[ga_credentials.Credentials] = None, - transport: Union[str, EnvironmentsTransport] = "grpc_asyncio", - client_options: Optional[ClientOptions] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the environments 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, ~.EnvironmentsTransport]): 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 = EnvironmentsClient( - credentials=credentials, - transport=transport, - client_options=client_options, - client_info=client_info, - - ) - - async def list_environments(self, - request: Optional[Union[environment.ListEnvironmentsRequest, dict]] = None, - *, - parent: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListEnvironmentsAsyncPager: - r"""Returns the list of all non-draft environments of the - specified agent. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import dialogflow_v2beta1 - - async def sample_list_environments(): - # Create a client - client = dialogflow_v2beta1.EnvironmentsAsyncClient() - - # Initialize request argument(s) - request = dialogflow_v2beta1.ListEnvironmentsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_environments(request=request) - - # Handle the response - async for response in page_result: - print(response) - - Args: - request (Optional[Union[google.cloud.dialogflow_v2beta1.types.ListEnvironmentsRequest, dict]]): - The request object. The request message for - [Environments.ListEnvironments][google.cloud.dialogflow.v2beta1.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. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.dialogflow_v2beta1.services.environments.pagers.ListEnvironmentsAsyncPager: - The response message for - [Environments.ListEnvironments][google.cloud.dialogflow.v2beta1.Environments.ListEnvironments]. - - Iterating over this object will yield results and - resolve additional pages automatically. - - """ - # Create or coerce a protobuf request object. - # Quick 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( - self._client._transport.list_environments, - 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.ListEnvironmentsAsyncPager( - method=rpc, - request=request, - response=response, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def get_environment(self, - request: Optional[Union[environment.GetEnvironmentRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> environment.Environment: - r"""Retrieves the specified agent environment. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import dialogflow_v2beta1 - - async def sample_get_environment(): - # Create a client - client = dialogflow_v2beta1.EnvironmentsAsyncClient() - - # Initialize request argument(s) - request = dialogflow_v2beta1.GetEnvironmentRequest( - name="name_value", - ) - - # Make the request - response = await client.get_environment(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.dialogflow_v2beta1.types.GetEnvironmentRequest, dict]]): - 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: Optional[Union[environment.CreateEnvironmentRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> environment.Environment: - r"""Creates an agent environment. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import dialogflow_v2beta1 - - async def sample_create_environment(): - # Create a client - client = dialogflow_v2beta1.EnvironmentsAsyncClient() - - # Initialize request argument(s) - request = dialogflow_v2beta1.CreateEnvironmentRequest( - parent="parent_value", - environment_id="environment_id_value", - ) - - # Make the request - response = await client.create_environment(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.dialogflow_v2beta1.types.CreateEnvironmentRequest, dict]]): - 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: Optional[Union[environment.UpdateEnvironmentRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - 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. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import dialogflow_v2beta1 - - async def sample_update_environment(): - # Create a client - client = dialogflow_v2beta1.EnvironmentsAsyncClient() - - # Initialize request argument(s) - request = dialogflow_v2beta1.UpdateEnvironmentRequest( - ) - - # Make the request - response = await client.update_environment(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.dialogflow_v2beta1.types.UpdateEnvironmentRequest, dict]]): - 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: Optional[Union[environment.DeleteEnvironmentRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> None: - r"""Deletes the specified agent environment. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import dialogflow_v2beta1 - - async def sample_delete_environment(): - # Create a client - client = dialogflow_v2beta1.EnvironmentsAsyncClient() - - # Initialize request argument(s) - request = dialogflow_v2beta1.DeleteEnvironmentRequest( - name="name_value", - ) - - # Make the request - await client.delete_environment(request=request) - - Args: - request (Optional[Union[google.cloud.dialogflow_v2beta1.types.DeleteEnvironmentRequest, dict]]): - 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: Optional[Union[environment.GetEnvironmentHistoryRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.GetEnvironmentHistoryAsyncPager: - r"""Gets the history of the specified environment. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import dialogflow_v2beta1 - - async def sample_get_environment_history(): - # Create a client - client = dialogflow_v2beta1.EnvironmentsAsyncClient() - - # Initialize request argument(s) - request = dialogflow_v2beta1.GetEnvironmentHistoryRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.get_environment_history(request=request) - - # Handle the response - async for response in page_result: - print(response) - - Args: - request (Optional[Union[google.cloud.dialogflow_v2beta1.types.GetEnvironmentHistoryRequest, dict]]): - 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 - - async def list_operations( - self, - request: Optional[operations_pb2.ListOperationsRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operations_pb2.ListOperationsResponse: - r"""Lists operations that match the specified filter in the request. - - Args: - request (:class:`~.operations_pb2.ListOperationsRequest`): - The request object. Request message for - `ListOperations` method. - 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: - ~.operations_pb2.ListOperationsResponse: - Response message for ``ListOperations`` method. - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = operations_pb2.ListOperationsRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._client._transport.list_operations, - 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 get_operation( - self, - request: Optional[operations_pb2.GetOperationRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operations_pb2.Operation: - r"""Gets the latest state of a long-running operation. - - Args: - request (:class:`~.operations_pb2.GetOperationRequest`): - The request object. Request message for - `GetOperation` method. - 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: - ~.operations_pb2.Operation: - An ``Operation`` object. - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = operations_pb2.GetOperationRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._client._transport.get_operation, - 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 cancel_operation( - self, - request: Optional[operations_pb2.CancelOperationRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> None: - r"""Starts asynchronous cancellation on a long-running operation. - - The server makes a best effort to cancel the operation, but success - is not guaranteed. If the server doesn't support this method, it returns - `google.rpc.Code.UNIMPLEMENTED`. - - Args: - request (:class:`~.operations_pb2.CancelOperationRequest`): - The request object. Request message for - `CancelOperation` method. - 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: - None - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = operations_pb2.CancelOperationRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._client._transport.cancel_operation, - 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_location( - self, - request: Optional[locations_pb2.GetLocationRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> locations_pb2.Location: - r"""Gets information about a location. - - Args: - request (:class:`~.location_pb2.GetLocationRequest`): - The request object. Request message for - `GetLocation` method. - 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: - ~.location_pb2.Location: - Location object. - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = locations_pb2.GetLocationRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._client._transport.get_location, - 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 list_locations( - self, - request: Optional[locations_pb2.ListLocationsRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> locations_pb2.ListLocationsResponse: - r"""Lists information about the supported locations for this service. - - Args: - request (:class:`~.location_pb2.ListLocationsRequest`): - The request object. Request message for - `ListLocations` method. - 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: - ~.location_pb2.ListLocationsResponse: - Response message for ``ListLocations`` method. - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = locations_pb2.ListLocationsRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._client._transport.list_locations, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("name", request.name),)), - ) - - # Send the request. - response = await rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - async def __aenter__(self): - return self - - async def __aexit__(self, exc_type, exc, tb): - await self.transport.close() - -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) - - -__all__ = ( - "EnvironmentsAsyncClient", -) diff --git a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/environments/client.py b/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/environments/client.py deleted file mode 100644 index 50c0e7fb6..000000000 --- a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/environments/client.py +++ /dev/null @@ -1,1277 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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 os -import re -from typing import Dict, Mapping, MutableMapping, MutableSequence, Optional, Sequence, Tuple, Type, Union, cast - -from google.cloud.dialogflow_v2beta1 import gapic_version as package_version - -from google.api_core import client_options as client_options_lib -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import retry as retries -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 - -try: - OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] -except AttributeError: # pragma: NO COVER - OptionalRetry = Union[retries.Retry, object] # 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.cloud.location import locations_pb2 # type: ignore -from google.longrunning import operations_pb2 -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 -from .transports.rest import EnvironmentsRestTransport - - -class EnvironmentsClientMeta(type): - """Metaclass for the Environments 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[EnvironmentsTransport]] - _transport_registry["grpc"] = EnvironmentsGrpcTransport - _transport_registry["grpc_asyncio"] = EnvironmentsGrpcAsyncIOTransport - _transport_registry["rest"] = EnvironmentsRestTransport - - def get_transport_class(cls, - label: Optional[str] = None, - ) -> Type[EnvironmentsTransport]: - """Returns an appropriate transport class. - - Args: - label: The name of the desired transport. If none is - provided, then the first transport in the registry is used. - - Returns: - The transport class to use. - """ - # If a specific transport is requested, return that one. - if label: - return cls._transport_registry[label] - - # No transport is requested; return the default (that is, the first one - # in the dictionary). - return next(iter(cls._transport_registry.values())) - - -class EnvironmentsClient(metaclass=EnvironmentsClientMeta): - """Service for managing - [Environments][google.cloud.dialogflow.v2beta1.Environment]. - """ - - @staticmethod - def _get_default_mtls_endpoint(api_endpoint): - """Converts api endpoint to mTLS endpoint. - - Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to - "*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively. - Args: - api_endpoint (Optional[str]): the api endpoint to convert. - Returns: - str: converted mTLS api endpoint. - """ - if not api_endpoint: - return api_endpoint - - mtls_endpoint_re = re.compile( - r"(?P[^.]+)(?P\.mtls)?(?P\.sandbox)?(?P\.googleapis\.com)?" - ) - - m = mtls_endpoint_re.match(api_endpoint) - name, mtls, sandbox, googledomain = m.groups() - if mtls or not googledomain: - return api_endpoint - - if sandbox: - return api_endpoint.replace( - "sandbox.googleapis.com", "mtls.sandbox.googleapis.com" - ) - - return api_endpoint.replace(".googleapis.com", ".mtls.googleapis.com") - - DEFAULT_ENDPOINT = "dialogflow.googleapis.com" - DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore - DEFAULT_ENDPOINT - ) - - @classmethod - def from_service_account_info(cls, info: dict, *args, **kwargs): - """Creates an instance of this client using the provided credentials - info. - - Args: - info (dict): The service account private key info. - args: Additional arguments to pass to the constructor. - kwargs: Additional arguments to pass to the constructor. - - Returns: - EnvironmentsClient: 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: - EnvironmentsClient: 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) -> EnvironmentsTransport: - """Returns the transport used by the client instance. - - Returns: - EnvironmentsTransport: The transport used by the client - instance. - """ - return self._transport - - @staticmethod - def environment_path(project: str,environment: str,) -> str: - """Returns a fully-qualified environment string.""" - return "projects/{project}/agent/environments/{environment}".format(project=project, environment=environment, ) - - @staticmethod - def parse_environment_path(path: str) -> Dict[str,str]: - """Parses a environment path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/agent/environments/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def fulfillment_path(project: str,) -> str: - """Returns a fully-qualified fulfillment string.""" - return "projects/{project}/agent/fulfillment".format(project=project, ) - - @staticmethod - def parse_fulfillment_path(path: str) -> Dict[str,str]: - """Parses a fulfillment path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/agent/fulfillment$", path) - return m.groupdict() if m else {} - - @staticmethod - def version_path(project: str,version: str,) -> str: - """Returns 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]: - """Parses 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: - """Returns a fully-qualified billing_account string.""" - return "billingAccounts/{billing_account}".format(billing_account=billing_account, ) - - @staticmethod - def parse_common_billing_account_path(path: str) -> Dict[str,str]: - """Parse a billing_account path into its component segments.""" - m = re.match(r"^billingAccounts/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_folder_path(folder: str, ) -> str: - """Returns a fully-qualified folder string.""" - return "folders/{folder}".format(folder=folder, ) - - @staticmethod - def parse_common_folder_path(path: str) -> Dict[str,str]: - """Parse a folder path into its component segments.""" - m = re.match(r"^folders/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_organization_path(organization: str, ) -> str: - """Returns a fully-qualified organization string.""" - return "organizations/{organization}".format(organization=organization, ) - - @staticmethod - def parse_common_organization_path(path: str) -> Dict[str,str]: - """Parse a organization path into its component segments.""" - m = re.match(r"^organizations/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_project_path(project: str, ) -> str: - """Returns a fully-qualified project string.""" - return "projects/{project}".format(project=project, ) - - @staticmethod - def parse_common_project_path(path: str) -> Dict[str,str]: - """Parse a project path into its component segments.""" - m = re.match(r"^projects/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_location_path(project: str, location: str, ) -> str: - """Returns a fully-qualified location string.""" - return "projects/{project}/locations/{location}".format(project=project, location=location, ) - - @staticmethod - def parse_common_location_path(path: str) -> Dict[str,str]: - """Parse a location path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)$", path) - return m.groupdict() if m else {} - - @classmethod - def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[client_options_lib.ClientOptions] = None): - """Return the API endpoint and client cert source for mutual TLS. - - The client cert source is determined in the following order: - (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the - client cert source is None. - (2) if `client_options.client_cert_source` is provided, use the provided one; if the - default client cert source exists, use the default one; otherwise the client cert - source is None. - - The API endpoint is determined in the following order: - (1) if `client_options.api_endpoint` if provided, use the provided one. - (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the - default mTLS endpoint; if the environment variable is "never", use the default API - endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise - use the default API endpoint. - - More details can be found at https://google.aip.dev/auth/4114. - - Args: - client_options (google.api_core.client_options.ClientOptions): Custom options for the - client. Only the `api_endpoint` and `client_cert_source` properties may be used - in this method. - - Returns: - Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the - client cert source to use. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If any errors happen. - """ - if client_options is None: - client_options = client_options_lib.ClientOptions() - use_client_cert = os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false") - use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") - if use_client_cert not in ("true", "false"): - raise ValueError("Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`") - if use_mtls_endpoint not in ("auto", "never", "always"): - raise MutualTLSChannelError("Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`") - - # Figure out the client cert source to use. - client_cert_source = None - if use_client_cert == "true": - if client_options.client_cert_source: - client_cert_source = client_options.client_cert_source - elif mtls.has_default_client_cert_source(): - client_cert_source = mtls.default_client_cert_source() - - # Figure out which api endpoint to use. - if client_options.api_endpoint is not None: - api_endpoint = client_options.api_endpoint - elif use_mtls_endpoint == "always" or (use_mtls_endpoint == "auto" and client_cert_source): - api_endpoint = cls.DEFAULT_MTLS_ENDPOINT - else: - api_endpoint = cls.DEFAULT_ENDPOINT - - return api_endpoint, client_cert_source - - def __init__(self, *, - credentials: Optional[ga_credentials.Credentials] = None, - transport: Optional[Union[str, EnvironmentsTransport]] = None, - client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the environments 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, EnvironmentsTransport]): The - transport to use. If set to None, a transport is chosen - automatically. - client_options (Optional[Union[google.api_core.client_options.ClientOptions, dict]]): 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() - client_options = cast(client_options_lib.ClientOptions, client_options) - - api_endpoint, client_cert_source_func = self.get_mtls_endpoint_and_cert_source(client_options) - - api_key_value = getattr(client_options, "api_key", None) - if api_key_value and credentials: - raise ValueError("client_options.api_key and credentials are mutually exclusive") - - # 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, EnvironmentsTransport): - # transport is a EnvironmentsTransport instance. - if credentials or client_options.credentials_file or api_key_value: - 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: - import google.auth._default # type: ignore - - if api_key_value and hasattr(google.auth._default, "get_api_key_credentials"): - credentials = google.auth._default.get_api_key_credentials(api_key_value) - - Transport = type(self).get_transport_class(transport) - self._transport = Transport( - credentials=credentials, - credentials_file=client_options.credentials_file, - host=api_endpoint, - scopes=client_options.scopes, - client_cert_source_for_mtls=client_cert_source_func, - quota_project_id=client_options.quota_project_id, - client_info=client_info, - always_use_jwt_access=True, - api_audience=client_options.api_audience, - ) - - def list_environments(self, - request: Optional[Union[environment.ListEnvironmentsRequest, dict]] = None, - *, - parent: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListEnvironmentsPager: - r"""Returns the list of all non-draft environments of the - specified agent. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import dialogflow_v2beta1 - - def sample_list_environments(): - # Create a client - client = dialogflow_v2beta1.EnvironmentsClient() - - # Initialize request argument(s) - request = dialogflow_v2beta1.ListEnvironmentsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_environments(request=request) - - # Handle the response - for response in page_result: - print(response) - - Args: - request (Union[google.cloud.dialogflow_v2beta1.types.ListEnvironmentsRequest, dict]): - The request object. The request message for - [Environments.ListEnvironments][google.cloud.dialogflow.v2beta1.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. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.dialogflow_v2beta1.services.environments.pagers.ListEnvironmentsPager: - The response message for - [Environments.ListEnvironments][google.cloud.dialogflow.v2beta1.Environments.ListEnvironments]. - - Iterating over this object will yield results and - resolve additional pages automatically. - - """ - # Create or coerce a protobuf request object. - # Quick 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. - # There's no risk of modifying the input as we've already verified - # 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. - rpc = self._transport._wrapped_methods[self._transport.list_environments] - - # 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.ListEnvironmentsPager( - method=rpc, - request=request, - response=response, - metadata=metadata, - ) - - # Done; return the response. - return response - - def get_environment(self, - request: Optional[Union[environment.GetEnvironmentRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> environment.Environment: - r"""Retrieves the specified agent environment. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import dialogflow_v2beta1 - - def sample_get_environment(): - # Create a client - client = dialogflow_v2beta1.EnvironmentsClient() - - # Initialize request argument(s) - request = dialogflow_v2beta1.GetEnvironmentRequest( - name="name_value", - ) - - # Make the request - response = client.get_environment(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.dialogflow_v2beta1.types.GetEnvironmentRequest, dict]): - 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: Optional[Union[environment.CreateEnvironmentRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> environment.Environment: - r"""Creates an agent environment. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import dialogflow_v2beta1 - - def sample_create_environment(): - # Create a client - client = dialogflow_v2beta1.EnvironmentsClient() - - # Initialize request argument(s) - request = dialogflow_v2beta1.CreateEnvironmentRequest( - parent="parent_value", - environment_id="environment_id_value", - ) - - # Make the request - response = client.create_environment(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.dialogflow_v2beta1.types.CreateEnvironmentRequest, dict]): - 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: Optional[Union[environment.UpdateEnvironmentRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - 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. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import dialogflow_v2beta1 - - def sample_update_environment(): - # Create a client - client = dialogflow_v2beta1.EnvironmentsClient() - - # Initialize request argument(s) - request = dialogflow_v2beta1.UpdateEnvironmentRequest( - ) - - # Make the request - response = client.update_environment(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.dialogflow_v2beta1.types.UpdateEnvironmentRequest, dict]): - 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: Optional[Union[environment.DeleteEnvironmentRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> None: - r"""Deletes the specified agent environment. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import dialogflow_v2beta1 - - def sample_delete_environment(): - # Create a client - client = dialogflow_v2beta1.EnvironmentsClient() - - # Initialize request argument(s) - request = dialogflow_v2beta1.DeleteEnvironmentRequest( - name="name_value", - ) - - # Make the request - client.delete_environment(request=request) - - Args: - request (Union[google.cloud.dialogflow_v2beta1.types.DeleteEnvironmentRequest, dict]): - 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: Optional[Union[environment.GetEnvironmentHistoryRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.GetEnvironmentHistoryPager: - r"""Gets the history of the specified environment. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import dialogflow_v2beta1 - - def sample_get_environment_history(): - # Create a client - client = dialogflow_v2beta1.EnvironmentsClient() - - # Initialize request argument(s) - request = dialogflow_v2beta1.GetEnvironmentHistoryRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.get_environment_history(request=request) - - # Handle the response - for response in page_result: - print(response) - - Args: - request (Union[google.cloud.dialogflow_v2beta1.types.GetEnvironmentHistoryRequest, dict]): - 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 - - def __enter__(self) -> "EnvironmentsClient": - return self - - def __exit__(self, type, value, traceback): - """Releases underlying transport's resources. - - .. warning:: - ONLY use as a context manager if the transport is NOT shared - with other clients! Exiting the with block will CLOSE the transport - and may cause errors in other clients! - """ - self.transport.close() - - def list_operations( - self, - request: Optional[operations_pb2.ListOperationsRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operations_pb2.ListOperationsResponse: - r"""Lists operations that match the specified filter in the request. - - Args: - request (:class:`~.operations_pb2.ListOperationsRequest`): - The request object. Request message for - `ListOperations` method. - 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: - ~.operations_pb2.ListOperationsResponse: - Response message for ``ListOperations`` method. - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = operations_pb2.ListOperationsRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._transport.list_operations, - 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 = rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - def get_operation( - self, - request: Optional[operations_pb2.GetOperationRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operations_pb2.Operation: - r"""Gets the latest state of a long-running operation. - - Args: - request (:class:`~.operations_pb2.GetOperationRequest`): - The request object. Request message for - `GetOperation` method. - 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: - ~.operations_pb2.Operation: - An ``Operation`` object. - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = operations_pb2.GetOperationRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._transport.get_operation, - 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 = rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - def cancel_operation( - self, - request: Optional[operations_pb2.CancelOperationRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> None: - r"""Starts asynchronous cancellation on a long-running operation. - - The server makes a best effort to cancel the operation, but success - is not guaranteed. If the server doesn't support this method, it returns - `google.rpc.Code.UNIMPLEMENTED`. - - Args: - request (:class:`~.operations_pb2.CancelOperationRequest`): - The request object. Request message for - `CancelOperation` method. - 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: - None - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = operations_pb2.CancelOperationRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._transport.cancel_operation, - 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. - rpc(request, retry=retry, timeout=timeout, metadata=metadata,) - - def get_location( - self, - request: Optional[locations_pb2.GetLocationRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> locations_pb2.Location: - r"""Gets information about a location. - - Args: - request (:class:`~.location_pb2.GetLocationRequest`): - The request object. Request message for - `GetLocation` method. - 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: - ~.location_pb2.Location: - Location object. - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = locations_pb2.GetLocationRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._transport.get_location, - 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 = rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - def list_locations( - self, - request: Optional[locations_pb2.ListLocationsRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> locations_pb2.ListLocationsResponse: - r"""Lists information about the supported locations for this service. - - Args: - request (:class:`~.location_pb2.ListLocationsRequest`): - The request object. Request message for - `ListLocations` method. - 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: - ~.location_pb2.ListLocationsResponse: - Response message for ``ListLocations`` method. - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = locations_pb2.ListLocationsRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._transport.list_locations, - 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 = rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) - - -__all__ = ( - "EnvironmentsClient", -) diff --git a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/environments/pagers.py b/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/environments/pagers.py deleted file mode 100644 index 06847e3c0..000000000 --- a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/environments/pagers.py +++ /dev/null @@ -1,260 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from typing import Any, AsyncIterator, Awaitable, Callable, Sequence, Tuple, Optional, Iterator - -from google.cloud.dialogflow_v2beta1.types import environment - - -class ListEnvironmentsPager: - """A pager for iterating through ``list_environments`` requests. - - This class thinly wraps an initial - :class:`google.cloud.dialogflow_v2beta1.types.ListEnvironmentsResponse` object, and - provides an ``__iter__`` method to iterate through its - ``environments`` field. - - If there are more pages, the ``__iter__`` method will make additional - ``ListEnvironments`` requests and continue to iterate - through the ``environments`` field on the - corresponding responses. - - All the usual :class:`google.cloud.dialogflow_v2beta1.types.ListEnvironmentsResponse` - 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.ListEnvironmentsResponse], - request: environment.ListEnvironmentsRequest, - response: environment.ListEnvironmentsResponse, - *, - 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.ListEnvironmentsRequest): - The initial request object. - response (google.cloud.dialogflow_v2beta1.types.ListEnvironmentsResponse): - 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.ListEnvironmentsRequest(request) - self._response = response - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - def pages(self) -> Iterator[environment.ListEnvironmentsResponse]: - yield self._response - while self._response.next_page_token: - self._request.page_token = self._response.next_page_token - self._response = self._method(self._request, metadata=self._metadata) - yield self._response - - def __iter__(self) -> Iterator[environment.Environment]: - for page in self.pages: - yield from page.environments - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListEnvironmentsAsyncPager: - """A pager for iterating through ``list_environments`` requests. - - This class thinly wraps an initial - :class:`google.cloud.dialogflow_v2beta1.types.ListEnvironmentsResponse` object, and - provides an ``__aiter__`` method to iterate through its - ``environments`` field. - - If there are more pages, the ``__aiter__`` method will make additional - ``ListEnvironments`` requests and continue to iterate - through the ``environments`` field on the - corresponding responses. - - All the usual :class:`google.cloud.dialogflow_v2beta1.types.ListEnvironmentsResponse` - 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.ListEnvironmentsResponse]], - request: environment.ListEnvironmentsRequest, - response: environment.ListEnvironmentsResponse, - *, - metadata: Sequence[Tuple[str, str]] = ()): - """Instantiates the pager. - - Args: - method (Callable): The method that was originally called, and - which instantiated this pager. - request (google.cloud.dialogflow_v2beta1.types.ListEnvironmentsRequest): - The initial request object. - response (google.cloud.dialogflow_v2beta1.types.ListEnvironmentsResponse): - 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.ListEnvironmentsRequest(request) - self._response = response - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - async def pages(self) -> AsyncIterator[environment.ListEnvironmentsResponse]: - yield self._response - while self._response.next_page_token: - self._request.page_token = self._response.next_page_token - self._response = await self._method(self._request, metadata=self._metadata) - yield self._response - def __aiter__(self) -> AsyncIterator[environment.Environment]: - async def async_generator(): - async for page in self.pages: - for response in page.environments: - yield response - - return 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) -> Iterator[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) -> Iterator[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]] = ()): - """Instantiates 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) -> AsyncIterator[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) -> AsyncIterator[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/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/environments/transports/__init__.py b/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/environments/transports/__init__.py deleted file mode 100644 index 9384fe0b2..000000000 --- a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/environments/transports/__init__.py +++ /dev/null @@ -1,38 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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 EnvironmentsTransport -from .grpc import EnvironmentsGrpcTransport -from .grpc_asyncio import EnvironmentsGrpcAsyncIOTransport -from .rest import EnvironmentsRestTransport -from .rest import EnvironmentsRestInterceptor - - -# Compile a registry of transports. -_transport_registry = OrderedDict() # type: Dict[str, Type[EnvironmentsTransport]] -_transport_registry['grpc'] = EnvironmentsGrpcTransport -_transport_registry['grpc_asyncio'] = EnvironmentsGrpcAsyncIOTransport -_transport_registry['rest'] = EnvironmentsRestTransport - -__all__ = ( - 'EnvironmentsTransport', - 'EnvironmentsGrpcTransport', - 'EnvironmentsGrpcAsyncIOTransport', - 'EnvironmentsRestTransport', - 'EnvironmentsRestInterceptor', -) diff --git a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/environments/transports/base.py b/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/environments/transports/base.py deleted file mode 100644 index 5e36d0b8b..000000000 --- a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/environments/transports/base.py +++ /dev/null @@ -1,265 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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 - -from google.cloud.dialogflow_v2beta1 import gapic_version as package_version - -import google.auth # type: ignore -import google.api_core -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import retry as retries -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 environment -from google.cloud.location import locations_pb2 # type: ignore -from google.longrunning import operations_pb2 -from google.protobuf import empty_pb2 # type: ignore - -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) - - -class EnvironmentsTransport(abc.ABC): - """Abstract transport class for Environments.""" - - 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: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - api_audience: Optional[str] = None, - **kwargs, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. - scopes (Optional[Sequence[str]]): A list of scopes. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - """ - - scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} - - # Save the scopes. - self._scopes = scopes - - # If no credentials are provided, then determine the appropriate - # defaults. - if credentials and credentials_file: - raise core_exceptions.DuplicateCredentialArgs("'credentials_file' and 'credentials' are mutually exclusive") - - if credentials_file is not None: - credentials, _ = google.auth.load_credentials_from_file( - credentials_file, - **scopes_kwargs, - quota_project_id=quota_project_id - ) - elif credentials is None: - credentials, _ = google.auth.default(**scopes_kwargs, quota_project_id=quota_project_id) - # Don't apply audience if the credentials file passed from user. - if hasattr(credentials, "with_gdch_audience"): - credentials = credentials.with_gdch_audience(api_audience if api_audience else host) - - # If the credentials are service account credentials, then always try to use self signed JWT. - if always_use_jwt_access and isinstance(credentials, service_account.Credentials) and hasattr(service_account.Credentials, "with_always_use_jwt_access"): - credentials = credentials.with_always_use_jwt_access(True) - - # Save the credentials. - self._credentials = credentials - - # Save the hostname. Default to port 443 (HTTPS) if none is specified. - if ':' not in host: - host += ':443' - self._host = host - - 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, - ), - } - - def close(self): - """Closes resources associated with the transport. - - .. warning:: - Only call this method if the transport is NOT shared - with other clients - this may cause errors in other clients! - """ - raise NotImplementedError() - - @property - def list_environments(self) -> Callable[ - [environment.ListEnvironmentsRequest], - Union[ - 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() - - @property - def list_operations( - self, - ) -> Callable[ - [operations_pb2.ListOperationsRequest], - Union[operations_pb2.ListOperationsResponse, Awaitable[operations_pb2.ListOperationsResponse]], - ]: - raise NotImplementedError() - - @property - def get_operation( - self, - ) -> Callable[ - [operations_pb2.GetOperationRequest], - Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], - ]: - raise NotImplementedError() - - @property - def cancel_operation( - self, - ) -> Callable[ - [operations_pb2.CancelOperationRequest], - None, - ]: - raise NotImplementedError() - - @property - def get_location(self, - ) -> Callable[ - [locations_pb2.GetLocationRequest], - Union[locations_pb2.Location, Awaitable[locations_pb2.Location]], - ]: - raise NotImplementedError() - - @property - def list_locations(self, - ) -> Callable[ - [locations_pb2.ListLocationsRequest], - Union[locations_pb2.ListLocationsResponse, Awaitable[locations_pb2.ListLocationsResponse]], - ]: - raise NotImplementedError() - - @property - def kind(self) -> str: - raise NotImplementedError() - - -__all__ = ( - 'EnvironmentsTransport', -) diff --git a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/environments/transports/grpc.py b/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/environments/transports/grpc.py deleted file mode 100644 index 89a395e0d..000000000 --- a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/environments/transports/grpc.py +++ /dev/null @@ -1,501 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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 -from google.api_core import gapic_v1 -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.cloud.location import locations_pb2 # type: ignore -from google.longrunning import operations_pb2 -from google.protobuf import empty_pb2 # type: ignore -from .base import EnvironmentsTransport, DEFAULT_CLIENT_INFO - - -class EnvironmentsGrpcTransport(EnvironmentsTransport): - """gRPC backend transport for Environments. - - Service for managing - [Environments][google.cloud.dialogflow.v2beta1.Environment]. - - 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: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - channel: Optional[grpc.Channel] = None, - api_mtls_endpoint: Optional[str] = None, - client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, - ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, - client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - api_audience: Optional[str] = None, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - This argument is ignored if ``channel`` is provided. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional(Sequence[str])): A list of scopes. This argument is - ignored if ``channel`` is provided. - channel (Optional[grpc.Channel]): A ``Channel`` instance through - which to make calls. - api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. - If provided, it overrides the ``host`` argument and tries to create - a mutual TLS channel with client SSL credentials from - ``client_cert_source`` or application default SSL credentials. - client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): - Deprecated. A callback to provide client SSL certificate bytes and - private key bytes, both in PEM format. It is ignored if - ``api_mtls_endpoint`` is None. - ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials - for the grpc channel. It is ignored if ``channel`` is provided. - client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): - A callback to provide client certificate bytes and private key bytes, - both in PEM format. It is used to configure a mutual TLS channel. It is - ignored if ``channel`` or ``ssl_channel_credentials`` is provided. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport - creation failed for any reason. - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - self._grpc_channel = None - self._ssl_channel_credentials = ssl_channel_credentials - self._stubs: Dict[str, Callable] = {} - - if api_mtls_endpoint: - warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) - if client_cert_source: - warnings.warn("client_cert_source is deprecated", DeprecationWarning) - - if channel: - # Ignore credentials if a channel was passed. - credentials = False - # If a channel was explicitly provided, set it. - self._grpc_channel = channel - self._ssl_channel_credentials = None - - else: - if api_mtls_endpoint: - host = api_mtls_endpoint - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - self._ssl_channel_credentials = SslCredentials().ssl_credentials - - else: - if client_cert_source_for_mtls and not ssl_channel_credentials: - cert, key = client_cert_source_for_mtls() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - - # The base transport sets the host, credentials and scopes - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes, - quota_project_id=quota_project_id, - client_info=client_info, - always_use_jwt_access=always_use_jwt_access, - api_audience=api_audience, - ) - - if not self._grpc_channel: - self._grpc_channel = type(self).create_channel( - self._host, - # use the credentials which are saved - credentials=self._credentials, - # Set ``credentials_file`` to ``None`` here as - # the credentials that we saved earlier should be used. - credentials_file=None, - 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: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - **kwargs) -> grpc.Channel: - """Create and return a gRPC channel object. - Args: - host (Optional[str]): The host for the channel to use. - credentials (Optional[~.Credentials]): The - authorization credentials to attach to requests. These - credentials identify this application to the service. If - none are specified, the client will attempt to ascertain - the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - kwargs (Optional[dict]): Keyword arguments, which are passed to the - channel creation. - Returns: - grpc.Channel: A gRPC channel object. - - Raises: - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - - return grpc_helpers.create_channel( - host, - credentials=credentials, - credentials_file=credentials_file, - quota_project_id=quota_project_id, - default_scopes=cls.AUTH_SCOPES, - scopes=scopes, - default_host=cls.DEFAULT_HOST, - **kwargs - ) - - @property - def grpc_channel(self) -> grpc.Channel: - """Return the channel designed to connect to this service. - """ - return self._grpc_channel - - @property - def list_environments(self) -> Callable[ - [environment.ListEnvironmentsRequest], - environment.ListEnvironmentsResponse]: - r"""Return a callable for the list environments method over gRPC. - - Returns the list of all non-draft environments of the - specified agent. - - Returns: - Callable[[~.ListEnvironmentsRequest], - ~.ListEnvironmentsResponse]: - 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_environments' not in self._stubs: - self._stubs['list_environments'] = self.grpc_channel.unary_unary( - '/google.cloud.dialogflow.v2beta1.Environments/ListEnvironments', - request_serializer=environment.ListEnvironmentsRequest.serialize, - response_deserializer=environment.ListEnvironmentsResponse.deserialize, - ) - 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'] - - def close(self): - self.grpc_channel.close() - - @property - def cancel_operation( - self, - ) -> Callable[[operations_pb2.CancelOperationRequest], None]: - r"""Return a callable for the cancel_operation method over gRPC. - """ - # 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 "cancel_operation" not in self._stubs: - self._stubs["cancel_operation"] = self.grpc_channel.unary_unary( - "/google.longrunning.Operations/CancelOperation", - request_serializer=operations_pb2.CancelOperationRequest.SerializeToString, - response_deserializer=None, - ) - return self._stubs["cancel_operation"] - - @property - def get_operation( - self, - ) -> Callable[[operations_pb2.GetOperationRequest], operations_pb2.Operation]: - r"""Return a callable for the get_operation method over gRPC. - """ - # 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_operation" not in self._stubs: - self._stubs["get_operation"] = self.grpc_channel.unary_unary( - "/google.longrunning.Operations/GetOperation", - request_serializer=operations_pb2.GetOperationRequest.SerializeToString, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs["get_operation"] - - @property - def list_operations( - self, - ) -> Callable[[operations_pb2.ListOperationsRequest], operations_pb2.ListOperationsResponse]: - r"""Return a callable for the list_operations method over gRPC. - """ - # 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_operations" not in self._stubs: - self._stubs["list_operations"] = self.grpc_channel.unary_unary( - "/google.longrunning.Operations/ListOperations", - request_serializer=operations_pb2.ListOperationsRequest.SerializeToString, - response_deserializer=operations_pb2.ListOperationsResponse.FromString, - ) - return self._stubs["list_operations"] - - @property - def list_locations( - self, - ) -> Callable[[locations_pb2.ListLocationsRequest], locations_pb2.ListLocationsResponse]: - r"""Return a callable for the list locations method over gRPC. - """ - # 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_locations" not in self._stubs: - self._stubs["list_locations"] = self.grpc_channel.unary_unary( - "/google.cloud.location.Locations/ListLocations", - request_serializer=locations_pb2.ListLocationsRequest.SerializeToString, - response_deserializer=locations_pb2.ListLocationsResponse.FromString, - ) - return self._stubs["list_locations"] - - @property - def get_location( - self, - ) -> Callable[[locations_pb2.GetLocationRequest], locations_pb2.Location]: - r"""Return a callable for the list locations method over gRPC. - """ - # 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_location" not in self._stubs: - self._stubs["get_location"] = self.grpc_channel.unary_unary( - "/google.cloud.location.Locations/GetLocation", - request_serializer=locations_pb2.GetLocationRequest.SerializeToString, - response_deserializer=locations_pb2.Location.FromString, - ) - return self._stubs["get_location"] - - @property - def kind(self) -> str: - return "grpc" - - -__all__ = ( - 'EnvironmentsGrpcTransport', -) diff --git a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/environments/transports/grpc_asyncio.py b/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/environments/transports/grpc_asyncio.py deleted file mode 100644 index 54dc5760a..000000000 --- a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/environments/transports/grpc_asyncio.py +++ /dev/null @@ -1,500 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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 -from google.api_core import grpc_helpers_async -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore - -import grpc # type: ignore -from grpc.experimental import aio # type: ignore - -from google.cloud.dialogflow_v2beta1.types import environment -from google.cloud.location import locations_pb2 # type: ignore -from google.longrunning import operations_pb2 -from google.protobuf import empty_pb2 # type: ignore -from .base import EnvironmentsTransport, DEFAULT_CLIENT_INFO -from .grpc import EnvironmentsGrpcTransport - - -class EnvironmentsGrpcAsyncIOTransport(EnvironmentsTransport): - """gRPC AsyncIO backend transport for Environments. - - Service for managing - [Environments][google.cloud.dialogflow.v2beta1.Environment]. - - 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: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - **kwargs) -> aio.Channel: - """Create and return a gRPC AsyncIO channel object. - Args: - host (Optional[str]): The host for the channel to use. - credentials (Optional[~.Credentials]): The - authorization credentials to attach to requests. These - credentials identify this application to the service. If - none are specified, the client will attempt to ascertain - the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - kwargs (Optional[dict]): Keyword arguments, which are passed to the - channel creation. - Returns: - aio.Channel: A gRPC AsyncIO channel object. - """ - - return grpc_helpers_async.create_channel( - host, - credentials=credentials, - credentials_file=credentials_file, - quota_project_id=quota_project_id, - default_scopes=cls.AUTH_SCOPES, - scopes=scopes, - default_host=cls.DEFAULT_HOST, - **kwargs - ) - - def __init__(self, *, - host: str = 'dialogflow.googleapis.com', - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - channel: Optional[aio.Channel] = None, - api_mtls_endpoint: Optional[str] = None, - client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, - ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, - client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - api_audience: Optional[str] = None, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - This argument is ignored if ``channel`` is provided. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - channel (Optional[aio.Channel]): A ``Channel`` instance through - which to make calls. - api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. - If provided, it overrides the ``host`` argument and tries to create - a mutual TLS channel with client SSL credentials from - ``client_cert_source`` or application default SSL credentials. - client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): - Deprecated. A callback to provide client SSL certificate bytes and - private key bytes, both in PEM format. It is ignored if - ``api_mtls_endpoint`` is None. - ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials - for the grpc channel. It is ignored if ``channel`` is provided. - client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): - A callback to provide client certificate bytes and private key bytes, - both in PEM format. It is used to configure a mutual TLS channel. It is - ignored if ``channel`` or ``ssl_channel_credentials`` is provided. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - - Raises: - google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport - creation failed for any reason. - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - self._grpc_channel = None - self._ssl_channel_credentials = ssl_channel_credentials - self._stubs: Dict[str, Callable] = {} - - if api_mtls_endpoint: - warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) - if client_cert_source: - warnings.warn("client_cert_source is deprecated", DeprecationWarning) - - if channel: - # Ignore credentials if a channel was passed. - credentials = False - # If a channel was explicitly provided, set it. - self._grpc_channel = channel - self._ssl_channel_credentials = None - else: - if api_mtls_endpoint: - host = api_mtls_endpoint - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - self._ssl_channel_credentials = SslCredentials().ssl_credentials - - else: - if client_cert_source_for_mtls and not ssl_channel_credentials: - cert, key = client_cert_source_for_mtls() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - - # The base transport sets the host, credentials and scopes - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes, - quota_project_id=quota_project_id, - client_info=client_info, - always_use_jwt_access=always_use_jwt_access, - api_audience=api_audience, - ) - - if not self._grpc_channel: - self._grpc_channel = type(self).create_channel( - self._host, - # use the credentials which are saved - credentials=self._credentials, - # Set ``credentials_file`` to ``None`` here as - # the credentials that we saved earlier should be used. - credentials_file=None, - 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_environments(self) -> Callable[ - [environment.ListEnvironmentsRequest], - Awaitable[environment.ListEnvironmentsResponse]]: - r"""Return a callable for the list environments method over gRPC. - - Returns the list of all non-draft environments of the - specified agent. - - Returns: - Callable[[~.ListEnvironmentsRequest], - Awaitable[~.ListEnvironmentsResponse]]: - 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_environments' not in self._stubs: - self._stubs['list_environments'] = self.grpc_channel.unary_unary( - '/google.cloud.dialogflow.v2beta1.Environments/ListEnvironments', - request_serializer=environment.ListEnvironmentsRequest.serialize, - response_deserializer=environment.ListEnvironmentsResponse.deserialize, - ) - 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'] - - def close(self): - return self.grpc_channel.close() - - @property - def cancel_operation( - self, - ) -> Callable[[operations_pb2.CancelOperationRequest], None]: - r"""Return a callable for the cancel_operation method over gRPC. - """ - # 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 "cancel_operation" not in self._stubs: - self._stubs["cancel_operation"] = self.grpc_channel.unary_unary( - "/google.longrunning.Operations/CancelOperation", - request_serializer=operations_pb2.CancelOperationRequest.SerializeToString, - response_deserializer=None, - ) - return self._stubs["cancel_operation"] - - @property - def get_operation( - self, - ) -> Callable[[operations_pb2.GetOperationRequest], operations_pb2.Operation]: - r"""Return a callable for the get_operation method over gRPC. - """ - # 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_operation" not in self._stubs: - self._stubs["get_operation"] = self.grpc_channel.unary_unary( - "/google.longrunning.Operations/GetOperation", - request_serializer=operations_pb2.GetOperationRequest.SerializeToString, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs["get_operation"] - - @property - def list_operations( - self, - ) -> Callable[[operations_pb2.ListOperationsRequest], operations_pb2.ListOperationsResponse]: - r"""Return a callable for the list_operations method over gRPC. - """ - # 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_operations" not in self._stubs: - self._stubs["list_operations"] = self.grpc_channel.unary_unary( - "/google.longrunning.Operations/ListOperations", - request_serializer=operations_pb2.ListOperationsRequest.SerializeToString, - response_deserializer=operations_pb2.ListOperationsResponse.FromString, - ) - return self._stubs["list_operations"] - - @property - def list_locations( - self, - ) -> Callable[[locations_pb2.ListLocationsRequest], locations_pb2.ListLocationsResponse]: - r"""Return a callable for the list locations method over gRPC. - """ - # 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_locations" not in self._stubs: - self._stubs["list_locations"] = self.grpc_channel.unary_unary( - "/google.cloud.location.Locations/ListLocations", - request_serializer=locations_pb2.ListLocationsRequest.SerializeToString, - response_deserializer=locations_pb2.ListLocationsResponse.FromString, - ) - return self._stubs["list_locations"] - - @property - def get_location( - self, - ) -> Callable[[locations_pb2.GetLocationRequest], locations_pb2.Location]: - r"""Return a callable for the list locations method over gRPC. - """ - # 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_location" not in self._stubs: - self._stubs["get_location"] = self.grpc_channel.unary_unary( - "/google.cloud.location.Locations/GetLocation", - request_serializer=locations_pb2.GetLocationRequest.SerializeToString, - response_deserializer=locations_pb2.Location.FromString, - ) - return self._stubs["get_location"] - - -__all__ = ( - 'EnvironmentsGrpcAsyncIOTransport', -) diff --git a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/environments/transports/rest.py b/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/environments/transports/rest.py deleted file mode 100644 index b3bdfe99b..000000000 --- a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/environments/transports/rest.py +++ /dev/null @@ -1,1361 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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 google.auth.transport.requests import AuthorizedSession # type: ignore -import json # type: ignore -import grpc # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore -from google.auth import credentials as ga_credentials # type: ignore -from google.api_core import exceptions as core_exceptions -from google.api_core import retry as retries -from google.api_core import rest_helpers -from google.api_core import rest_streaming -from google.api_core import path_template -from google.api_core import gapic_v1 - -from google.protobuf import json_format -from google.cloud.location import locations_pb2 # type: ignore -from google.longrunning import operations_pb2 -from requests import __version__ as requests_version -import dataclasses -import re -from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union -import warnings - -try: - OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] -except AttributeError: # pragma: NO COVER - OptionalRetry = Union[retries.Retry, object] # 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 as BASE_DEFAULT_CLIENT_INFO - - -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=BASE_DEFAULT_CLIENT_INFO.gapic_version, - grpc_version=None, - rest_version=requests_version, -) - - -class EnvironmentsRestInterceptor: - """Interceptor for Environments. - - Interceptors are used to manipulate requests, request metadata, and responses - in arbitrary ways. - Example use cases include: - * Logging - * Verifying requests according to service or custom semantics - * Stripping extraneous information from responses - - These use cases and more can be enabled by injecting an - instance of a custom subclass when constructing the EnvironmentsRestTransport. - - .. code-block:: python - class MyCustomEnvironmentsInterceptor(EnvironmentsRestInterceptor): - def pre_create_environment(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_create_environment(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_delete_environment(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def pre_get_environment(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_get_environment(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_get_environment_history(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_get_environment_history(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_list_environments(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_list_environments(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_update_environment(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_update_environment(self, response): - logging.log(f"Received response: {response}") - return response - - transport = EnvironmentsRestTransport(interceptor=MyCustomEnvironmentsInterceptor()) - client = EnvironmentsClient(transport=transport) - - - """ - def pre_create_environment(self, request: environment.CreateEnvironmentRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[environment.CreateEnvironmentRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for create_environment - - Override in a subclass to manipulate the request or metadata - before they are sent to the Environments server. - """ - return request, metadata - - def post_create_environment(self, response: environment.Environment) -> environment.Environment: - """Post-rpc interceptor for create_environment - - Override in a subclass to manipulate the response - after it is returned by the Environments server but before - it is returned to user code. - """ - return response - def pre_delete_environment(self, request: environment.DeleteEnvironmentRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[environment.DeleteEnvironmentRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for delete_environment - - Override in a subclass to manipulate the request or metadata - before they are sent to the Environments server. - """ - return request, metadata - - def pre_get_environment(self, request: environment.GetEnvironmentRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[environment.GetEnvironmentRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for get_environment - - Override in a subclass to manipulate the request or metadata - before they are sent to the Environments server. - """ - return request, metadata - - def post_get_environment(self, response: environment.Environment) -> environment.Environment: - """Post-rpc interceptor for get_environment - - Override in a subclass to manipulate the response - after it is returned by the Environments server but before - it is returned to user code. - """ - return response - def pre_get_environment_history(self, request: environment.GetEnvironmentHistoryRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[environment.GetEnvironmentHistoryRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for get_environment_history - - Override in a subclass to manipulate the request or metadata - before they are sent to the Environments server. - """ - return request, metadata - - def post_get_environment_history(self, response: environment.EnvironmentHistory) -> environment.EnvironmentHistory: - """Post-rpc interceptor for get_environment_history - - Override in a subclass to manipulate the response - after it is returned by the Environments server but before - it is returned to user code. - """ - return response - def pre_list_environments(self, request: environment.ListEnvironmentsRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[environment.ListEnvironmentsRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for list_environments - - Override in a subclass to manipulate the request or metadata - before they are sent to the Environments server. - """ - return request, metadata - - def post_list_environments(self, response: environment.ListEnvironmentsResponse) -> environment.ListEnvironmentsResponse: - """Post-rpc interceptor for list_environments - - Override in a subclass to manipulate the response - after it is returned by the Environments server but before - it is returned to user code. - """ - return response - def pre_update_environment(self, request: environment.UpdateEnvironmentRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[environment.UpdateEnvironmentRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for update_environment - - Override in a subclass to manipulate the request or metadata - before they are sent to the Environments server. - """ - return request, metadata - - def post_update_environment(self, response: environment.Environment) -> environment.Environment: - """Post-rpc interceptor for update_environment - - Override in a subclass to manipulate the response - after it is returned by the Environments server but before - it is returned to user code. - """ - return response - - def pre_get_location( - self, request: locations_pb2.GetLocationRequest, metadata: Sequence[Tuple[str, str]] - ) -> Tuple[locations_pb2.GetLocationRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for get_location - - Override in a subclass to manipulate the request or metadata - before they are sent to the Environments server. - """ - return request, metadata - - def post_get_location( - self, response: locations_pb2.Location - ) -> locations_pb2.Location: - """Post-rpc interceptor for get_location - - Override in a subclass to manipulate the response - after it is returned by the Environments server but before - it is returned to user code. - """ - return response - def pre_list_locations( - self, request: locations_pb2.ListLocationsRequest, metadata: Sequence[Tuple[str, str]] - ) -> Tuple[locations_pb2.ListLocationsRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for list_locations - - Override in a subclass to manipulate the request or metadata - before they are sent to the Environments server. - """ - return request, metadata - - def post_list_locations( - self, response: locations_pb2.ListLocationsResponse - ) -> locations_pb2.ListLocationsResponse: - """Post-rpc interceptor for list_locations - - Override in a subclass to manipulate the response - after it is returned by the Environments server but before - it is returned to user code. - """ - return response - def pre_cancel_operation( - self, request: operations_pb2.CancelOperationRequest, metadata: Sequence[Tuple[str, str]] - ) -> Tuple[operations_pb2.CancelOperationRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for cancel_operation - - Override in a subclass to manipulate the request or metadata - before they are sent to the Environments server. - """ - return request, metadata - - def post_cancel_operation( - self, response: None - ) -> None: - """Post-rpc interceptor for cancel_operation - - Override in a subclass to manipulate the response - after it is returned by the Environments server but before - it is returned to user code. - """ - return response - def pre_get_operation( - self, request: operations_pb2.GetOperationRequest, metadata: Sequence[Tuple[str, str]] - ) -> Tuple[operations_pb2.GetOperationRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for get_operation - - Override in a subclass to manipulate the request or metadata - before they are sent to the Environments server. - """ - return request, metadata - - def post_get_operation( - self, response: operations_pb2.Operation - ) -> operations_pb2.Operation: - """Post-rpc interceptor for get_operation - - Override in a subclass to manipulate the response - after it is returned by the Environments server but before - it is returned to user code. - """ - return response - def pre_list_operations( - self, request: operations_pb2.ListOperationsRequest, metadata: Sequence[Tuple[str, str]] - ) -> Tuple[operations_pb2.ListOperationsRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for list_operations - - Override in a subclass to manipulate the request or metadata - before they are sent to the Environments server. - """ - return request, metadata - - def post_list_operations( - self, response: operations_pb2.ListOperationsResponse - ) -> operations_pb2.ListOperationsResponse: - """Post-rpc interceptor for list_operations - - Override in a subclass to manipulate the response - after it is returned by the Environments server but before - it is returned to user code. - """ - return response - - -@dataclasses.dataclass -class EnvironmentsRestStub: - _session: AuthorizedSession - _host: str - _interceptor: EnvironmentsRestInterceptor - - -class EnvironmentsRestTransport(EnvironmentsTransport): - """REST backend transport for Environments. - - Service for managing - [Environments][google.cloud.dialogflow.v2beta1.Environment]. - - 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 JSON representations of protocol buffers over HTTP/1.1 - - """ - - def __init__(self, *, - host: str = 'dialogflow.googleapis.com', - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - client_cert_source_for_mtls: Optional[Callable[[ - ], Tuple[bytes, bytes]]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - url_scheme: str = 'https', - interceptor: Optional[EnvironmentsRestInterceptor] = None, - api_audience: Optional[str] = None, - ) -> 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 ignored if ``channel`` is provided. - scopes (Optional(Sequence[str])): A list of scopes. This argument is - ignored if ``channel`` is provided. - client_cert_source_for_mtls (Callable[[], Tuple[bytes, bytes]]): Client - certificate to configure mutual TLS HTTP channel. It is ignored - if ``channel`` is provided. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you are developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - url_scheme: the protocol scheme for the API endpoint. Normally - "https", but for testing or local servers, - "http" can be specified. - """ - # Run the base constructor - # TODO(yon-mg): resolve other ctor params i.e. scopes, quota, etc. - # TODO: When custom host (api_endpoint) is set, `scopes` must *also* be set on the - # credentials object - maybe_url_match = re.match("^(?Phttp(?:s)?://)?(?P.*)$", host) - if maybe_url_match is None: - raise ValueError(f"Unexpected hostname structure: {host}") # pragma: NO COVER - - url_match_items = maybe_url_match.groupdict() - - host = f"{url_scheme}://{host}" if not url_match_items["scheme"] else host - - super().__init__( - host=host, - credentials=credentials, - client_info=client_info, - always_use_jwt_access=always_use_jwt_access, - api_audience=api_audience - ) - self._session = AuthorizedSession( - self._credentials, default_host=self.DEFAULT_HOST) - if client_cert_source_for_mtls: - self._session.configure_mtls_channel(client_cert_source_for_mtls) - self._interceptor = interceptor or EnvironmentsRestInterceptor() - self._prep_wrapped_messages(client_info) - - class _CreateEnvironment(EnvironmentsRestStub): - def __hash__(self): - return hash("CreateEnvironment") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - "environmentId" : "", } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: environment.CreateEnvironmentRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> environment.Environment: - r"""Call the create environment method over HTTP. - - Args: - request (~.environment.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: - ~.environment.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 `__. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'post', - 'uri': '/v2beta1/{parent=projects/*/agent}/environments', - 'body': 'environment', - }, -{ - 'method': 'post', - 'uri': '/v2beta1/{parent=projects/*/locations/*/agent}/environments', - 'body': 'environment', - }, - ] - request, metadata = self._interceptor.pre_create_environment(request, metadata) - pb_request = environment.CreateEnvironmentRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request['body'], - including_default_value_fields=False, - use_integers_for_enums=True - ) - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - including_default_value_fields=False, - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = environment.Environment() - pb_resp = environment.Environment.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_create_environment(resp) - return resp - - class _DeleteEnvironment(EnvironmentsRestStub): - def __hash__(self): - return hash("DeleteEnvironment") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: environment.DeleteEnvironmentRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ): - r"""Call the delete environment method over HTTP. - - Args: - request (~.environment.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. - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'delete', - 'uri': '/v2beta1/{name=projects/*/agent/environments/*}', - }, -{ - 'method': 'delete', - 'uri': '/v2beta1/{name=projects/*/locations/*/agent/environments/*}', - }, - ] - request, metadata = self._interceptor.pre_delete_environment(request, metadata) - pb_request = environment.DeleteEnvironmentRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - including_default_value_fields=False, - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - class _GetEnvironment(EnvironmentsRestStub): - def __hash__(self): - return hash("GetEnvironment") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: environment.GetEnvironmentRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> environment.Environment: - r"""Call the get environment method over HTTP. - - Args: - request (~.environment.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: - ~.environment.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 `__. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v2beta1/{name=projects/*/agent/environments/*}', - }, -{ - 'method': 'get', - 'uri': '/v2beta1/{name=projects/*/locations/*/agent/environments/*}', - }, - ] - request, metadata = self._interceptor.pre_get_environment(request, metadata) - pb_request = environment.GetEnvironmentRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - including_default_value_fields=False, - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = environment.Environment() - pb_resp = environment.Environment.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_get_environment(resp) - return resp - - class _GetEnvironmentHistory(EnvironmentsRestStub): - def __hash__(self): - return hash("GetEnvironmentHistory") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: environment.GetEnvironmentHistoryRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> environment.EnvironmentHistory: - r"""Call the get environment history method over HTTP. - - Args: - request (~.environment.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: - ~.environment.EnvironmentHistory: - The response message for - [Environments.GetEnvironmentHistory][google.cloud.dialogflow.v2beta1.Environments.GetEnvironmentHistory]. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v2beta1/{parent=projects/*/agent/environments/*}/history', - }, -{ - 'method': 'get', - 'uri': '/v2beta1/{parent=projects/*/locations/*/agent/environments/*}/history', - }, - ] - request, metadata = self._interceptor.pre_get_environment_history(request, metadata) - pb_request = environment.GetEnvironmentHistoryRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - including_default_value_fields=False, - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = environment.EnvironmentHistory() - pb_resp = environment.EnvironmentHistory.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_get_environment_history(resp) - return resp - - class _ListEnvironments(EnvironmentsRestStub): - def __hash__(self): - return hash("ListEnvironments") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: environment.ListEnvironmentsRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> environment.ListEnvironmentsResponse: - r"""Call the list environments method over HTTP. - - Args: - request (~.environment.ListEnvironmentsRequest): - The request object. The request message for - [Environments.ListEnvironments][google.cloud.dialogflow.v2beta1.Environments.ListEnvironments]. - 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: - ~.environment.ListEnvironmentsResponse: - The response message for - [Environments.ListEnvironments][google.cloud.dialogflow.v2beta1.Environments.ListEnvironments]. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v2beta1/{parent=projects/*/agent}/environments', - }, -{ - 'method': 'get', - 'uri': '/v2beta1/{parent=projects/*/locations/*/agent}/environments', - }, - ] - request, metadata = self._interceptor.pre_list_environments(request, metadata) - pb_request = environment.ListEnvironmentsRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - including_default_value_fields=False, - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = environment.ListEnvironmentsResponse() - pb_resp = environment.ListEnvironmentsResponse.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_list_environments(resp) - return resp - - class _UpdateEnvironment(EnvironmentsRestStub): - def __hash__(self): - return hash("UpdateEnvironment") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - "updateMask" : {}, } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: environment.UpdateEnvironmentRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> environment.Environment: - r"""Call the update environment method over HTTP. - - Args: - request (~.environment.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: - ~.environment.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 `__. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'patch', - 'uri': '/v2beta1/{environment.name=projects/*/agent/environments/*}', - 'body': 'environment', - }, -{ - 'method': 'patch', - 'uri': '/v2beta1/{environment.name=projects/*/locations/*/agent/environments/*}', - 'body': 'environment', - }, - ] - request, metadata = self._interceptor.pre_update_environment(request, metadata) - pb_request = environment.UpdateEnvironmentRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request['body'], - including_default_value_fields=False, - use_integers_for_enums=True - ) - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - including_default_value_fields=False, - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = environment.Environment() - pb_resp = environment.Environment.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_update_environment(resp) - return resp - - @property - def create_environment(self) -> Callable[ - [environment.CreateEnvironmentRequest], - environment.Environment]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._CreateEnvironment(self._session, self._host, self._interceptor) # type: ignore - - @property - def delete_environment(self) -> Callable[ - [environment.DeleteEnvironmentRequest], - empty_pb2.Empty]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._DeleteEnvironment(self._session, self._host, self._interceptor) # type: ignore - - @property - def get_environment(self) -> Callable[ - [environment.GetEnvironmentRequest], - environment.Environment]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._GetEnvironment(self._session, self._host, self._interceptor) # type: ignore - - @property - def get_environment_history(self) -> Callable[ - [environment.GetEnvironmentHistoryRequest], - environment.EnvironmentHistory]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._GetEnvironmentHistory(self._session, self._host, self._interceptor) # type: ignore - - @property - def list_environments(self) -> Callable[ - [environment.ListEnvironmentsRequest], - environment.ListEnvironmentsResponse]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._ListEnvironments(self._session, self._host, self._interceptor) # type: ignore - - @property - def update_environment(self) -> Callable[ - [environment.UpdateEnvironmentRequest], - environment.Environment]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._UpdateEnvironment(self._session, self._host, self._interceptor) # type: ignore - - @property - def get_location(self): - return self._GetLocation(self._session, self._host, self._interceptor) # type: ignore - - class _GetLocation(EnvironmentsRestStub): - def __call__(self, - request: locations_pb2.GetLocationRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> locations_pb2.Location: - - r"""Call the get location method over HTTP. - - Args: - request (locations_pb2.GetLocationRequest): - The request object for GetLocation method. - 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: - locations_pb2.Location: Response from GetLocation method. - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v2beta1/{name=projects/*/locations/*}', - }, - ] - - request, metadata = self._interceptor.pre_get_location(request, metadata) - request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode( - http_options, **request_kwargs) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json.dumps(transcoded_request['query_params'])) - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - resp = locations_pb2.Location() - resp = json_format.Parse(response.content.decode("utf-8"), resp) - resp = self._interceptor.post_get_location(resp) - return resp - - @property - def list_locations(self): - return self._ListLocations(self._session, self._host, self._interceptor) # type: ignore - - class _ListLocations(EnvironmentsRestStub): - def __call__(self, - request: locations_pb2.ListLocationsRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> locations_pb2.ListLocationsResponse: - - r"""Call the list locations method over HTTP. - - Args: - request (locations_pb2.ListLocationsRequest): - The request object for ListLocations method. - 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: - locations_pb2.ListLocationsResponse: Response from ListLocations method. - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v2beta1/{name=projects/*}/locations', - }, - ] - - request, metadata = self._interceptor.pre_list_locations(request, metadata) - request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode( - http_options, **request_kwargs) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json.dumps(transcoded_request['query_params'])) - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - resp = locations_pb2.ListLocationsResponse() - resp = json_format.Parse(response.content.decode("utf-8"), resp) - resp = self._interceptor.post_list_locations(resp) - return resp - - @property - def cancel_operation(self): - return self._CancelOperation(self._session, self._host, self._interceptor) # type: ignore - - class _CancelOperation(EnvironmentsRestStub): - def __call__(self, - request: operations_pb2.CancelOperationRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> None: - - r"""Call the cancel operation method over HTTP. - - Args: - request (operations_pb2.CancelOperationRequest): - The request object for CancelOperation method. - 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. - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'post', - 'uri': '/v2beta1/{name=projects/*/operations/*}:cancel', - }, -{ - 'method': 'post', - 'uri': '/v2beta1/{name=projects/*/locations/*/operations/*}:cancel', - }, - ] - - request, metadata = self._interceptor.pre_cancel_operation(request, metadata) - request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode( - http_options, **request_kwargs) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json.dumps(transcoded_request['query_params'])) - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - return self._interceptor.post_cancel_operation(None) - - @property - def get_operation(self): - return self._GetOperation(self._session, self._host, self._interceptor) # type: ignore - - class _GetOperation(EnvironmentsRestStub): - def __call__(self, - request: operations_pb2.GetOperationRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> operations_pb2.Operation: - - r"""Call the get operation method over HTTP. - - Args: - request (operations_pb2.GetOperationRequest): - The request object for GetOperation method. - 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: - operations_pb2.Operation: Response from GetOperation method. - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v2beta1/{name=projects/*/operations/*}', - }, -{ - 'method': 'get', - 'uri': '/v2beta1/{name=projects/*/locations/*/operations/*}', - }, - ] - - request, metadata = self._interceptor.pre_get_operation(request, metadata) - request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode( - http_options, **request_kwargs) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json.dumps(transcoded_request['query_params'])) - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - resp = operations_pb2.Operation() - resp = json_format.Parse(response.content.decode("utf-8"), resp) - resp = self._interceptor.post_get_operation(resp) - return resp - - @property - def list_operations(self): - return self._ListOperations(self._session, self._host, self._interceptor) # type: ignore - - class _ListOperations(EnvironmentsRestStub): - def __call__(self, - request: operations_pb2.ListOperationsRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> operations_pb2.ListOperationsResponse: - - r"""Call the list operations method over HTTP. - - Args: - request (operations_pb2.ListOperationsRequest): - The request object for ListOperations method. - 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: - operations_pb2.ListOperationsResponse: Response from ListOperations method. - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v2beta1/{name=projects/*}/operations', - }, -{ - 'method': 'get', - 'uri': '/v2beta1/{name=projects/*/locations/*}/operations', - }, - ] - - request, metadata = self._interceptor.pre_list_operations(request, metadata) - request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode( - http_options, **request_kwargs) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json.dumps(transcoded_request['query_params'])) - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - resp = operations_pb2.ListOperationsResponse() - resp = json_format.Parse(response.content.decode("utf-8"), resp) - resp = self._interceptor.post_list_operations(resp) - return resp - - @property - def kind(self) -> str: - return "rest" - - def close(self): - self._session.close() - - -__all__=( - 'EnvironmentsRestTransport', -) diff --git a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/fulfillments/__init__.py b/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/fulfillments/__init__.py deleted file mode 100644 index ba9b6c08e..000000000 --- a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/fulfillments/__init__.py +++ /dev/null @@ -1,22 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/fulfillments/async_client.py b/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/fulfillments/async_client.py deleted file mode 100644 index f2b615318..000000000 --- a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/fulfillments/async_client.py +++ /dev/null @@ -1,695 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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, Mapping, MutableMapping, MutableSequence, Optional, Sequence, Tuple, Type, Union - -from google.cloud.dialogflow_v2beta1 import gapic_version as package_version - -from google.api_core.client_options import ClientOptions -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import retry as retries -from google.auth import credentials as ga_credentials # type: ignore -from google.oauth2 import service_account # type: ignore - -try: - OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] -except AttributeError: # pragma: NO COVER - OptionalRetry = Union[retries.Retry, object] # type: ignore - -from google.cloud.dialogflow_v2beta1.types import fulfillment -from google.cloud.dialogflow_v2beta1.types import fulfillment as gcd_fulfillment -from google.cloud.location import locations_pb2 # type: ignore -from google.longrunning import operations_pb2 -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 - - @classmethod - def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[ClientOptions] = None): - """Return the API endpoint and client cert source for mutual TLS. - - The client cert source is determined in the following order: - (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the - client cert source is None. - (2) if `client_options.client_cert_source` is provided, use the provided one; if the - default client cert source exists, use the default one; otherwise the client cert - source is None. - - The API endpoint is determined in the following order: - (1) if `client_options.api_endpoint` if provided, use the provided one. - (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the - default mTLS endpoint; if the environment variable is "never", use the default API - endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise - use the default API endpoint. - - More details can be found at https://google.aip.dev/auth/4114. - - Args: - client_options (google.api_core.client_options.ClientOptions): Custom options for the - client. Only the `api_endpoint` and `client_cert_source` properties may be used - in this method. - - Returns: - Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the - client cert source to use. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If any errors happen. - """ - return FulfillmentsClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore - - @property - def transport(self) -> FulfillmentsTransport: - """Returns 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: Optional[ga_credentials.Credentials] = None, - transport: Union[str, FulfillmentsTransport] = "grpc_asyncio", - client_options: Optional[ClientOptions] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates 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: Optional[Union[fulfillment.GetFulfillmentRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> fulfillment.Fulfillment: - r"""Retrieves the fulfillment. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import dialogflow_v2beta1 - - async def sample_get_fulfillment(): - # Create a client - client = dialogflow_v2beta1.FulfillmentsAsyncClient() - - # Initialize request argument(s) - request = dialogflow_v2beta1.GetFulfillmentRequest( - name="name_value", - ) - - # Make the request - response = await client.get_fulfillment(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.dialogflow_v2beta1.types.GetFulfillmentRequest, dict]]): - 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. - # Quick 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: Optional[Union[gcd_fulfillment.UpdateFulfillmentRequest, dict]] = None, - *, - fulfillment: Optional[gcd_fulfillment.Fulfillment] = None, - update_mask: Optional[field_mask_pb2.FieldMask] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gcd_fulfillment.Fulfillment: - r"""Updates the fulfillment. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import dialogflow_v2beta1 - - async def sample_update_fulfillment(): - # Create a client - client = dialogflow_v2beta1.FulfillmentsAsyncClient() - - # Initialize request argument(s) - fulfillment = dialogflow_v2beta1.Fulfillment() - fulfillment.generic_web_service.uri = "uri_value" - fulfillment.name = "name_value" - - request = dialogflow_v2beta1.UpdateFulfillmentRequest( - fulfillment=fulfillment, - ) - - # Make the request - response = await client.update_fulfillment(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.dialogflow_v2beta1.types.UpdateFulfillmentRequest, dict]]): - 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. - # Quick 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 - - async def list_operations( - self, - request: Optional[operations_pb2.ListOperationsRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operations_pb2.ListOperationsResponse: - r"""Lists operations that match the specified filter in the request. - - Args: - request (:class:`~.operations_pb2.ListOperationsRequest`): - The request object. Request message for - `ListOperations` method. - 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: - ~.operations_pb2.ListOperationsResponse: - Response message for ``ListOperations`` method. - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = operations_pb2.ListOperationsRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._client._transport.list_operations, - 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 get_operation( - self, - request: Optional[operations_pb2.GetOperationRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operations_pb2.Operation: - r"""Gets the latest state of a long-running operation. - - Args: - request (:class:`~.operations_pb2.GetOperationRequest`): - The request object. Request message for - `GetOperation` method. - 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: - ~.operations_pb2.Operation: - An ``Operation`` object. - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = operations_pb2.GetOperationRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._client._transport.get_operation, - 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 cancel_operation( - self, - request: Optional[operations_pb2.CancelOperationRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> None: - r"""Starts asynchronous cancellation on a long-running operation. - - The server makes a best effort to cancel the operation, but success - is not guaranteed. If the server doesn't support this method, it returns - `google.rpc.Code.UNIMPLEMENTED`. - - Args: - request (:class:`~.operations_pb2.CancelOperationRequest`): - The request object. Request message for - `CancelOperation` method. - 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: - None - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = operations_pb2.CancelOperationRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._client._transport.cancel_operation, - 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_location( - self, - request: Optional[locations_pb2.GetLocationRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> locations_pb2.Location: - r"""Gets information about a location. - - Args: - request (:class:`~.location_pb2.GetLocationRequest`): - The request object. Request message for - `GetLocation` method. - 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: - ~.location_pb2.Location: - Location object. - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = locations_pb2.GetLocationRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._client._transport.get_location, - 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 list_locations( - self, - request: Optional[locations_pb2.ListLocationsRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> locations_pb2.ListLocationsResponse: - r"""Lists information about the supported locations for this service. - - Args: - request (:class:`~.location_pb2.ListLocationsRequest`): - The request object. Request message for - `ListLocations` method. - 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: - ~.location_pb2.ListLocationsResponse: - Response message for ``ListLocations`` method. - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = locations_pb2.ListLocationsRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._client._transport.list_locations, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("name", request.name),)), - ) - - # Send the request. - response = await rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - async def __aenter__(self): - return self - - async def __aexit__(self, exc_type, exc, tb): - await self.transport.close() - -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) - - -__all__ = ( - "FulfillmentsAsyncClient", -) diff --git a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/fulfillments/client.py b/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/fulfillments/client.py deleted file mode 100644 index 05f3a0128..000000000 --- a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/fulfillments/client.py +++ /dev/null @@ -1,894 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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 os -import re -from typing import Dict, Mapping, MutableMapping, MutableSequence, Optional, Sequence, Tuple, Type, Union, cast - -from google.cloud.dialogflow_v2beta1 import gapic_version as package_version - -from google.api_core import client_options as client_options_lib -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import retry as retries -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 - -try: - OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] -except AttributeError: # pragma: NO COVER - OptionalRetry = Union[retries.Retry, object] # type: ignore - -from google.cloud.dialogflow_v2beta1.types import fulfillment -from google.cloud.dialogflow_v2beta1.types import fulfillment as gcd_fulfillment -from google.cloud.location import locations_pb2 # type: ignore -from google.longrunning import operations_pb2 -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 -from .transports.rest import FulfillmentsRestTransport - - -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 - _transport_registry["rest"] = FulfillmentsRestTransport - - def get_transport_class(cls, - label: Optional[str] = None, - ) -> Type[FulfillmentsTransport]: - """Returns an appropriate transport class. - - Args: - label: The name of the desired transport. If none is - provided, then the first transport in the registry is used. - - Returns: - The transport class to use. - """ - # If a specific transport is requested, return that one. - if label: - return cls._transport_registry[label] - - # No transport is requested; return the default (that is, the first one - # in the dictionary). - return next(iter(cls._transport_registry.values())) - - -class FulfillmentsClient(metaclass=FulfillmentsClientMeta): - """Service for managing - [Fulfillments][google.cloud.dialogflow.v2beta1.Fulfillment]. - """ - - @staticmethod - def _get_default_mtls_endpoint(api_endpoint): - """Converts api endpoint to mTLS endpoint. - - Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to - "*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively. - Args: - api_endpoint (Optional[str]): the api endpoint to convert. - Returns: - str: converted mTLS api endpoint. - """ - if not api_endpoint: - return api_endpoint - - mtls_endpoint_re = re.compile( - r"(?P[^.]+)(?P\.mtls)?(?P\.sandbox)?(?P\.googleapis\.com)?" - ) - - m = mtls_endpoint_re.match(api_endpoint) - name, mtls, sandbox, googledomain = m.groups() - if mtls or not googledomain: - return api_endpoint - - if sandbox: - return api_endpoint.replace( - "sandbox.googleapis.com", "mtls.sandbox.googleapis.com" - ) - - return api_endpoint.replace(".googleapis.com", ".mtls.googleapis.com") - - DEFAULT_ENDPOINT = "dialogflow.googleapis.com" - DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore - DEFAULT_ENDPOINT - ) - - @classmethod - def from_service_account_info(cls, info: dict, *args, **kwargs): - """Creates an instance of this client using the provided credentials - info. - - Args: - info (dict): The service account private key info. - args: Additional arguments to pass to the constructor. - kwargs: Additional arguments to pass to the constructor. - - Returns: - 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: - """Returns 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: - """Returns a fully-qualified fulfillment string.""" - return "projects/{project}/agent/fulfillment".format(project=project, ) - - @staticmethod - def parse_fulfillment_path(path: str) -> Dict[str,str]: - """Parses 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: - """Returns a fully-qualified billing_account string.""" - return "billingAccounts/{billing_account}".format(billing_account=billing_account, ) - - @staticmethod - def parse_common_billing_account_path(path: str) -> Dict[str,str]: - """Parse a billing_account path into its component segments.""" - m = re.match(r"^billingAccounts/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_folder_path(folder: str, ) -> str: - """Returns a fully-qualified folder string.""" - return "folders/{folder}".format(folder=folder, ) - - @staticmethod - def parse_common_folder_path(path: str) -> Dict[str,str]: - """Parse a folder path into its component segments.""" - m = re.match(r"^folders/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_organization_path(organization: str, ) -> str: - """Returns a fully-qualified organization string.""" - return "organizations/{organization}".format(organization=organization, ) - - @staticmethod - def parse_common_organization_path(path: str) -> Dict[str,str]: - """Parse a organization path into its component segments.""" - m = re.match(r"^organizations/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_project_path(project: str, ) -> str: - """Returns a fully-qualified project string.""" - return "projects/{project}".format(project=project, ) - - @staticmethod - def parse_common_project_path(path: str) -> Dict[str,str]: - """Parse a project path into its component segments.""" - m = re.match(r"^projects/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_location_path(project: str, location: str, ) -> str: - """Returns a fully-qualified location string.""" - return "projects/{project}/locations/{location}".format(project=project, location=location, ) - - @staticmethod - def parse_common_location_path(path: str) -> Dict[str,str]: - """Parse a location path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)$", path) - return m.groupdict() if m else {} - - @classmethod - def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[client_options_lib.ClientOptions] = None): - """Return the API endpoint and client cert source for mutual TLS. - - The client cert source is determined in the following order: - (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the - client cert source is None. - (2) if `client_options.client_cert_source` is provided, use the provided one; if the - default client cert source exists, use the default one; otherwise the client cert - source is None. - - The API endpoint is determined in the following order: - (1) if `client_options.api_endpoint` if provided, use the provided one. - (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the - default mTLS endpoint; if the environment variable is "never", use the default API - endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise - use the default API endpoint. - - More details can be found at https://google.aip.dev/auth/4114. - - Args: - client_options (google.api_core.client_options.ClientOptions): Custom options for the - client. Only the `api_endpoint` and `client_cert_source` properties may be used - in this method. - - Returns: - Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the - client cert source to use. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If any errors happen. - """ - if client_options is None: - client_options = client_options_lib.ClientOptions() - use_client_cert = os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false") - use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") - if use_client_cert not in ("true", "false"): - raise ValueError("Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`") - if use_mtls_endpoint not in ("auto", "never", "always"): - raise MutualTLSChannelError("Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`") - - # Figure out the client cert source to use. - client_cert_source = None - if use_client_cert == "true": - if client_options.client_cert_source: - client_cert_source = client_options.client_cert_source - elif mtls.has_default_client_cert_source(): - client_cert_source = mtls.default_client_cert_source() - - # Figure out which api endpoint to use. - if client_options.api_endpoint is not None: - api_endpoint = client_options.api_endpoint - elif use_mtls_endpoint == "always" or (use_mtls_endpoint == "auto" and client_cert_source): - api_endpoint = cls.DEFAULT_MTLS_ENDPOINT - else: - api_endpoint = cls.DEFAULT_ENDPOINT - - return api_endpoint, client_cert_source - - def __init__(self, *, - credentials: Optional[ga_credentials.Credentials] = None, - transport: Optional[Union[str, FulfillmentsTransport]] = None, - client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates 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 (Optional[Union[google.api_core.client_options.ClientOptions, dict]]): 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() - client_options = cast(client_options_lib.ClientOptions, client_options) - - api_endpoint, client_cert_source_func = self.get_mtls_endpoint_and_cert_source(client_options) - - api_key_value = getattr(client_options, "api_key", None) - if api_key_value and credentials: - raise ValueError("client_options.api_key and credentials are mutually exclusive") - - # 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 or api_key_value: - 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: - import google.auth._default # type: ignore - - if api_key_value and hasattr(google.auth._default, "get_api_key_credentials"): - credentials = google.auth._default.get_api_key_credentials(api_key_value) - - Transport = type(self).get_transport_class(transport) - self._transport = Transport( - credentials=credentials, - credentials_file=client_options.credentials_file, - host=api_endpoint, - scopes=client_options.scopes, - client_cert_source_for_mtls=client_cert_source_func, - quota_project_id=client_options.quota_project_id, - client_info=client_info, - always_use_jwt_access=True, - api_audience=client_options.api_audience, - ) - - def get_fulfillment(self, - request: Optional[Union[fulfillment.GetFulfillmentRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> fulfillment.Fulfillment: - r"""Retrieves the fulfillment. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import dialogflow_v2beta1 - - def sample_get_fulfillment(): - # Create a client - client = dialogflow_v2beta1.FulfillmentsClient() - - # Initialize request argument(s) - request = dialogflow_v2beta1.GetFulfillmentRequest( - name="name_value", - ) - - # Make the request - response = client.get_fulfillment(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.dialogflow_v2beta1.types.GetFulfillmentRequest, dict]): - 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. - # Quick 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: Optional[Union[gcd_fulfillment.UpdateFulfillmentRequest, dict]] = None, - *, - fulfillment: Optional[gcd_fulfillment.Fulfillment] = None, - update_mask: Optional[field_mask_pb2.FieldMask] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gcd_fulfillment.Fulfillment: - r"""Updates the fulfillment. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import dialogflow_v2beta1 - - def sample_update_fulfillment(): - # Create a client - client = dialogflow_v2beta1.FulfillmentsClient() - - # Initialize request argument(s) - fulfillment = dialogflow_v2beta1.Fulfillment() - fulfillment.generic_web_service.uri = "uri_value" - fulfillment.name = "name_value" - - request = dialogflow_v2beta1.UpdateFulfillmentRequest( - fulfillment=fulfillment, - ) - - # Make the request - response = client.update_fulfillment(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.dialogflow_v2beta1.types.UpdateFulfillmentRequest, dict]): - 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. - # Quick 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 - - def __enter__(self) -> "FulfillmentsClient": - return self - - def __exit__(self, type, value, traceback): - """Releases underlying transport's resources. - - .. warning:: - ONLY use as a context manager if the transport is NOT shared - with other clients! Exiting the with block will CLOSE the transport - and may cause errors in other clients! - """ - self.transport.close() - - def list_operations( - self, - request: Optional[operations_pb2.ListOperationsRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operations_pb2.ListOperationsResponse: - r"""Lists operations that match the specified filter in the request. - - Args: - request (:class:`~.operations_pb2.ListOperationsRequest`): - The request object. Request message for - `ListOperations` method. - 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: - ~.operations_pb2.ListOperationsResponse: - Response message for ``ListOperations`` method. - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = operations_pb2.ListOperationsRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._transport.list_operations, - 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 = rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - def get_operation( - self, - request: Optional[operations_pb2.GetOperationRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operations_pb2.Operation: - r"""Gets the latest state of a long-running operation. - - Args: - request (:class:`~.operations_pb2.GetOperationRequest`): - The request object. Request message for - `GetOperation` method. - 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: - ~.operations_pb2.Operation: - An ``Operation`` object. - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = operations_pb2.GetOperationRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._transport.get_operation, - 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 = rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - def cancel_operation( - self, - request: Optional[operations_pb2.CancelOperationRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> None: - r"""Starts asynchronous cancellation on a long-running operation. - - The server makes a best effort to cancel the operation, but success - is not guaranteed. If the server doesn't support this method, it returns - `google.rpc.Code.UNIMPLEMENTED`. - - Args: - request (:class:`~.operations_pb2.CancelOperationRequest`): - The request object. Request message for - `CancelOperation` method. - 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: - None - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = operations_pb2.CancelOperationRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._transport.cancel_operation, - 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. - rpc(request, retry=retry, timeout=timeout, metadata=metadata,) - - def get_location( - self, - request: Optional[locations_pb2.GetLocationRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> locations_pb2.Location: - r"""Gets information about a location. - - Args: - request (:class:`~.location_pb2.GetLocationRequest`): - The request object. Request message for - `GetLocation` method. - 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: - ~.location_pb2.Location: - Location object. - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = locations_pb2.GetLocationRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._transport.get_location, - 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 = rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - def list_locations( - self, - request: Optional[locations_pb2.ListLocationsRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> locations_pb2.ListLocationsResponse: - r"""Lists information about the supported locations for this service. - - Args: - request (:class:`~.location_pb2.ListLocationsRequest`): - The request object. Request message for - `ListLocations` method. - 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: - ~.location_pb2.ListLocationsResponse: - Response message for ``ListLocations`` method. - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = locations_pb2.ListLocationsRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._transport.list_locations, - 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 = rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) - - -__all__ = ( - "FulfillmentsClient", -) diff --git a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/fulfillments/transports/__init__.py b/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/fulfillments/transports/__init__.py deleted file mode 100644 index bc9bf0c81..000000000 --- a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/fulfillments/transports/__init__.py +++ /dev/null @@ -1,38 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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 -from .rest import FulfillmentsRestTransport -from .rest import FulfillmentsRestInterceptor - - -# Compile a registry of transports. -_transport_registry = OrderedDict() # type: Dict[str, Type[FulfillmentsTransport]] -_transport_registry['grpc'] = FulfillmentsGrpcTransport -_transport_registry['grpc_asyncio'] = FulfillmentsGrpcAsyncIOTransport -_transport_registry['rest'] = FulfillmentsRestTransport - -__all__ = ( - 'FulfillmentsTransport', - 'FulfillmentsGrpcTransport', - 'FulfillmentsGrpcAsyncIOTransport', - 'FulfillmentsRestTransport', - 'FulfillmentsRestInterceptor', -) diff --git a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/fulfillments/transports/base.py b/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/fulfillments/transports/base.py deleted file mode 100644 index 9db520be5..000000000 --- a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/fulfillments/transports/base.py +++ /dev/null @@ -1,209 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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 - -from google.cloud.dialogflow_v2beta1 import gapic_version as package_version - -import google.auth # type: ignore -import google.api_core -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import retry as retries -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.cloud.location import locations_pb2 # type: ignore -from google.longrunning import operations_pb2 - -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__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: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - api_audience: Optional[str] = None, - **kwargs, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. - scopes (Optional[Sequence[str]]): A list of scopes. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - """ - - scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} - - # Save the scopes. - self._scopes = scopes - - # If no credentials are provided, then determine the appropriate - # defaults. - if credentials and credentials_file: - raise core_exceptions.DuplicateCredentialArgs("'credentials_file' and 'credentials' are mutually exclusive") - - if credentials_file is not None: - credentials, _ = google.auth.load_credentials_from_file( - credentials_file, - **scopes_kwargs, - quota_project_id=quota_project_id - ) - elif credentials is None: - credentials, _ = google.auth.default(**scopes_kwargs, quota_project_id=quota_project_id) - # Don't apply audience if the credentials file passed from user. - if hasattr(credentials, "with_gdch_audience"): - credentials = credentials.with_gdch_audience(api_audience if api_audience else host) - - # If the credentials are service account credentials, then always try to use self signed JWT. - if always_use_jwt_access and isinstance(credentials, service_account.Credentials) and hasattr(service_account.Credentials, "with_always_use_jwt_access"): - credentials = credentials.with_always_use_jwt_access(True) - - # Save the credentials. - self._credentials = credentials - - # Save the hostname. Default to port 443 (HTTPS) if none is specified. - if ':' not in host: - host += ':443' - self._host = host - - 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, - ), - } - - def close(self): - """Closes resources associated with the transport. - - .. warning:: - Only call this method if the transport is NOT shared - with other clients - this may cause errors in other clients! - """ - raise NotImplementedError() - - @property - def 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() - - @property - def list_operations( - self, - ) -> Callable[ - [operations_pb2.ListOperationsRequest], - Union[operations_pb2.ListOperationsResponse, Awaitable[operations_pb2.ListOperationsResponse]], - ]: - raise NotImplementedError() - - @property - def get_operation( - self, - ) -> Callable[ - [operations_pb2.GetOperationRequest], - Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], - ]: - raise NotImplementedError() - - @property - def cancel_operation( - self, - ) -> Callable[ - [operations_pb2.CancelOperationRequest], - None, - ]: - raise NotImplementedError() - - @property - def get_location(self, - ) -> Callable[ - [locations_pb2.GetLocationRequest], - Union[locations_pb2.Location, Awaitable[locations_pb2.Location]], - ]: - raise NotImplementedError() - - @property - def list_locations(self, - ) -> Callable[ - [locations_pb2.ListLocationsRequest], - Union[locations_pb2.ListLocationsResponse, Awaitable[locations_pb2.ListLocationsResponse]], - ]: - raise NotImplementedError() - - @property - def kind(self) -> str: - raise NotImplementedError() - - -__all__ = ( - 'FulfillmentsTransport', -) diff --git a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/fulfillments/transports/grpc.py b/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/fulfillments/transports/grpc.py deleted file mode 100644 index dd1bf4ef9..000000000 --- a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/fulfillments/transports/grpc.py +++ /dev/null @@ -1,384 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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 -from google.api_core import gapic_v1 -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 google.cloud.location import locations_pb2 # type: ignore -from google.longrunning import operations_pb2 -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: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - channel: Optional[grpc.Channel] = None, - api_mtls_endpoint: Optional[str] = None, - client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, - ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, - client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - api_audience: Optional[str] = None, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - This argument is ignored if ``channel`` is provided. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional(Sequence[str])): A list of scopes. This argument is - ignored if ``channel`` is provided. - channel (Optional[grpc.Channel]): A ``Channel`` instance through - which to make calls. - api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. - If provided, it overrides the ``host`` argument and tries to create - a mutual TLS channel with client SSL credentials from - ``client_cert_source`` or application default SSL credentials. - client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): - Deprecated. A callback to provide client SSL certificate bytes and - private key bytes, both in PEM format. It is ignored if - ``api_mtls_endpoint`` is None. - ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials - for the grpc channel. It is ignored if ``channel`` is provided. - client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): - A callback to provide client certificate bytes and private key bytes, - both in PEM format. It is used to configure a mutual TLS channel. It is - ignored if ``channel`` or ``ssl_channel_credentials`` is provided. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport - creation failed for any reason. - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - self._grpc_channel = None - self._ssl_channel_credentials = ssl_channel_credentials - self._stubs: Dict[str, Callable] = {} - - if api_mtls_endpoint: - warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) - if client_cert_source: - warnings.warn("client_cert_source is deprecated", DeprecationWarning) - - if channel: - # Ignore credentials if a channel was passed. - credentials = False - # If a channel was explicitly provided, set it. - self._grpc_channel = channel - self._ssl_channel_credentials = None - - else: - if api_mtls_endpoint: - host = api_mtls_endpoint - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - self._ssl_channel_credentials = SslCredentials().ssl_credentials - - else: - if client_cert_source_for_mtls and not ssl_channel_credentials: - cert, key = client_cert_source_for_mtls() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - - # The base transport sets the host, credentials and scopes - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes, - quota_project_id=quota_project_id, - client_info=client_info, - always_use_jwt_access=always_use_jwt_access, - api_audience=api_audience, - ) - - if not self._grpc_channel: - self._grpc_channel = type(self).create_channel( - self._host, - # use the credentials which are saved - credentials=self._credentials, - # Set ``credentials_file`` to ``None`` here as - # the credentials that we saved earlier should be used. - credentials_file=None, - 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: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - **kwargs) -> grpc.Channel: - """Create and return a gRPC channel object. - Args: - host (Optional[str]): The host for the channel to use. - credentials (Optional[~.Credentials]): The - authorization credentials to attach to requests. These - credentials identify this application to the service. If - none are specified, the client will attempt to ascertain - the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - kwargs (Optional[dict]): Keyword arguments, which are passed to the - channel creation. - Returns: - grpc.Channel: A gRPC channel object. - - Raises: - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - - return grpc_helpers.create_channel( - host, - credentials=credentials, - credentials_file=credentials_file, - quota_project_id=quota_project_id, - default_scopes=cls.AUTH_SCOPES, - scopes=scopes, - default_host=cls.DEFAULT_HOST, - **kwargs - ) - - @property - def grpc_channel(self) -> grpc.Channel: - """Return the channel designed to connect to this service. - """ - return self._grpc_channel - - @property - def 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'] - - def close(self): - self.grpc_channel.close() - - @property - def cancel_operation( - self, - ) -> Callable[[operations_pb2.CancelOperationRequest], None]: - r"""Return a callable for the cancel_operation method over gRPC. - """ - # 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 "cancel_operation" not in self._stubs: - self._stubs["cancel_operation"] = self.grpc_channel.unary_unary( - "/google.longrunning.Operations/CancelOperation", - request_serializer=operations_pb2.CancelOperationRequest.SerializeToString, - response_deserializer=None, - ) - return self._stubs["cancel_operation"] - - @property - def get_operation( - self, - ) -> Callable[[operations_pb2.GetOperationRequest], operations_pb2.Operation]: - r"""Return a callable for the get_operation method over gRPC. - """ - # 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_operation" not in self._stubs: - self._stubs["get_operation"] = self.grpc_channel.unary_unary( - "/google.longrunning.Operations/GetOperation", - request_serializer=operations_pb2.GetOperationRequest.SerializeToString, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs["get_operation"] - - @property - def list_operations( - self, - ) -> Callable[[operations_pb2.ListOperationsRequest], operations_pb2.ListOperationsResponse]: - r"""Return a callable for the list_operations method over gRPC. - """ - # 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_operations" not in self._stubs: - self._stubs["list_operations"] = self.grpc_channel.unary_unary( - "/google.longrunning.Operations/ListOperations", - request_serializer=operations_pb2.ListOperationsRequest.SerializeToString, - response_deserializer=operations_pb2.ListOperationsResponse.FromString, - ) - return self._stubs["list_operations"] - - @property - def list_locations( - self, - ) -> Callable[[locations_pb2.ListLocationsRequest], locations_pb2.ListLocationsResponse]: - r"""Return a callable for the list locations method over gRPC. - """ - # 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_locations" not in self._stubs: - self._stubs["list_locations"] = self.grpc_channel.unary_unary( - "/google.cloud.location.Locations/ListLocations", - request_serializer=locations_pb2.ListLocationsRequest.SerializeToString, - response_deserializer=locations_pb2.ListLocationsResponse.FromString, - ) - return self._stubs["list_locations"] - - @property - def get_location( - self, - ) -> Callable[[locations_pb2.GetLocationRequest], locations_pb2.Location]: - r"""Return a callable for the list locations method over gRPC. - """ - # 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_location" not in self._stubs: - self._stubs["get_location"] = self.grpc_channel.unary_unary( - "/google.cloud.location.Locations/GetLocation", - request_serializer=locations_pb2.GetLocationRequest.SerializeToString, - response_deserializer=locations_pb2.Location.FromString, - ) - return self._stubs["get_location"] - - @property - def kind(self) -> str: - return "grpc" - - -__all__ = ( - 'FulfillmentsGrpcTransport', -) diff --git a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/fulfillments/transports/grpc_asyncio.py b/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/fulfillments/transports/grpc_asyncio.py deleted file mode 100644 index ea0e3de31..000000000 --- a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/fulfillments/transports/grpc_asyncio.py +++ /dev/null @@ -1,383 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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 -from google.api_core import grpc_helpers_async -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore - -import grpc # type: ignore -from grpc.experimental import aio # type: ignore - -from google.cloud.dialogflow_v2beta1.types import fulfillment -from google.cloud.dialogflow_v2beta1.types import fulfillment as gcd_fulfillment -from google.cloud.location import locations_pb2 # type: ignore -from google.longrunning import operations_pb2 -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: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - **kwargs) -> aio.Channel: - """Create and return a gRPC AsyncIO channel object. - Args: - host (Optional[str]): The host for the channel to use. - credentials (Optional[~.Credentials]): The - authorization credentials to attach to requests. These - credentials identify this application to the service. If - none are specified, the client will attempt to ascertain - the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - kwargs (Optional[dict]): Keyword arguments, which are passed to the - channel creation. - Returns: - aio.Channel: A gRPC AsyncIO channel object. - """ - - return grpc_helpers_async.create_channel( - host, - credentials=credentials, - credentials_file=credentials_file, - quota_project_id=quota_project_id, - default_scopes=cls.AUTH_SCOPES, - scopes=scopes, - default_host=cls.DEFAULT_HOST, - **kwargs - ) - - def __init__(self, *, - host: str = 'dialogflow.googleapis.com', - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - channel: Optional[aio.Channel] = None, - api_mtls_endpoint: Optional[str] = None, - client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, - ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, - client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - api_audience: Optional[str] = None, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - This argument is ignored if ``channel`` is provided. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - channel (Optional[aio.Channel]): A ``Channel`` instance through - which to make calls. - api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. - If provided, it overrides the ``host`` argument and tries to create - a mutual TLS channel with client SSL credentials from - ``client_cert_source`` or application default SSL credentials. - client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): - Deprecated. A callback to provide client SSL certificate bytes and - private key bytes, both in PEM format. It is ignored if - ``api_mtls_endpoint`` is None. - ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials - for the grpc channel. It is ignored if ``channel`` is provided. - client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): - A callback to provide client certificate bytes and private key bytes, - both in PEM format. It is used to configure a mutual TLS channel. It is - ignored if ``channel`` or ``ssl_channel_credentials`` is provided. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - - Raises: - google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport - creation failed for any reason. - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - self._grpc_channel = None - self._ssl_channel_credentials = ssl_channel_credentials - self._stubs: Dict[str, Callable] = {} - - if api_mtls_endpoint: - warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) - if client_cert_source: - warnings.warn("client_cert_source is deprecated", DeprecationWarning) - - if channel: - # Ignore credentials if a channel was passed. - credentials = False - # If a channel was explicitly provided, set it. - self._grpc_channel = channel - self._ssl_channel_credentials = None - else: - if api_mtls_endpoint: - host = api_mtls_endpoint - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - self._ssl_channel_credentials = SslCredentials().ssl_credentials - - else: - if client_cert_source_for_mtls and not ssl_channel_credentials: - cert, key = client_cert_source_for_mtls() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - - # The base transport sets the host, credentials and scopes - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes, - quota_project_id=quota_project_id, - client_info=client_info, - always_use_jwt_access=always_use_jwt_access, - api_audience=api_audience, - ) - - if not self._grpc_channel: - self._grpc_channel = type(self).create_channel( - self._host, - # use the credentials which are saved - credentials=self._credentials, - # Set ``credentials_file`` to ``None`` here as - # the credentials that we saved earlier should be used. - credentials_file=None, - 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'] - - def close(self): - return self.grpc_channel.close() - - @property - def cancel_operation( - self, - ) -> Callable[[operations_pb2.CancelOperationRequest], None]: - r"""Return a callable for the cancel_operation method over gRPC. - """ - # 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 "cancel_operation" not in self._stubs: - self._stubs["cancel_operation"] = self.grpc_channel.unary_unary( - "/google.longrunning.Operations/CancelOperation", - request_serializer=operations_pb2.CancelOperationRequest.SerializeToString, - response_deserializer=None, - ) - return self._stubs["cancel_operation"] - - @property - def get_operation( - self, - ) -> Callable[[operations_pb2.GetOperationRequest], operations_pb2.Operation]: - r"""Return a callable for the get_operation method over gRPC. - """ - # 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_operation" not in self._stubs: - self._stubs["get_operation"] = self.grpc_channel.unary_unary( - "/google.longrunning.Operations/GetOperation", - request_serializer=operations_pb2.GetOperationRequest.SerializeToString, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs["get_operation"] - - @property - def list_operations( - self, - ) -> Callable[[operations_pb2.ListOperationsRequest], operations_pb2.ListOperationsResponse]: - r"""Return a callable for the list_operations method over gRPC. - """ - # 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_operations" not in self._stubs: - self._stubs["list_operations"] = self.grpc_channel.unary_unary( - "/google.longrunning.Operations/ListOperations", - request_serializer=operations_pb2.ListOperationsRequest.SerializeToString, - response_deserializer=operations_pb2.ListOperationsResponse.FromString, - ) - return self._stubs["list_operations"] - - @property - def list_locations( - self, - ) -> Callable[[locations_pb2.ListLocationsRequest], locations_pb2.ListLocationsResponse]: - r"""Return a callable for the list locations method over gRPC. - """ - # 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_locations" not in self._stubs: - self._stubs["list_locations"] = self.grpc_channel.unary_unary( - "/google.cloud.location.Locations/ListLocations", - request_serializer=locations_pb2.ListLocationsRequest.SerializeToString, - response_deserializer=locations_pb2.ListLocationsResponse.FromString, - ) - return self._stubs["list_locations"] - - @property - def get_location( - self, - ) -> Callable[[locations_pb2.GetLocationRequest], locations_pb2.Location]: - r"""Return a callable for the list locations method over gRPC. - """ - # 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_location" not in self._stubs: - self._stubs["get_location"] = self.grpc_channel.unary_unary( - "/google.cloud.location.Locations/GetLocation", - request_serializer=locations_pb2.GetLocationRequest.SerializeToString, - response_deserializer=locations_pb2.Location.FromString, - ) - return self._stubs["get_location"] - - -__all__ = ( - 'FulfillmentsGrpcAsyncIOTransport', -) diff --git a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/fulfillments/transports/rest.py b/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/fulfillments/transports/rest.py deleted file mode 100644 index 4f8f314ab..000000000 --- a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/fulfillments/transports/rest.py +++ /dev/null @@ -1,878 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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 google.auth.transport.requests import AuthorizedSession # type: ignore -import json # type: ignore -import grpc # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore -from google.auth import credentials as ga_credentials # type: ignore -from google.api_core import exceptions as core_exceptions -from google.api_core import retry as retries -from google.api_core import rest_helpers -from google.api_core import rest_streaming -from google.api_core import path_template -from google.api_core import gapic_v1 - -from google.protobuf import json_format -from google.cloud.location import locations_pb2 # type: ignore -from google.longrunning import operations_pb2 -from requests import __version__ as requests_version -import dataclasses -import re -from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union -import warnings - -try: - OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] -except AttributeError: # pragma: NO COVER - OptionalRetry = Union[retries.Retry, object] # 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 as BASE_DEFAULT_CLIENT_INFO - - -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=BASE_DEFAULT_CLIENT_INFO.gapic_version, - grpc_version=None, - rest_version=requests_version, -) - - -class FulfillmentsRestInterceptor: - """Interceptor for Fulfillments. - - Interceptors are used to manipulate requests, request metadata, and responses - in arbitrary ways. - Example use cases include: - * Logging - * Verifying requests according to service or custom semantics - * Stripping extraneous information from responses - - These use cases and more can be enabled by injecting an - instance of a custom subclass when constructing the FulfillmentsRestTransport. - - .. code-block:: python - class MyCustomFulfillmentsInterceptor(FulfillmentsRestInterceptor): - def pre_get_fulfillment(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_get_fulfillment(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_update_fulfillment(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_update_fulfillment(self, response): - logging.log(f"Received response: {response}") - return response - - transport = FulfillmentsRestTransport(interceptor=MyCustomFulfillmentsInterceptor()) - client = FulfillmentsClient(transport=transport) - - - """ - def pre_get_fulfillment(self, request: fulfillment.GetFulfillmentRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[fulfillment.GetFulfillmentRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for get_fulfillment - - Override in a subclass to manipulate the request or metadata - before they are sent to the Fulfillments server. - """ - return request, metadata - - def post_get_fulfillment(self, response: fulfillment.Fulfillment) -> fulfillment.Fulfillment: - """Post-rpc interceptor for get_fulfillment - - Override in a subclass to manipulate the response - after it is returned by the Fulfillments server but before - it is returned to user code. - """ - return response - def pre_update_fulfillment(self, request: gcd_fulfillment.UpdateFulfillmentRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[gcd_fulfillment.UpdateFulfillmentRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for update_fulfillment - - Override in a subclass to manipulate the request or metadata - before they are sent to the Fulfillments server. - """ - return request, metadata - - def post_update_fulfillment(self, response: gcd_fulfillment.Fulfillment) -> gcd_fulfillment.Fulfillment: - """Post-rpc interceptor for update_fulfillment - - Override in a subclass to manipulate the response - after it is returned by the Fulfillments server but before - it is returned to user code. - """ - return response - - def pre_get_location( - self, request: locations_pb2.GetLocationRequest, metadata: Sequence[Tuple[str, str]] - ) -> Tuple[locations_pb2.GetLocationRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for get_location - - Override in a subclass to manipulate the request or metadata - before they are sent to the Fulfillments server. - """ - return request, metadata - - def post_get_location( - self, response: locations_pb2.Location - ) -> locations_pb2.Location: - """Post-rpc interceptor for get_location - - Override in a subclass to manipulate the response - after it is returned by the Fulfillments server but before - it is returned to user code. - """ - return response - def pre_list_locations( - self, request: locations_pb2.ListLocationsRequest, metadata: Sequence[Tuple[str, str]] - ) -> Tuple[locations_pb2.ListLocationsRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for list_locations - - Override in a subclass to manipulate the request or metadata - before they are sent to the Fulfillments server. - """ - return request, metadata - - def post_list_locations( - self, response: locations_pb2.ListLocationsResponse - ) -> locations_pb2.ListLocationsResponse: - """Post-rpc interceptor for list_locations - - Override in a subclass to manipulate the response - after it is returned by the Fulfillments server but before - it is returned to user code. - """ - return response - def pre_cancel_operation( - self, request: operations_pb2.CancelOperationRequest, metadata: Sequence[Tuple[str, str]] - ) -> Tuple[operations_pb2.CancelOperationRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for cancel_operation - - Override in a subclass to manipulate the request or metadata - before they are sent to the Fulfillments server. - """ - return request, metadata - - def post_cancel_operation( - self, response: None - ) -> None: - """Post-rpc interceptor for cancel_operation - - Override in a subclass to manipulate the response - after it is returned by the Fulfillments server but before - it is returned to user code. - """ - return response - def pre_get_operation( - self, request: operations_pb2.GetOperationRequest, metadata: Sequence[Tuple[str, str]] - ) -> Tuple[operations_pb2.GetOperationRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for get_operation - - Override in a subclass to manipulate the request or metadata - before they are sent to the Fulfillments server. - """ - return request, metadata - - def post_get_operation( - self, response: operations_pb2.Operation - ) -> operations_pb2.Operation: - """Post-rpc interceptor for get_operation - - Override in a subclass to manipulate the response - after it is returned by the Fulfillments server but before - it is returned to user code. - """ - return response - def pre_list_operations( - self, request: operations_pb2.ListOperationsRequest, metadata: Sequence[Tuple[str, str]] - ) -> Tuple[operations_pb2.ListOperationsRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for list_operations - - Override in a subclass to manipulate the request or metadata - before they are sent to the Fulfillments server. - """ - return request, metadata - - def post_list_operations( - self, response: operations_pb2.ListOperationsResponse - ) -> operations_pb2.ListOperationsResponse: - """Post-rpc interceptor for list_operations - - Override in a subclass to manipulate the response - after it is returned by the Fulfillments server but before - it is returned to user code. - """ - return response - - -@dataclasses.dataclass -class FulfillmentsRestStub: - _session: AuthorizedSession - _host: str - _interceptor: FulfillmentsRestInterceptor - - -class FulfillmentsRestTransport(FulfillmentsTransport): - """REST 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 JSON representations of protocol buffers over HTTP/1.1 - - """ - - def __init__(self, *, - host: str = 'dialogflow.googleapis.com', - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - client_cert_source_for_mtls: Optional[Callable[[ - ], Tuple[bytes, bytes]]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - url_scheme: str = 'https', - interceptor: Optional[FulfillmentsRestInterceptor] = None, - api_audience: Optional[str] = None, - ) -> 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 ignored if ``channel`` is provided. - scopes (Optional(Sequence[str])): A list of scopes. This argument is - ignored if ``channel`` is provided. - client_cert_source_for_mtls (Callable[[], Tuple[bytes, bytes]]): Client - certificate to configure mutual TLS HTTP channel. It is ignored - if ``channel`` is provided. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you are developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - url_scheme: the protocol scheme for the API endpoint. Normally - "https", but for testing or local servers, - "http" can be specified. - """ - # Run the base constructor - # TODO(yon-mg): resolve other ctor params i.e. scopes, quota, etc. - # TODO: When custom host (api_endpoint) is set, `scopes` must *also* be set on the - # credentials object - maybe_url_match = re.match("^(?Phttp(?:s)?://)?(?P.*)$", host) - if maybe_url_match is None: - raise ValueError(f"Unexpected hostname structure: {host}") # pragma: NO COVER - - url_match_items = maybe_url_match.groupdict() - - host = f"{url_scheme}://{host}" if not url_match_items["scheme"] else host - - super().__init__( - host=host, - credentials=credentials, - client_info=client_info, - always_use_jwt_access=always_use_jwt_access, - api_audience=api_audience - ) - self._session = AuthorizedSession( - self._credentials, default_host=self.DEFAULT_HOST) - if client_cert_source_for_mtls: - self._session.configure_mtls_channel(client_cert_source_for_mtls) - self._interceptor = interceptor or FulfillmentsRestInterceptor() - self._prep_wrapped_messages(client_info) - - class _GetFulfillment(FulfillmentsRestStub): - def __hash__(self): - return hash("GetFulfillment") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: fulfillment.GetFulfillmentRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> fulfillment.Fulfillment: - r"""Call the get fulfillment method over HTTP. - - Args: - request (~.fulfillment.GetFulfillmentRequest): - The request object. The request message for - [Fulfillments.GetFulfillment][google.cloud.dialogflow.v2beta1.Fulfillments.GetFulfillment]. - 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: - ~.fulfillment.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 `__. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v2beta1/{name=projects/*/agent/fulfillment}', - }, -{ - 'method': 'get', - 'uri': '/v2beta1/{name=projects/*/locations/*/agent/fulfillment}', - }, - ] - request, metadata = self._interceptor.pre_get_fulfillment(request, metadata) - pb_request = fulfillment.GetFulfillmentRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - including_default_value_fields=False, - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = fulfillment.Fulfillment() - pb_resp = fulfillment.Fulfillment.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_get_fulfillment(resp) - return resp - - class _UpdateFulfillment(FulfillmentsRestStub): - def __hash__(self): - return hash("UpdateFulfillment") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - "updateMask" : {}, } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: gcd_fulfillment.UpdateFulfillmentRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> gcd_fulfillment.Fulfillment: - r"""Call the update fulfillment method over HTTP. - - Args: - request (~.gcd_fulfillment.UpdateFulfillmentRequest): - The request object. The request message for - [Fulfillments.UpdateFulfillment][google.cloud.dialogflow.v2beta1.Fulfillments.UpdateFulfillment]. - 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: - ~.gcd_fulfillment.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 `__. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'patch', - 'uri': '/v2beta1/{fulfillment.name=projects/*/agent/fulfillment}', - 'body': 'fulfillment', - }, -{ - 'method': 'patch', - 'uri': '/v2beta1/{fulfillment.name=projects/*/locations/*/agent/fulfillment}', - 'body': 'fulfillment', - }, - ] - request, metadata = self._interceptor.pre_update_fulfillment(request, metadata) - pb_request = gcd_fulfillment.UpdateFulfillmentRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request['body'], - including_default_value_fields=False, - use_integers_for_enums=True - ) - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - including_default_value_fields=False, - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = gcd_fulfillment.Fulfillment() - pb_resp = gcd_fulfillment.Fulfillment.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_update_fulfillment(resp) - return resp - - @property - def get_fulfillment(self) -> Callable[ - [fulfillment.GetFulfillmentRequest], - fulfillment.Fulfillment]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._GetFulfillment(self._session, self._host, self._interceptor) # type: ignore - - @property - def update_fulfillment(self) -> Callable[ - [gcd_fulfillment.UpdateFulfillmentRequest], - gcd_fulfillment.Fulfillment]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._UpdateFulfillment(self._session, self._host, self._interceptor) # type: ignore - - @property - def get_location(self): - return self._GetLocation(self._session, self._host, self._interceptor) # type: ignore - - class _GetLocation(FulfillmentsRestStub): - def __call__(self, - request: locations_pb2.GetLocationRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> locations_pb2.Location: - - r"""Call the get location method over HTTP. - - Args: - request (locations_pb2.GetLocationRequest): - The request object for GetLocation method. - 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: - locations_pb2.Location: Response from GetLocation method. - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v2beta1/{name=projects/*/locations/*}', - }, - ] - - request, metadata = self._interceptor.pre_get_location(request, metadata) - request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode( - http_options, **request_kwargs) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json.dumps(transcoded_request['query_params'])) - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - resp = locations_pb2.Location() - resp = json_format.Parse(response.content.decode("utf-8"), resp) - resp = self._interceptor.post_get_location(resp) - return resp - - @property - def list_locations(self): - return self._ListLocations(self._session, self._host, self._interceptor) # type: ignore - - class _ListLocations(FulfillmentsRestStub): - def __call__(self, - request: locations_pb2.ListLocationsRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> locations_pb2.ListLocationsResponse: - - r"""Call the list locations method over HTTP. - - Args: - request (locations_pb2.ListLocationsRequest): - The request object for ListLocations method. - 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: - locations_pb2.ListLocationsResponse: Response from ListLocations method. - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v2beta1/{name=projects/*}/locations', - }, - ] - - request, metadata = self._interceptor.pre_list_locations(request, metadata) - request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode( - http_options, **request_kwargs) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json.dumps(transcoded_request['query_params'])) - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - resp = locations_pb2.ListLocationsResponse() - resp = json_format.Parse(response.content.decode("utf-8"), resp) - resp = self._interceptor.post_list_locations(resp) - return resp - - @property - def cancel_operation(self): - return self._CancelOperation(self._session, self._host, self._interceptor) # type: ignore - - class _CancelOperation(FulfillmentsRestStub): - def __call__(self, - request: operations_pb2.CancelOperationRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> None: - - r"""Call the cancel operation method over HTTP. - - Args: - request (operations_pb2.CancelOperationRequest): - The request object for CancelOperation method. - 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. - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'post', - 'uri': '/v2beta1/{name=projects/*/operations/*}:cancel', - }, -{ - 'method': 'post', - 'uri': '/v2beta1/{name=projects/*/locations/*/operations/*}:cancel', - }, - ] - - request, metadata = self._interceptor.pre_cancel_operation(request, metadata) - request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode( - http_options, **request_kwargs) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json.dumps(transcoded_request['query_params'])) - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - return self._interceptor.post_cancel_operation(None) - - @property - def get_operation(self): - return self._GetOperation(self._session, self._host, self._interceptor) # type: ignore - - class _GetOperation(FulfillmentsRestStub): - def __call__(self, - request: operations_pb2.GetOperationRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> operations_pb2.Operation: - - r"""Call the get operation method over HTTP. - - Args: - request (operations_pb2.GetOperationRequest): - The request object for GetOperation method. - 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: - operations_pb2.Operation: Response from GetOperation method. - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v2beta1/{name=projects/*/operations/*}', - }, -{ - 'method': 'get', - 'uri': '/v2beta1/{name=projects/*/locations/*/operations/*}', - }, - ] - - request, metadata = self._interceptor.pre_get_operation(request, metadata) - request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode( - http_options, **request_kwargs) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json.dumps(transcoded_request['query_params'])) - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - resp = operations_pb2.Operation() - resp = json_format.Parse(response.content.decode("utf-8"), resp) - resp = self._interceptor.post_get_operation(resp) - return resp - - @property - def list_operations(self): - return self._ListOperations(self._session, self._host, self._interceptor) # type: ignore - - class _ListOperations(FulfillmentsRestStub): - def __call__(self, - request: operations_pb2.ListOperationsRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> operations_pb2.ListOperationsResponse: - - r"""Call the list operations method over HTTP. - - Args: - request (operations_pb2.ListOperationsRequest): - The request object for ListOperations method. - 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: - operations_pb2.ListOperationsResponse: Response from ListOperations method. - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v2beta1/{name=projects/*}/operations', - }, -{ - 'method': 'get', - 'uri': '/v2beta1/{name=projects/*/locations/*}/operations', - }, - ] - - request, metadata = self._interceptor.pre_list_operations(request, metadata) - request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode( - http_options, **request_kwargs) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json.dumps(transcoded_request['query_params'])) - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - resp = operations_pb2.ListOperationsResponse() - resp = json_format.Parse(response.content.decode("utf-8"), resp) - resp = self._interceptor.post_list_operations(resp) - return resp - - @property - def kind(self) -> str: - return "rest" - - def close(self): - self._session.close() - - -__all__=( - 'FulfillmentsRestTransport', -) diff --git a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/intents/__init__.py b/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/intents/__init__.py deleted file mode 100644 index 536f6a0a2..000000000 --- a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/intents/__init__.py +++ /dev/null @@ -1,22 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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 IntentsClient -from .async_client import IntentsAsyncClient - -__all__ = ( - 'IntentsClient', - 'IntentsAsyncClient', -) diff --git a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/intents/async_client.py b/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/intents/async_client.py deleted file mode 100644 index b4a9f2b28..000000000 --- a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/intents/async_client.py +++ /dev/null @@ -1,1418 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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, Mapping, MutableMapping, MutableSequence, Optional, Sequence, Tuple, Type, Union - -from google.cloud.dialogflow_v2beta1 import gapic_version as package_version - -from google.api_core.client_options import ClientOptions -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import retry as retries -from google.auth import credentials as ga_credentials # type: ignore -from google.oauth2 import service_account # type: ignore - -try: - OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] -except AttributeError: # pragma: NO COVER - OptionalRetry = Union[retries.Retry, object] # type: ignore - -from google.api_core import operation # type: ignore -from google.api_core import operation_async # type: ignore -from google.cloud.dialogflow_v2beta1.services.intents import pagers -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.cloud.location import locations_pb2 # type: ignore -from google.longrunning import operations_pb2 -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 - - -class IntentsAsyncClient: - """Service for managing - [Intents][google.cloud.dialogflow.v2beta1.Intent]. - """ - - _client: IntentsClient - - DEFAULT_ENDPOINT = IntentsClient.DEFAULT_ENDPOINT - DEFAULT_MTLS_ENDPOINT = IntentsClient.DEFAULT_MTLS_ENDPOINT - - context_path = staticmethod(IntentsClient.context_path) - 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) - - @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: - IntentsAsyncClient: The constructed client. - """ - return IntentsClient.from_service_account_info.__func__(IntentsAsyncClient, 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: - IntentsAsyncClient: The constructed client. - """ - return IntentsClient.from_service_account_file.__func__(IntentsAsyncClient, filename, *args, **kwargs) # type: ignore - - from_service_account_json = from_service_account_file - - @classmethod - def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[ClientOptions] = None): - """Return the API endpoint and client cert source for mutual TLS. - - The client cert source is determined in the following order: - (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the - client cert source is None. - (2) if `client_options.client_cert_source` is provided, use the provided one; if the - default client cert source exists, use the default one; otherwise the client cert - source is None. - - The API endpoint is determined in the following order: - (1) if `client_options.api_endpoint` if provided, use the provided one. - (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the - default mTLS endpoint; if the environment variable is "never", use the default API - endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise - use the default API endpoint. - - More details can be found at https://google.aip.dev/auth/4114. - - Args: - client_options (google.api_core.client_options.ClientOptions): Custom options for the - client. Only the `api_endpoint` and `client_cert_source` properties may be used - in this method. - - Returns: - Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the - client cert source to use. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If any errors happen. - """ - return IntentsClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore - - @property - def transport(self) -> IntentsTransport: - """Returns the transport used by the client instance. - - Returns: - IntentsTransport: The transport used by the client instance. - """ - return self._client.transport - - get_transport_class = functools.partial(type(IntentsClient).get_transport_class, type(IntentsClient)) - - def __init__(self, *, - credentials: Optional[ga_credentials.Credentials] = None, - transport: Union[str, IntentsTransport] = "grpc_asyncio", - client_options: Optional[ClientOptions] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the intents 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, ~.IntentsTransport]): 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 = IntentsClient( - credentials=credentials, - transport=transport, - client_options=client_options, - client_info=client_info, - - ) - - async def list_intents(self, - request: Optional[Union[intent.ListIntentsRequest, dict]] = None, - *, - parent: Optional[str] = None, - language_code: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListIntentsAsyncPager: - r"""Returns the list of all intents in the specified - agent. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import dialogflow_v2beta1 - - async def sample_list_intents(): - # Create a client - client = dialogflow_v2beta1.IntentsAsyncClient() - - # Initialize request argument(s) - request = dialogflow_v2beta1.ListIntentsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_intents(request=request) - - # Handle the response - async for response in page_result: - print(response) - - Args: - request (Optional[Union[google.cloud.dialogflow_v2beta1.types.ListIntentsRequest, dict]]): - The request object. The request message for - [Intents.ListIntents][google.cloud.dialogflow.v2beta1.Intents.ListIntents]. - parent (:class:`str`): - Required. The agent to list all intents from. Format: - ``projects//agent`` or - ``projects//locations//agent``. - - Alternatively, you can specify the environment to list - intents for. Format: - ``projects//agent/environments/`` - or - ``projects//locations//agent/environments/``. - Note: training phrases of the intents will not be - returned for non-draft environment. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - language_code (:class:`str`): - Optional. The language used to access language-specific - data. If not specified, the agent's default language is - used. For more information, see `Multilingual intent and - entity - data `__. - - 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. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.dialogflow_v2beta1.services.intents.pagers.ListIntentsAsyncPager: - The response message for - [Intents.ListIntents][google.cloud.dialogflow.v2beta1.Intents.ListIntents]. - - Iterating over this object will yield results and - resolve additional pages automatically. - - """ - # Create or coerce a protobuf request object. - # Quick 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, language_code]) - 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 = 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: - request.language_code = language_code - - # 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_intents, - 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.ListIntentsAsyncPager( - method=rpc, - request=request, - response=response, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def get_intent(self, - request: Optional[Union[intent.GetIntentRequest, dict]] = None, - *, - name: Optional[str] = None, - language_code: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> intent.Intent: - r"""Retrieves the specified intent. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import dialogflow_v2beta1 - - async def sample_get_intent(): - # Create a client - client = dialogflow_v2beta1.IntentsAsyncClient() - - # Initialize request argument(s) - request = dialogflow_v2beta1.GetIntentRequest( - name="name_value", - ) - - # Make the request - response = await client.get_intent(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.dialogflow_v2beta1.types.GetIntentRequest, dict]]): - The request object. The request message for - [Intents.GetIntent][google.cloud.dialogflow.v2beta1.Intents.GetIntent]. - name (:class:`str`): - Required. The name of the intent. Supported formats: - - - ``projects//agent/intents/`` - - ``projects//locations//agent/intents/`` - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - language_code (:class:`str`): - Optional. The language used to access language-specific - data. If not specified, the agent's default language is - used. For more information, see `Multilingual intent and - entity - data `__. - - 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. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.dialogflow_v2beta1.types.Intent: - An intent categorizes an end-user's intention for one conversation turn. For - each agent, you define many intents, where your - combined intents can handle a complete conversation. - When an end-user writes or says something, referred - to as an end-user expression or end-user input, - Dialogflow matches the end-user input to the best - intent in your agent. Matching an intent is also - known as intent classification. - - For more information, see the [intent - guide](\ https://cloud.google.com/dialogflow/docs/intents-overview). - - """ - # Create or coerce a protobuf request object. - # Quick 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, language_code]) - 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 = 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: - request.language_code = language_code - - # 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_intent, - 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_intent(self, - request: Optional[Union[gcd_intent.CreateIntentRequest, dict]] = None, - *, - parent: Optional[str] = None, - intent: Optional[gcd_intent.Intent] = None, - language_code: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gcd_intent.Intent: - r"""Creates an intent in the specified agent. - - Note: You should always train an agent prior to sending it - queries. See the `training - documentation `__. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import dialogflow_v2beta1 - - async def sample_create_intent(): - # Create a client - client = dialogflow_v2beta1.IntentsAsyncClient() - - # Initialize request argument(s) - intent = dialogflow_v2beta1.Intent() - intent.display_name = "display_name_value" - - request = dialogflow_v2beta1.CreateIntentRequest( - parent="parent_value", - intent=intent, - ) - - # Make the request - response = await client.create_intent(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.dialogflow_v2beta1.types.CreateIntentRequest, dict]]): - The request object. The request message for - [Intents.CreateIntent][google.cloud.dialogflow.v2beta1.Intents.CreateIntent]. - parent (:class:`str`): - Required. The agent to create a intent 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. - intent (:class:`google.cloud.dialogflow_v2beta1.types.Intent`): - Required. The intent to create. - This corresponds to the ``intent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - language_code (:class:`str`): - Optional. The language used to access language-specific - data. If not specified, the agent's default language is - used. For more information, see `Multilingual intent and - entity - data `__. - - 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. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.dialogflow_v2beta1.types.Intent: - An intent categorizes an end-user's intention for one conversation turn. For - each agent, you define many intents, where your - combined intents can handle a complete conversation. - When an end-user writes or says something, referred - to as an end-user expression or end-user input, - Dialogflow matches the end-user input to the best - intent in your agent. Matching an intent is also - known as intent classification. - - For more information, see the [intent - guide](\ https://cloud.google.com/dialogflow/docs/intents-overview). - - """ - # Create or coerce a protobuf request object. - # Quick 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, intent, language_code]) - 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_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: - request.intent = intent - if language_code is not None: - request.language_code = language_code - - # 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_intent, - 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_intent(self, - request: Optional[Union[gcd_intent.UpdateIntentRequest, dict]] = None, - *, - intent: Optional[gcd_intent.Intent] = None, - update_mask: Optional[field_mask_pb2.FieldMask] = None, - language_code: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gcd_intent.Intent: - r"""Updates the specified intent. - - Note: You should always train an agent prior to sending it - queries. See the `training - documentation `__. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import dialogflow_v2beta1 - - async def sample_update_intent(): - # Create a client - client = dialogflow_v2beta1.IntentsAsyncClient() - - # Initialize request argument(s) - intent = dialogflow_v2beta1.Intent() - intent.display_name = "display_name_value" - - request = dialogflow_v2beta1.UpdateIntentRequest( - intent=intent, - ) - - # Make the request - response = await client.update_intent(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.dialogflow_v2beta1.types.UpdateIntentRequest, dict]]): - The request object. The request message for - [Intents.UpdateIntent][google.cloud.dialogflow.v2beta1.Intents.UpdateIntent]. - intent (:class:`google.cloud.dialogflow_v2beta1.types.Intent`): - Required. The intent to update. - This corresponds to the ``intent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - update_mask (:class:`google.protobuf.field_mask_pb2.FieldMask`): - Optional. 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. - language_code (:class:`str`): - Optional. The language used to access language-specific - data. If not specified, the agent's default language is - used. For more information, see `Multilingual intent and - entity - data `__. - - 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. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.dialogflow_v2beta1.types.Intent: - An intent categorizes an end-user's intention for one conversation turn. For - each agent, you define many intents, where your - combined intents can handle a complete conversation. - When an end-user writes or says something, referred - to as an end-user expression or end-user input, - Dialogflow matches the end-user input to the best - intent in your agent. Matching an intent is also - known as intent classification. - - For more information, see the [intent - guide](\ https://cloud.google.com/dialogflow/docs/intents-overview). - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([intent, update_mask, language_code]) - 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_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: - request.update_mask = update_mask - if language_code is not None: - request.language_code = language_code - - # 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_intent, - 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(( - ("intent.name", request.intent.name), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def delete_intent(self, - request: Optional[Union[intent.DeleteIntentRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> None: - r"""Deletes the specified intent and its direct or indirect followup - intents. - - Note: You should always train an agent prior to sending it - queries. See the `training - documentation `__. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import dialogflow_v2beta1 - - async def sample_delete_intent(): - # Create a client - client = dialogflow_v2beta1.IntentsAsyncClient() - - # Initialize request argument(s) - request = dialogflow_v2beta1.DeleteIntentRequest( - name="name_value", - ) - - # Make the request - await client.delete_intent(request=request) - - Args: - request (Optional[Union[google.cloud.dialogflow_v2beta1.types.DeleteIntentRequest, dict]]): - The request object. The request message for - [Intents.DeleteIntent][google.cloud.dialogflow.v2beta1.Intents.DeleteIntent]. - name (:class:`str`): - Required. The name of the intent to delete. If this - intent has direct or indirect followup intents, we also - delete them. - - Supported formats: - - - ``projects//agent/intents/`` - - ``projects//locations//agent/intents/`` - - 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. - # Quick 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 = intent.DeleteIntentRequest(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_intent, - 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 batch_update_intents(self, - request: Optional[Union[intent.BatchUpdateIntentsRequest, dict]] = None, - *, - parent: Optional[str] = None, - intent_batch_uri: Optional[str] = None, - intent_batch_inline: Optional[intent.IntentBatch] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation_async.AsyncOperation: - r"""Updates/Creates multiple intents in the specified agent. - - This method is a `long-running - operation `__. - The returned ``Operation`` type has the following - method-specific fields: - - - ``metadata``: An empty `Struct - message `__ - - ``response``: - [BatchUpdateIntentsResponse][google.cloud.dialogflow.v2beta1.BatchUpdateIntentsResponse] - - Note: You should always train an agent prior to sending it - queries. See the `training - documentation `__. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import dialogflow_v2beta1 - - async def sample_batch_update_intents(): - # Create a client - client = dialogflow_v2beta1.IntentsAsyncClient() - - # Initialize request argument(s) - request = dialogflow_v2beta1.BatchUpdateIntentsRequest( - intent_batch_uri="intent_batch_uri_value", - parent="parent_value", - ) - - # Make the request - operation = client.batch_update_intents(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.dialogflow_v2beta1.types.BatchUpdateIntentsRequest, dict]]): - The request object. The request message for - [Intents.BatchUpdateIntents][google.cloud.dialogflow.v2beta1.Intents.BatchUpdateIntents]. - parent (:class:`str`): - Required. The name of the agent to update or create - intents in. 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. - intent_batch_uri (:class:`str`): - The URI to a Google Cloud Storage - file containing intents to update or - create. The file format can either be a - serialized proto (of IntentBatch type) - or JSON object. Note: The URI must start - with "gs://". - - This corresponds to the ``intent_batch_uri`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - intent_batch_inline (:class:`google.cloud.dialogflow_v2beta1.types.IntentBatch`): - The collection of intents to update - or create. - - 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. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.api_core.operation_async.AsyncOperation: - An object representing a long-running operation. - - The result type for the operation will be :class:`google.cloud.dialogflow_v2beta1.types.BatchUpdateIntentsResponse` The response message for - [Intents.BatchUpdateIntents][google.cloud.dialogflow.v2beta1.Intents.BatchUpdateIntents]. - - """ - # Create or coerce a protobuf request object. - # Quick 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, intent_batch_uri, intent_batch_inline]) - 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 = 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: - request.intent_batch_uri = intent_batch_uri - if intent_batch_inline is not None: - request.intent_batch_inline = intent_batch_inline - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.batch_update_intents, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Wrap the response in an operation future. - response = operation_async.from_gapic( - response, - self._client._transport.operations_client, - intent.BatchUpdateIntentsResponse, - metadata_type=struct_pb2.Struct, - ) - - # Done; return the response. - return response - - async def batch_delete_intents(self, - request: Optional[Union[intent.BatchDeleteIntentsRequest, dict]] = None, - *, - parent: Optional[str] = None, - intents: Optional[MutableSequence[intent.Intent]] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation_async.AsyncOperation: - r"""Deletes intents in the specified agent. - - This method is a `long-running - operation `__. - The returned ``Operation`` type has the following - method-specific fields: - - - ``metadata``: An empty `Struct - message `__ - - ``response``: An `Empty - message `__ - - Note: You should always train an agent prior to sending it - queries. See the `training - documentation `__. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import dialogflow_v2beta1 - - async def sample_batch_delete_intents(): - # Create a client - client = dialogflow_v2beta1.IntentsAsyncClient() - - # Initialize request argument(s) - intents = dialogflow_v2beta1.Intent() - intents.display_name = "display_name_value" - - request = dialogflow_v2beta1.BatchDeleteIntentsRequest( - parent="parent_value", - intents=intents, - ) - - # Make the request - operation = client.batch_delete_intents(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.dialogflow_v2beta1.types.BatchDeleteIntentsRequest, dict]]): - The request object. The request message for - [Intents.BatchDeleteIntents][google.cloud.dialogflow.v2beta1.Intents.BatchDeleteIntents]. - parent (:class:`str`): - Required. The name of the agent to delete all entities - types 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. - intents (:class:`MutableSequence[google.cloud.dialogflow_v2beta1.types.Intent]`): - Required. The collection of intents to delete. Only - intent ``name`` must be filled in. - - 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. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.api_core.operation_async.AsyncOperation: - An object representing a long-running operation. - - The result type for the operation will be :class:`google.protobuf.empty_pb2.Empty` A generic empty message that you can re-use to avoid defining duplicated - empty messages in your APIs. A typical example is to - use it as the request or the response type of an API - method. For instance: - - service Foo { - rpc Bar(google.protobuf.Empty) returns - (google.protobuf.Empty); - - } - - """ - # Create or coerce a protobuf request object. - # Quick 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, intents]) - 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 = 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: - request.intents.extend(intents) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.batch_delete_intents, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Wrap the response in an operation future. - response = operation_async.from_gapic( - response, - self._client._transport.operations_client, - empty_pb2.Empty, - metadata_type=struct_pb2.Struct, - ) - - # Done; return the response. - return response - - async def list_operations( - self, - request: Optional[operations_pb2.ListOperationsRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operations_pb2.ListOperationsResponse: - r"""Lists operations that match the specified filter in the request. - - Args: - request (:class:`~.operations_pb2.ListOperationsRequest`): - The request object. Request message for - `ListOperations` method. - 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: - ~.operations_pb2.ListOperationsResponse: - Response message for ``ListOperations`` method. - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = operations_pb2.ListOperationsRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._client._transport.list_operations, - 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 get_operation( - self, - request: Optional[operations_pb2.GetOperationRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operations_pb2.Operation: - r"""Gets the latest state of a long-running operation. - - Args: - request (:class:`~.operations_pb2.GetOperationRequest`): - The request object. Request message for - `GetOperation` method. - 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: - ~.operations_pb2.Operation: - An ``Operation`` object. - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = operations_pb2.GetOperationRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._client._transport.get_operation, - 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 cancel_operation( - self, - request: Optional[operations_pb2.CancelOperationRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> None: - r"""Starts asynchronous cancellation on a long-running operation. - - The server makes a best effort to cancel the operation, but success - is not guaranteed. If the server doesn't support this method, it returns - `google.rpc.Code.UNIMPLEMENTED`. - - Args: - request (:class:`~.operations_pb2.CancelOperationRequest`): - The request object. Request message for - `CancelOperation` method. - 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: - None - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = operations_pb2.CancelOperationRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._client._transport.cancel_operation, - 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_location( - self, - request: Optional[locations_pb2.GetLocationRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> locations_pb2.Location: - r"""Gets information about a location. - - Args: - request (:class:`~.location_pb2.GetLocationRequest`): - The request object. Request message for - `GetLocation` method. - 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: - ~.location_pb2.Location: - Location object. - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = locations_pb2.GetLocationRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._client._transport.get_location, - 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 list_locations( - self, - request: Optional[locations_pb2.ListLocationsRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> locations_pb2.ListLocationsResponse: - r"""Lists information about the supported locations for this service. - - Args: - request (:class:`~.location_pb2.ListLocationsRequest`): - The request object. Request message for - `ListLocations` method. - 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: - ~.location_pb2.ListLocationsResponse: - Response message for ``ListLocations`` method. - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = locations_pb2.ListLocationsRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._client._transport.list_locations, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("name", request.name),)), - ) - - # Send the request. - response = await rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - async def __aenter__(self): - return self - - async def __aexit__(self, exc_type, exc, tb): - await self.transport.close() - -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) - - -__all__ = ( - "IntentsAsyncClient", -) diff --git a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/intents/client.py b/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/intents/client.py deleted file mode 100644 index d004f7cf4..000000000 --- a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/intents/client.py +++ /dev/null @@ -1,1626 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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 os -import re -from typing import Dict, Mapping, MutableMapping, MutableSequence, Optional, Sequence, Tuple, Type, Union, cast - -from google.cloud.dialogflow_v2beta1 import gapic_version as package_version - -from google.api_core import client_options as client_options_lib -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import retry as retries -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 - -try: - OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] -except AttributeError: # pragma: NO COVER - OptionalRetry = Union[retries.Retry, object] # type: ignore - -from google.api_core import operation # type: ignore -from google.api_core import operation_async # type: ignore -from google.cloud.dialogflow_v2beta1.services.intents import pagers -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.cloud.location import locations_pb2 # type: ignore -from google.longrunning import operations_pb2 -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 -from .transports.rest import IntentsRestTransport - - -class IntentsClientMeta(type): - """Metaclass for the Intents 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[IntentsTransport]] - _transport_registry["grpc"] = IntentsGrpcTransport - _transport_registry["grpc_asyncio"] = IntentsGrpcAsyncIOTransport - _transport_registry["rest"] = IntentsRestTransport - - def get_transport_class(cls, - label: Optional[str] = None, - ) -> Type[IntentsTransport]: - """Returns an appropriate transport class. - - Args: - label: The name of the desired transport. If none is - provided, then the first transport in the registry is used. - - Returns: - The transport class to use. - """ - # If a specific transport is requested, return that one. - if label: - return cls._transport_registry[label] - - # No transport is requested; return the default (that is, the first one - # in the dictionary). - return next(iter(cls._transport_registry.values())) - - -class IntentsClient(metaclass=IntentsClientMeta): - """Service for managing - [Intents][google.cloud.dialogflow.v2beta1.Intent]. - """ - - @staticmethod - def _get_default_mtls_endpoint(api_endpoint): - """Converts api endpoint to mTLS endpoint. - - Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to - "*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively. - Args: - api_endpoint (Optional[str]): the api endpoint to convert. - Returns: - str: converted mTLS api endpoint. - """ - if not api_endpoint: - return api_endpoint - - mtls_endpoint_re = re.compile( - r"(?P[^.]+)(?P\.mtls)?(?P\.sandbox)?(?P\.googleapis\.com)?" - ) - - m = mtls_endpoint_re.match(api_endpoint) - name, mtls, sandbox, googledomain = m.groups() - if mtls or not googledomain: - return api_endpoint - - if sandbox: - return api_endpoint.replace( - "sandbox.googleapis.com", "mtls.sandbox.googleapis.com" - ) - - return api_endpoint.replace(".googleapis.com", ".mtls.googleapis.com") - - DEFAULT_ENDPOINT = "dialogflow.googleapis.com" - DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore - DEFAULT_ENDPOINT - ) - - @classmethod - def from_service_account_info(cls, info: dict, *args, **kwargs): - """Creates an instance of this client using the provided credentials - info. - - Args: - info (dict): The service account private key info. - args: Additional arguments to pass to the constructor. - kwargs: Additional arguments to pass to the constructor. - - Returns: - IntentsClient: 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: - IntentsClient: 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) -> IntentsTransport: - """Returns the transport used by the client instance. - - Returns: - IntentsTransport: The transport used by the client - instance. - """ - return self._transport - - @staticmethod - def context_path(project: str,session: str,context: str,) -> str: - """Returns a fully-qualified context string.""" - return "projects/{project}/agent/sessions/{session}/contexts/{context}".format(project=project, session=session, context=context, ) - - @staticmethod - def parse_context_path(path: str) -> Dict[str,str]: - """Parses a context path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/agent/sessions/(?P.+?)/contexts/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def intent_path(project: str,intent: str,) -> str: - """Returns a fully-qualified intent string.""" - return "projects/{project}/agent/intents/{intent}".format(project=project, intent=intent, ) - - @staticmethod - def parse_intent_path(path: str) -> Dict[str,str]: - """Parses a intent path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/agent/intents/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_billing_account_path(billing_account: str, ) -> str: - """Returns a fully-qualified billing_account string.""" - return "billingAccounts/{billing_account}".format(billing_account=billing_account, ) - - @staticmethod - def parse_common_billing_account_path(path: str) -> Dict[str,str]: - """Parse a billing_account path into its component segments.""" - m = re.match(r"^billingAccounts/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_folder_path(folder: str, ) -> str: - """Returns a fully-qualified folder string.""" - return "folders/{folder}".format(folder=folder, ) - - @staticmethod - def parse_common_folder_path(path: str) -> Dict[str,str]: - """Parse a folder path into its component segments.""" - m = re.match(r"^folders/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_organization_path(organization: str, ) -> str: - """Returns a fully-qualified organization string.""" - return "organizations/{organization}".format(organization=organization, ) - - @staticmethod - def parse_common_organization_path(path: str) -> Dict[str,str]: - """Parse a organization path into its component segments.""" - m = re.match(r"^organizations/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_project_path(project: str, ) -> str: - """Returns a fully-qualified project string.""" - return "projects/{project}".format(project=project, ) - - @staticmethod - def parse_common_project_path(path: str) -> Dict[str,str]: - """Parse a project path into its component segments.""" - m = re.match(r"^projects/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_location_path(project: str, location: str, ) -> str: - """Returns a fully-qualified location string.""" - return "projects/{project}/locations/{location}".format(project=project, location=location, ) - - @staticmethod - def parse_common_location_path(path: str) -> Dict[str,str]: - """Parse a location path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)$", path) - return m.groupdict() if m else {} - - @classmethod - def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[client_options_lib.ClientOptions] = None): - """Return the API endpoint and client cert source for mutual TLS. - - The client cert source is determined in the following order: - (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the - client cert source is None. - (2) if `client_options.client_cert_source` is provided, use the provided one; if the - default client cert source exists, use the default one; otherwise the client cert - source is None. - - The API endpoint is determined in the following order: - (1) if `client_options.api_endpoint` if provided, use the provided one. - (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the - default mTLS endpoint; if the environment variable is "never", use the default API - endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise - use the default API endpoint. - - More details can be found at https://google.aip.dev/auth/4114. - - Args: - client_options (google.api_core.client_options.ClientOptions): Custom options for the - client. Only the `api_endpoint` and `client_cert_source` properties may be used - in this method. - - Returns: - Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the - client cert source to use. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If any errors happen. - """ - if client_options is None: - client_options = client_options_lib.ClientOptions() - use_client_cert = os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false") - use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") - if use_client_cert not in ("true", "false"): - raise ValueError("Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`") - if use_mtls_endpoint not in ("auto", "never", "always"): - raise MutualTLSChannelError("Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`") - - # Figure out the client cert source to use. - client_cert_source = None - if use_client_cert == "true": - if client_options.client_cert_source: - client_cert_source = client_options.client_cert_source - elif mtls.has_default_client_cert_source(): - client_cert_source = mtls.default_client_cert_source() - - # Figure out which api endpoint to use. - if client_options.api_endpoint is not None: - api_endpoint = client_options.api_endpoint - elif use_mtls_endpoint == "always" or (use_mtls_endpoint == "auto" and client_cert_source): - api_endpoint = cls.DEFAULT_MTLS_ENDPOINT - else: - api_endpoint = cls.DEFAULT_ENDPOINT - - return api_endpoint, client_cert_source - - def __init__(self, *, - credentials: Optional[ga_credentials.Credentials] = None, - transport: Optional[Union[str, IntentsTransport]] = None, - client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the intents 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, IntentsTransport]): The - transport to use. If set to None, a transport is chosen - automatically. - client_options (Optional[Union[google.api_core.client_options.ClientOptions, dict]]): 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() - client_options = cast(client_options_lib.ClientOptions, client_options) - - api_endpoint, client_cert_source_func = self.get_mtls_endpoint_and_cert_source(client_options) - - api_key_value = getattr(client_options, "api_key", None) - if api_key_value and credentials: - raise ValueError("client_options.api_key and credentials are mutually exclusive") - - # 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, IntentsTransport): - # transport is a IntentsTransport instance. - if credentials or client_options.credentials_file or api_key_value: - 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: - import google.auth._default # type: ignore - - if api_key_value and hasattr(google.auth._default, "get_api_key_credentials"): - credentials = google.auth._default.get_api_key_credentials(api_key_value) - - Transport = type(self).get_transport_class(transport) - self._transport = Transport( - credentials=credentials, - credentials_file=client_options.credentials_file, - host=api_endpoint, - scopes=client_options.scopes, - client_cert_source_for_mtls=client_cert_source_func, - quota_project_id=client_options.quota_project_id, - client_info=client_info, - always_use_jwt_access=True, - api_audience=client_options.api_audience, - ) - - def list_intents(self, - request: Optional[Union[intent.ListIntentsRequest, dict]] = None, - *, - parent: Optional[str] = None, - language_code: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListIntentsPager: - r"""Returns the list of all intents in the specified - agent. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import dialogflow_v2beta1 - - def sample_list_intents(): - # Create a client - client = dialogflow_v2beta1.IntentsClient() - - # Initialize request argument(s) - request = dialogflow_v2beta1.ListIntentsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_intents(request=request) - - # Handle the response - for response in page_result: - print(response) - - Args: - request (Union[google.cloud.dialogflow_v2beta1.types.ListIntentsRequest, dict]): - The request object. The request message for - [Intents.ListIntents][google.cloud.dialogflow.v2beta1.Intents.ListIntents]. - parent (str): - Required. The agent to list all intents from. Format: - ``projects//agent`` or - ``projects//locations//agent``. - - Alternatively, you can specify the environment to list - intents for. Format: - ``projects//agent/environments/`` - or - ``projects//locations//agent/environments/``. - Note: training phrases of the intents will not be - returned for non-draft environment. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - language_code (str): - Optional. The language used to access language-specific - data. If not specified, the agent's default language is - used. For more information, see `Multilingual intent and - entity - data `__. - - 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. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.dialogflow_v2beta1.services.intents.pagers.ListIntentsPager: - The response message for - [Intents.ListIntents][google.cloud.dialogflow.v2beta1.Intents.ListIntents]. - - Iterating over this object will yield results and - resolve additional pages automatically. - - """ - # Create or coerce a protobuf request object. - # Quick 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, language_code]) - 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 intent.ListIntentsRequest. - # There's no risk of modifying the input as we've already verified - # 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: - request.language_code = language_code - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.list_intents] - - # 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.ListIntentsPager( - method=rpc, - request=request, - response=response, - metadata=metadata, - ) - - # Done; return the response. - return response - - def get_intent(self, - request: Optional[Union[intent.GetIntentRequest, dict]] = None, - *, - name: Optional[str] = None, - language_code: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> intent.Intent: - r"""Retrieves the specified intent. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import dialogflow_v2beta1 - - def sample_get_intent(): - # Create a client - client = dialogflow_v2beta1.IntentsClient() - - # Initialize request argument(s) - request = dialogflow_v2beta1.GetIntentRequest( - name="name_value", - ) - - # Make the request - response = client.get_intent(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.dialogflow_v2beta1.types.GetIntentRequest, dict]): - The request object. The request message for - [Intents.GetIntent][google.cloud.dialogflow.v2beta1.Intents.GetIntent]. - name (str): - Required. The name of the intent. Supported formats: - - - ``projects//agent/intents/`` - - ``projects//locations//agent/intents/`` - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - language_code (str): - Optional. The language used to access language-specific - data. If not specified, the agent's default language is - used. For more information, see `Multilingual intent and - entity - data `__. - - 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. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.dialogflow_v2beta1.types.Intent: - An intent categorizes an end-user's intention for one conversation turn. For - each agent, you define many intents, where your - combined intents can handle a complete conversation. - When an end-user writes or says something, referred - to as an end-user expression or end-user input, - Dialogflow matches the end-user input to the best - intent in your agent. Matching an intent is also - known as intent classification. - - For more information, see the [intent - guide](\ https://cloud.google.com/dialogflow/docs/intents-overview). - - """ - # Create or coerce a protobuf request object. - # Quick 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, language_code]) - 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 intent.GetIntentRequest. - # There's no risk of modifying the input as we've already verified - # 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: - request.language_code = language_code - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.get_intent] - - # 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_intent(self, - request: Optional[Union[gcd_intent.CreateIntentRequest, dict]] = None, - *, - parent: Optional[str] = None, - intent: Optional[gcd_intent.Intent] = None, - language_code: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gcd_intent.Intent: - r"""Creates an intent in the specified agent. - - Note: You should always train an agent prior to sending it - queries. See the `training - documentation `__. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import dialogflow_v2beta1 - - def sample_create_intent(): - # Create a client - client = dialogflow_v2beta1.IntentsClient() - - # Initialize request argument(s) - intent = dialogflow_v2beta1.Intent() - intent.display_name = "display_name_value" - - request = dialogflow_v2beta1.CreateIntentRequest( - parent="parent_value", - intent=intent, - ) - - # Make the request - response = client.create_intent(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.dialogflow_v2beta1.types.CreateIntentRequest, dict]): - The request object. The request message for - [Intents.CreateIntent][google.cloud.dialogflow.v2beta1.Intents.CreateIntent]. - parent (str): - Required. The agent to create a intent 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. - intent (google.cloud.dialogflow_v2beta1.types.Intent): - Required. The intent to create. - This corresponds to the ``intent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - language_code (str): - Optional. The language used to access language-specific - data. If not specified, the agent's default language is - used. For more information, see `Multilingual intent and - entity - data `__. - - 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. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.dialogflow_v2beta1.types.Intent: - An intent categorizes an end-user's intention for one conversation turn. For - each agent, you define many intents, where your - combined intents can handle a complete conversation. - When an end-user writes or says something, referred - to as an end-user expression or end-user input, - Dialogflow matches the end-user input to the best - intent in your agent. Matching an intent is also - known as intent classification. - - For more information, see the [intent - guide](\ https://cloud.google.com/dialogflow/docs/intents-overview). - - """ - # Create or coerce a protobuf request object. - # Quick 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, intent, language_code]) - 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_intent.CreateIntentRequest. - # There's no risk of modifying the input as we've already verified - # 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: - request.intent = intent - if language_code is not None: - request.language_code = language_code - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.create_intent] - - # 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_intent(self, - request: Optional[Union[gcd_intent.UpdateIntentRequest, dict]] = None, - *, - intent: Optional[gcd_intent.Intent] = None, - update_mask: Optional[field_mask_pb2.FieldMask] = None, - language_code: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gcd_intent.Intent: - r"""Updates the specified intent. - - Note: You should always train an agent prior to sending it - queries. See the `training - documentation `__. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import dialogflow_v2beta1 - - def sample_update_intent(): - # Create a client - client = dialogflow_v2beta1.IntentsClient() - - # Initialize request argument(s) - intent = dialogflow_v2beta1.Intent() - intent.display_name = "display_name_value" - - request = dialogflow_v2beta1.UpdateIntentRequest( - intent=intent, - ) - - # Make the request - response = client.update_intent(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.dialogflow_v2beta1.types.UpdateIntentRequest, dict]): - The request object. The request message for - [Intents.UpdateIntent][google.cloud.dialogflow.v2beta1.Intents.UpdateIntent]. - intent (google.cloud.dialogflow_v2beta1.types.Intent): - Required. The intent to update. - This corresponds to the ``intent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - update_mask (google.protobuf.field_mask_pb2.FieldMask): - Optional. 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. - language_code (str): - Optional. The language used to access language-specific - data. If not specified, the agent's default language is - used. For more information, see `Multilingual intent and - entity - data `__. - - 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. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.dialogflow_v2beta1.types.Intent: - An intent categorizes an end-user's intention for one conversation turn. For - each agent, you define many intents, where your - combined intents can handle a complete conversation. - When an end-user writes or says something, referred - to as an end-user expression or end-user input, - Dialogflow matches the end-user input to the best - intent in your agent. Matching an intent is also - known as intent classification. - - For more information, see the [intent - guide](\ https://cloud.google.com/dialogflow/docs/intents-overview). - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([intent, update_mask, language_code]) - 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_intent.UpdateIntentRequest. - # There's no risk of modifying the input as we've already verified - # 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: - request.update_mask = update_mask - if language_code is not None: - request.language_code = language_code - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.update_intent] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("intent.name", request.intent.name), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def delete_intent(self, - request: Optional[Union[intent.DeleteIntentRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> None: - r"""Deletes the specified intent and its direct or indirect followup - intents. - - Note: You should always train an agent prior to sending it - queries. See the `training - documentation `__. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import dialogflow_v2beta1 - - def sample_delete_intent(): - # Create a client - client = dialogflow_v2beta1.IntentsClient() - - # Initialize request argument(s) - request = dialogflow_v2beta1.DeleteIntentRequest( - name="name_value", - ) - - # Make the request - client.delete_intent(request=request) - - Args: - request (Union[google.cloud.dialogflow_v2beta1.types.DeleteIntentRequest, dict]): - The request object. The request message for - [Intents.DeleteIntent][google.cloud.dialogflow.v2beta1.Intents.DeleteIntent]. - name (str): - Required. The name of the intent to delete. If this - intent has direct or indirect followup intents, we also - delete them. - - Supported formats: - - - ``projects//agent/intents/`` - - ``projects//locations//agent/intents/`` - - 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. - # Quick 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 intent.DeleteIntentRequest. - # There's no risk of modifying the input as we've already verified - # 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 - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.delete_intent] - - # 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 batch_update_intents(self, - request: Optional[Union[intent.BatchUpdateIntentsRequest, dict]] = None, - *, - parent: Optional[str] = None, - intent_batch_uri: Optional[str] = None, - intent_batch_inline: Optional[intent.IntentBatch] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation.Operation: - r"""Updates/Creates multiple intents in the specified agent. - - This method is a `long-running - operation `__. - The returned ``Operation`` type has the following - method-specific fields: - - - ``metadata``: An empty `Struct - message `__ - - ``response``: - [BatchUpdateIntentsResponse][google.cloud.dialogflow.v2beta1.BatchUpdateIntentsResponse] - - Note: You should always train an agent prior to sending it - queries. See the `training - documentation `__. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import dialogflow_v2beta1 - - def sample_batch_update_intents(): - # Create a client - client = dialogflow_v2beta1.IntentsClient() - - # Initialize request argument(s) - request = dialogflow_v2beta1.BatchUpdateIntentsRequest( - intent_batch_uri="intent_batch_uri_value", - parent="parent_value", - ) - - # Make the request - operation = client.batch_update_intents(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.dialogflow_v2beta1.types.BatchUpdateIntentsRequest, dict]): - The request object. The request message for - [Intents.BatchUpdateIntents][google.cloud.dialogflow.v2beta1.Intents.BatchUpdateIntents]. - parent (str): - Required. The name of the agent to update or create - intents in. 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. - intent_batch_uri (str): - The URI to a Google Cloud Storage - file containing intents to update or - create. The file format can either be a - serialized proto (of IntentBatch type) - or JSON object. Note: The URI must start - with "gs://". - - This corresponds to the ``intent_batch_uri`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - intent_batch_inline (google.cloud.dialogflow_v2beta1.types.IntentBatch): - The collection of intents to update - or create. - - 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. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.api_core.operation.Operation: - An object representing a long-running operation. - - The result type for the operation will be :class:`google.cloud.dialogflow_v2beta1.types.BatchUpdateIntentsResponse` The response message for - [Intents.BatchUpdateIntents][google.cloud.dialogflow.v2beta1.Intents.BatchUpdateIntents]. - - """ - # Create or coerce a protobuf request object. - # Quick 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, intent_batch_uri, intent_batch_inline]) - 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 intent.BatchUpdateIntentsRequest. - # There's no risk of modifying the input as we've already verified - # 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: - request.intent_batch_uri = intent_batch_uri - if intent_batch_inline is not None: - request.intent_batch_inline = intent_batch_inline - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.batch_update_intents] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Wrap the response in an operation future. - response = operation.from_gapic( - response, - self._transport.operations_client, - intent.BatchUpdateIntentsResponse, - metadata_type=struct_pb2.Struct, - ) - - # Done; return the response. - return response - - def batch_delete_intents(self, - request: Optional[Union[intent.BatchDeleteIntentsRequest, dict]] = None, - *, - parent: Optional[str] = None, - intents: Optional[MutableSequence[intent.Intent]] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation.Operation: - r"""Deletes intents in the specified agent. - - This method is a `long-running - operation `__. - The returned ``Operation`` type has the following - method-specific fields: - - - ``metadata``: An empty `Struct - message `__ - - ``response``: An `Empty - message `__ - - Note: You should always train an agent prior to sending it - queries. See the `training - documentation `__. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import dialogflow_v2beta1 - - def sample_batch_delete_intents(): - # Create a client - client = dialogflow_v2beta1.IntentsClient() - - # Initialize request argument(s) - intents = dialogflow_v2beta1.Intent() - intents.display_name = "display_name_value" - - request = dialogflow_v2beta1.BatchDeleteIntentsRequest( - parent="parent_value", - intents=intents, - ) - - # Make the request - operation = client.batch_delete_intents(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.dialogflow_v2beta1.types.BatchDeleteIntentsRequest, dict]): - The request object. The request message for - [Intents.BatchDeleteIntents][google.cloud.dialogflow.v2beta1.Intents.BatchDeleteIntents]. - parent (str): - Required. The name of the agent to delete all entities - types 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. - intents (MutableSequence[google.cloud.dialogflow_v2beta1.types.Intent]): - Required. The collection of intents to delete. Only - intent ``name`` must be filled in. - - 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. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.api_core.operation.Operation: - An object representing a long-running operation. - - The result type for the operation will be :class:`google.protobuf.empty_pb2.Empty` A generic empty message that you can re-use to avoid defining duplicated - empty messages in your APIs. A typical example is to - use it as the request or the response type of an API - method. For instance: - - service Foo { - rpc Bar(google.protobuf.Empty) returns - (google.protobuf.Empty); - - } - - """ - # Create or coerce a protobuf request object. - # Quick 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, intents]) - 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 intent.BatchDeleteIntentsRequest. - # There's no risk of modifying the input as we've already verified - # 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: - request.intents = intents - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.batch_delete_intents] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Wrap the response in an operation future. - response = operation.from_gapic( - response, - self._transport.operations_client, - empty_pb2.Empty, - metadata_type=struct_pb2.Struct, - ) - - # Done; return the response. - return response - - def __enter__(self) -> "IntentsClient": - return self - - def __exit__(self, type, value, traceback): - """Releases underlying transport's resources. - - .. warning:: - ONLY use as a context manager if the transport is NOT shared - with other clients! Exiting the with block will CLOSE the transport - and may cause errors in other clients! - """ - self.transport.close() - - def list_operations( - self, - request: Optional[operations_pb2.ListOperationsRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operations_pb2.ListOperationsResponse: - r"""Lists operations that match the specified filter in the request. - - Args: - request (:class:`~.operations_pb2.ListOperationsRequest`): - The request object. Request message for - `ListOperations` method. - 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: - ~.operations_pb2.ListOperationsResponse: - Response message for ``ListOperations`` method. - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = operations_pb2.ListOperationsRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._transport.list_operations, - 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 = rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - def get_operation( - self, - request: Optional[operations_pb2.GetOperationRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operations_pb2.Operation: - r"""Gets the latest state of a long-running operation. - - Args: - request (:class:`~.operations_pb2.GetOperationRequest`): - The request object. Request message for - `GetOperation` method. - 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: - ~.operations_pb2.Operation: - An ``Operation`` object. - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = operations_pb2.GetOperationRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._transport.get_operation, - 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 = rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - def cancel_operation( - self, - request: Optional[operations_pb2.CancelOperationRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> None: - r"""Starts asynchronous cancellation on a long-running operation. - - The server makes a best effort to cancel the operation, but success - is not guaranteed. If the server doesn't support this method, it returns - `google.rpc.Code.UNIMPLEMENTED`. - - Args: - request (:class:`~.operations_pb2.CancelOperationRequest`): - The request object. Request message for - `CancelOperation` method. - 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: - None - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = operations_pb2.CancelOperationRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._transport.cancel_operation, - 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. - rpc(request, retry=retry, timeout=timeout, metadata=metadata,) - - def get_location( - self, - request: Optional[locations_pb2.GetLocationRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> locations_pb2.Location: - r"""Gets information about a location. - - Args: - request (:class:`~.location_pb2.GetLocationRequest`): - The request object. Request message for - `GetLocation` method. - 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: - ~.location_pb2.Location: - Location object. - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = locations_pb2.GetLocationRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._transport.get_location, - 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 = rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - def list_locations( - self, - request: Optional[locations_pb2.ListLocationsRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> locations_pb2.ListLocationsResponse: - r"""Lists information about the supported locations for this service. - - Args: - request (:class:`~.location_pb2.ListLocationsRequest`): - The request object. Request message for - `ListLocations` method. - 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: - ~.location_pb2.ListLocationsResponse: - Response message for ``ListLocations`` method. - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = locations_pb2.ListLocationsRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._transport.list_locations, - 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 = rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) - - -__all__ = ( - "IntentsClient", -) diff --git a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/intents/pagers.py b/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/intents/pagers.py deleted file mode 100644 index 8bc3c078f..000000000 --- a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/intents/pagers.py +++ /dev/null @@ -1,139 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from typing import Any, AsyncIterator, Awaitable, Callable, Sequence, Tuple, Optional, Iterator - -from google.cloud.dialogflow_v2beta1.types import intent - - -class ListIntentsPager: - """A pager for iterating through ``list_intents`` requests. - - This class thinly wraps an initial - :class:`google.cloud.dialogflow_v2beta1.types.ListIntentsResponse` object, and - provides an ``__iter__`` method to iterate through its - ``intents`` field. - - If there are more pages, the ``__iter__`` method will make additional - ``ListIntents`` requests and continue to iterate - through the ``intents`` field on the - corresponding responses. - - All the usual :class:`google.cloud.dialogflow_v2beta1.types.ListIntentsResponse` - 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[..., intent.ListIntentsResponse], - request: intent.ListIntentsRequest, - response: intent.ListIntentsResponse, - *, - 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.ListIntentsRequest): - The initial request object. - response (google.cloud.dialogflow_v2beta1.types.ListIntentsResponse): - 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 = intent.ListIntentsRequest(request) - self._response = response - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - def pages(self) -> Iterator[intent.ListIntentsResponse]: - yield self._response - while self._response.next_page_token: - self._request.page_token = self._response.next_page_token - self._response = self._method(self._request, metadata=self._metadata) - yield self._response - - def __iter__(self) -> Iterator[intent.Intent]: - for page in self.pages: - yield from page.intents - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListIntentsAsyncPager: - """A pager for iterating through ``list_intents`` requests. - - This class thinly wraps an initial - :class:`google.cloud.dialogflow_v2beta1.types.ListIntentsResponse` object, and - provides an ``__aiter__`` method to iterate through its - ``intents`` field. - - If there are more pages, the ``__aiter__`` method will make additional - ``ListIntents`` requests and continue to iterate - through the ``intents`` field on the - corresponding responses. - - All the usual :class:`google.cloud.dialogflow_v2beta1.types.ListIntentsResponse` - 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[intent.ListIntentsResponse]], - request: intent.ListIntentsRequest, - response: intent.ListIntentsResponse, - *, - metadata: Sequence[Tuple[str, str]] = ()): - """Instantiates the pager. - - Args: - method (Callable): The method that was originally called, and - which instantiated this pager. - request (google.cloud.dialogflow_v2beta1.types.ListIntentsRequest): - The initial request object. - response (google.cloud.dialogflow_v2beta1.types.ListIntentsResponse): - 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 = intent.ListIntentsRequest(request) - self._response = response - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - async def pages(self) -> AsyncIterator[intent.ListIntentsResponse]: - yield self._response - while self._response.next_page_token: - self._request.page_token = self._response.next_page_token - self._response = await self._method(self._request, metadata=self._metadata) - yield self._response - def __aiter__(self) -> AsyncIterator[intent.Intent]: - async def async_generator(): - async for page in self.pages: - for response in page.intents: - yield response - - return async_generator() - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) diff --git a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/intents/transports/__init__.py b/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/intents/transports/__init__.py deleted file mode 100644 index 97fdd7315..000000000 --- a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/intents/transports/__init__.py +++ /dev/null @@ -1,38 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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 IntentsTransport -from .grpc import IntentsGrpcTransport -from .grpc_asyncio import IntentsGrpcAsyncIOTransport -from .rest import IntentsRestTransport -from .rest import IntentsRestInterceptor - - -# Compile a registry of transports. -_transport_registry = OrderedDict() # type: Dict[str, Type[IntentsTransport]] -_transport_registry['grpc'] = IntentsGrpcTransport -_transport_registry['grpc_asyncio'] = IntentsGrpcAsyncIOTransport -_transport_registry['rest'] = IntentsRestTransport - -__all__ = ( - 'IntentsTransport', - 'IntentsGrpcTransport', - 'IntentsGrpcAsyncIOTransport', - 'IntentsRestTransport', - 'IntentsRestInterceptor', -) diff --git a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/intents/transports/base.py b/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/intents/transports/base.py deleted file mode 100644 index 36d70611d..000000000 --- a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/intents/transports/base.py +++ /dev/null @@ -1,287 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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 - -from google.cloud.dialogflow_v2beta1 import gapic_version as package_version - -import google.auth # type: ignore -import google.api_core -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import retry as retries -from google.api_core import operations_v1 -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 intent -from google.cloud.dialogflow_v2beta1.types import intent as gcd_intent -from google.cloud.location import locations_pb2 # type: ignore -from google.longrunning import operations_pb2 -from google.longrunning import operations_pb2 # type: ignore -from google.protobuf import empty_pb2 # type: ignore - -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) - - -class IntentsTransport(abc.ABC): - """Abstract transport class for Intents.""" - - 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: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - api_audience: Optional[str] = None, - **kwargs, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. - scopes (Optional[Sequence[str]]): A list of scopes. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - """ - - scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} - - # Save the scopes. - self._scopes = scopes - - # If no credentials are provided, then determine the appropriate - # defaults. - if credentials and credentials_file: - raise core_exceptions.DuplicateCredentialArgs("'credentials_file' and 'credentials' are mutually exclusive") - - if credentials_file is not None: - credentials, _ = google.auth.load_credentials_from_file( - credentials_file, - **scopes_kwargs, - quota_project_id=quota_project_id - ) - elif credentials is None: - credentials, _ = google.auth.default(**scopes_kwargs, quota_project_id=quota_project_id) - # Don't apply audience if the credentials file passed from user. - if hasattr(credentials, "with_gdch_audience"): - credentials = credentials.with_gdch_audience(api_audience if api_audience else host) - - # If the credentials are service account credentials, then always try to use self signed JWT. - if always_use_jwt_access and isinstance(credentials, service_account.Credentials) and hasattr(service_account.Credentials, "with_always_use_jwt_access"): - credentials = credentials.with_always_use_jwt_access(True) - - # Save the credentials. - self._credentials = credentials - - # Save the hostname. Default to port 443 (HTTPS) if none is specified. - if ':' not in host: - host += ':443' - self._host = host - - def _prep_wrapped_messages(self, client_info): - # Precompute the wrapped methods. - self._wrapped_methods = { - self.list_intents: gapic_v1.method.wrap_method( - self.list_intents, - default_timeout=None, - client_info=client_info, - ), - self.get_intent: gapic_v1.method.wrap_method( - self.get_intent, - default_timeout=None, - client_info=client_info, - ), - self.create_intent: gapic_v1.method.wrap_method( - self.create_intent, - default_timeout=None, - client_info=client_info, - ), - self.update_intent: gapic_v1.method.wrap_method( - self.update_intent, - default_timeout=None, - client_info=client_info, - ), - self.delete_intent: gapic_v1.method.wrap_method( - self.delete_intent, - default_timeout=None, - client_info=client_info, - ), - self.batch_update_intents: gapic_v1.method.wrap_method( - self.batch_update_intents, - default_timeout=None, - client_info=client_info, - ), - self.batch_delete_intents: gapic_v1.method.wrap_method( - self.batch_delete_intents, - default_timeout=None, - client_info=client_info, - ), - } - - def close(self): - """Closes resources associated with the transport. - - .. warning:: - Only call this method if the transport is NOT shared - with other clients - this may cause errors in other clients! - """ - raise NotImplementedError() - - @property - def operations_client(self): - """Return the client designed to process long-running operations.""" - raise NotImplementedError() - - @property - def list_intents(self) -> Callable[ - [intent.ListIntentsRequest], - Union[ - intent.ListIntentsResponse, - Awaitable[intent.ListIntentsResponse] - ]]: - raise NotImplementedError() - - @property - def get_intent(self) -> Callable[ - [intent.GetIntentRequest], - Union[ - intent.Intent, - Awaitable[intent.Intent] - ]]: - raise NotImplementedError() - - @property - def create_intent(self) -> Callable[ - [gcd_intent.CreateIntentRequest], - Union[ - gcd_intent.Intent, - Awaitable[gcd_intent.Intent] - ]]: - raise NotImplementedError() - - @property - def update_intent(self) -> Callable[ - [gcd_intent.UpdateIntentRequest], - Union[ - gcd_intent.Intent, - Awaitable[gcd_intent.Intent] - ]]: - raise NotImplementedError() - - @property - def delete_intent(self) -> Callable[ - [intent.DeleteIntentRequest], - Union[ - empty_pb2.Empty, - Awaitable[empty_pb2.Empty] - ]]: - raise NotImplementedError() - - @property - def batch_update_intents(self) -> Callable[ - [intent.BatchUpdateIntentsRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: - raise NotImplementedError() - - @property - def batch_delete_intents(self) -> Callable[ - [intent.BatchDeleteIntentsRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: - raise NotImplementedError() - - @property - def list_operations( - self, - ) -> Callable[ - [operations_pb2.ListOperationsRequest], - Union[operations_pb2.ListOperationsResponse, Awaitable[operations_pb2.ListOperationsResponse]], - ]: - raise NotImplementedError() - - @property - def get_operation( - self, - ) -> Callable[ - [operations_pb2.GetOperationRequest], - Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], - ]: - raise NotImplementedError() - - @property - def cancel_operation( - self, - ) -> Callable[ - [operations_pb2.CancelOperationRequest], - None, - ]: - raise NotImplementedError() - - @property - def get_location(self, - ) -> Callable[ - [locations_pb2.GetLocationRequest], - Union[locations_pb2.Location, Awaitable[locations_pb2.Location]], - ]: - raise NotImplementedError() - - @property - def list_locations(self, - ) -> Callable[ - [locations_pb2.ListLocationsRequest], - Union[locations_pb2.ListLocationsResponse, Awaitable[locations_pb2.ListLocationsResponse]], - ]: - raise NotImplementedError() - - @property - def kind(self) -> str: - raise NotImplementedError() - - -__all__ = ( - 'IntentsTransport', -) diff --git a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/intents/transports/grpc.py b/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/intents/transports/grpc.py deleted file mode 100644 index 11dc13f33..000000000 --- a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/intents/transports/grpc.py +++ /dev/null @@ -1,576 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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 -from google.api_core import operations_v1 -from google.api_core import gapic_v1 -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.cloud.location import locations_pb2 # type: ignore -from google.longrunning import operations_pb2 -from google.longrunning import operations_pb2 # type: ignore -from google.protobuf import empty_pb2 # type: ignore -from .base import IntentsTransport, DEFAULT_CLIENT_INFO - - -class IntentsGrpcTransport(IntentsTransport): - """gRPC backend transport for Intents. - - Service for managing - [Intents][google.cloud.dialogflow.v2beta1.Intent]. - - 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: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - channel: Optional[grpc.Channel] = None, - api_mtls_endpoint: Optional[str] = None, - client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, - ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, - client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - api_audience: Optional[str] = None, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - This argument is ignored if ``channel`` is provided. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional(Sequence[str])): A list of scopes. This argument is - ignored if ``channel`` is provided. - channel (Optional[grpc.Channel]): A ``Channel`` instance through - which to make calls. - api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. - If provided, it overrides the ``host`` argument and tries to create - a mutual TLS channel with client SSL credentials from - ``client_cert_source`` or application default SSL credentials. - client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): - Deprecated. A callback to provide client SSL certificate bytes and - private key bytes, both in PEM format. It is ignored if - ``api_mtls_endpoint`` is None. - ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials - for the grpc channel. It is ignored if ``channel`` is provided. - client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): - A callback to provide client certificate bytes and private key bytes, - both in PEM format. It is used to configure a mutual TLS channel. It is - ignored if ``channel`` or ``ssl_channel_credentials`` is provided. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport - creation failed for any reason. - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - self._grpc_channel = None - self._ssl_channel_credentials = ssl_channel_credentials - self._stubs: Dict[str, Callable] = {} - self._operations_client: Optional[operations_v1.OperationsClient] = None - - if api_mtls_endpoint: - warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) - if client_cert_source: - warnings.warn("client_cert_source is deprecated", DeprecationWarning) - - if channel: - # Ignore credentials if a channel was passed. - credentials = False - # If a channel was explicitly provided, set it. - self._grpc_channel = channel - self._ssl_channel_credentials = None - - else: - if api_mtls_endpoint: - host = api_mtls_endpoint - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - self._ssl_channel_credentials = SslCredentials().ssl_credentials - - else: - if client_cert_source_for_mtls and not ssl_channel_credentials: - cert, key = client_cert_source_for_mtls() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - - # The base transport sets the host, credentials and scopes - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes, - quota_project_id=quota_project_id, - client_info=client_info, - always_use_jwt_access=always_use_jwt_access, - api_audience=api_audience, - ) - - if not self._grpc_channel: - self._grpc_channel = type(self).create_channel( - self._host, - # use the credentials which are saved - credentials=self._credentials, - # Set ``credentials_file`` to ``None`` here as - # the credentials that we saved earlier should be used. - credentials_file=None, - 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: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - **kwargs) -> grpc.Channel: - """Create and return a gRPC channel object. - Args: - host (Optional[str]): The host for the channel to use. - credentials (Optional[~.Credentials]): The - authorization credentials to attach to requests. These - credentials identify this application to the service. If - none are specified, the client will attempt to ascertain - the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - kwargs (Optional[dict]): Keyword arguments, which are passed to the - channel creation. - Returns: - grpc.Channel: A gRPC channel object. - - Raises: - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - - return grpc_helpers.create_channel( - host, - credentials=credentials, - credentials_file=credentials_file, - quota_project_id=quota_project_id, - default_scopes=cls.AUTH_SCOPES, - scopes=scopes, - default_host=cls.DEFAULT_HOST, - **kwargs - ) - - @property - def grpc_channel(self) -> grpc.Channel: - """Return the channel designed to connect to this service. - """ - return self._grpc_channel - - @property - def operations_client(self) -> operations_v1.OperationsClient: - """Create the client designed to process long-running operations. - - This property caches on the instance; repeated calls return the same - client. - """ - # Quick check: Only create a new client if we do not already have one. - if self._operations_client is None: - self._operations_client = operations_v1.OperationsClient( - self.grpc_channel - ) - - # Return the client from cache. - return self._operations_client - - @property - def list_intents(self) -> Callable[ - [intent.ListIntentsRequest], - intent.ListIntentsResponse]: - r"""Return a callable for the list intents method over gRPC. - - Returns the list of all intents in the specified - agent. - - Returns: - Callable[[~.ListIntentsRequest], - ~.ListIntentsResponse]: - 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_intents' not in self._stubs: - self._stubs['list_intents'] = self.grpc_channel.unary_unary( - '/google.cloud.dialogflow.v2beta1.Intents/ListIntents', - request_serializer=intent.ListIntentsRequest.serialize, - response_deserializer=intent.ListIntentsResponse.deserialize, - ) - return self._stubs['list_intents'] - - @property - def get_intent(self) -> Callable[ - [intent.GetIntentRequest], - intent.Intent]: - r"""Return a callable for the get intent method over gRPC. - - Retrieves the specified intent. - - Returns: - Callable[[~.GetIntentRequest], - ~.Intent]: - 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_intent' not in self._stubs: - self._stubs['get_intent'] = self.grpc_channel.unary_unary( - '/google.cloud.dialogflow.v2beta1.Intents/GetIntent', - request_serializer=intent.GetIntentRequest.serialize, - response_deserializer=intent.Intent.deserialize, - ) - return self._stubs['get_intent'] - - @property - def create_intent(self) -> Callable[ - [gcd_intent.CreateIntentRequest], - gcd_intent.Intent]: - r"""Return a callable for the create intent method over gRPC. - - Creates an intent in the specified agent. - - Note: You should always train an agent prior to sending it - queries. See the `training - documentation `__. - - Returns: - Callable[[~.CreateIntentRequest], - ~.Intent]: - 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_intent' not in self._stubs: - self._stubs['create_intent'] = self.grpc_channel.unary_unary( - '/google.cloud.dialogflow.v2beta1.Intents/CreateIntent', - request_serializer=gcd_intent.CreateIntentRequest.serialize, - response_deserializer=gcd_intent.Intent.deserialize, - ) - return self._stubs['create_intent'] - - @property - def update_intent(self) -> Callable[ - [gcd_intent.UpdateIntentRequest], - gcd_intent.Intent]: - r"""Return a callable for the update intent method over gRPC. - - Updates the specified intent. - - Note: You should always train an agent prior to sending it - queries. See the `training - documentation `__. - - Returns: - Callable[[~.UpdateIntentRequest], - ~.Intent]: - 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_intent' not in self._stubs: - self._stubs['update_intent'] = self.grpc_channel.unary_unary( - '/google.cloud.dialogflow.v2beta1.Intents/UpdateIntent', - request_serializer=gcd_intent.UpdateIntentRequest.serialize, - response_deserializer=gcd_intent.Intent.deserialize, - ) - return self._stubs['update_intent'] - - @property - 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 indirect followup - intents. - - Note: You should always train an agent prior to sending it - queries. See the `training - documentation `__. - - Returns: - Callable[[~.DeleteIntentRequest], - ~.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_intent' not in self._stubs: - self._stubs['delete_intent'] = self.grpc_channel.unary_unary( - '/google.cloud.dialogflow.v2beta1.Intents/DeleteIntent', - request_serializer=intent.DeleteIntentRequest.serialize, - response_deserializer=empty_pb2.Empty.FromString, - ) - return self._stubs['delete_intent'] - - @property - def batch_update_intents(self) -> 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. - - This method is a `long-running - operation `__. - The returned ``Operation`` type has the following - method-specific fields: - - - ``metadata``: An empty `Struct - message `__ - - ``response``: - [BatchUpdateIntentsResponse][google.cloud.dialogflow.v2beta1.BatchUpdateIntentsResponse] - - Note: You should always train an agent prior to sending it - queries. See the `training - documentation `__. - - Returns: - Callable[[~.BatchUpdateIntentsRequest], - ~.Operation]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'batch_update_intents' not in self._stubs: - self._stubs['batch_update_intents'] = self.grpc_channel.unary_unary( - '/google.cloud.dialogflow.v2beta1.Intents/BatchUpdateIntents', - request_serializer=intent.BatchUpdateIntentsRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['batch_update_intents'] - - @property - def batch_delete_intents(self) -> Callable[ - [intent.BatchDeleteIntentsRequest], - operations_pb2.Operation]: - r"""Return a callable for the batch delete intents method over gRPC. - - Deletes intents in the specified agent. - - This method is a `long-running - operation `__. - The returned ``Operation`` type has the following - method-specific fields: - - - ``metadata``: An empty `Struct - message `__ - - ``response``: An `Empty - message `__ - - Note: You should always train an agent prior to sending it - queries. See the `training - documentation `__. - - Returns: - Callable[[~.BatchDeleteIntentsRequest], - ~.Operation]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'batch_delete_intents' not in self._stubs: - self._stubs['batch_delete_intents'] = self.grpc_channel.unary_unary( - '/google.cloud.dialogflow.v2beta1.Intents/BatchDeleteIntents', - request_serializer=intent.BatchDeleteIntentsRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['batch_delete_intents'] - - def close(self): - self.grpc_channel.close() - - @property - def cancel_operation( - self, - ) -> Callable[[operations_pb2.CancelOperationRequest], None]: - r"""Return a callable for the cancel_operation method over gRPC. - """ - # 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 "cancel_operation" not in self._stubs: - self._stubs["cancel_operation"] = self.grpc_channel.unary_unary( - "/google.longrunning.Operations/CancelOperation", - request_serializer=operations_pb2.CancelOperationRequest.SerializeToString, - response_deserializer=None, - ) - return self._stubs["cancel_operation"] - - @property - def get_operation( - self, - ) -> Callable[[operations_pb2.GetOperationRequest], operations_pb2.Operation]: - r"""Return a callable for the get_operation method over gRPC. - """ - # 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_operation" not in self._stubs: - self._stubs["get_operation"] = self.grpc_channel.unary_unary( - "/google.longrunning.Operations/GetOperation", - request_serializer=operations_pb2.GetOperationRequest.SerializeToString, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs["get_operation"] - - @property - def list_operations( - self, - ) -> Callable[[operations_pb2.ListOperationsRequest], operations_pb2.ListOperationsResponse]: - r"""Return a callable for the list_operations method over gRPC. - """ - # 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_operations" not in self._stubs: - self._stubs["list_operations"] = self.grpc_channel.unary_unary( - "/google.longrunning.Operations/ListOperations", - request_serializer=operations_pb2.ListOperationsRequest.SerializeToString, - response_deserializer=operations_pb2.ListOperationsResponse.FromString, - ) - return self._stubs["list_operations"] - - @property - def list_locations( - self, - ) -> Callable[[locations_pb2.ListLocationsRequest], locations_pb2.ListLocationsResponse]: - r"""Return a callable for the list locations method over gRPC. - """ - # 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_locations" not in self._stubs: - self._stubs["list_locations"] = self.grpc_channel.unary_unary( - "/google.cloud.location.Locations/ListLocations", - request_serializer=locations_pb2.ListLocationsRequest.SerializeToString, - response_deserializer=locations_pb2.ListLocationsResponse.FromString, - ) - return self._stubs["list_locations"] - - @property - def get_location( - self, - ) -> Callable[[locations_pb2.GetLocationRequest], locations_pb2.Location]: - r"""Return a callable for the list locations method over gRPC. - """ - # 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_location" not in self._stubs: - self._stubs["get_location"] = self.grpc_channel.unary_unary( - "/google.cloud.location.Locations/GetLocation", - request_serializer=locations_pb2.GetLocationRequest.SerializeToString, - response_deserializer=locations_pb2.Location.FromString, - ) - return self._stubs["get_location"] - - @property - def kind(self) -> str: - return "grpc" - - -__all__ = ( - 'IntentsGrpcTransport', -) diff --git a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/intents/transports/grpc_asyncio.py b/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/intents/transports/grpc_asyncio.py deleted file mode 100644 index a8fe204e4..000000000 --- a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/intents/transports/grpc_asyncio.py +++ /dev/null @@ -1,575 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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 -from google.api_core import grpc_helpers_async -from google.api_core import operations_v1 -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore - -import grpc # type: ignore -from grpc.experimental import aio # type: ignore - -from google.cloud.dialogflow_v2beta1.types import intent -from google.cloud.dialogflow_v2beta1.types import intent as gcd_intent -from google.cloud.location import locations_pb2 # type: ignore -from google.longrunning import operations_pb2 -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 - - -class IntentsGrpcAsyncIOTransport(IntentsTransport): - """gRPC AsyncIO backend transport for Intents. - - Service for managing - [Intents][google.cloud.dialogflow.v2beta1.Intent]. - - 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: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - **kwargs) -> aio.Channel: - """Create and return a gRPC AsyncIO channel object. - Args: - host (Optional[str]): The host for the channel to use. - credentials (Optional[~.Credentials]): The - authorization credentials to attach to requests. These - credentials identify this application to the service. If - none are specified, the client will attempt to ascertain - the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - kwargs (Optional[dict]): Keyword arguments, which are passed to the - channel creation. - Returns: - aio.Channel: A gRPC AsyncIO channel object. - """ - - return grpc_helpers_async.create_channel( - host, - credentials=credentials, - credentials_file=credentials_file, - quota_project_id=quota_project_id, - default_scopes=cls.AUTH_SCOPES, - scopes=scopes, - default_host=cls.DEFAULT_HOST, - **kwargs - ) - - def __init__(self, *, - host: str = 'dialogflow.googleapis.com', - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - channel: Optional[aio.Channel] = None, - api_mtls_endpoint: Optional[str] = None, - client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, - ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, - client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - api_audience: Optional[str] = None, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - This argument is ignored if ``channel`` is provided. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - channel (Optional[aio.Channel]): A ``Channel`` instance through - which to make calls. - api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. - If provided, it overrides the ``host`` argument and tries to create - a mutual TLS channel with client SSL credentials from - ``client_cert_source`` or application default SSL credentials. - client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): - Deprecated. A callback to provide client SSL certificate bytes and - private key bytes, both in PEM format. It is ignored if - ``api_mtls_endpoint`` is None. - ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials - for the grpc channel. It is ignored if ``channel`` is provided. - client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): - A callback to provide client certificate bytes and private key bytes, - both in PEM format. It is used to configure a mutual TLS channel. It is - ignored if ``channel`` or ``ssl_channel_credentials`` is provided. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - - Raises: - google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport - creation failed for any reason. - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - self._grpc_channel = None - self._ssl_channel_credentials = ssl_channel_credentials - self._stubs: Dict[str, Callable] = {} - self._operations_client: Optional[operations_v1.OperationsAsyncClient] = None - - if api_mtls_endpoint: - warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) - if client_cert_source: - warnings.warn("client_cert_source is deprecated", DeprecationWarning) - - if channel: - # Ignore credentials if a channel was passed. - credentials = False - # If a channel was explicitly provided, set it. - self._grpc_channel = channel - self._ssl_channel_credentials = None - else: - if api_mtls_endpoint: - host = api_mtls_endpoint - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - self._ssl_channel_credentials = SslCredentials().ssl_credentials - - else: - if client_cert_source_for_mtls and not ssl_channel_credentials: - cert, key = client_cert_source_for_mtls() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - - # The base transport sets the host, credentials and scopes - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes, - quota_project_id=quota_project_id, - client_info=client_info, - always_use_jwt_access=always_use_jwt_access, - api_audience=api_audience, - ) - - if not self._grpc_channel: - self._grpc_channel = type(self).create_channel( - self._host, - # use the credentials which are saved - credentials=self._credentials, - # Set ``credentials_file`` to ``None`` here as - # the credentials that we saved earlier should be used. - credentials_file=None, - 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 operations_client(self) -> operations_v1.OperationsAsyncClient: - """Create the client designed to process long-running operations. - - This property caches on the instance; repeated calls return the same - client. - """ - # Quick check: Only create a new client if we do not already have one. - if self._operations_client is None: - self._operations_client = operations_v1.OperationsAsyncClient( - self.grpc_channel - ) - - # Return the client from cache. - return self._operations_client - - @property - def list_intents(self) -> Callable[ - [intent.ListIntentsRequest], - Awaitable[intent.ListIntentsResponse]]: - r"""Return a callable for the list intents method over gRPC. - - Returns the list of all intents in the specified - agent. - - Returns: - Callable[[~.ListIntentsRequest], - Awaitable[~.ListIntentsResponse]]: - 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_intents' not in self._stubs: - self._stubs['list_intents'] = self.grpc_channel.unary_unary( - '/google.cloud.dialogflow.v2beta1.Intents/ListIntents', - request_serializer=intent.ListIntentsRequest.serialize, - response_deserializer=intent.ListIntentsResponse.deserialize, - ) - return self._stubs['list_intents'] - - @property - def get_intent(self) -> Callable[ - [intent.GetIntentRequest], - Awaitable[intent.Intent]]: - r"""Return a callable for the get intent method over gRPC. - - Retrieves the specified intent. - - Returns: - Callable[[~.GetIntentRequest], - Awaitable[~.Intent]]: - 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_intent' not in self._stubs: - self._stubs['get_intent'] = self.grpc_channel.unary_unary( - '/google.cloud.dialogflow.v2beta1.Intents/GetIntent', - request_serializer=intent.GetIntentRequest.serialize, - response_deserializer=intent.Intent.deserialize, - ) - return self._stubs['get_intent'] - - @property - def create_intent(self) -> Callable[ - [gcd_intent.CreateIntentRequest], - Awaitable[gcd_intent.Intent]]: - r"""Return a callable for the create intent method over gRPC. - - Creates an intent in the specified agent. - - Note: You should always train an agent prior to sending it - queries. See the `training - documentation `__. - - Returns: - Callable[[~.CreateIntentRequest], - Awaitable[~.Intent]]: - 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_intent' not in self._stubs: - self._stubs['create_intent'] = self.grpc_channel.unary_unary( - '/google.cloud.dialogflow.v2beta1.Intents/CreateIntent', - request_serializer=gcd_intent.CreateIntentRequest.serialize, - response_deserializer=gcd_intent.Intent.deserialize, - ) - return self._stubs['create_intent'] - - @property - def update_intent(self) -> Callable[ - [gcd_intent.UpdateIntentRequest], - Awaitable[gcd_intent.Intent]]: - r"""Return a callable for the update intent method over gRPC. - - Updates the specified intent. - - Note: You should always train an agent prior to sending it - queries. See the `training - documentation `__. - - Returns: - Callable[[~.UpdateIntentRequest], - Awaitable[~.Intent]]: - 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_intent' not in self._stubs: - self._stubs['update_intent'] = self.grpc_channel.unary_unary( - '/google.cloud.dialogflow.v2beta1.Intents/UpdateIntent', - request_serializer=gcd_intent.UpdateIntentRequest.serialize, - response_deserializer=gcd_intent.Intent.deserialize, - ) - return self._stubs['update_intent'] - - @property - def delete_intent(self) -> 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 indirect followup - intents. - - Note: You should always train an agent prior to sending it - queries. See the `training - documentation `__. - - Returns: - Callable[[~.DeleteIntentRequest], - 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_intent' not in self._stubs: - self._stubs['delete_intent'] = self.grpc_channel.unary_unary( - '/google.cloud.dialogflow.v2beta1.Intents/DeleteIntent', - request_serializer=intent.DeleteIntentRequest.serialize, - response_deserializer=empty_pb2.Empty.FromString, - ) - return self._stubs['delete_intent'] - - @property - def batch_update_intents(self) -> 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. - - This method is a `long-running - operation `__. - The returned ``Operation`` type has the following - method-specific fields: - - - ``metadata``: An empty `Struct - message `__ - - ``response``: - [BatchUpdateIntentsResponse][google.cloud.dialogflow.v2beta1.BatchUpdateIntentsResponse] - - Note: You should always train an agent prior to sending it - queries. See the `training - documentation `__. - - Returns: - Callable[[~.BatchUpdateIntentsRequest], - Awaitable[~.Operation]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'batch_update_intents' not in self._stubs: - self._stubs['batch_update_intents'] = self.grpc_channel.unary_unary( - '/google.cloud.dialogflow.v2beta1.Intents/BatchUpdateIntents', - request_serializer=intent.BatchUpdateIntentsRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['batch_update_intents'] - - @property - def batch_delete_intents(self) -> 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. - - This method is a `long-running - operation `__. - The returned ``Operation`` type has the following - method-specific fields: - - - ``metadata``: An empty `Struct - message `__ - - ``response``: An `Empty - message `__ - - Note: You should always train an agent prior to sending it - queries. See the `training - documentation `__. - - Returns: - Callable[[~.BatchDeleteIntentsRequest], - Awaitable[~.Operation]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'batch_delete_intents' not in self._stubs: - self._stubs['batch_delete_intents'] = self.grpc_channel.unary_unary( - '/google.cloud.dialogflow.v2beta1.Intents/BatchDeleteIntents', - request_serializer=intent.BatchDeleteIntentsRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['batch_delete_intents'] - - def close(self): - return self.grpc_channel.close() - - @property - def cancel_operation( - self, - ) -> Callable[[operations_pb2.CancelOperationRequest], None]: - r"""Return a callable for the cancel_operation method over gRPC. - """ - # 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 "cancel_operation" not in self._stubs: - self._stubs["cancel_operation"] = self.grpc_channel.unary_unary( - "/google.longrunning.Operations/CancelOperation", - request_serializer=operations_pb2.CancelOperationRequest.SerializeToString, - response_deserializer=None, - ) - return self._stubs["cancel_operation"] - - @property - def get_operation( - self, - ) -> Callable[[operations_pb2.GetOperationRequest], operations_pb2.Operation]: - r"""Return a callable for the get_operation method over gRPC. - """ - # 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_operation" not in self._stubs: - self._stubs["get_operation"] = self.grpc_channel.unary_unary( - "/google.longrunning.Operations/GetOperation", - request_serializer=operations_pb2.GetOperationRequest.SerializeToString, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs["get_operation"] - - @property - def list_operations( - self, - ) -> Callable[[operations_pb2.ListOperationsRequest], operations_pb2.ListOperationsResponse]: - r"""Return a callable for the list_operations method over gRPC. - """ - # 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_operations" not in self._stubs: - self._stubs["list_operations"] = self.grpc_channel.unary_unary( - "/google.longrunning.Operations/ListOperations", - request_serializer=operations_pb2.ListOperationsRequest.SerializeToString, - response_deserializer=operations_pb2.ListOperationsResponse.FromString, - ) - return self._stubs["list_operations"] - - @property - def list_locations( - self, - ) -> Callable[[locations_pb2.ListLocationsRequest], locations_pb2.ListLocationsResponse]: - r"""Return a callable for the list locations method over gRPC. - """ - # 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_locations" not in self._stubs: - self._stubs["list_locations"] = self.grpc_channel.unary_unary( - "/google.cloud.location.Locations/ListLocations", - request_serializer=locations_pb2.ListLocationsRequest.SerializeToString, - response_deserializer=locations_pb2.ListLocationsResponse.FromString, - ) - return self._stubs["list_locations"] - - @property - def get_location( - self, - ) -> Callable[[locations_pb2.GetLocationRequest], locations_pb2.Location]: - r"""Return a callable for the list locations method over gRPC. - """ - # 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_location" not in self._stubs: - self._stubs["get_location"] = self.grpc_channel.unary_unary( - "/google.cloud.location.Locations/GetLocation", - request_serializer=locations_pb2.GetLocationRequest.SerializeToString, - response_deserializer=locations_pb2.Location.FromString, - ) - return self._stubs["get_location"] - - -__all__ = ( - 'IntentsGrpcAsyncIOTransport', -) diff --git a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/intents/transports/rest.py b/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/intents/transports/rest.py deleted file mode 100644 index 90ca589c1..000000000 --- a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/intents/transports/rest.py +++ /dev/null @@ -1,1539 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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 google.auth.transport.requests import AuthorizedSession # type: ignore -import json # type: ignore -import grpc # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore -from google.auth import credentials as ga_credentials # type: ignore -from google.api_core import exceptions as core_exceptions -from google.api_core import retry as retries -from google.api_core import rest_helpers -from google.api_core import rest_streaming -from google.api_core import path_template -from google.api_core import gapic_v1 - -from google.protobuf import json_format -from google.api_core import operations_v1 -from google.cloud.location import locations_pb2 # type: ignore -from google.longrunning import operations_pb2 -from requests import __version__ as requests_version -import dataclasses -import re -from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union -import warnings - -try: - OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] -except AttributeError: # pragma: NO COVER - OptionalRetry = Union[retries.Retry, object] # 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 # type: ignore -from google.protobuf import empty_pb2 # type: ignore - -from .base import IntentsTransport, DEFAULT_CLIENT_INFO as BASE_DEFAULT_CLIENT_INFO - - -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=BASE_DEFAULT_CLIENT_INFO.gapic_version, - grpc_version=None, - rest_version=requests_version, -) - - -class IntentsRestInterceptor: - """Interceptor for Intents. - - Interceptors are used to manipulate requests, request metadata, and responses - in arbitrary ways. - Example use cases include: - * Logging - * Verifying requests according to service or custom semantics - * Stripping extraneous information from responses - - These use cases and more can be enabled by injecting an - instance of a custom subclass when constructing the IntentsRestTransport. - - .. code-block:: python - class MyCustomIntentsInterceptor(IntentsRestInterceptor): - def pre_batch_delete_intents(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_batch_delete_intents(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_batch_update_intents(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_batch_update_intents(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_create_intent(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_create_intent(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_delete_intent(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def pre_get_intent(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_get_intent(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_list_intents(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_list_intents(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_update_intent(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_update_intent(self, response): - logging.log(f"Received response: {response}") - return response - - transport = IntentsRestTransport(interceptor=MyCustomIntentsInterceptor()) - client = IntentsClient(transport=transport) - - - """ - def pre_batch_delete_intents(self, request: intent.BatchDeleteIntentsRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[intent.BatchDeleteIntentsRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for batch_delete_intents - - Override in a subclass to manipulate the request or metadata - before they are sent to the Intents server. - """ - return request, metadata - - def post_batch_delete_intents(self, response: operations_pb2.Operation) -> operations_pb2.Operation: - """Post-rpc interceptor for batch_delete_intents - - Override in a subclass to manipulate the response - after it is returned by the Intents server but before - it is returned to user code. - """ - return response - def pre_batch_update_intents(self, request: intent.BatchUpdateIntentsRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[intent.BatchUpdateIntentsRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for batch_update_intents - - Override in a subclass to manipulate the request or metadata - before they are sent to the Intents server. - """ - return request, metadata - - def post_batch_update_intents(self, response: operations_pb2.Operation) -> operations_pb2.Operation: - """Post-rpc interceptor for batch_update_intents - - Override in a subclass to manipulate the response - after it is returned by the Intents server but before - it is returned to user code. - """ - return response - def pre_create_intent(self, request: gcd_intent.CreateIntentRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[gcd_intent.CreateIntentRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for create_intent - - Override in a subclass to manipulate the request or metadata - before they are sent to the Intents server. - """ - return request, metadata - - def post_create_intent(self, response: gcd_intent.Intent) -> gcd_intent.Intent: - """Post-rpc interceptor for create_intent - - Override in a subclass to manipulate the response - after it is returned by the Intents server but before - it is returned to user code. - """ - return response - def pre_delete_intent(self, request: intent.DeleteIntentRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[intent.DeleteIntentRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for delete_intent - - Override in a subclass to manipulate the request or metadata - before they are sent to the Intents server. - """ - return request, metadata - - def pre_get_intent(self, request: intent.GetIntentRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[intent.GetIntentRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for get_intent - - Override in a subclass to manipulate the request or metadata - before they are sent to the Intents server. - """ - return request, metadata - - def post_get_intent(self, response: intent.Intent) -> intent.Intent: - """Post-rpc interceptor for get_intent - - Override in a subclass to manipulate the response - after it is returned by the Intents server but before - it is returned to user code. - """ - return response - def pre_list_intents(self, request: intent.ListIntentsRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[intent.ListIntentsRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for list_intents - - Override in a subclass to manipulate the request or metadata - before they are sent to the Intents server. - """ - return request, metadata - - def post_list_intents(self, response: intent.ListIntentsResponse) -> intent.ListIntentsResponse: - """Post-rpc interceptor for list_intents - - Override in a subclass to manipulate the response - after it is returned by the Intents server but before - it is returned to user code. - """ - return response - def pre_update_intent(self, request: gcd_intent.UpdateIntentRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[gcd_intent.UpdateIntentRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for update_intent - - Override in a subclass to manipulate the request or metadata - before they are sent to the Intents server. - """ - return request, metadata - - def post_update_intent(self, response: gcd_intent.Intent) -> gcd_intent.Intent: - """Post-rpc interceptor for update_intent - - Override in a subclass to manipulate the response - after it is returned by the Intents server but before - it is returned to user code. - """ - return response - - def pre_get_location( - self, request: locations_pb2.GetLocationRequest, metadata: Sequence[Tuple[str, str]] - ) -> Tuple[locations_pb2.GetLocationRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for get_location - - Override in a subclass to manipulate the request or metadata - before they are sent to the Intents server. - """ - return request, metadata - - def post_get_location( - self, response: locations_pb2.Location - ) -> locations_pb2.Location: - """Post-rpc interceptor for get_location - - Override in a subclass to manipulate the response - after it is returned by the Intents server but before - it is returned to user code. - """ - return response - def pre_list_locations( - self, request: locations_pb2.ListLocationsRequest, metadata: Sequence[Tuple[str, str]] - ) -> Tuple[locations_pb2.ListLocationsRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for list_locations - - Override in a subclass to manipulate the request or metadata - before they are sent to the Intents server. - """ - return request, metadata - - def post_list_locations( - self, response: locations_pb2.ListLocationsResponse - ) -> locations_pb2.ListLocationsResponse: - """Post-rpc interceptor for list_locations - - Override in a subclass to manipulate the response - after it is returned by the Intents server but before - it is returned to user code. - """ - return response - def pre_cancel_operation( - self, request: operations_pb2.CancelOperationRequest, metadata: Sequence[Tuple[str, str]] - ) -> Tuple[operations_pb2.CancelOperationRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for cancel_operation - - Override in a subclass to manipulate the request or metadata - before they are sent to the Intents server. - """ - return request, metadata - - def post_cancel_operation( - self, response: None - ) -> None: - """Post-rpc interceptor for cancel_operation - - Override in a subclass to manipulate the response - after it is returned by the Intents server but before - it is returned to user code. - """ - return response - def pre_get_operation( - self, request: operations_pb2.GetOperationRequest, metadata: Sequence[Tuple[str, str]] - ) -> Tuple[operations_pb2.GetOperationRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for get_operation - - Override in a subclass to manipulate the request or metadata - before they are sent to the Intents server. - """ - return request, metadata - - def post_get_operation( - self, response: operations_pb2.Operation - ) -> operations_pb2.Operation: - """Post-rpc interceptor for get_operation - - Override in a subclass to manipulate the response - after it is returned by the Intents server but before - it is returned to user code. - """ - return response - def pre_list_operations( - self, request: operations_pb2.ListOperationsRequest, metadata: Sequence[Tuple[str, str]] - ) -> Tuple[operations_pb2.ListOperationsRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for list_operations - - Override in a subclass to manipulate the request or metadata - before they are sent to the Intents server. - """ - return request, metadata - - def post_list_operations( - self, response: operations_pb2.ListOperationsResponse - ) -> operations_pb2.ListOperationsResponse: - """Post-rpc interceptor for list_operations - - Override in a subclass to manipulate the response - after it is returned by the Intents server but before - it is returned to user code. - """ - return response - - -@dataclasses.dataclass -class IntentsRestStub: - _session: AuthorizedSession - _host: str - _interceptor: IntentsRestInterceptor - - -class IntentsRestTransport(IntentsTransport): - """REST backend transport for Intents. - - Service for managing - [Intents][google.cloud.dialogflow.v2beta1.Intent]. - - 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 JSON representations of protocol buffers over HTTP/1.1 - - """ - - def __init__(self, *, - host: str = 'dialogflow.googleapis.com', - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - client_cert_source_for_mtls: Optional[Callable[[ - ], Tuple[bytes, bytes]]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - url_scheme: str = 'https', - interceptor: Optional[IntentsRestInterceptor] = None, - api_audience: Optional[str] = None, - ) -> 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 ignored if ``channel`` is provided. - scopes (Optional(Sequence[str])): A list of scopes. This argument is - ignored if ``channel`` is provided. - client_cert_source_for_mtls (Callable[[], Tuple[bytes, bytes]]): Client - certificate to configure mutual TLS HTTP channel. It is ignored - if ``channel`` is provided. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you are developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - url_scheme: the protocol scheme for the API endpoint. Normally - "https", but for testing or local servers, - "http" can be specified. - """ - # Run the base constructor - # TODO(yon-mg): resolve other ctor params i.e. scopes, quota, etc. - # TODO: When custom host (api_endpoint) is set, `scopes` must *also* be set on the - # credentials object - maybe_url_match = re.match("^(?Phttp(?:s)?://)?(?P.*)$", host) - if maybe_url_match is None: - raise ValueError(f"Unexpected hostname structure: {host}") # pragma: NO COVER - - url_match_items = maybe_url_match.groupdict() - - host = f"{url_scheme}://{host}" if not url_match_items["scheme"] else host - - super().__init__( - host=host, - credentials=credentials, - client_info=client_info, - always_use_jwt_access=always_use_jwt_access, - api_audience=api_audience - ) - self._session = AuthorizedSession( - self._credentials, default_host=self.DEFAULT_HOST) - self._operations_client: Optional[operations_v1.AbstractOperationsClient] = None - if client_cert_source_for_mtls: - self._session.configure_mtls_channel(client_cert_source_for_mtls) - self._interceptor = interceptor or IntentsRestInterceptor() - self._prep_wrapped_messages(client_info) - - @property - def operations_client(self) -> operations_v1.AbstractOperationsClient: - """Create the client designed to process long-running operations. - - This property caches on the instance; repeated calls return the same - client. - """ - # Only create a new client if we do not already have one. - if self._operations_client is None: - http_options: Dict[str, List[Dict[str, str]]] = { - 'google.longrunning.Operations.CancelOperation': [ - { - 'method': 'post', - 'uri': '/v2beta1/{name=projects/*/operations/*}:cancel', - }, - { - 'method': 'post', - 'uri': '/v2beta1/{name=projects/*/locations/*/operations/*}:cancel', - }, - ], - 'google.longrunning.Operations.GetOperation': [ - { - 'method': 'get', - 'uri': '/v2beta1/{name=projects/*/operations/*}', - }, - { - 'method': 'get', - 'uri': '/v2beta1/{name=projects/*/locations/*/operations/*}', - }, - ], - 'google.longrunning.Operations.ListOperations': [ - { - 'method': 'get', - 'uri': '/v2beta1/{name=projects/*}/operations', - }, - { - 'method': 'get', - 'uri': '/v2beta1/{name=projects/*/locations/*}/operations', - }, - ], - } - - rest_transport = operations_v1.OperationsRestTransport( - host=self._host, - # use the credentials which are saved - credentials=self._credentials, - scopes=self._scopes, - http_options=http_options, - path_prefix="v2beta1") - - self._operations_client = operations_v1.AbstractOperationsClient(transport=rest_transport) - - # Return the client from cache. - return self._operations_client - - class _BatchDeleteIntents(IntentsRestStub): - def __hash__(self): - return hash("BatchDeleteIntents") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: intent.BatchDeleteIntentsRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> operations_pb2.Operation: - r"""Call the batch delete intents method over HTTP. - - Args: - request (~.intent.BatchDeleteIntentsRequest): - The request object. The request message for - [Intents.BatchDeleteIntents][google.cloud.dialogflow.v2beta1.Intents.BatchDeleteIntents]. - 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: - ~.operations_pb2.Operation: - This resource represents a - long-running operation that is the - result of a network API call. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'post', - 'uri': '/v2beta1/{parent=projects/*/agent}/intents:batchDelete', - 'body': '*', - }, -{ - 'method': 'post', - 'uri': '/v2beta1/{parent=projects/*/locations/*/agent}/intents:batchDelete', - 'body': '*', - }, - ] - request, metadata = self._interceptor.pre_batch_delete_intents(request, metadata) - pb_request = intent.BatchDeleteIntentsRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request['body'], - including_default_value_fields=False, - use_integers_for_enums=True - ) - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - including_default_value_fields=False, - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = operations_pb2.Operation() - json_format.Parse(response.content, resp, ignore_unknown_fields=True) - resp = self._interceptor.post_batch_delete_intents(resp) - return resp - - class _BatchUpdateIntents(IntentsRestStub): - def __hash__(self): - return hash("BatchUpdateIntents") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: intent.BatchUpdateIntentsRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> operations_pb2.Operation: - r"""Call the batch update intents method over HTTP. - - Args: - request (~.intent.BatchUpdateIntentsRequest): - The request object. The request message for - [Intents.BatchUpdateIntents][google.cloud.dialogflow.v2beta1.Intents.BatchUpdateIntents]. - 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: - ~.operations_pb2.Operation: - This resource represents a - long-running operation that is the - result of a network API call. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'post', - 'uri': '/v2beta1/{parent=projects/*/agent}/intents:batchUpdate', - 'body': '*', - }, -{ - 'method': 'post', - 'uri': '/v2beta1/{parent=projects/*/locations/*/agent}/intents:batchUpdate', - 'body': '*', - }, - ] - request, metadata = self._interceptor.pre_batch_update_intents(request, metadata) - pb_request = intent.BatchUpdateIntentsRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request['body'], - including_default_value_fields=False, - use_integers_for_enums=True - ) - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - including_default_value_fields=False, - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = operations_pb2.Operation() - json_format.Parse(response.content, resp, ignore_unknown_fields=True) - resp = self._interceptor.post_batch_update_intents(resp) - return resp - - class _CreateIntent(IntentsRestStub): - def __hash__(self): - return hash("CreateIntent") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: gcd_intent.CreateIntentRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> gcd_intent.Intent: - r"""Call the create intent method over HTTP. - - Args: - request (~.gcd_intent.CreateIntentRequest): - The request object. The request message for - [Intents.CreateIntent][google.cloud.dialogflow.v2beta1.Intents.CreateIntent]. - 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: - ~.gcd_intent.Intent: - An intent categorizes an end-user's intention for one - conversation turn. For each agent, you define many - intents, where your combined intents can handle a - complete conversation. When an end-user writes or says - something, referred to as an end-user expression or - end-user input, Dialogflow matches the end-user input to - the best intent in your agent. Matching an intent is - also known as intent classification. - - For more information, see the `intent - guide `__. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'post', - 'uri': '/v2beta1/{parent=projects/*/agent}/intents', - 'body': 'intent', - }, -{ - 'method': 'post', - 'uri': '/v2beta1/{parent=projects/*/locations/*/agent}/intents', - 'body': 'intent', - }, - ] - request, metadata = self._interceptor.pre_create_intent(request, metadata) - pb_request = gcd_intent.CreateIntentRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request['body'], - including_default_value_fields=False, - use_integers_for_enums=True - ) - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - including_default_value_fields=False, - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = gcd_intent.Intent() - pb_resp = gcd_intent.Intent.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_create_intent(resp) - return resp - - class _DeleteIntent(IntentsRestStub): - def __hash__(self): - return hash("DeleteIntent") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: intent.DeleteIntentRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ): - r"""Call the delete intent method over HTTP. - - Args: - request (~.intent.DeleteIntentRequest): - The request object. The request message for - [Intents.DeleteIntent][google.cloud.dialogflow.v2beta1.Intents.DeleteIntent]. - 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. - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'delete', - 'uri': '/v2beta1/{name=projects/*/agent/intents/*}', - }, -{ - 'method': 'delete', - 'uri': '/v2beta1/{name=projects/*/locations/*/agent/intents/*}', - }, - ] - request, metadata = self._interceptor.pre_delete_intent(request, metadata) - pb_request = intent.DeleteIntentRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - including_default_value_fields=False, - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - class _GetIntent(IntentsRestStub): - def __hash__(self): - return hash("GetIntent") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: intent.GetIntentRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> intent.Intent: - r"""Call the get intent method over HTTP. - - Args: - request (~.intent.GetIntentRequest): - The request object. The request message for - [Intents.GetIntent][google.cloud.dialogflow.v2beta1.Intents.GetIntent]. - 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: - ~.intent.Intent: - An intent categorizes an end-user's intention for one - conversation turn. For each agent, you define many - intents, where your combined intents can handle a - complete conversation. When an end-user writes or says - something, referred to as an end-user expression or - end-user input, Dialogflow matches the end-user input to - the best intent in your agent. Matching an intent is - also known as intent classification. - - For more information, see the `intent - guide `__. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v2beta1/{name=projects/*/agent/intents/*}', - }, -{ - 'method': 'get', - 'uri': '/v2beta1/{name=projects/*/locations/*/agent/intents/*}', - }, - ] - request, metadata = self._interceptor.pre_get_intent(request, metadata) - pb_request = intent.GetIntentRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - including_default_value_fields=False, - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = intent.Intent() - pb_resp = intent.Intent.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_get_intent(resp) - return resp - - class _ListIntents(IntentsRestStub): - def __hash__(self): - return hash("ListIntents") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: intent.ListIntentsRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> intent.ListIntentsResponse: - r"""Call the list intents method over HTTP. - - Args: - request (~.intent.ListIntentsRequest): - The request object. The request message for - [Intents.ListIntents][google.cloud.dialogflow.v2beta1.Intents.ListIntents]. - 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: - ~.intent.ListIntentsResponse: - The response message for - [Intents.ListIntents][google.cloud.dialogflow.v2beta1.Intents.ListIntents]. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v2beta1/{parent=projects/*/agent}/intents', - }, -{ - 'method': 'get', - 'uri': '/v2beta1/{parent=projects/*/locations/*/agent}/intents', - }, -{ - 'method': 'get', - 'uri': '/v2beta1/{parent=projects/*/agent/environments/*}/intents', - }, -{ - 'method': 'get', - 'uri': '/v2beta1/{parent=projects/*/locations/*/agent/environments/*}/intents', - }, - ] - request, metadata = self._interceptor.pre_list_intents(request, metadata) - pb_request = intent.ListIntentsRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - including_default_value_fields=False, - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = intent.ListIntentsResponse() - pb_resp = intent.ListIntentsResponse.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_list_intents(resp) - return resp - - class _UpdateIntent(IntentsRestStub): - def __hash__(self): - return hash("UpdateIntent") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: gcd_intent.UpdateIntentRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> gcd_intent.Intent: - r"""Call the update intent method over HTTP. - - Args: - request (~.gcd_intent.UpdateIntentRequest): - The request object. The request message for - [Intents.UpdateIntent][google.cloud.dialogflow.v2beta1.Intents.UpdateIntent]. - 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: - ~.gcd_intent.Intent: - An intent categorizes an end-user's intention for one - conversation turn. For each agent, you define many - intents, where your combined intents can handle a - complete conversation. When an end-user writes or says - something, referred to as an end-user expression or - end-user input, Dialogflow matches the end-user input to - the best intent in your agent. Matching an intent is - also known as intent classification. - - For more information, see the `intent - guide `__. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'patch', - 'uri': '/v2beta1/{intent.name=projects/*/agent/intents/*}', - 'body': 'intent', - }, -{ - 'method': 'patch', - 'uri': '/v2beta1/{intent.name=projects/*/locations/*/agent/intents/*}', - 'body': 'intent', - }, - ] - request, metadata = self._interceptor.pre_update_intent(request, metadata) - pb_request = gcd_intent.UpdateIntentRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request['body'], - including_default_value_fields=False, - use_integers_for_enums=True - ) - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - including_default_value_fields=False, - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = gcd_intent.Intent() - pb_resp = gcd_intent.Intent.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_update_intent(resp) - return resp - - @property - def batch_delete_intents(self) -> Callable[ - [intent.BatchDeleteIntentsRequest], - operations_pb2.Operation]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._BatchDeleteIntents(self._session, self._host, self._interceptor) # type: ignore - - @property - def batch_update_intents(self) -> Callable[ - [intent.BatchUpdateIntentsRequest], - operations_pb2.Operation]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._BatchUpdateIntents(self._session, self._host, self._interceptor) # type: ignore - - @property - def create_intent(self) -> Callable[ - [gcd_intent.CreateIntentRequest], - gcd_intent.Intent]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._CreateIntent(self._session, self._host, self._interceptor) # type: ignore - - @property - def delete_intent(self) -> Callable[ - [intent.DeleteIntentRequest], - empty_pb2.Empty]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._DeleteIntent(self._session, self._host, self._interceptor) # type: ignore - - @property - def get_intent(self) -> Callable[ - [intent.GetIntentRequest], - intent.Intent]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._GetIntent(self._session, self._host, self._interceptor) # type: ignore - - @property - def list_intents(self) -> Callable[ - [intent.ListIntentsRequest], - intent.ListIntentsResponse]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._ListIntents(self._session, self._host, self._interceptor) # type: ignore - - @property - def update_intent(self) -> Callable[ - [gcd_intent.UpdateIntentRequest], - gcd_intent.Intent]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._UpdateIntent(self._session, self._host, self._interceptor) # type: ignore - - @property - def get_location(self): - return self._GetLocation(self._session, self._host, self._interceptor) # type: ignore - - class _GetLocation(IntentsRestStub): - def __call__(self, - request: locations_pb2.GetLocationRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> locations_pb2.Location: - - r"""Call the get location method over HTTP. - - Args: - request (locations_pb2.GetLocationRequest): - The request object for GetLocation method. - 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: - locations_pb2.Location: Response from GetLocation method. - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v2beta1/{name=projects/*/locations/*}', - }, - ] - - request, metadata = self._interceptor.pre_get_location(request, metadata) - request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode( - http_options, **request_kwargs) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json.dumps(transcoded_request['query_params'])) - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - resp = locations_pb2.Location() - resp = json_format.Parse(response.content.decode("utf-8"), resp) - resp = self._interceptor.post_get_location(resp) - return resp - - @property - def list_locations(self): - return self._ListLocations(self._session, self._host, self._interceptor) # type: ignore - - class _ListLocations(IntentsRestStub): - def __call__(self, - request: locations_pb2.ListLocationsRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> locations_pb2.ListLocationsResponse: - - r"""Call the list locations method over HTTP. - - Args: - request (locations_pb2.ListLocationsRequest): - The request object for ListLocations method. - 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: - locations_pb2.ListLocationsResponse: Response from ListLocations method. - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v2beta1/{name=projects/*}/locations', - }, - ] - - request, metadata = self._interceptor.pre_list_locations(request, metadata) - request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode( - http_options, **request_kwargs) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json.dumps(transcoded_request['query_params'])) - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - resp = locations_pb2.ListLocationsResponse() - resp = json_format.Parse(response.content.decode("utf-8"), resp) - resp = self._interceptor.post_list_locations(resp) - return resp - - @property - def cancel_operation(self): - return self._CancelOperation(self._session, self._host, self._interceptor) # type: ignore - - class _CancelOperation(IntentsRestStub): - def __call__(self, - request: operations_pb2.CancelOperationRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> None: - - r"""Call the cancel operation method over HTTP. - - Args: - request (operations_pb2.CancelOperationRequest): - The request object for CancelOperation method. - 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. - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'post', - 'uri': '/v2beta1/{name=projects/*/operations/*}:cancel', - }, -{ - 'method': 'post', - 'uri': '/v2beta1/{name=projects/*/locations/*/operations/*}:cancel', - }, - ] - - request, metadata = self._interceptor.pre_cancel_operation(request, metadata) - request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode( - http_options, **request_kwargs) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json.dumps(transcoded_request['query_params'])) - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - return self._interceptor.post_cancel_operation(None) - - @property - def get_operation(self): - return self._GetOperation(self._session, self._host, self._interceptor) # type: ignore - - class _GetOperation(IntentsRestStub): - def __call__(self, - request: operations_pb2.GetOperationRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> operations_pb2.Operation: - - r"""Call the get operation method over HTTP. - - Args: - request (operations_pb2.GetOperationRequest): - The request object for GetOperation method. - 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: - operations_pb2.Operation: Response from GetOperation method. - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v2beta1/{name=projects/*/operations/*}', - }, -{ - 'method': 'get', - 'uri': '/v2beta1/{name=projects/*/locations/*/operations/*}', - }, - ] - - request, metadata = self._interceptor.pre_get_operation(request, metadata) - request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode( - http_options, **request_kwargs) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json.dumps(transcoded_request['query_params'])) - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - resp = operations_pb2.Operation() - resp = json_format.Parse(response.content.decode("utf-8"), resp) - resp = self._interceptor.post_get_operation(resp) - return resp - - @property - def list_operations(self): - return self._ListOperations(self._session, self._host, self._interceptor) # type: ignore - - class _ListOperations(IntentsRestStub): - def __call__(self, - request: operations_pb2.ListOperationsRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> operations_pb2.ListOperationsResponse: - - r"""Call the list operations method over HTTP. - - Args: - request (operations_pb2.ListOperationsRequest): - The request object for ListOperations method. - 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: - operations_pb2.ListOperationsResponse: Response from ListOperations method. - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v2beta1/{name=projects/*}/operations', - }, -{ - 'method': 'get', - 'uri': '/v2beta1/{name=projects/*/locations/*}/operations', - }, - ] - - request, metadata = self._interceptor.pre_list_operations(request, metadata) - request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode( - http_options, **request_kwargs) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json.dumps(transcoded_request['query_params'])) - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - resp = operations_pb2.ListOperationsResponse() - resp = json_format.Parse(response.content.decode("utf-8"), resp) - resp = self._interceptor.post_list_operations(resp) - return resp - - @property - def kind(self) -> str: - return "rest" - - def close(self): - self._session.close() - - -__all__=( - 'IntentsRestTransport', -) diff --git a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/knowledge_bases/__init__.py b/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/knowledge_bases/__init__.py deleted file mode 100644 index 9dd82d2fd..000000000 --- a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/knowledge_bases/__init__.py +++ /dev/null @@ -1,22 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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 KnowledgeBasesClient -from .async_client import KnowledgeBasesAsyncClient - -__all__ = ( - 'KnowledgeBasesClient', - 'KnowledgeBasesAsyncClient', -) diff --git a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/knowledge_bases/async_client.py b/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/knowledge_bases/async_client.py deleted file mode 100644 index 5514b877c..000000000 --- a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/knowledge_bases/async_client.py +++ /dev/null @@ -1,1041 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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, Mapping, MutableMapping, MutableSequence, Optional, Sequence, Tuple, Type, Union - -from google.cloud.dialogflow_v2beta1 import gapic_version as package_version - -from google.api_core.client_options import ClientOptions -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import retry as retries -from google.auth import credentials as ga_credentials # type: ignore -from google.oauth2 import service_account # type: ignore - -try: - OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] -except AttributeError: # pragma: NO COVER - OptionalRetry = Union[retries.Retry, object] # 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.cloud.location import locations_pb2 # type: ignore -from google.longrunning import operations_pb2 -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 - - -class KnowledgeBasesAsyncClient: - """Service for managing - [KnowledgeBases][google.cloud.dialogflow.v2beta1.KnowledgeBase]. - """ - - _client: KnowledgeBasesClient - - DEFAULT_ENDPOINT = KnowledgeBasesClient.DEFAULT_ENDPOINT - DEFAULT_MTLS_ENDPOINT = KnowledgeBasesClient.DEFAULT_MTLS_ENDPOINT - - knowledge_base_path = staticmethod(KnowledgeBasesClient.knowledge_base_path) - 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) - - @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: - KnowledgeBasesAsyncClient: The constructed client. - """ - return KnowledgeBasesClient.from_service_account_info.__func__(KnowledgeBasesAsyncClient, 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: - KnowledgeBasesAsyncClient: The constructed client. - """ - return KnowledgeBasesClient.from_service_account_file.__func__(KnowledgeBasesAsyncClient, filename, *args, **kwargs) # type: ignore - - from_service_account_json = from_service_account_file - - @classmethod - def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[ClientOptions] = None): - """Return the API endpoint and client cert source for mutual TLS. - - The client cert source is determined in the following order: - (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the - client cert source is None. - (2) if `client_options.client_cert_source` is provided, use the provided one; if the - default client cert source exists, use the default one; otherwise the client cert - source is None. - - The API endpoint is determined in the following order: - (1) if `client_options.api_endpoint` if provided, use the provided one. - (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the - default mTLS endpoint; if the environment variable is "never", use the default API - endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise - use the default API endpoint. - - More details can be found at https://google.aip.dev/auth/4114. - - Args: - client_options (google.api_core.client_options.ClientOptions): Custom options for the - client. Only the `api_endpoint` and `client_cert_source` properties may be used - in this method. - - Returns: - Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the - client cert source to use. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If any errors happen. - """ - return KnowledgeBasesClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore - - @property - def transport(self) -> KnowledgeBasesTransport: - """Returns the transport used by the client instance. - - Returns: - KnowledgeBasesTransport: The transport used by the client instance. - """ - return self._client.transport - - get_transport_class = functools.partial(type(KnowledgeBasesClient).get_transport_class, type(KnowledgeBasesClient)) - - def __init__(self, *, - credentials: Optional[ga_credentials.Credentials] = None, - transport: Union[str, KnowledgeBasesTransport] = "grpc_asyncio", - client_options: Optional[ClientOptions] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the knowledge bases 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, ~.KnowledgeBasesTransport]): 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 = KnowledgeBasesClient( - credentials=credentials, - transport=transport, - client_options=client_options, - client_info=client_info, - - ) - - async def list_knowledge_bases(self, - request: Optional[Union[knowledge_base.ListKnowledgeBasesRequest, dict]] = None, - *, - parent: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListKnowledgeBasesAsyncPager: - r"""Returns the list of all knowledge bases of the specified agent. - - Note: The ``projects.agent.knowledgeBases`` resource is - deprecated; only use ``projects.knowledgeBases``. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import dialogflow_v2beta1 - - async def sample_list_knowledge_bases(): - # Create a client - client = dialogflow_v2beta1.KnowledgeBasesAsyncClient() - - # Initialize request argument(s) - request = dialogflow_v2beta1.ListKnowledgeBasesRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_knowledge_bases(request=request) - - # Handle the response - async for response in page_result: - print(response) - - Args: - request (Optional[Union[google.cloud.dialogflow_v2beta1.types.ListKnowledgeBasesRequest, dict]]): - The request object. Request message for - [KnowledgeBases.ListKnowledgeBases][google.cloud.dialogflow.v2beta1.KnowledgeBases.ListKnowledgeBases]. - parent (:class:`str`): - Required. The project to list of knowledge bases for. - Format: - ``projects//locations/``. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.dialogflow_v2beta1.services.knowledge_bases.pagers.ListKnowledgeBasesAsyncPager: - Response message for - [KnowledgeBases.ListKnowledgeBases][google.cloud.dialogflow.v2beta1.KnowledgeBases.ListKnowledgeBases]. - - Iterating over this object will yield results and - resolve additional pages automatically. - - """ - # Create or coerce a protobuf request object. - # Quick 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 = 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 - - # 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_knowledge_bases, - 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.ListKnowledgeBasesAsyncPager( - method=rpc, - request=request, - response=response, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def get_knowledge_base(self, - request: Optional[Union[knowledge_base.GetKnowledgeBaseRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> knowledge_base.KnowledgeBase: - r"""Retrieves the specified knowledge base. - - Note: The ``projects.agent.knowledgeBases`` resource is - deprecated; only use ``projects.knowledgeBases``. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import dialogflow_v2beta1 - - async def sample_get_knowledge_base(): - # Create a client - client = dialogflow_v2beta1.KnowledgeBasesAsyncClient() - - # Initialize request argument(s) - request = dialogflow_v2beta1.GetKnowledgeBaseRequest( - name="name_value", - ) - - # Make the request - response = await client.get_knowledge_base(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.dialogflow_v2beta1.types.GetKnowledgeBaseRequest, dict]]): - The request object. Request message for - [KnowledgeBases.GetKnowledgeBase][google.cloud.dialogflow.v2beta1.KnowledgeBases.GetKnowledgeBase]. - name (:class:`str`): - Required. The name of the knowledge base to retrieve. - Format - ``projects//locations//knowledgeBases/``. - - 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.KnowledgeBase: - A knowledge base represents a collection of knowledge documents that you - provide to Dialogflow. Your knowledge documents - contain information that may be useful during - conversations with end-users. Some Dialogflow - features use knowledge bases when looking for a - response to an end-user input. - - For more information, see the [knowledge base - guide](\ https://cloud.google.com/dialogflow/docs/how/knowledge-bases). - - Note: The projects.agent.knowledgeBases resource is - deprecated; only use projects.knowledgeBases. - - """ - # Create or coerce a protobuf request object. - # Quick 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 = 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 - - # 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_knowledge_base, - 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_knowledge_base(self, - request: Optional[Union[gcd_knowledge_base.CreateKnowledgeBaseRequest, dict]] = None, - *, - parent: Optional[str] = None, - knowledge_base: Optional[gcd_knowledge_base.KnowledgeBase] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gcd_knowledge_base.KnowledgeBase: - r"""Creates a knowledge base. - - Note: The ``projects.agent.knowledgeBases`` resource is - deprecated; only use ``projects.knowledgeBases``. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import dialogflow_v2beta1 - - async def sample_create_knowledge_base(): - # Create a client - client = dialogflow_v2beta1.KnowledgeBasesAsyncClient() - - # Initialize request argument(s) - knowledge_base = dialogflow_v2beta1.KnowledgeBase() - knowledge_base.display_name = "display_name_value" - - request = dialogflow_v2beta1.CreateKnowledgeBaseRequest( - parent="parent_value", - knowledge_base=knowledge_base, - ) - - # Make the request - response = await client.create_knowledge_base(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.dialogflow_v2beta1.types.CreateKnowledgeBaseRequest, dict]]): - The request object. Request message for - [KnowledgeBases.CreateKnowledgeBase][google.cloud.dialogflow.v2beta1.KnowledgeBases.CreateKnowledgeBase]. - parent (:class:`str`): - Required. The project to create a knowledge base for. - Format: - ``projects//locations/``. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - knowledge_base (:class:`google.cloud.dialogflow_v2beta1.types.KnowledgeBase`): - Required. The knowledge base to - create. - - 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. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.dialogflow_v2beta1.types.KnowledgeBase: - A knowledge base represents a collection of knowledge documents that you - provide to Dialogflow. Your knowledge documents - contain information that may be useful during - conversations with end-users. Some Dialogflow - features use knowledge bases when looking for a - response to an end-user input. - - For more information, see the [knowledge base - guide](\ https://cloud.google.com/dialogflow/docs/how/knowledge-bases). - - Note: The projects.agent.knowledgeBases resource is - deprecated; only use projects.knowledgeBases. - - """ - # Create or coerce a protobuf request object. - # Quick 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, knowledge_base]) - 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_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: - request.knowledge_base = knowledge_base - - # 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_knowledge_base, - 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 delete_knowledge_base(self, - request: Optional[Union[knowledge_base.DeleteKnowledgeBaseRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> None: - r"""Deletes the specified knowledge base. - - Note: The ``projects.agent.knowledgeBases`` resource is - deprecated; only use ``projects.knowledgeBases``. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import dialogflow_v2beta1 - - async def sample_delete_knowledge_base(): - # Create a client - client = dialogflow_v2beta1.KnowledgeBasesAsyncClient() - - # Initialize request argument(s) - request = dialogflow_v2beta1.DeleteKnowledgeBaseRequest( - name="name_value", - ) - - # Make the request - await client.delete_knowledge_base(request=request) - - Args: - request (Optional[Union[google.cloud.dialogflow_v2beta1.types.DeleteKnowledgeBaseRequest, dict]]): - The request object. Request message for - [KnowledgeBases.DeleteKnowledgeBase][google.cloud.dialogflow.v2beta1.KnowledgeBases.DeleteKnowledgeBase]. - name (:class:`str`): - Required. The name of the knowledge base to delete. - Format: - ``projects//locations//knowledgeBases/``. - - 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. - # Quick 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 = 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 - - # 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_knowledge_base, - 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 update_knowledge_base(self, - request: Optional[Union[gcd_knowledge_base.UpdateKnowledgeBaseRequest, dict]] = None, - *, - knowledge_base: Optional[gcd_knowledge_base.KnowledgeBase] = None, - update_mask: Optional[field_mask_pb2.FieldMask] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gcd_knowledge_base.KnowledgeBase: - r"""Updates the specified knowledge base. - - Note: The ``projects.agent.knowledgeBases`` resource is - deprecated; only use ``projects.knowledgeBases``. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import dialogflow_v2beta1 - - async def sample_update_knowledge_base(): - # Create a client - client = dialogflow_v2beta1.KnowledgeBasesAsyncClient() - - # Initialize request argument(s) - knowledge_base = dialogflow_v2beta1.KnowledgeBase() - knowledge_base.display_name = "display_name_value" - - request = dialogflow_v2beta1.UpdateKnowledgeBaseRequest( - knowledge_base=knowledge_base, - ) - - # Make the request - response = await client.update_knowledge_base(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.dialogflow_v2beta1.types.UpdateKnowledgeBaseRequest, dict]]): - The request object. Request message for - [KnowledgeBases.UpdateKnowledgeBase][google.cloud.dialogflow.v2beta1.KnowledgeBases.UpdateKnowledgeBase]. - knowledge_base (:class:`google.cloud.dialogflow_v2beta1.types.KnowledgeBase`): - Required. The knowledge base to - update. - - This corresponds to the ``knowledge_base`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - update_mask (:class:`google.protobuf.field_mask_pb2.FieldMask`): - Optional. Not specified means ``update all``. Currently, - only ``display_name`` can be updated, an InvalidArgument - will be returned for attempting to update other fields. - - 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.KnowledgeBase: - A knowledge base represents a collection of knowledge documents that you - provide to Dialogflow. Your knowledge documents - contain information that may be useful during - conversations with end-users. Some Dialogflow - features use knowledge bases when looking for a - response to an end-user input. - - For more information, see the [knowledge base - guide](\ https://cloud.google.com/dialogflow/docs/how/knowledge-bases). - - Note: The projects.agent.knowledgeBases resource is - deprecated; only use projects.knowledgeBases. - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([knowledge_base, 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_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: - 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_knowledge_base, - 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(( - ("knowledge_base.name", request.knowledge_base.name), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def list_operations( - self, - request: Optional[operations_pb2.ListOperationsRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operations_pb2.ListOperationsResponse: - r"""Lists operations that match the specified filter in the request. - - Args: - request (:class:`~.operations_pb2.ListOperationsRequest`): - The request object. Request message for - `ListOperations` method. - 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: - ~.operations_pb2.ListOperationsResponse: - Response message for ``ListOperations`` method. - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = operations_pb2.ListOperationsRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._client._transport.list_operations, - 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 get_operation( - self, - request: Optional[operations_pb2.GetOperationRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operations_pb2.Operation: - r"""Gets the latest state of a long-running operation. - - Args: - request (:class:`~.operations_pb2.GetOperationRequest`): - The request object. Request message for - `GetOperation` method. - 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: - ~.operations_pb2.Operation: - An ``Operation`` object. - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = operations_pb2.GetOperationRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._client._transport.get_operation, - 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 cancel_operation( - self, - request: Optional[operations_pb2.CancelOperationRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> None: - r"""Starts asynchronous cancellation on a long-running operation. - - The server makes a best effort to cancel the operation, but success - is not guaranteed. If the server doesn't support this method, it returns - `google.rpc.Code.UNIMPLEMENTED`. - - Args: - request (:class:`~.operations_pb2.CancelOperationRequest`): - The request object. Request message for - `CancelOperation` method. - 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: - None - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = operations_pb2.CancelOperationRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._client._transport.cancel_operation, - 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_location( - self, - request: Optional[locations_pb2.GetLocationRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> locations_pb2.Location: - r"""Gets information about a location. - - Args: - request (:class:`~.location_pb2.GetLocationRequest`): - The request object. Request message for - `GetLocation` method. - 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: - ~.location_pb2.Location: - Location object. - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = locations_pb2.GetLocationRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._client._transport.get_location, - 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 list_locations( - self, - request: Optional[locations_pb2.ListLocationsRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> locations_pb2.ListLocationsResponse: - r"""Lists information about the supported locations for this service. - - Args: - request (:class:`~.location_pb2.ListLocationsRequest`): - The request object. Request message for - `ListLocations` method. - 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: - ~.location_pb2.ListLocationsResponse: - Response message for ``ListLocations`` method. - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = locations_pb2.ListLocationsRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._client._transport.list_locations, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("name", request.name),)), - ) - - # Send the request. - response = await rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - async def __aenter__(self): - return self - - async def __aexit__(self, exc_type, exc, tb): - await self.transport.close() - -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) - - -__all__ = ( - "KnowledgeBasesAsyncClient", -) diff --git a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/knowledge_bases/client.py b/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/knowledge_bases/client.py deleted file mode 100644 index fd0fdbdf5..000000000 --- a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/knowledge_bases/client.py +++ /dev/null @@ -1,1240 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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 os -import re -from typing import Dict, Mapping, MutableMapping, MutableSequence, Optional, Sequence, Tuple, Type, Union, cast - -from google.cloud.dialogflow_v2beta1 import gapic_version as package_version - -from google.api_core import client_options as client_options_lib -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import retry as retries -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 - -try: - OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] -except AttributeError: # pragma: NO COVER - OptionalRetry = Union[retries.Retry, object] # 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.cloud.location import locations_pb2 # type: ignore -from google.longrunning import operations_pb2 -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 -from .transports.rest import KnowledgeBasesRestTransport - - -class KnowledgeBasesClientMeta(type): - """Metaclass for the KnowledgeBases 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[KnowledgeBasesTransport]] - _transport_registry["grpc"] = KnowledgeBasesGrpcTransport - _transport_registry["grpc_asyncio"] = KnowledgeBasesGrpcAsyncIOTransport - _transport_registry["rest"] = KnowledgeBasesRestTransport - - def get_transport_class(cls, - label: Optional[str] = None, - ) -> Type[KnowledgeBasesTransport]: - """Returns an appropriate transport class. - - Args: - label: The name of the desired transport. If none is - provided, then the first transport in the registry is used. - - Returns: - The transport class to use. - """ - # If a specific transport is requested, return that one. - if label: - return cls._transport_registry[label] - - # No transport is requested; return the default (that is, the first one - # in the dictionary). - return next(iter(cls._transport_registry.values())) - - -class KnowledgeBasesClient(metaclass=KnowledgeBasesClientMeta): - """Service for managing - [KnowledgeBases][google.cloud.dialogflow.v2beta1.KnowledgeBase]. - """ - - @staticmethod - def _get_default_mtls_endpoint(api_endpoint): - """Converts api endpoint to mTLS endpoint. - - Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to - "*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively. - Args: - api_endpoint (Optional[str]): the api endpoint to convert. - Returns: - str: converted mTLS api endpoint. - """ - if not api_endpoint: - return api_endpoint - - mtls_endpoint_re = re.compile( - r"(?P[^.]+)(?P\.mtls)?(?P\.sandbox)?(?P\.googleapis\.com)?" - ) - - m = mtls_endpoint_re.match(api_endpoint) - name, mtls, sandbox, googledomain = m.groups() - if mtls or not googledomain: - return api_endpoint - - if sandbox: - return api_endpoint.replace( - "sandbox.googleapis.com", "mtls.sandbox.googleapis.com" - ) - - return api_endpoint.replace(".googleapis.com", ".mtls.googleapis.com") - - DEFAULT_ENDPOINT = "dialogflow.googleapis.com" - DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore - DEFAULT_ENDPOINT - ) - - @classmethod - def from_service_account_info(cls, info: dict, *args, **kwargs): - """Creates an instance of this client using the provided credentials - info. - - Args: - info (dict): The service account private key info. - args: Additional arguments to pass to the constructor. - kwargs: Additional arguments to pass to the constructor. - - Returns: - KnowledgeBasesClient: 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: - KnowledgeBasesClient: 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) -> KnowledgeBasesTransport: - """Returns the transport used by the client instance. - - Returns: - KnowledgeBasesTransport: The transport used by the client - instance. - """ - return self._transport - - @staticmethod - def knowledge_base_path(project: str,knowledge_base: str,) -> str: - """Returns a fully-qualified knowledge_base string.""" - return "projects/{project}/knowledgeBases/{knowledge_base}".format(project=project, knowledge_base=knowledge_base, ) - - @staticmethod - def parse_knowledge_base_path(path: str) -> Dict[str,str]: - """Parses a knowledge_base path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/knowledgeBases/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_billing_account_path(billing_account: str, ) -> str: - """Returns a fully-qualified billing_account string.""" - return "billingAccounts/{billing_account}".format(billing_account=billing_account, ) - - @staticmethod - def parse_common_billing_account_path(path: str) -> Dict[str,str]: - """Parse a billing_account path into its component segments.""" - m = re.match(r"^billingAccounts/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_folder_path(folder: str, ) -> str: - """Returns a fully-qualified folder string.""" - return "folders/{folder}".format(folder=folder, ) - - @staticmethod - def parse_common_folder_path(path: str) -> Dict[str,str]: - """Parse a folder path into its component segments.""" - m = re.match(r"^folders/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_organization_path(organization: str, ) -> str: - """Returns a fully-qualified organization string.""" - return "organizations/{organization}".format(organization=organization, ) - - @staticmethod - def parse_common_organization_path(path: str) -> Dict[str,str]: - """Parse a organization path into its component segments.""" - m = re.match(r"^organizations/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_project_path(project: str, ) -> str: - """Returns a fully-qualified project string.""" - return "projects/{project}".format(project=project, ) - - @staticmethod - def parse_common_project_path(path: str) -> Dict[str,str]: - """Parse a project path into its component segments.""" - m = re.match(r"^projects/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_location_path(project: str, location: str, ) -> str: - """Returns a fully-qualified location string.""" - return "projects/{project}/locations/{location}".format(project=project, location=location, ) - - @staticmethod - def parse_common_location_path(path: str) -> Dict[str,str]: - """Parse a location path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)$", path) - return m.groupdict() if m else {} - - @classmethod - def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[client_options_lib.ClientOptions] = None): - """Return the API endpoint and client cert source for mutual TLS. - - The client cert source is determined in the following order: - (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the - client cert source is None. - (2) if `client_options.client_cert_source` is provided, use the provided one; if the - default client cert source exists, use the default one; otherwise the client cert - source is None. - - The API endpoint is determined in the following order: - (1) if `client_options.api_endpoint` if provided, use the provided one. - (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the - default mTLS endpoint; if the environment variable is "never", use the default API - endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise - use the default API endpoint. - - More details can be found at https://google.aip.dev/auth/4114. - - Args: - client_options (google.api_core.client_options.ClientOptions): Custom options for the - client. Only the `api_endpoint` and `client_cert_source` properties may be used - in this method. - - Returns: - Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the - client cert source to use. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If any errors happen. - """ - if client_options is None: - client_options = client_options_lib.ClientOptions() - use_client_cert = os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false") - use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") - if use_client_cert not in ("true", "false"): - raise ValueError("Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`") - if use_mtls_endpoint not in ("auto", "never", "always"): - raise MutualTLSChannelError("Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`") - - # Figure out the client cert source to use. - client_cert_source = None - if use_client_cert == "true": - if client_options.client_cert_source: - client_cert_source = client_options.client_cert_source - elif mtls.has_default_client_cert_source(): - client_cert_source = mtls.default_client_cert_source() - - # Figure out which api endpoint to use. - if client_options.api_endpoint is not None: - api_endpoint = client_options.api_endpoint - elif use_mtls_endpoint == "always" or (use_mtls_endpoint == "auto" and client_cert_source): - api_endpoint = cls.DEFAULT_MTLS_ENDPOINT - else: - api_endpoint = cls.DEFAULT_ENDPOINT - - return api_endpoint, client_cert_source - - def __init__(self, *, - credentials: Optional[ga_credentials.Credentials] = None, - transport: Optional[Union[str, KnowledgeBasesTransport]] = None, - client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the knowledge bases 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, KnowledgeBasesTransport]): The - transport to use. If set to None, a transport is chosen - automatically. - client_options (Optional[Union[google.api_core.client_options.ClientOptions, dict]]): 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() - client_options = cast(client_options_lib.ClientOptions, client_options) - - api_endpoint, client_cert_source_func = self.get_mtls_endpoint_and_cert_source(client_options) - - api_key_value = getattr(client_options, "api_key", None) - if api_key_value and credentials: - raise ValueError("client_options.api_key and credentials are mutually exclusive") - - # 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, KnowledgeBasesTransport): - # transport is a KnowledgeBasesTransport instance. - if credentials or client_options.credentials_file or api_key_value: - 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: - import google.auth._default # type: ignore - - if api_key_value and hasattr(google.auth._default, "get_api_key_credentials"): - credentials = google.auth._default.get_api_key_credentials(api_key_value) - - Transport = type(self).get_transport_class(transport) - self._transport = Transport( - credentials=credentials, - credentials_file=client_options.credentials_file, - host=api_endpoint, - scopes=client_options.scopes, - client_cert_source_for_mtls=client_cert_source_func, - quota_project_id=client_options.quota_project_id, - client_info=client_info, - always_use_jwt_access=True, - api_audience=client_options.api_audience, - ) - - def list_knowledge_bases(self, - request: Optional[Union[knowledge_base.ListKnowledgeBasesRequest, dict]] = None, - *, - parent: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListKnowledgeBasesPager: - r"""Returns the list of all knowledge bases of the specified agent. - - Note: The ``projects.agent.knowledgeBases`` resource is - deprecated; only use ``projects.knowledgeBases``. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import dialogflow_v2beta1 - - def sample_list_knowledge_bases(): - # Create a client - client = dialogflow_v2beta1.KnowledgeBasesClient() - - # Initialize request argument(s) - request = dialogflow_v2beta1.ListKnowledgeBasesRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_knowledge_bases(request=request) - - # Handle the response - for response in page_result: - print(response) - - Args: - request (Union[google.cloud.dialogflow_v2beta1.types.ListKnowledgeBasesRequest, dict]): - The request object. Request message for - [KnowledgeBases.ListKnowledgeBases][google.cloud.dialogflow.v2beta1.KnowledgeBases.ListKnowledgeBases]. - parent (str): - Required. The project to list of knowledge bases for. - Format: - ``projects//locations/``. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.dialogflow_v2beta1.services.knowledge_bases.pagers.ListKnowledgeBasesPager: - Response message for - [KnowledgeBases.ListKnowledgeBases][google.cloud.dialogflow.v2beta1.KnowledgeBases.ListKnowledgeBases]. - - Iterating over this object will yield results and - resolve additional pages automatically. - - """ - # Create or coerce a protobuf request object. - # Quick 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 knowledge_base.ListKnowledgeBasesRequest. - # There's no risk of modifying the input as we've already verified - # 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 - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.list_knowledge_bases] - - # 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.ListKnowledgeBasesPager( - method=rpc, - request=request, - response=response, - metadata=metadata, - ) - - # Done; return the response. - return response - - def get_knowledge_base(self, - request: Optional[Union[knowledge_base.GetKnowledgeBaseRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> knowledge_base.KnowledgeBase: - r"""Retrieves the specified knowledge base. - - Note: The ``projects.agent.knowledgeBases`` resource is - deprecated; only use ``projects.knowledgeBases``. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import dialogflow_v2beta1 - - def sample_get_knowledge_base(): - # Create a client - client = dialogflow_v2beta1.KnowledgeBasesClient() - - # Initialize request argument(s) - request = dialogflow_v2beta1.GetKnowledgeBaseRequest( - name="name_value", - ) - - # Make the request - response = client.get_knowledge_base(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.dialogflow_v2beta1.types.GetKnowledgeBaseRequest, dict]): - The request object. Request message for - [KnowledgeBases.GetKnowledgeBase][google.cloud.dialogflow.v2beta1.KnowledgeBases.GetKnowledgeBase]. - name (str): - Required. The name of the knowledge base to retrieve. - Format - ``projects//locations//knowledgeBases/``. - - 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.KnowledgeBase: - A knowledge base represents a collection of knowledge documents that you - provide to Dialogflow. Your knowledge documents - contain information that may be useful during - conversations with end-users. Some Dialogflow - features use knowledge bases when looking for a - response to an end-user input. - - For more information, see the [knowledge base - guide](\ https://cloud.google.com/dialogflow/docs/how/knowledge-bases). - - Note: The projects.agent.knowledgeBases resource is - deprecated; only use projects.knowledgeBases. - - """ - # Create or coerce a protobuf request object. - # Quick 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 knowledge_base.GetKnowledgeBaseRequest. - # There's no risk of modifying the input as we've already verified - # 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 - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.get_knowledge_base] - - # 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_knowledge_base(self, - request: Optional[Union[gcd_knowledge_base.CreateKnowledgeBaseRequest, dict]] = None, - *, - parent: Optional[str] = None, - knowledge_base: Optional[gcd_knowledge_base.KnowledgeBase] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gcd_knowledge_base.KnowledgeBase: - r"""Creates a knowledge base. - - Note: The ``projects.agent.knowledgeBases`` resource is - deprecated; only use ``projects.knowledgeBases``. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import dialogflow_v2beta1 - - def sample_create_knowledge_base(): - # Create a client - client = dialogflow_v2beta1.KnowledgeBasesClient() - - # Initialize request argument(s) - knowledge_base = dialogflow_v2beta1.KnowledgeBase() - knowledge_base.display_name = "display_name_value" - - request = dialogflow_v2beta1.CreateKnowledgeBaseRequest( - parent="parent_value", - knowledge_base=knowledge_base, - ) - - # Make the request - response = client.create_knowledge_base(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.dialogflow_v2beta1.types.CreateKnowledgeBaseRequest, dict]): - The request object. Request message for - [KnowledgeBases.CreateKnowledgeBase][google.cloud.dialogflow.v2beta1.KnowledgeBases.CreateKnowledgeBase]. - parent (str): - Required. The project to create a knowledge base for. - Format: - ``projects//locations/``. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - knowledge_base (google.cloud.dialogflow_v2beta1.types.KnowledgeBase): - Required. The knowledge base to - create. - - 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. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.dialogflow_v2beta1.types.KnowledgeBase: - A knowledge base represents a collection of knowledge documents that you - provide to Dialogflow. Your knowledge documents - contain information that may be useful during - conversations with end-users. Some Dialogflow - features use knowledge bases when looking for a - response to an end-user input. - - For more information, see the [knowledge base - guide](\ https://cloud.google.com/dialogflow/docs/how/knowledge-bases). - - Note: The projects.agent.knowledgeBases resource is - deprecated; only use projects.knowledgeBases. - - """ - # Create or coerce a protobuf request object. - # Quick 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, knowledge_base]) - 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_knowledge_base.CreateKnowledgeBaseRequest. - # There's no risk of modifying the input as we've already verified - # 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: - request.knowledge_base = knowledge_base - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.create_knowledge_base] - - # 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 delete_knowledge_base(self, - request: Optional[Union[knowledge_base.DeleteKnowledgeBaseRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> None: - r"""Deletes the specified knowledge base. - - Note: The ``projects.agent.knowledgeBases`` resource is - deprecated; only use ``projects.knowledgeBases``. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import dialogflow_v2beta1 - - def sample_delete_knowledge_base(): - # Create a client - client = dialogflow_v2beta1.KnowledgeBasesClient() - - # Initialize request argument(s) - request = dialogflow_v2beta1.DeleteKnowledgeBaseRequest( - name="name_value", - ) - - # Make the request - client.delete_knowledge_base(request=request) - - Args: - request (Union[google.cloud.dialogflow_v2beta1.types.DeleteKnowledgeBaseRequest, dict]): - The request object. Request message for - [KnowledgeBases.DeleteKnowledgeBase][google.cloud.dialogflow.v2beta1.KnowledgeBases.DeleteKnowledgeBase]. - name (str): - Required. The name of the knowledge base to delete. - Format: - ``projects//locations//knowledgeBases/``. - - 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. - # Quick 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 knowledge_base.DeleteKnowledgeBaseRequest. - # There's no risk of modifying the input as we've already verified - # 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 - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.delete_knowledge_base] - - # 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 update_knowledge_base(self, - request: Optional[Union[gcd_knowledge_base.UpdateKnowledgeBaseRequest, dict]] = None, - *, - knowledge_base: Optional[gcd_knowledge_base.KnowledgeBase] = None, - update_mask: Optional[field_mask_pb2.FieldMask] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gcd_knowledge_base.KnowledgeBase: - r"""Updates the specified knowledge base. - - Note: The ``projects.agent.knowledgeBases`` resource is - deprecated; only use ``projects.knowledgeBases``. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import dialogflow_v2beta1 - - def sample_update_knowledge_base(): - # Create a client - client = dialogflow_v2beta1.KnowledgeBasesClient() - - # Initialize request argument(s) - knowledge_base = dialogflow_v2beta1.KnowledgeBase() - knowledge_base.display_name = "display_name_value" - - request = dialogflow_v2beta1.UpdateKnowledgeBaseRequest( - knowledge_base=knowledge_base, - ) - - # Make the request - response = client.update_knowledge_base(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.dialogflow_v2beta1.types.UpdateKnowledgeBaseRequest, dict]): - The request object. Request message for - [KnowledgeBases.UpdateKnowledgeBase][google.cloud.dialogflow.v2beta1.KnowledgeBases.UpdateKnowledgeBase]. - knowledge_base (google.cloud.dialogflow_v2beta1.types.KnowledgeBase): - Required. The knowledge base to - update. - - This corresponds to the ``knowledge_base`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - update_mask (google.protobuf.field_mask_pb2.FieldMask): - Optional. Not specified means ``update all``. Currently, - only ``display_name`` can be updated, an InvalidArgument - will be returned for attempting to update other fields. - - 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.KnowledgeBase: - A knowledge base represents a collection of knowledge documents that you - provide to Dialogflow. Your knowledge documents - contain information that may be useful during - conversations with end-users. Some Dialogflow - features use knowledge bases when looking for a - response to an end-user input. - - For more information, see the [knowledge base - guide](\ https://cloud.google.com/dialogflow/docs/how/knowledge-bases). - - Note: The projects.agent.knowledgeBases resource is - deprecated; only use projects.knowledgeBases. - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([knowledge_base, 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_knowledge_base.UpdateKnowledgeBaseRequest. - # There's no risk of modifying the input as we've already verified - # 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: - 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_knowledge_base] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("knowledge_base.name", request.knowledge_base.name), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def __enter__(self) -> "KnowledgeBasesClient": - return self - - def __exit__(self, type, value, traceback): - """Releases underlying transport's resources. - - .. warning:: - ONLY use as a context manager if the transport is NOT shared - with other clients! Exiting the with block will CLOSE the transport - and may cause errors in other clients! - """ - self.transport.close() - - def list_operations( - self, - request: Optional[operations_pb2.ListOperationsRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operations_pb2.ListOperationsResponse: - r"""Lists operations that match the specified filter in the request. - - Args: - request (:class:`~.operations_pb2.ListOperationsRequest`): - The request object. Request message for - `ListOperations` method. - 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: - ~.operations_pb2.ListOperationsResponse: - Response message for ``ListOperations`` method. - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = operations_pb2.ListOperationsRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._transport.list_operations, - 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 = rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - def get_operation( - self, - request: Optional[operations_pb2.GetOperationRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operations_pb2.Operation: - r"""Gets the latest state of a long-running operation. - - Args: - request (:class:`~.operations_pb2.GetOperationRequest`): - The request object. Request message for - `GetOperation` method. - 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: - ~.operations_pb2.Operation: - An ``Operation`` object. - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = operations_pb2.GetOperationRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._transport.get_operation, - 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 = rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - def cancel_operation( - self, - request: Optional[operations_pb2.CancelOperationRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> None: - r"""Starts asynchronous cancellation on a long-running operation. - - The server makes a best effort to cancel the operation, but success - is not guaranteed. If the server doesn't support this method, it returns - `google.rpc.Code.UNIMPLEMENTED`. - - Args: - request (:class:`~.operations_pb2.CancelOperationRequest`): - The request object. Request message for - `CancelOperation` method. - 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: - None - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = operations_pb2.CancelOperationRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._transport.cancel_operation, - 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. - rpc(request, retry=retry, timeout=timeout, metadata=metadata,) - - def get_location( - self, - request: Optional[locations_pb2.GetLocationRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> locations_pb2.Location: - r"""Gets information about a location. - - Args: - request (:class:`~.location_pb2.GetLocationRequest`): - The request object. Request message for - `GetLocation` method. - 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: - ~.location_pb2.Location: - Location object. - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = locations_pb2.GetLocationRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._transport.get_location, - 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 = rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - def list_locations( - self, - request: Optional[locations_pb2.ListLocationsRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> locations_pb2.ListLocationsResponse: - r"""Lists information about the supported locations for this service. - - Args: - request (:class:`~.location_pb2.ListLocationsRequest`): - The request object. Request message for - `ListLocations` method. - 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: - ~.location_pb2.ListLocationsResponse: - Response message for ``ListLocations`` method. - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = locations_pb2.ListLocationsRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._transport.list_locations, - 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 = rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) - - -__all__ = ( - "KnowledgeBasesClient", -) diff --git a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/knowledge_bases/pagers.py b/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/knowledge_bases/pagers.py deleted file mode 100644 index 119b110b5..000000000 --- a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/knowledge_bases/pagers.py +++ /dev/null @@ -1,139 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from typing import Any, AsyncIterator, Awaitable, Callable, Sequence, Tuple, Optional, Iterator - -from google.cloud.dialogflow_v2beta1.types import knowledge_base - - -class ListKnowledgeBasesPager: - """A pager for iterating through ``list_knowledge_bases`` requests. - - This class thinly wraps an initial - :class:`google.cloud.dialogflow_v2beta1.types.ListKnowledgeBasesResponse` object, and - provides an ``__iter__`` method to iterate through its - ``knowledge_bases`` field. - - If there are more pages, the ``__iter__`` method will make additional - ``ListKnowledgeBases`` requests and continue to iterate - through the ``knowledge_bases`` field on the - corresponding responses. - - All the usual :class:`google.cloud.dialogflow_v2beta1.types.ListKnowledgeBasesResponse` - 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[..., knowledge_base.ListKnowledgeBasesResponse], - request: knowledge_base.ListKnowledgeBasesRequest, - response: knowledge_base.ListKnowledgeBasesResponse, - *, - 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.ListKnowledgeBasesRequest): - The initial request object. - response (google.cloud.dialogflow_v2beta1.types.ListKnowledgeBasesResponse): - 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 = knowledge_base.ListKnowledgeBasesRequest(request) - self._response = response - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - def pages(self) -> Iterator[knowledge_base.ListKnowledgeBasesResponse]: - yield self._response - while self._response.next_page_token: - self._request.page_token = self._response.next_page_token - self._response = self._method(self._request, metadata=self._metadata) - yield self._response - - def __iter__(self) -> Iterator[knowledge_base.KnowledgeBase]: - for page in self.pages: - yield from page.knowledge_bases - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListKnowledgeBasesAsyncPager: - """A pager for iterating through ``list_knowledge_bases`` requests. - - This class thinly wraps an initial - :class:`google.cloud.dialogflow_v2beta1.types.ListKnowledgeBasesResponse` object, and - provides an ``__aiter__`` method to iterate through its - ``knowledge_bases`` field. - - If there are more pages, the ``__aiter__`` method will make additional - ``ListKnowledgeBases`` requests and continue to iterate - through the ``knowledge_bases`` field on the - corresponding responses. - - All the usual :class:`google.cloud.dialogflow_v2beta1.types.ListKnowledgeBasesResponse` - 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[knowledge_base.ListKnowledgeBasesResponse]], - request: knowledge_base.ListKnowledgeBasesRequest, - response: knowledge_base.ListKnowledgeBasesResponse, - *, - metadata: Sequence[Tuple[str, str]] = ()): - """Instantiates the pager. - - Args: - method (Callable): The method that was originally called, and - which instantiated this pager. - request (google.cloud.dialogflow_v2beta1.types.ListKnowledgeBasesRequest): - The initial request object. - response (google.cloud.dialogflow_v2beta1.types.ListKnowledgeBasesResponse): - 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 = knowledge_base.ListKnowledgeBasesRequest(request) - self._response = response - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - async def pages(self) -> AsyncIterator[knowledge_base.ListKnowledgeBasesResponse]: - yield self._response - while self._response.next_page_token: - self._request.page_token = self._response.next_page_token - self._response = await self._method(self._request, metadata=self._metadata) - yield self._response - def __aiter__(self) -> AsyncIterator[knowledge_base.KnowledgeBase]: - async def async_generator(): - async for page in self.pages: - for response in page.knowledge_bases: - yield response - - return async_generator() - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) diff --git a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/knowledge_bases/transports/__init__.py b/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/knowledge_bases/transports/__init__.py deleted file mode 100644 index bcb1968b6..000000000 --- a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/knowledge_bases/transports/__init__.py +++ /dev/null @@ -1,38 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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 KnowledgeBasesTransport -from .grpc import KnowledgeBasesGrpcTransport -from .grpc_asyncio import KnowledgeBasesGrpcAsyncIOTransport -from .rest import KnowledgeBasesRestTransport -from .rest import KnowledgeBasesRestInterceptor - - -# Compile a registry of transports. -_transport_registry = OrderedDict() # type: Dict[str, Type[KnowledgeBasesTransport]] -_transport_registry['grpc'] = KnowledgeBasesGrpcTransport -_transport_registry['grpc_asyncio'] = KnowledgeBasesGrpcAsyncIOTransport -_transport_registry['rest'] = KnowledgeBasesRestTransport - -__all__ = ( - 'KnowledgeBasesTransport', - 'KnowledgeBasesGrpcTransport', - 'KnowledgeBasesGrpcAsyncIOTransport', - 'KnowledgeBasesRestTransport', - 'KnowledgeBasesRestInterceptor', -) diff --git a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/knowledge_bases/transports/base.py b/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/knowledge_bases/transports/base.py deleted file mode 100644 index 6e5c28837..000000000 --- a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/knowledge_bases/transports/base.py +++ /dev/null @@ -1,252 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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 - -from google.cloud.dialogflow_v2beta1 import gapic_version as package_version - -import google.auth # type: ignore -import google.api_core -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import retry as retries -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 knowledge_base -from google.cloud.dialogflow_v2beta1.types import knowledge_base as gcd_knowledge_base -from google.cloud.location import locations_pb2 # type: ignore -from google.longrunning import operations_pb2 -from google.protobuf import empty_pb2 # type: ignore - -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) - - -class KnowledgeBasesTransport(abc.ABC): - """Abstract transport class for KnowledgeBases.""" - - 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: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - api_audience: Optional[str] = None, - **kwargs, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. - scopes (Optional[Sequence[str]]): A list of scopes. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - """ - - scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} - - # Save the scopes. - self._scopes = scopes - - # If no credentials are provided, then determine the appropriate - # defaults. - if credentials and credentials_file: - raise core_exceptions.DuplicateCredentialArgs("'credentials_file' and 'credentials' are mutually exclusive") - - if credentials_file is not None: - credentials, _ = google.auth.load_credentials_from_file( - credentials_file, - **scopes_kwargs, - quota_project_id=quota_project_id - ) - elif credentials is None: - credentials, _ = google.auth.default(**scopes_kwargs, quota_project_id=quota_project_id) - # Don't apply audience if the credentials file passed from user. - if hasattr(credentials, "with_gdch_audience"): - credentials = credentials.with_gdch_audience(api_audience if api_audience else host) - - # If the credentials are service account credentials, then always try to use self signed JWT. - if always_use_jwt_access and isinstance(credentials, service_account.Credentials) and hasattr(service_account.Credentials, "with_always_use_jwt_access"): - credentials = credentials.with_always_use_jwt_access(True) - - # Save the credentials. - self._credentials = credentials - - # Save the hostname. Default to port 443 (HTTPS) if none is specified. - if ':' not in host: - host += ':443' - self._host = host - - def _prep_wrapped_messages(self, client_info): - # Precompute the wrapped methods. - self._wrapped_methods = { - self.list_knowledge_bases: gapic_v1.method.wrap_method( - self.list_knowledge_bases, - default_timeout=None, - client_info=client_info, - ), - self.get_knowledge_base: gapic_v1.method.wrap_method( - self.get_knowledge_base, - default_timeout=None, - client_info=client_info, - ), - self.create_knowledge_base: gapic_v1.method.wrap_method( - self.create_knowledge_base, - default_timeout=None, - client_info=client_info, - ), - self.delete_knowledge_base: gapic_v1.method.wrap_method( - self.delete_knowledge_base, - default_timeout=None, - client_info=client_info, - ), - self.update_knowledge_base: gapic_v1.method.wrap_method( - self.update_knowledge_base, - default_timeout=None, - client_info=client_info, - ), - } - - def close(self): - """Closes resources associated with the transport. - - .. warning:: - Only call this method if the transport is NOT shared - with other clients - this may cause errors in other clients! - """ - raise NotImplementedError() - - @property - def list_knowledge_bases(self) -> Callable[ - [knowledge_base.ListKnowledgeBasesRequest], - Union[ - knowledge_base.ListKnowledgeBasesResponse, - Awaitable[knowledge_base.ListKnowledgeBasesResponse] - ]]: - raise NotImplementedError() - - @property - def get_knowledge_base(self) -> Callable[ - [knowledge_base.GetKnowledgeBaseRequest], - Union[ - knowledge_base.KnowledgeBase, - Awaitable[knowledge_base.KnowledgeBase] - ]]: - raise NotImplementedError() - - @property - def create_knowledge_base(self) -> Callable[ - [gcd_knowledge_base.CreateKnowledgeBaseRequest], - Union[ - gcd_knowledge_base.KnowledgeBase, - Awaitable[gcd_knowledge_base.KnowledgeBase] - ]]: - raise NotImplementedError() - - @property - def delete_knowledge_base(self) -> Callable[ - [knowledge_base.DeleteKnowledgeBaseRequest], - Union[ - empty_pb2.Empty, - Awaitable[empty_pb2.Empty] - ]]: - raise NotImplementedError() - - @property - def update_knowledge_base(self) -> Callable[ - [gcd_knowledge_base.UpdateKnowledgeBaseRequest], - Union[ - gcd_knowledge_base.KnowledgeBase, - Awaitable[gcd_knowledge_base.KnowledgeBase] - ]]: - raise NotImplementedError() - - @property - def list_operations( - self, - ) -> Callable[ - [operations_pb2.ListOperationsRequest], - Union[operations_pb2.ListOperationsResponse, Awaitable[operations_pb2.ListOperationsResponse]], - ]: - raise NotImplementedError() - - @property - def get_operation( - self, - ) -> Callable[ - [operations_pb2.GetOperationRequest], - Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], - ]: - raise NotImplementedError() - - @property - def cancel_operation( - self, - ) -> Callable[ - [operations_pb2.CancelOperationRequest], - None, - ]: - raise NotImplementedError() - - @property - def get_location(self, - ) -> Callable[ - [locations_pb2.GetLocationRequest], - Union[locations_pb2.Location, Awaitable[locations_pb2.Location]], - ]: - raise NotImplementedError() - - @property - def list_locations(self, - ) -> Callable[ - [locations_pb2.ListLocationsRequest], - Union[locations_pb2.ListLocationsResponse, Awaitable[locations_pb2.ListLocationsResponse]], - ]: - raise NotImplementedError() - - @property - def kind(self) -> str: - raise NotImplementedError() - - -__all__ = ( - 'KnowledgeBasesTransport', -) diff --git a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/knowledge_bases/transports/grpc.py b/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/knowledge_bases/transports/grpc.py deleted file mode 100644 index 83026bd55..000000000 --- a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/knowledge_bases/transports/grpc.py +++ /dev/null @@ -1,478 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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 -from google.api_core import gapic_v1 -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.cloud.location import locations_pb2 # type: ignore -from google.longrunning import operations_pb2 -from google.protobuf import empty_pb2 # type: ignore -from .base import KnowledgeBasesTransport, DEFAULT_CLIENT_INFO - - -class KnowledgeBasesGrpcTransport(KnowledgeBasesTransport): - """gRPC backend transport for KnowledgeBases. - - Service for managing - [KnowledgeBases][google.cloud.dialogflow.v2beta1.KnowledgeBase]. - - 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: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - channel: Optional[grpc.Channel] = None, - api_mtls_endpoint: Optional[str] = None, - client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, - ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, - client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - api_audience: Optional[str] = None, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - This argument is ignored if ``channel`` is provided. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional(Sequence[str])): A list of scopes. This argument is - ignored if ``channel`` is provided. - channel (Optional[grpc.Channel]): A ``Channel`` instance through - which to make calls. - api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. - If provided, it overrides the ``host`` argument and tries to create - a mutual TLS channel with client SSL credentials from - ``client_cert_source`` or application default SSL credentials. - client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): - Deprecated. A callback to provide client SSL certificate bytes and - private key bytes, both in PEM format. It is ignored if - ``api_mtls_endpoint`` is None. - ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials - for the grpc channel. It is ignored if ``channel`` is provided. - client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): - A callback to provide client certificate bytes and private key bytes, - both in PEM format. It is used to configure a mutual TLS channel. It is - ignored if ``channel`` or ``ssl_channel_credentials`` is provided. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport - creation failed for any reason. - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - self._grpc_channel = None - self._ssl_channel_credentials = ssl_channel_credentials - self._stubs: Dict[str, Callable] = {} - - if api_mtls_endpoint: - warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) - if client_cert_source: - warnings.warn("client_cert_source is deprecated", DeprecationWarning) - - if channel: - # Ignore credentials if a channel was passed. - credentials = False - # If a channel was explicitly provided, set it. - self._grpc_channel = channel - self._ssl_channel_credentials = None - - else: - if api_mtls_endpoint: - host = api_mtls_endpoint - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - self._ssl_channel_credentials = SslCredentials().ssl_credentials - - else: - if client_cert_source_for_mtls and not ssl_channel_credentials: - cert, key = client_cert_source_for_mtls() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - - # The base transport sets the host, credentials and scopes - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes, - quota_project_id=quota_project_id, - client_info=client_info, - always_use_jwt_access=always_use_jwt_access, - api_audience=api_audience, - ) - - if not self._grpc_channel: - self._grpc_channel = type(self).create_channel( - self._host, - # use the credentials which are saved - credentials=self._credentials, - # Set ``credentials_file`` to ``None`` here as - # the credentials that we saved earlier should be used. - credentials_file=None, - 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: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - **kwargs) -> grpc.Channel: - """Create and return a gRPC channel object. - Args: - host (Optional[str]): The host for the channel to use. - credentials (Optional[~.Credentials]): The - authorization credentials to attach to requests. These - credentials identify this application to the service. If - none are specified, the client will attempt to ascertain - the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - kwargs (Optional[dict]): Keyword arguments, which are passed to the - channel creation. - Returns: - grpc.Channel: A gRPC channel object. - - Raises: - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - - return grpc_helpers.create_channel( - host, - credentials=credentials, - credentials_file=credentials_file, - quota_project_id=quota_project_id, - default_scopes=cls.AUTH_SCOPES, - scopes=scopes, - default_host=cls.DEFAULT_HOST, - **kwargs - ) - - @property - def grpc_channel(self) -> grpc.Channel: - """Return the channel designed to connect to this service. - """ - return self._grpc_channel - - @property - def list_knowledge_bases(self) -> Callable[ - [knowledge_base.ListKnowledgeBasesRequest], - knowledge_base.ListKnowledgeBasesResponse]: - r"""Return a callable for the list knowledge bases method over gRPC. - - Returns the list of all knowledge bases of the specified agent. - - Note: The ``projects.agent.knowledgeBases`` resource is - deprecated; only use ``projects.knowledgeBases``. - - Returns: - Callable[[~.ListKnowledgeBasesRequest], - ~.ListKnowledgeBasesResponse]: - 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_knowledge_bases' not in self._stubs: - self._stubs['list_knowledge_bases'] = self.grpc_channel.unary_unary( - '/google.cloud.dialogflow.v2beta1.KnowledgeBases/ListKnowledgeBases', - request_serializer=knowledge_base.ListKnowledgeBasesRequest.serialize, - response_deserializer=knowledge_base.ListKnowledgeBasesResponse.deserialize, - ) - return self._stubs['list_knowledge_bases'] - - @property - def get_knowledge_base(self) -> Callable[ - [knowledge_base.GetKnowledgeBaseRequest], - knowledge_base.KnowledgeBase]: - r"""Return a callable for the get knowledge base method over gRPC. - - Retrieves the specified knowledge base. - - Note: The ``projects.agent.knowledgeBases`` resource is - deprecated; only use ``projects.knowledgeBases``. - - Returns: - Callable[[~.GetKnowledgeBaseRequest], - ~.KnowledgeBase]: - 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_knowledge_base' not in self._stubs: - self._stubs['get_knowledge_base'] = self.grpc_channel.unary_unary( - '/google.cloud.dialogflow.v2beta1.KnowledgeBases/GetKnowledgeBase', - request_serializer=knowledge_base.GetKnowledgeBaseRequest.serialize, - response_deserializer=knowledge_base.KnowledgeBase.deserialize, - ) - return self._stubs['get_knowledge_base'] - - @property - def create_knowledge_base(self) -> Callable[ - [gcd_knowledge_base.CreateKnowledgeBaseRequest], - gcd_knowledge_base.KnowledgeBase]: - r"""Return a callable for the create knowledge base method over gRPC. - - Creates a knowledge base. - - Note: The ``projects.agent.knowledgeBases`` resource is - deprecated; only use ``projects.knowledgeBases``. - - Returns: - Callable[[~.CreateKnowledgeBaseRequest], - ~.KnowledgeBase]: - 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_knowledge_base' not in self._stubs: - self._stubs['create_knowledge_base'] = self.grpc_channel.unary_unary( - '/google.cloud.dialogflow.v2beta1.KnowledgeBases/CreateKnowledgeBase', - request_serializer=gcd_knowledge_base.CreateKnowledgeBaseRequest.serialize, - response_deserializer=gcd_knowledge_base.KnowledgeBase.deserialize, - ) - return self._stubs['create_knowledge_base'] - - @property - def delete_knowledge_base(self) -> Callable[ - [knowledge_base.DeleteKnowledgeBaseRequest], - empty_pb2.Empty]: - r"""Return a callable for the delete knowledge base method over gRPC. - - Deletes the specified knowledge base. - - Note: The ``projects.agent.knowledgeBases`` resource is - deprecated; only use ``projects.knowledgeBases``. - - Returns: - Callable[[~.DeleteKnowledgeBaseRequest], - ~.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_knowledge_base' not in self._stubs: - 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_pb2.Empty.FromString, - ) - return self._stubs['delete_knowledge_base'] - - @property - def update_knowledge_base(self) -> Callable[ - [gcd_knowledge_base.UpdateKnowledgeBaseRequest], - gcd_knowledge_base.KnowledgeBase]: - r"""Return a callable for the update knowledge base method over gRPC. - - Updates the specified knowledge base. - - Note: The ``projects.agent.knowledgeBases`` resource is - deprecated; only use ``projects.knowledgeBases``. - - Returns: - Callable[[~.UpdateKnowledgeBaseRequest], - ~.KnowledgeBase]: - 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_knowledge_base' not in self._stubs: - self._stubs['update_knowledge_base'] = self.grpc_channel.unary_unary( - '/google.cloud.dialogflow.v2beta1.KnowledgeBases/UpdateKnowledgeBase', - request_serializer=gcd_knowledge_base.UpdateKnowledgeBaseRequest.serialize, - response_deserializer=gcd_knowledge_base.KnowledgeBase.deserialize, - ) - return self._stubs['update_knowledge_base'] - - def close(self): - self.grpc_channel.close() - - @property - def cancel_operation( - self, - ) -> Callable[[operations_pb2.CancelOperationRequest], None]: - r"""Return a callable for the cancel_operation method over gRPC. - """ - # 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 "cancel_operation" not in self._stubs: - self._stubs["cancel_operation"] = self.grpc_channel.unary_unary( - "/google.longrunning.Operations/CancelOperation", - request_serializer=operations_pb2.CancelOperationRequest.SerializeToString, - response_deserializer=None, - ) - return self._stubs["cancel_operation"] - - @property - def get_operation( - self, - ) -> Callable[[operations_pb2.GetOperationRequest], operations_pb2.Operation]: - r"""Return a callable for the get_operation method over gRPC. - """ - # 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_operation" not in self._stubs: - self._stubs["get_operation"] = self.grpc_channel.unary_unary( - "/google.longrunning.Operations/GetOperation", - request_serializer=operations_pb2.GetOperationRequest.SerializeToString, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs["get_operation"] - - @property - def list_operations( - self, - ) -> Callable[[operations_pb2.ListOperationsRequest], operations_pb2.ListOperationsResponse]: - r"""Return a callable for the list_operations method over gRPC. - """ - # 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_operations" not in self._stubs: - self._stubs["list_operations"] = self.grpc_channel.unary_unary( - "/google.longrunning.Operations/ListOperations", - request_serializer=operations_pb2.ListOperationsRequest.SerializeToString, - response_deserializer=operations_pb2.ListOperationsResponse.FromString, - ) - return self._stubs["list_operations"] - - @property - def list_locations( - self, - ) -> Callable[[locations_pb2.ListLocationsRequest], locations_pb2.ListLocationsResponse]: - r"""Return a callable for the list locations method over gRPC. - """ - # 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_locations" not in self._stubs: - self._stubs["list_locations"] = self.grpc_channel.unary_unary( - "/google.cloud.location.Locations/ListLocations", - request_serializer=locations_pb2.ListLocationsRequest.SerializeToString, - response_deserializer=locations_pb2.ListLocationsResponse.FromString, - ) - return self._stubs["list_locations"] - - @property - def get_location( - self, - ) -> Callable[[locations_pb2.GetLocationRequest], locations_pb2.Location]: - r"""Return a callable for the list locations method over gRPC. - """ - # 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_location" not in self._stubs: - self._stubs["get_location"] = self.grpc_channel.unary_unary( - "/google.cloud.location.Locations/GetLocation", - request_serializer=locations_pb2.GetLocationRequest.SerializeToString, - response_deserializer=locations_pb2.Location.FromString, - ) - return self._stubs["get_location"] - - @property - def kind(self) -> str: - return "grpc" - - -__all__ = ( - 'KnowledgeBasesGrpcTransport', -) diff --git a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/knowledge_bases/transports/grpc_asyncio.py b/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/knowledge_bases/transports/grpc_asyncio.py deleted file mode 100644 index 55ca40693..000000000 --- a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/knowledge_bases/transports/grpc_asyncio.py +++ /dev/null @@ -1,477 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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 -from google.api_core import grpc_helpers_async -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore - -import grpc # type: ignore -from grpc.experimental import aio # type: ignore - -from google.cloud.dialogflow_v2beta1.types import knowledge_base -from google.cloud.dialogflow_v2beta1.types import knowledge_base as gcd_knowledge_base -from google.cloud.location import locations_pb2 # type: ignore -from google.longrunning import operations_pb2 -from google.protobuf import empty_pb2 # type: ignore -from .base import KnowledgeBasesTransport, DEFAULT_CLIENT_INFO -from .grpc import KnowledgeBasesGrpcTransport - - -class KnowledgeBasesGrpcAsyncIOTransport(KnowledgeBasesTransport): - """gRPC AsyncIO backend transport for KnowledgeBases. - - Service for managing - [KnowledgeBases][google.cloud.dialogflow.v2beta1.KnowledgeBase]. - - 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: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - **kwargs) -> aio.Channel: - """Create and return a gRPC AsyncIO channel object. - Args: - host (Optional[str]): The host for the channel to use. - credentials (Optional[~.Credentials]): The - authorization credentials to attach to requests. These - credentials identify this application to the service. If - none are specified, the client will attempt to ascertain - the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - kwargs (Optional[dict]): Keyword arguments, which are passed to the - channel creation. - Returns: - aio.Channel: A gRPC AsyncIO channel object. - """ - - return grpc_helpers_async.create_channel( - host, - credentials=credentials, - credentials_file=credentials_file, - quota_project_id=quota_project_id, - default_scopes=cls.AUTH_SCOPES, - scopes=scopes, - default_host=cls.DEFAULT_HOST, - **kwargs - ) - - def __init__(self, *, - host: str = 'dialogflow.googleapis.com', - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - channel: Optional[aio.Channel] = None, - api_mtls_endpoint: Optional[str] = None, - client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, - ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, - client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - api_audience: Optional[str] = None, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - This argument is ignored if ``channel`` is provided. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - channel (Optional[aio.Channel]): A ``Channel`` instance through - which to make calls. - api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. - If provided, it overrides the ``host`` argument and tries to create - a mutual TLS channel with client SSL credentials from - ``client_cert_source`` or application default SSL credentials. - client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): - Deprecated. A callback to provide client SSL certificate bytes and - private key bytes, both in PEM format. It is ignored if - ``api_mtls_endpoint`` is None. - ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials - for the grpc channel. It is ignored if ``channel`` is provided. - client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): - A callback to provide client certificate bytes and private key bytes, - both in PEM format. It is used to configure a mutual TLS channel. It is - ignored if ``channel`` or ``ssl_channel_credentials`` is provided. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - - Raises: - google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport - creation failed for any reason. - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - self._grpc_channel = None - self._ssl_channel_credentials = ssl_channel_credentials - self._stubs: Dict[str, Callable] = {} - - if api_mtls_endpoint: - warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) - if client_cert_source: - warnings.warn("client_cert_source is deprecated", DeprecationWarning) - - if channel: - # Ignore credentials if a channel was passed. - credentials = False - # If a channel was explicitly provided, set it. - self._grpc_channel = channel - self._ssl_channel_credentials = None - else: - if api_mtls_endpoint: - host = api_mtls_endpoint - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - self._ssl_channel_credentials = SslCredentials().ssl_credentials - - else: - if client_cert_source_for_mtls and not ssl_channel_credentials: - cert, key = client_cert_source_for_mtls() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - - # The base transport sets the host, credentials and scopes - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes, - quota_project_id=quota_project_id, - client_info=client_info, - always_use_jwt_access=always_use_jwt_access, - api_audience=api_audience, - ) - - if not self._grpc_channel: - self._grpc_channel = type(self).create_channel( - self._host, - # use the credentials which are saved - credentials=self._credentials, - # Set ``credentials_file`` to ``None`` here as - # the credentials that we saved earlier should be used. - credentials_file=None, - 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_knowledge_bases(self) -> Callable[ - [knowledge_base.ListKnowledgeBasesRequest], - Awaitable[knowledge_base.ListKnowledgeBasesResponse]]: - r"""Return a callable for the list knowledge bases method over gRPC. - - Returns the list of all knowledge bases of the specified agent. - - Note: The ``projects.agent.knowledgeBases`` resource is - deprecated; only use ``projects.knowledgeBases``. - - Returns: - Callable[[~.ListKnowledgeBasesRequest], - Awaitable[~.ListKnowledgeBasesResponse]]: - 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_knowledge_bases' not in self._stubs: - self._stubs['list_knowledge_bases'] = self.grpc_channel.unary_unary( - '/google.cloud.dialogflow.v2beta1.KnowledgeBases/ListKnowledgeBases', - request_serializer=knowledge_base.ListKnowledgeBasesRequest.serialize, - response_deserializer=knowledge_base.ListKnowledgeBasesResponse.deserialize, - ) - return self._stubs['list_knowledge_bases'] - - @property - def get_knowledge_base(self) -> Callable[ - [knowledge_base.GetKnowledgeBaseRequest], - Awaitable[knowledge_base.KnowledgeBase]]: - r"""Return a callable for the get knowledge base method over gRPC. - - Retrieves the specified knowledge base. - - Note: The ``projects.agent.knowledgeBases`` resource is - deprecated; only use ``projects.knowledgeBases``. - - Returns: - Callable[[~.GetKnowledgeBaseRequest], - Awaitable[~.KnowledgeBase]]: - 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_knowledge_base' not in self._stubs: - self._stubs['get_knowledge_base'] = self.grpc_channel.unary_unary( - '/google.cloud.dialogflow.v2beta1.KnowledgeBases/GetKnowledgeBase', - request_serializer=knowledge_base.GetKnowledgeBaseRequest.serialize, - response_deserializer=knowledge_base.KnowledgeBase.deserialize, - ) - return self._stubs['get_knowledge_base'] - - @property - def create_knowledge_base(self) -> Callable[ - [gcd_knowledge_base.CreateKnowledgeBaseRequest], - Awaitable[gcd_knowledge_base.KnowledgeBase]]: - r"""Return a callable for the create knowledge base method over gRPC. - - Creates a knowledge base. - - Note: The ``projects.agent.knowledgeBases`` resource is - deprecated; only use ``projects.knowledgeBases``. - - Returns: - Callable[[~.CreateKnowledgeBaseRequest], - Awaitable[~.KnowledgeBase]]: - 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_knowledge_base' not in self._stubs: - self._stubs['create_knowledge_base'] = self.grpc_channel.unary_unary( - '/google.cloud.dialogflow.v2beta1.KnowledgeBases/CreateKnowledgeBase', - request_serializer=gcd_knowledge_base.CreateKnowledgeBaseRequest.serialize, - response_deserializer=gcd_knowledge_base.KnowledgeBase.deserialize, - ) - return self._stubs['create_knowledge_base'] - - @property - def delete_knowledge_base(self) -> 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. - - Note: The ``projects.agent.knowledgeBases`` resource is - deprecated; only use ``projects.knowledgeBases``. - - Returns: - Callable[[~.DeleteKnowledgeBaseRequest], - 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_knowledge_base' not in self._stubs: - 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_pb2.Empty.FromString, - ) - return self._stubs['delete_knowledge_base'] - - @property - def update_knowledge_base(self) -> Callable[ - [gcd_knowledge_base.UpdateKnowledgeBaseRequest], - Awaitable[gcd_knowledge_base.KnowledgeBase]]: - r"""Return a callable for the update knowledge base method over gRPC. - - Updates the specified knowledge base. - - Note: The ``projects.agent.knowledgeBases`` resource is - deprecated; only use ``projects.knowledgeBases``. - - Returns: - Callable[[~.UpdateKnowledgeBaseRequest], - Awaitable[~.KnowledgeBase]]: - 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_knowledge_base' not in self._stubs: - self._stubs['update_knowledge_base'] = self.grpc_channel.unary_unary( - '/google.cloud.dialogflow.v2beta1.KnowledgeBases/UpdateKnowledgeBase', - request_serializer=gcd_knowledge_base.UpdateKnowledgeBaseRequest.serialize, - response_deserializer=gcd_knowledge_base.KnowledgeBase.deserialize, - ) - return self._stubs['update_knowledge_base'] - - def close(self): - return self.grpc_channel.close() - - @property - def cancel_operation( - self, - ) -> Callable[[operations_pb2.CancelOperationRequest], None]: - r"""Return a callable for the cancel_operation method over gRPC. - """ - # 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 "cancel_operation" not in self._stubs: - self._stubs["cancel_operation"] = self.grpc_channel.unary_unary( - "/google.longrunning.Operations/CancelOperation", - request_serializer=operations_pb2.CancelOperationRequest.SerializeToString, - response_deserializer=None, - ) - return self._stubs["cancel_operation"] - - @property - def get_operation( - self, - ) -> Callable[[operations_pb2.GetOperationRequest], operations_pb2.Operation]: - r"""Return a callable for the get_operation method over gRPC. - """ - # 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_operation" not in self._stubs: - self._stubs["get_operation"] = self.grpc_channel.unary_unary( - "/google.longrunning.Operations/GetOperation", - request_serializer=operations_pb2.GetOperationRequest.SerializeToString, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs["get_operation"] - - @property - def list_operations( - self, - ) -> Callable[[operations_pb2.ListOperationsRequest], operations_pb2.ListOperationsResponse]: - r"""Return a callable for the list_operations method over gRPC. - """ - # 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_operations" not in self._stubs: - self._stubs["list_operations"] = self.grpc_channel.unary_unary( - "/google.longrunning.Operations/ListOperations", - request_serializer=operations_pb2.ListOperationsRequest.SerializeToString, - response_deserializer=operations_pb2.ListOperationsResponse.FromString, - ) - return self._stubs["list_operations"] - - @property - def list_locations( - self, - ) -> Callable[[locations_pb2.ListLocationsRequest], locations_pb2.ListLocationsResponse]: - r"""Return a callable for the list locations method over gRPC. - """ - # 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_locations" not in self._stubs: - self._stubs["list_locations"] = self.grpc_channel.unary_unary( - "/google.cloud.location.Locations/ListLocations", - request_serializer=locations_pb2.ListLocationsRequest.SerializeToString, - response_deserializer=locations_pb2.ListLocationsResponse.FromString, - ) - return self._stubs["list_locations"] - - @property - def get_location( - self, - ) -> Callable[[locations_pb2.GetLocationRequest], locations_pb2.Location]: - r"""Return a callable for the list locations method over gRPC. - """ - # 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_location" not in self._stubs: - self._stubs["get_location"] = self.grpc_channel.unary_unary( - "/google.cloud.location.Locations/GetLocation", - request_serializer=locations_pb2.GetLocationRequest.SerializeToString, - response_deserializer=locations_pb2.Location.FromString, - ) - return self._stubs["get_location"] - - -__all__ = ( - 'KnowledgeBasesGrpcAsyncIOTransport', -) diff --git a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/knowledge_bases/transports/rest.py b/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/knowledge_bases/transports/rest.py deleted file mode 100644 index efc00a2bf..000000000 --- a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/knowledge_bases/transports/rest.py +++ /dev/null @@ -1,1246 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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 google.auth.transport.requests import AuthorizedSession # type: ignore -import json # type: ignore -import grpc # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore -from google.auth import credentials as ga_credentials # type: ignore -from google.api_core import exceptions as core_exceptions -from google.api_core import retry as retries -from google.api_core import rest_helpers -from google.api_core import rest_streaming -from google.api_core import path_template -from google.api_core import gapic_v1 - -from google.protobuf import json_format -from google.cloud.location import locations_pb2 # type: ignore -from google.longrunning import operations_pb2 -from requests import __version__ as requests_version -import dataclasses -import re -from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union -import warnings - -try: - OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] -except AttributeError: # pragma: NO COVER - OptionalRetry = Union[retries.Retry, object] # 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 # type: ignore - -from .base import KnowledgeBasesTransport, DEFAULT_CLIENT_INFO as BASE_DEFAULT_CLIENT_INFO - - -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=BASE_DEFAULT_CLIENT_INFO.gapic_version, - grpc_version=None, - rest_version=requests_version, -) - - -class KnowledgeBasesRestInterceptor: - """Interceptor for KnowledgeBases. - - Interceptors are used to manipulate requests, request metadata, and responses - in arbitrary ways. - Example use cases include: - * Logging - * Verifying requests according to service or custom semantics - * Stripping extraneous information from responses - - These use cases and more can be enabled by injecting an - instance of a custom subclass when constructing the KnowledgeBasesRestTransport. - - .. code-block:: python - class MyCustomKnowledgeBasesInterceptor(KnowledgeBasesRestInterceptor): - def pre_create_knowledge_base(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_create_knowledge_base(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_delete_knowledge_base(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def pre_get_knowledge_base(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_get_knowledge_base(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_list_knowledge_bases(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_list_knowledge_bases(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_update_knowledge_base(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_update_knowledge_base(self, response): - logging.log(f"Received response: {response}") - return response - - transport = KnowledgeBasesRestTransport(interceptor=MyCustomKnowledgeBasesInterceptor()) - client = KnowledgeBasesClient(transport=transport) - - - """ - def pre_create_knowledge_base(self, request: gcd_knowledge_base.CreateKnowledgeBaseRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[gcd_knowledge_base.CreateKnowledgeBaseRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for create_knowledge_base - - Override in a subclass to manipulate the request or metadata - before they are sent to the KnowledgeBases server. - """ - return request, metadata - - def post_create_knowledge_base(self, response: gcd_knowledge_base.KnowledgeBase) -> gcd_knowledge_base.KnowledgeBase: - """Post-rpc interceptor for create_knowledge_base - - Override in a subclass to manipulate the response - after it is returned by the KnowledgeBases server but before - it is returned to user code. - """ - return response - def pre_delete_knowledge_base(self, request: knowledge_base.DeleteKnowledgeBaseRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[knowledge_base.DeleteKnowledgeBaseRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for delete_knowledge_base - - Override in a subclass to manipulate the request or metadata - before they are sent to the KnowledgeBases server. - """ - return request, metadata - - def pre_get_knowledge_base(self, request: knowledge_base.GetKnowledgeBaseRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[knowledge_base.GetKnowledgeBaseRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for get_knowledge_base - - Override in a subclass to manipulate the request or metadata - before they are sent to the KnowledgeBases server. - """ - return request, metadata - - def post_get_knowledge_base(self, response: knowledge_base.KnowledgeBase) -> knowledge_base.KnowledgeBase: - """Post-rpc interceptor for get_knowledge_base - - Override in a subclass to manipulate the response - after it is returned by the KnowledgeBases server but before - it is returned to user code. - """ - return response - def pre_list_knowledge_bases(self, request: knowledge_base.ListKnowledgeBasesRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[knowledge_base.ListKnowledgeBasesRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for list_knowledge_bases - - Override in a subclass to manipulate the request or metadata - before they are sent to the KnowledgeBases server. - """ - return request, metadata - - def post_list_knowledge_bases(self, response: knowledge_base.ListKnowledgeBasesResponse) -> knowledge_base.ListKnowledgeBasesResponse: - """Post-rpc interceptor for list_knowledge_bases - - Override in a subclass to manipulate the response - after it is returned by the KnowledgeBases server but before - it is returned to user code. - """ - return response - def pre_update_knowledge_base(self, request: gcd_knowledge_base.UpdateKnowledgeBaseRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[gcd_knowledge_base.UpdateKnowledgeBaseRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for update_knowledge_base - - Override in a subclass to manipulate the request or metadata - before they are sent to the KnowledgeBases server. - """ - return request, metadata - - def post_update_knowledge_base(self, response: gcd_knowledge_base.KnowledgeBase) -> gcd_knowledge_base.KnowledgeBase: - """Post-rpc interceptor for update_knowledge_base - - Override in a subclass to manipulate the response - after it is returned by the KnowledgeBases server but before - it is returned to user code. - """ - return response - - def pre_get_location( - self, request: locations_pb2.GetLocationRequest, metadata: Sequence[Tuple[str, str]] - ) -> Tuple[locations_pb2.GetLocationRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for get_location - - Override in a subclass to manipulate the request or metadata - before they are sent to the KnowledgeBases server. - """ - return request, metadata - - def post_get_location( - self, response: locations_pb2.Location - ) -> locations_pb2.Location: - """Post-rpc interceptor for get_location - - Override in a subclass to manipulate the response - after it is returned by the KnowledgeBases server but before - it is returned to user code. - """ - return response - def pre_list_locations( - self, request: locations_pb2.ListLocationsRequest, metadata: Sequence[Tuple[str, str]] - ) -> Tuple[locations_pb2.ListLocationsRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for list_locations - - Override in a subclass to manipulate the request or metadata - before they are sent to the KnowledgeBases server. - """ - return request, metadata - - def post_list_locations( - self, response: locations_pb2.ListLocationsResponse - ) -> locations_pb2.ListLocationsResponse: - """Post-rpc interceptor for list_locations - - Override in a subclass to manipulate the response - after it is returned by the KnowledgeBases server but before - it is returned to user code. - """ - return response - def pre_cancel_operation( - self, request: operations_pb2.CancelOperationRequest, metadata: Sequence[Tuple[str, str]] - ) -> Tuple[operations_pb2.CancelOperationRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for cancel_operation - - Override in a subclass to manipulate the request or metadata - before they are sent to the KnowledgeBases server. - """ - return request, metadata - - def post_cancel_operation( - self, response: None - ) -> None: - """Post-rpc interceptor for cancel_operation - - Override in a subclass to manipulate the response - after it is returned by the KnowledgeBases server but before - it is returned to user code. - """ - return response - def pre_get_operation( - self, request: operations_pb2.GetOperationRequest, metadata: Sequence[Tuple[str, str]] - ) -> Tuple[operations_pb2.GetOperationRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for get_operation - - Override in a subclass to manipulate the request or metadata - before they are sent to the KnowledgeBases server. - """ - return request, metadata - - def post_get_operation( - self, response: operations_pb2.Operation - ) -> operations_pb2.Operation: - """Post-rpc interceptor for get_operation - - Override in a subclass to manipulate the response - after it is returned by the KnowledgeBases server but before - it is returned to user code. - """ - return response - def pre_list_operations( - self, request: operations_pb2.ListOperationsRequest, metadata: Sequence[Tuple[str, str]] - ) -> Tuple[operations_pb2.ListOperationsRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for list_operations - - Override in a subclass to manipulate the request or metadata - before they are sent to the KnowledgeBases server. - """ - return request, metadata - - def post_list_operations( - self, response: operations_pb2.ListOperationsResponse - ) -> operations_pb2.ListOperationsResponse: - """Post-rpc interceptor for list_operations - - Override in a subclass to manipulate the response - after it is returned by the KnowledgeBases server but before - it is returned to user code. - """ - return response - - -@dataclasses.dataclass -class KnowledgeBasesRestStub: - _session: AuthorizedSession - _host: str - _interceptor: KnowledgeBasesRestInterceptor - - -class KnowledgeBasesRestTransport(KnowledgeBasesTransport): - """REST backend transport for KnowledgeBases. - - Service for managing - [KnowledgeBases][google.cloud.dialogflow.v2beta1.KnowledgeBase]. - - 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 JSON representations of protocol buffers over HTTP/1.1 - - """ - - def __init__(self, *, - host: str = 'dialogflow.googleapis.com', - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - client_cert_source_for_mtls: Optional[Callable[[ - ], Tuple[bytes, bytes]]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - url_scheme: str = 'https', - interceptor: Optional[KnowledgeBasesRestInterceptor] = None, - api_audience: Optional[str] = None, - ) -> 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 ignored if ``channel`` is provided. - scopes (Optional(Sequence[str])): A list of scopes. This argument is - ignored if ``channel`` is provided. - client_cert_source_for_mtls (Callable[[], Tuple[bytes, bytes]]): Client - certificate to configure mutual TLS HTTP channel. It is ignored - if ``channel`` is provided. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you are developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - url_scheme: the protocol scheme for the API endpoint. Normally - "https", but for testing or local servers, - "http" can be specified. - """ - # Run the base constructor - # TODO(yon-mg): resolve other ctor params i.e. scopes, quota, etc. - # TODO: When custom host (api_endpoint) is set, `scopes` must *also* be set on the - # credentials object - maybe_url_match = re.match("^(?Phttp(?:s)?://)?(?P.*)$", host) - if maybe_url_match is None: - raise ValueError(f"Unexpected hostname structure: {host}") # pragma: NO COVER - - url_match_items = maybe_url_match.groupdict() - - host = f"{url_scheme}://{host}" if not url_match_items["scheme"] else host - - super().__init__( - host=host, - credentials=credentials, - client_info=client_info, - always_use_jwt_access=always_use_jwt_access, - api_audience=api_audience - ) - self._session = AuthorizedSession( - self._credentials, default_host=self.DEFAULT_HOST) - if client_cert_source_for_mtls: - self._session.configure_mtls_channel(client_cert_source_for_mtls) - self._interceptor = interceptor or KnowledgeBasesRestInterceptor() - self._prep_wrapped_messages(client_info) - - class _CreateKnowledgeBase(KnowledgeBasesRestStub): - def __hash__(self): - return hash("CreateKnowledgeBase") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: gcd_knowledge_base.CreateKnowledgeBaseRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> gcd_knowledge_base.KnowledgeBase: - r"""Call the create knowledge base method over HTTP. - - Args: - request (~.gcd_knowledge_base.CreateKnowledgeBaseRequest): - The request object. Request message for - [KnowledgeBases.CreateKnowledgeBase][google.cloud.dialogflow.v2beta1.KnowledgeBases.CreateKnowledgeBase]. - 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: - ~.gcd_knowledge_base.KnowledgeBase: - A knowledge base represents a collection of knowledge - documents that you provide to Dialogflow. Your knowledge - documents contain information that may be useful during - conversations with end-users. Some Dialogflow features - use knowledge bases when looking for a response to an - end-user input. - - For more information, see the `knowledge base - guide `__. - - Note: The ``projects.agent.knowledgeBases`` resource is - deprecated; only use ``projects.knowledgeBases``. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'post', - 'uri': '/v2beta1/{parent=projects/*}/knowledgeBases', - 'body': 'knowledge_base', - }, -{ - 'method': 'post', - 'uri': '/v2beta1/{parent=projects/*/locations/*}/knowledgeBases', - 'body': 'knowledge_base', - }, -{ - 'method': 'post', - 'uri': '/v2beta1/{parent=projects/*/agent}/knowledgeBases', - 'body': 'knowledge_base', - }, - ] - request, metadata = self._interceptor.pre_create_knowledge_base(request, metadata) - pb_request = gcd_knowledge_base.CreateKnowledgeBaseRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request['body'], - including_default_value_fields=False, - use_integers_for_enums=True - ) - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - including_default_value_fields=False, - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = gcd_knowledge_base.KnowledgeBase() - pb_resp = gcd_knowledge_base.KnowledgeBase.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_create_knowledge_base(resp) - return resp - - class _DeleteKnowledgeBase(KnowledgeBasesRestStub): - def __hash__(self): - return hash("DeleteKnowledgeBase") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: knowledge_base.DeleteKnowledgeBaseRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ): - r"""Call the delete knowledge base method over HTTP. - - Args: - request (~.knowledge_base.DeleteKnowledgeBaseRequest): - The request object. Request message for - [KnowledgeBases.DeleteKnowledgeBase][google.cloud.dialogflow.v2beta1.KnowledgeBases.DeleteKnowledgeBase]. - 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. - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'delete', - 'uri': '/v2beta1/{name=projects/*/knowledgeBases/*}', - }, -{ - 'method': 'delete', - 'uri': '/v2beta1/{name=projects/*/locations/*/knowledgeBases/*}', - }, -{ - 'method': 'delete', - 'uri': '/v2beta1/{name=projects/*/agent/knowledgeBases/*}', - }, - ] - request, metadata = self._interceptor.pre_delete_knowledge_base(request, metadata) - pb_request = knowledge_base.DeleteKnowledgeBaseRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - including_default_value_fields=False, - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - class _GetKnowledgeBase(KnowledgeBasesRestStub): - def __hash__(self): - return hash("GetKnowledgeBase") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: knowledge_base.GetKnowledgeBaseRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> knowledge_base.KnowledgeBase: - r"""Call the get knowledge base method over HTTP. - - Args: - request (~.knowledge_base.GetKnowledgeBaseRequest): - The request object. Request message for - [KnowledgeBases.GetKnowledgeBase][google.cloud.dialogflow.v2beta1.KnowledgeBases.GetKnowledgeBase]. - 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: - ~.knowledge_base.KnowledgeBase: - A knowledge base represents a collection of knowledge - documents that you provide to Dialogflow. Your knowledge - documents contain information that may be useful during - conversations with end-users. Some Dialogflow features - use knowledge bases when looking for a response to an - end-user input. - - For more information, see the `knowledge base - guide `__. - - Note: The ``projects.agent.knowledgeBases`` resource is - deprecated; only use ``projects.knowledgeBases``. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v2beta1/{name=projects/*/knowledgeBases/*}', - }, -{ - 'method': 'get', - 'uri': '/v2beta1/{name=projects/*/locations/*/knowledgeBases/*}', - }, -{ - 'method': 'get', - 'uri': '/v2beta1/{name=projects/*/agent/knowledgeBases/*}', - }, - ] - request, metadata = self._interceptor.pre_get_knowledge_base(request, metadata) - pb_request = knowledge_base.GetKnowledgeBaseRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - including_default_value_fields=False, - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = knowledge_base.KnowledgeBase() - pb_resp = knowledge_base.KnowledgeBase.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_get_knowledge_base(resp) - return resp - - class _ListKnowledgeBases(KnowledgeBasesRestStub): - def __hash__(self): - return hash("ListKnowledgeBases") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: knowledge_base.ListKnowledgeBasesRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> knowledge_base.ListKnowledgeBasesResponse: - r"""Call the list knowledge bases method over HTTP. - - Args: - request (~.knowledge_base.ListKnowledgeBasesRequest): - The request object. Request message for - [KnowledgeBases.ListKnowledgeBases][google.cloud.dialogflow.v2beta1.KnowledgeBases.ListKnowledgeBases]. - 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: - ~.knowledge_base.ListKnowledgeBasesResponse: - Response message for - [KnowledgeBases.ListKnowledgeBases][google.cloud.dialogflow.v2beta1.KnowledgeBases.ListKnowledgeBases]. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v2beta1/{parent=projects/*}/knowledgeBases', - }, -{ - 'method': 'get', - 'uri': '/v2beta1/{parent=projects/*/locations/*}/knowledgeBases', - }, -{ - 'method': 'get', - 'uri': '/v2beta1/{parent=projects/*/agent}/knowledgeBases', - }, - ] - request, metadata = self._interceptor.pre_list_knowledge_bases(request, metadata) - pb_request = knowledge_base.ListKnowledgeBasesRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - including_default_value_fields=False, - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = knowledge_base.ListKnowledgeBasesResponse() - pb_resp = knowledge_base.ListKnowledgeBasesResponse.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_list_knowledge_bases(resp) - return resp - - class _UpdateKnowledgeBase(KnowledgeBasesRestStub): - def __hash__(self): - return hash("UpdateKnowledgeBase") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: gcd_knowledge_base.UpdateKnowledgeBaseRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> gcd_knowledge_base.KnowledgeBase: - r"""Call the update knowledge base method over HTTP. - - Args: - request (~.gcd_knowledge_base.UpdateKnowledgeBaseRequest): - The request object. Request message for - [KnowledgeBases.UpdateKnowledgeBase][google.cloud.dialogflow.v2beta1.KnowledgeBases.UpdateKnowledgeBase]. - 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: - ~.gcd_knowledge_base.KnowledgeBase: - A knowledge base represents a collection of knowledge - documents that you provide to Dialogflow. Your knowledge - documents contain information that may be useful during - conversations with end-users. Some Dialogflow features - use knowledge bases when looking for a response to an - end-user input. - - For more information, see the `knowledge base - guide `__. - - Note: The ``projects.agent.knowledgeBases`` resource is - deprecated; only use ``projects.knowledgeBases``. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'patch', - 'uri': '/v2beta1/{knowledge_base.name=projects/*/knowledgeBases/*}', - 'body': 'knowledge_base', - }, -{ - 'method': 'patch', - 'uri': '/v2beta1/{knowledge_base.name=projects/*/locations/*/knowledgeBases/*}', - 'body': 'knowledge_base', - }, -{ - 'method': 'patch', - 'uri': '/v2beta1/{knowledge_base.name=projects/*/agent/knowledgeBases/*}', - 'body': 'knowledge_base', - }, - ] - request, metadata = self._interceptor.pre_update_knowledge_base(request, metadata) - pb_request = gcd_knowledge_base.UpdateKnowledgeBaseRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request['body'], - including_default_value_fields=False, - use_integers_for_enums=True - ) - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - including_default_value_fields=False, - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = gcd_knowledge_base.KnowledgeBase() - pb_resp = gcd_knowledge_base.KnowledgeBase.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_update_knowledge_base(resp) - return resp - - @property - def create_knowledge_base(self) -> Callable[ - [gcd_knowledge_base.CreateKnowledgeBaseRequest], - gcd_knowledge_base.KnowledgeBase]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._CreateKnowledgeBase(self._session, self._host, self._interceptor) # type: ignore - - @property - def delete_knowledge_base(self) -> Callable[ - [knowledge_base.DeleteKnowledgeBaseRequest], - empty_pb2.Empty]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._DeleteKnowledgeBase(self._session, self._host, self._interceptor) # type: ignore - - @property - def get_knowledge_base(self) -> Callable[ - [knowledge_base.GetKnowledgeBaseRequest], - knowledge_base.KnowledgeBase]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._GetKnowledgeBase(self._session, self._host, self._interceptor) # type: ignore - - @property - def list_knowledge_bases(self) -> Callable[ - [knowledge_base.ListKnowledgeBasesRequest], - knowledge_base.ListKnowledgeBasesResponse]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._ListKnowledgeBases(self._session, self._host, self._interceptor) # type: ignore - - @property - def update_knowledge_base(self) -> Callable[ - [gcd_knowledge_base.UpdateKnowledgeBaseRequest], - gcd_knowledge_base.KnowledgeBase]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._UpdateKnowledgeBase(self._session, self._host, self._interceptor) # type: ignore - - @property - def get_location(self): - return self._GetLocation(self._session, self._host, self._interceptor) # type: ignore - - class _GetLocation(KnowledgeBasesRestStub): - def __call__(self, - request: locations_pb2.GetLocationRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> locations_pb2.Location: - - r"""Call the get location method over HTTP. - - Args: - request (locations_pb2.GetLocationRequest): - The request object for GetLocation method. - 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: - locations_pb2.Location: Response from GetLocation method. - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v2beta1/{name=projects/*/locations/*}', - }, - ] - - request, metadata = self._interceptor.pre_get_location(request, metadata) - request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode( - http_options, **request_kwargs) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json.dumps(transcoded_request['query_params'])) - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - resp = locations_pb2.Location() - resp = json_format.Parse(response.content.decode("utf-8"), resp) - resp = self._interceptor.post_get_location(resp) - return resp - - @property - def list_locations(self): - return self._ListLocations(self._session, self._host, self._interceptor) # type: ignore - - class _ListLocations(KnowledgeBasesRestStub): - def __call__(self, - request: locations_pb2.ListLocationsRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> locations_pb2.ListLocationsResponse: - - r"""Call the list locations method over HTTP. - - Args: - request (locations_pb2.ListLocationsRequest): - The request object for ListLocations method. - 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: - locations_pb2.ListLocationsResponse: Response from ListLocations method. - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v2beta1/{name=projects/*}/locations', - }, - ] - - request, metadata = self._interceptor.pre_list_locations(request, metadata) - request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode( - http_options, **request_kwargs) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json.dumps(transcoded_request['query_params'])) - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - resp = locations_pb2.ListLocationsResponse() - resp = json_format.Parse(response.content.decode("utf-8"), resp) - resp = self._interceptor.post_list_locations(resp) - return resp - - @property - def cancel_operation(self): - return self._CancelOperation(self._session, self._host, self._interceptor) # type: ignore - - class _CancelOperation(KnowledgeBasesRestStub): - def __call__(self, - request: operations_pb2.CancelOperationRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> None: - - r"""Call the cancel operation method over HTTP. - - Args: - request (operations_pb2.CancelOperationRequest): - The request object for CancelOperation method. - 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. - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'post', - 'uri': '/v2beta1/{name=projects/*/operations/*}:cancel', - }, -{ - 'method': 'post', - 'uri': '/v2beta1/{name=projects/*/locations/*/operations/*}:cancel', - }, - ] - - request, metadata = self._interceptor.pre_cancel_operation(request, metadata) - request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode( - http_options, **request_kwargs) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json.dumps(transcoded_request['query_params'])) - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - return self._interceptor.post_cancel_operation(None) - - @property - def get_operation(self): - return self._GetOperation(self._session, self._host, self._interceptor) # type: ignore - - class _GetOperation(KnowledgeBasesRestStub): - def __call__(self, - request: operations_pb2.GetOperationRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> operations_pb2.Operation: - - r"""Call the get operation method over HTTP. - - Args: - request (operations_pb2.GetOperationRequest): - The request object for GetOperation method. - 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: - operations_pb2.Operation: Response from GetOperation method. - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v2beta1/{name=projects/*/operations/*}', - }, -{ - 'method': 'get', - 'uri': '/v2beta1/{name=projects/*/locations/*/operations/*}', - }, - ] - - request, metadata = self._interceptor.pre_get_operation(request, metadata) - request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode( - http_options, **request_kwargs) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json.dumps(transcoded_request['query_params'])) - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - resp = operations_pb2.Operation() - resp = json_format.Parse(response.content.decode("utf-8"), resp) - resp = self._interceptor.post_get_operation(resp) - return resp - - @property - def list_operations(self): - return self._ListOperations(self._session, self._host, self._interceptor) # type: ignore - - class _ListOperations(KnowledgeBasesRestStub): - def __call__(self, - request: operations_pb2.ListOperationsRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> operations_pb2.ListOperationsResponse: - - r"""Call the list operations method over HTTP. - - Args: - request (operations_pb2.ListOperationsRequest): - The request object for ListOperations method. - 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: - operations_pb2.ListOperationsResponse: Response from ListOperations method. - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v2beta1/{name=projects/*}/operations', - }, -{ - 'method': 'get', - 'uri': '/v2beta1/{name=projects/*/locations/*}/operations', - }, - ] - - request, metadata = self._interceptor.pre_list_operations(request, metadata) - request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode( - http_options, **request_kwargs) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json.dumps(transcoded_request['query_params'])) - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - resp = operations_pb2.ListOperationsResponse() - resp = json_format.Parse(response.content.decode("utf-8"), resp) - resp = self._interceptor.post_list_operations(resp) - return resp - - @property - def kind(self) -> str: - return "rest" - - def close(self): - self._session.close() - - -__all__=( - 'KnowledgeBasesRestTransport', -) diff --git a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/participants/__init__.py b/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/participants/__init__.py deleted file mode 100644 index f97cdb2aa..000000000 --- a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/participants/__init__.py +++ /dev/null @@ -1,22 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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 ParticipantsClient -from .async_client import ParticipantsAsyncClient - -__all__ = ( - 'ParticipantsClient', - 'ParticipantsAsyncClient', -) diff --git a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/participants/async_client.py b/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/participants/async_client.py deleted file mode 100644 index 8b21a0f63..000000000 --- a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/participants/async_client.py +++ /dev/null @@ -1,1739 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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, Mapping, MutableMapping, MutableSequence, Optional, AsyncIterable, Awaitable, AsyncIterator, Sequence, Tuple, Type, Union -import warnings - -from google.cloud.dialogflow_v2beta1 import gapic_version as package_version - -from google.api_core.client_options import ClientOptions -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import retry as retries -from google.auth import credentials as ga_credentials # type: ignore -from google.oauth2 import service_account # type: ignore - -try: - OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] -except AttributeError: # pragma: NO COVER - OptionalRetry = Union[retries.Retry, object] # 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.cloud.location import locations_pb2 # type: ignore -from google.longrunning import operations_pb2 -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 - - -class ParticipantsAsyncClient: - """Service for managing - [Participants][google.cloud.dialogflow.v2beta1.Participant]. - """ - - _client: ParticipantsClient - - DEFAULT_ENDPOINT = ParticipantsClient.DEFAULT_ENDPOINT - DEFAULT_MTLS_ENDPOINT = ParticipantsClient.DEFAULT_MTLS_ENDPOINT - - answer_record_path = staticmethod(ParticipantsClient.answer_record_path) - parse_answer_record_path = staticmethod(ParticipantsClient.parse_answer_record_path) - context_path = staticmethod(ParticipantsClient.context_path) - parse_context_path = staticmethod(ParticipantsClient.parse_context_path) - document_path = staticmethod(ParticipantsClient.document_path) - parse_document_path = staticmethod(ParticipantsClient.parse_document_path) - intent_path = staticmethod(ParticipantsClient.intent_path) - parse_intent_path = staticmethod(ParticipantsClient.parse_intent_path) - message_path = staticmethod(ParticipantsClient.message_path) - parse_message_path = staticmethod(ParticipantsClient.parse_message_path) - participant_path = staticmethod(ParticipantsClient.participant_path) - parse_participant_path = staticmethod(ParticipantsClient.parse_participant_path) - session_entity_type_path = staticmethod(ParticipantsClient.session_entity_type_path) - 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) - - @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: - ParticipantsAsyncClient: The constructed client. - """ - return ParticipantsClient.from_service_account_info.__func__(ParticipantsAsyncClient, 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: - ParticipantsAsyncClient: The constructed client. - """ - return ParticipantsClient.from_service_account_file.__func__(ParticipantsAsyncClient, filename, *args, **kwargs) # type: ignore - - from_service_account_json = from_service_account_file - - @classmethod - def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[ClientOptions] = None): - """Return the API endpoint and client cert source for mutual TLS. - - The client cert source is determined in the following order: - (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the - client cert source is None. - (2) if `client_options.client_cert_source` is provided, use the provided one; if the - default client cert source exists, use the default one; otherwise the client cert - source is None. - - The API endpoint is determined in the following order: - (1) if `client_options.api_endpoint` if provided, use the provided one. - (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the - default mTLS endpoint; if the environment variable is "never", use the default API - endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise - use the default API endpoint. - - More details can be found at https://google.aip.dev/auth/4114. - - Args: - client_options (google.api_core.client_options.ClientOptions): Custom options for the - client. Only the `api_endpoint` and `client_cert_source` properties may be used - in this method. - - Returns: - Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the - client cert source to use. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If any errors happen. - """ - return ParticipantsClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore - - @property - def transport(self) -> ParticipantsTransport: - """Returns the transport used by the client instance. - - Returns: - ParticipantsTransport: The transport used by the client instance. - """ - return self._client.transport - - get_transport_class = functools.partial(type(ParticipantsClient).get_transport_class, type(ParticipantsClient)) - - def __init__(self, *, - credentials: Optional[ga_credentials.Credentials] = None, - transport: Union[str, ParticipantsTransport] = "grpc_asyncio", - client_options: Optional[ClientOptions] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the participants 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, ~.ParticipantsTransport]): 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 = ParticipantsClient( - credentials=credentials, - transport=transport, - client_options=client_options, - client_info=client_info, - - ) - - async def create_participant(self, - request: Optional[Union[gcd_participant.CreateParticipantRequest, dict]] = None, - *, - parent: Optional[str] = None, - participant: Optional[gcd_participant.Participant] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gcd_participant.Participant: - r"""Creates a new participant in a conversation. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import dialogflow_v2beta1 - - async def sample_create_participant(): - # Create a client - client = dialogflow_v2beta1.ParticipantsAsyncClient() - - # Initialize request argument(s) - request = dialogflow_v2beta1.CreateParticipantRequest( - parent="parent_value", - ) - - # Make the request - response = await client.create_participant(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.dialogflow_v2beta1.types.CreateParticipantRequest, dict]]): - The request object. The request message for - [Participants.CreateParticipant][google.cloud.dialogflow.v2beta1.Participants.CreateParticipant]. - parent (:class:`str`): - Required. Resource identifier of the conversation adding - the participant. Format: - ``projects//locations//conversations/``. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - participant (:class:`google.cloud.dialogflow_v2beta1.types.Participant`): - Required. The participant to create. - 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. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.dialogflow_v2beta1.types.Participant: - Represents a conversation participant - (human agent, virtual agent, end-user). - - """ - # Create or coerce a protobuf request object. - # Quick 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, participant]) - 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_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: - request.participant = participant - - # 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_participant, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def get_participant(self, - request: Optional[Union[participant.GetParticipantRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> participant.Participant: - r"""Retrieves a conversation participant. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import dialogflow_v2beta1 - - async def sample_get_participant(): - # Create a client - client = dialogflow_v2beta1.ParticipantsAsyncClient() - - # Initialize request argument(s) - request = dialogflow_v2beta1.GetParticipantRequest( - name="name_value", - ) - - # Make the request - response = await client.get_participant(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.dialogflow_v2beta1.types.GetParticipantRequest, dict]]): - The request object. The request message for - [Participants.GetParticipant][google.cloud.dialogflow.v2beta1.Participants.GetParticipant]. - name (:class:`str`): - Required. The name of the participant. Format: - ``projects//locations//conversations//participants/``. - - 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.Participant: - Represents a conversation participant - (human agent, virtual agent, end-user). - - """ - # Create or coerce a protobuf request object. - # Quick 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 = participant.GetParticipantRequest(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_participant, - 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 list_participants(self, - request: Optional[Union[participant.ListParticipantsRequest, dict]] = None, - *, - parent: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListParticipantsAsyncPager: - r"""Returns the list of all participants in the specified - conversation. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import dialogflow_v2beta1 - - async def sample_list_participants(): - # Create a client - client = dialogflow_v2beta1.ParticipantsAsyncClient() - - # Initialize request argument(s) - request = dialogflow_v2beta1.ListParticipantsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_participants(request=request) - - # Handle the response - async for response in page_result: - print(response) - - Args: - request (Optional[Union[google.cloud.dialogflow_v2beta1.types.ListParticipantsRequest, dict]]): - The request object. The request message for - [Participants.ListParticipants][google.cloud.dialogflow.v2beta1.Participants.ListParticipants]. - parent (:class:`str`): - Required. The conversation to list all participants - from. Format: - ``projects//locations//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. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.dialogflow_v2beta1.services.participants.pagers.ListParticipantsAsyncPager: - The response message for - [Participants.ListParticipants][google.cloud.dialogflow.v2beta1.Participants.ListParticipants]. - - Iterating over this object will yield results and - resolve additional pages automatically. - - """ - # Create or coerce a protobuf request object. - # Quick 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 = participant.ListParticipantsRequest(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_participants, - 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.ListParticipantsAsyncPager( - method=rpc, - request=request, - response=response, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def update_participant(self, - request: Optional[Union[gcd_participant.UpdateParticipantRequest, dict]] = None, - *, - participant: Optional[gcd_participant.Participant] = None, - update_mask: Optional[field_mask_pb2.FieldMask] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gcd_participant.Participant: - r"""Updates the specified participant. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import dialogflow_v2beta1 - - async def sample_update_participant(): - # Create a client - client = dialogflow_v2beta1.ParticipantsAsyncClient() - - # Initialize request argument(s) - request = dialogflow_v2beta1.UpdateParticipantRequest( - ) - - # Make the request - response = await client.update_participant(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.dialogflow_v2beta1.types.UpdateParticipantRequest, dict]]): - The request object. The request message for - [Participants.UpdateParticipant][google.cloud.dialogflow.v2beta1.Participants.UpdateParticipant]. - participant (:class:`google.cloud.dialogflow_v2beta1.types.Participant`): - Required. The participant to update. - This corresponds to the ``participant`` 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 specify which - fields to update. - - 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.Participant: - Represents a conversation participant - (human agent, virtual agent, end-user). - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([participant, 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_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: - 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_participant, - 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(( - ("participant.name", request.participant.name), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def analyze_content(self, - request: Optional[Union[gcd_participant.AnalyzeContentRequest, dict]] = None, - *, - participant: Optional[str] = None, - text_input: Optional[session.TextInput] = None, - audio_input: Optional[gcd_participant.AudioInput] = None, - event_input: Optional[session.EventInput] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gcd_participant.AnalyzeContentResponse: - r"""Adds a text (chat, for example), or audio (phone recording, for - example) message from a participant into the conversation. - - Note: Always use agent versions for production traffic sent to - virtual agents. See `Versions and - environments `__. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import dialogflow_v2beta1 - - async def sample_analyze_content(): - # Create a client - client = dialogflow_v2beta1.ParticipantsAsyncClient() - - # Initialize request argument(s) - request = dialogflow_v2beta1.AnalyzeContentRequest( - participant="participant_value", - ) - - # Make the request - response = await client.analyze_content(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.dialogflow_v2beta1.types.AnalyzeContentRequest, dict]]): - The request object. The request message for - [Participants.AnalyzeContent][google.cloud.dialogflow.v2beta1.Participants.AnalyzeContent]. - participant (:class:`str`): - Required. The name of the participant this text comes - from. Format: - ``projects//locations//conversations//participants/``. - - This corresponds to the ``participant`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - text_input (:class:`google.cloud.dialogflow_v2beta1.types.TextInput`): - The natural language text to be - processed. - - This corresponds to the ``text_input`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - audio_input (:class:`google.cloud.dialogflow_v2beta1.types.AudioInput`): - The natural language speech audio to - be processed. - - This corresponds to the ``audio_input`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - event_input (:class:`google.cloud.dialogflow_v2beta1.types.EventInput`): - An input event to send to Dialogflow. - 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. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.dialogflow_v2beta1.types.AnalyzeContentResponse: - The response message for - [Participants.AnalyzeContent][google.cloud.dialogflow.v2beta1.Participants.AnalyzeContent]. - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([participant, text_input, audio_input, event_input]) - 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_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: - request.text_input = text_input - if audio_input is not None: - request.audio_input = audio_input - if event_input is not None: - request.event_input = event_input - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.analyze_content, - default_retry=retries.Retry( -initial=0.1,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( - core_exceptions.ServiceUnavailable, - ), - deadline=220.0, - ), - default_timeout=220.0, - 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(( - ("participant", request.participant), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def streaming_analyze_content(self, - requests: Optional[AsyncIterator[participant.StreamingAnalyzeContentRequest]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> Awaitable[AsyncIterable[participant.StreamingAnalyzeContentResponse]]: - r"""Adds a text (e.g., chat) or audio (e.g., phone recording) - message from a participant into the conversation. Note: This - method is only available through the gRPC API (not REST). - - The top-level message sent to the client by the server is - ``StreamingAnalyzeContentResponse``. Multiple response messages - can be returned in order. The first one or more messages contain - the ``recognition_result`` field. Each result represents a more - complete transcript of what the user said. The next message - contains the ``reply_text`` field, and potentially the - ``reply_audio`` and/or the ``automated_agent_reply`` fields. - - Note: Always use agent versions for production traffic sent to - virtual agents. See `Versions and - environments `__. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import dialogflow_v2beta1 - - async def sample_streaming_analyze_content(): - # Create a client - client = dialogflow_v2beta1.ParticipantsAsyncClient() - - # Initialize request argument(s) - request = dialogflow_v2beta1.StreamingAnalyzeContentRequest( - input_audio=b'input_audio_blob', - participant="participant_value", - ) - - # This method expects an iterator which contains - # 'dialogflow_v2beta1.StreamingAnalyzeContentRequest' objects - # Here we create a generator that yields a single `request` for - # demonstrative purposes. - requests = [request] - - def request_generator(): - for request in requests: - yield request - - # Make the request - stream = await client.streaming_analyze_content(requests=request_generator()) - - # Handle the response - async for response in stream: - print(response) - - Args: - requests (AsyncIterator[`google.cloud.dialogflow_v2beta1.types.StreamingAnalyzeContentRequest`]): - The request object AsyncIterator. The top-level message sent by the client to the - [Participants.StreamingAnalyzeContent][google.cloud.dialogflow.v2beta1.Participants.StreamingAnalyzeContent] - method. - - Multiple request messages should be sent in order: - - 1. The first message must contain - [participant][google.cloud.dialogflow.v2beta1.StreamingAnalyzeContentRequest.participant], - [config][google.cloud.dialogflow.v2beta1.StreamingAnalyzeContentRequest.config] - and optionally - [query_params][google.cloud.dialogflow.v2beta1.StreamingAnalyzeContentRequest.query_params]. - If you want to receive an audio response, it should - also contain - [reply_audio_config][google.cloud.dialogflow.v2beta1.StreamingAnalyzeContentRequest.reply_audio_config]. - The message must not contain - [input][google.cloud.dialogflow.v2beta1.StreamingAnalyzeContentRequest.input]. - - 2. If - [config][google.cloud.dialogflow.v2beta1.StreamingAnalyzeContentRequest.config] - in the first message was set to - [audio_config][google.cloud.dialogflow.v2beta1.StreamingAnalyzeContentRequest.audio_config], - all subsequent messages must contain - [input_audio][google.cloud.dialogflow.v2beta1.StreamingAnalyzeContentRequest.input_audio] - to continue with Speech recognition. If you decide to - rather analyze text input after you already started - Speech recognition, please send a message with - [StreamingAnalyzeContentRequest.input_text][google.cloud.dialogflow.v2beta1.StreamingAnalyzeContentRequest.input_text]. - - However, note that: - - - Dialogflow will bill you for the audio so far. - - Dialogflow discards all Speech recognition results - in favor of the text input. - - 3. If - [StreamingAnalyzeContentRequest.config][google.cloud.dialogflow.v2beta1.StreamingAnalyzeContentRequest.config] - in the first message was set to - [StreamingAnalyzeContentRequest.text_config][google.cloud.dialogflow.v2beta1.StreamingAnalyzeContentRequest.text_config], - then the second message must contain only - [input_text][google.cloud.dialogflow.v2beta1.StreamingAnalyzeContentRequest.input_text]. - Moreover, you must not send more than two messages. - - After you sent all input, you must half-close or abort - the request stream. - 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: - AsyncIterable[google.cloud.dialogflow_v2beta1.types.StreamingAnalyzeContentResponse]: - The top-level message returned from the - StreamingAnalyzeContent method. - - Multiple response messages can be returned in order: - - 1. If the input was set to streaming audio, the first - one or more messages contain recognition_result. - Each recognition_result represents a more complete - transcript of what the user said. The last - recognition_result has is_final set to true. - 2. In virtual agent stage: if - enable_partial_automated_agent_reply is true, the - following N (currently 1 <= N <= 4) messages - contain automated_agent_reply and optionally - reply_audio returned by the virtual agent. The - first (N-1) automated_agent_replys will have - automated_agent_reply_type set to PARTIAL. The - last automated_agent_reply has - automated_agent_reply_type set to FINAL. If - enable_partial_automated_agent_reply is not - enabled, response stream only contains the final - reply. - - In human assist stage: the following N (N >= 1) - messages contain human_agent_suggestion_results, - end_user_suggestion_results or message. - - """ - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.streaming_analyze_content, - default_timeout=220.0, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Send the request. - response = rpc( - requests, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def suggest_articles(self, - request: Optional[Union[participant.SuggestArticlesRequest, dict]] = None, - *, - parent: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> participant.SuggestArticlesResponse: - r"""Gets suggested articles for a participant based on specific - historical messages. - - Note that - [ListSuggestions][google.cloud.dialogflow.v2beta1.Participants.ListSuggestions] - will only list the auto-generated suggestions, while - [CompileSuggestion][google.cloud.dialogflow.v2beta1.Participants.CompileSuggestion] - will try to compile suggestion based on the provided - conversation context in the real time. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import dialogflow_v2beta1 - - async def sample_suggest_articles(): - # Create a client - client = dialogflow_v2beta1.ParticipantsAsyncClient() - - # Initialize request argument(s) - request = dialogflow_v2beta1.SuggestArticlesRequest( - parent="parent_value", - ) - - # Make the request - response = await client.suggest_articles(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.dialogflow_v2beta1.types.SuggestArticlesRequest, dict]]): - The request object. The request message for - [Participants.SuggestArticles][google.cloud.dialogflow.v2beta1.Participants.SuggestArticles]. - parent (:class:`str`): - Required. The name of the participant to fetch - suggestion for. Format: - ``projects//locations//conversations//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. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.dialogflow_v2beta1.types.SuggestArticlesResponse: - The response message for - [Participants.SuggestArticles][google.cloud.dialogflow.v2beta1.Participants.SuggestArticles]. - - """ - # Create or coerce a protobuf request object. - # Quick 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 = participant.SuggestArticlesRequest(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.suggest_articles, - 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 suggest_faq_answers(self, - request: Optional[Union[participant.SuggestFaqAnswersRequest, dict]] = None, - *, - parent: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> participant.SuggestFaqAnswersResponse: - r"""Gets suggested faq answers for a participant based on - specific historical messages. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import dialogflow_v2beta1 - - async def sample_suggest_faq_answers(): - # Create a client - client = dialogflow_v2beta1.ParticipantsAsyncClient() - - # Initialize request argument(s) - request = dialogflow_v2beta1.SuggestFaqAnswersRequest( - parent="parent_value", - ) - - # Make the request - response = await client.suggest_faq_answers(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.dialogflow_v2beta1.types.SuggestFaqAnswersRequest, dict]]): - The request object. The request message for - [Participants.SuggestFaqAnswers][google.cloud.dialogflow.v2beta1.Participants.SuggestFaqAnswers]. - parent (:class:`str`): - Required. The name of the participant to fetch - suggestion for. Format: - ``projects//locations//conversations//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. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.dialogflow_v2beta1.types.SuggestFaqAnswersResponse: - The request message for - [Participants.SuggestFaqAnswers][google.cloud.dialogflow.v2beta1.Participants.SuggestFaqAnswers]. - - """ - # Create or coerce a protobuf request object. - # Quick 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 = participant.SuggestFaqAnswersRequest(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.suggest_faq_answers, - 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 suggest_smart_replies(self, - request: Optional[Union[participant.SuggestSmartRepliesRequest, dict]] = None, - *, - parent: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> participant.SuggestSmartRepliesResponse: - r"""Gets smart replies for a participant based on - specific historical messages. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import dialogflow_v2beta1 - - async def sample_suggest_smart_replies(): - # Create a client - client = dialogflow_v2beta1.ParticipantsAsyncClient() - - # Initialize request argument(s) - request = dialogflow_v2beta1.SuggestSmartRepliesRequest( - parent="parent_value", - ) - - # Make the request - response = await client.suggest_smart_replies(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.dialogflow_v2beta1.types.SuggestSmartRepliesRequest, dict]]): - The request object. The request message for - [Participants.SuggestSmartReplies][google.cloud.dialogflow.v2beta1.Participants.SuggestSmartReplies]. - parent (:class:`str`): - Required. The name of the participant to fetch - suggestion for. Format: - ``projects//locations//conversations//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. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.dialogflow_v2beta1.types.SuggestSmartRepliesResponse: - The response message for - [Participants.SuggestSmartReplies][google.cloud.dialogflow.v2beta1.Participants.SuggestSmartReplies]. - - """ - # Create or coerce a protobuf request object. - # Quick 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 = participant.SuggestSmartRepliesRequest(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.suggest_smart_replies, - 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 list_suggestions(self, - request: Optional[Union[participant.ListSuggestionsRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListSuggestionsAsyncPager: - r"""Deprecated: Use inline suggestion, event based suggestion or - Suggestion\* API instead. See - [HumanAgentAssistantConfig.name][google.cloud.dialogflow.v2beta1.HumanAgentAssistantConfig.name] - for more details. Removal Date: 2020-09-01. - - Retrieves suggestions for live agents. - - This method should be used by human agent client software to - 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 `__ - 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 - descending order. To fetch latest suggestion, just set - ``page_size`` to 1. To fetch new suggestions without - duplication, send request with filter - ``create_time_epoch_microseconds > [first item's create_time of previous request]`` - and empty page_token. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import dialogflow_v2beta1 - - async def sample_list_suggestions(): - # Create a client - client = dialogflow_v2beta1.ParticipantsAsyncClient() - - # Initialize request argument(s) - request = dialogflow_v2beta1.ListSuggestionsRequest( - ) - - # Make the request - page_result = client.list_suggestions(request=request) - - # Handle the response - async for response in page_result: - print(response) - - Args: - request (Optional[Union[google.cloud.dialogflow_v2beta1.types.ListSuggestionsRequest, dict]]): - 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. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.dialogflow_v2beta1.services.participants.pagers.ListSuggestionsAsyncPager: - The response message for - [Participants.ListSuggestions][google.cloud.dialogflow.v2beta1.Participants.ListSuggestions]. - - Iterating over this object will yield results and - resolve additional pages automatically. - - """ - warnings.warn("ParticipantsAsyncClient.list_suggestions is deprecated", - DeprecationWarning) - - # Create or coerce a protobuf request object. - request = participant.ListSuggestionsRequest(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.list_suggestions, - 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.ListSuggestionsAsyncPager( - method=rpc, - request=request, - response=response, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def compile_suggestion(self, - request: Optional[Union[participant.CompileSuggestionRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> participant.CompileSuggestionResponse: - r"""Deprecated. use - [SuggestArticles][google.cloud.dialogflow.v2beta1.Participants.SuggestArticles] - and - [SuggestFaqAnswers][google.cloud.dialogflow.v2beta1.Participants.SuggestFaqAnswers] - instead. - - Gets suggestions for a participant based on specific historical - messages. - - Note that - [ListSuggestions][google.cloud.dialogflow.v2beta1.Participants.ListSuggestions] - will only list the auto-generated suggestions, while - [CompileSuggestion][google.cloud.dialogflow.v2beta1.Participants.CompileSuggestion] - will try to compile suggestion based on the provided - conversation context in the real time. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import dialogflow_v2beta1 - - async def sample_compile_suggestion(): - # Create a client - client = dialogflow_v2beta1.ParticipantsAsyncClient() - - # Initialize request argument(s) - request = dialogflow_v2beta1.CompileSuggestionRequest( - ) - - # Make the request - response = await client.compile_suggestion(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.dialogflow_v2beta1.types.CompileSuggestionRequest, dict]]): - 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. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.dialogflow_v2beta1.types.CompileSuggestionResponse: - The response message for - [Participants.CompileSuggestion][google.cloud.dialogflow.v2beta1.Participants.CompileSuggestion]. - - """ - warnings.warn("ParticipantsAsyncClient.compile_suggestion is deprecated", - DeprecationWarning) - - # Create or coerce a protobuf request object. - request = participant.CompileSuggestionRequest(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.compile_suggestion, - 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 list_operations( - self, - request: Optional[operations_pb2.ListOperationsRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operations_pb2.ListOperationsResponse: - r"""Lists operations that match the specified filter in the request. - - Args: - request (:class:`~.operations_pb2.ListOperationsRequest`): - The request object. Request message for - `ListOperations` method. - 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: - ~.operations_pb2.ListOperationsResponse: - Response message for ``ListOperations`` method. - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = operations_pb2.ListOperationsRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._client._transport.list_operations, - 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 get_operation( - self, - request: Optional[operations_pb2.GetOperationRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operations_pb2.Operation: - r"""Gets the latest state of a long-running operation. - - Args: - request (:class:`~.operations_pb2.GetOperationRequest`): - The request object. Request message for - `GetOperation` method. - 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: - ~.operations_pb2.Operation: - An ``Operation`` object. - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = operations_pb2.GetOperationRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._client._transport.get_operation, - 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 cancel_operation( - self, - request: Optional[operations_pb2.CancelOperationRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> None: - r"""Starts asynchronous cancellation on a long-running operation. - - The server makes a best effort to cancel the operation, but success - is not guaranteed. If the server doesn't support this method, it returns - `google.rpc.Code.UNIMPLEMENTED`. - - Args: - request (:class:`~.operations_pb2.CancelOperationRequest`): - The request object. Request message for - `CancelOperation` method. - 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: - None - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = operations_pb2.CancelOperationRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._client._transport.cancel_operation, - 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_location( - self, - request: Optional[locations_pb2.GetLocationRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> locations_pb2.Location: - r"""Gets information about a location. - - Args: - request (:class:`~.location_pb2.GetLocationRequest`): - The request object. Request message for - `GetLocation` method. - 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: - ~.location_pb2.Location: - Location object. - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = locations_pb2.GetLocationRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._client._transport.get_location, - 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 list_locations( - self, - request: Optional[locations_pb2.ListLocationsRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> locations_pb2.ListLocationsResponse: - r"""Lists information about the supported locations for this service. - - Args: - request (:class:`~.location_pb2.ListLocationsRequest`): - The request object. Request message for - `ListLocations` method. - 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: - ~.location_pb2.ListLocationsResponse: - Response message for ``ListLocations`` method. - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = locations_pb2.ListLocationsRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._client._transport.list_locations, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("name", request.name),)), - ) - - # Send the request. - response = await rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - async def __aenter__(self): - return self - - async def __aexit__(self, exc_type, exc, tb): - await self.transport.close() - -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) - - -__all__ = ( - "ParticipantsAsyncClient", -) diff --git a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/participants/client.py b/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/participants/client.py deleted file mode 100644 index db759e7d5..000000000 --- a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/participants/client.py +++ /dev/null @@ -1,1984 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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 os -import re -from typing import Dict, Mapping, MutableMapping, MutableSequence, Optional, Iterable, Iterator, Sequence, Tuple, Type, Union, cast -import warnings - -from google.cloud.dialogflow_v2beta1 import gapic_version as package_version - -from google.api_core import client_options as client_options_lib -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import retry as retries -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 - -try: - OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] -except AttributeError: # pragma: NO COVER - OptionalRetry = Union[retries.Retry, object] # 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.cloud.location import locations_pb2 # type: ignore -from google.longrunning import operations_pb2 -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 -from .transports.rest import ParticipantsRestTransport - - -class ParticipantsClientMeta(type): - """Metaclass for the Participants 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[ParticipantsTransport]] - _transport_registry["grpc"] = ParticipantsGrpcTransport - _transport_registry["grpc_asyncio"] = ParticipantsGrpcAsyncIOTransport - _transport_registry["rest"] = ParticipantsRestTransport - - def get_transport_class(cls, - label: Optional[str] = None, - ) -> Type[ParticipantsTransport]: - """Returns an appropriate transport class. - - Args: - label: The name of the desired transport. If none is - provided, then the first transport in the registry is used. - - Returns: - The transport class to use. - """ - # If a specific transport is requested, return that one. - if label: - return cls._transport_registry[label] - - # No transport is requested; return the default (that is, the first one - # in the dictionary). - return next(iter(cls._transport_registry.values())) - - -class ParticipantsClient(metaclass=ParticipantsClientMeta): - """Service for managing - [Participants][google.cloud.dialogflow.v2beta1.Participant]. - """ - - @staticmethod - def _get_default_mtls_endpoint(api_endpoint): - """Converts api endpoint to mTLS endpoint. - - Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to - "*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively. - Args: - api_endpoint (Optional[str]): the api endpoint to convert. - Returns: - str: converted mTLS api endpoint. - """ - if not api_endpoint: - return api_endpoint - - mtls_endpoint_re = re.compile( - r"(?P[^.]+)(?P\.mtls)?(?P\.sandbox)?(?P\.googleapis\.com)?" - ) - - m = mtls_endpoint_re.match(api_endpoint) - name, mtls, sandbox, googledomain = m.groups() - if mtls or not googledomain: - return api_endpoint - - if sandbox: - return api_endpoint.replace( - "sandbox.googleapis.com", "mtls.sandbox.googleapis.com" - ) - - return api_endpoint.replace(".googleapis.com", ".mtls.googleapis.com") - - DEFAULT_ENDPOINT = "dialogflow.googleapis.com" - DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore - DEFAULT_ENDPOINT - ) - - @classmethod - def from_service_account_info(cls, info: dict, *args, **kwargs): - """Creates an instance of this client using the provided credentials - info. - - Args: - info (dict): The service account private key info. - args: Additional arguments to pass to the constructor. - kwargs: Additional arguments to pass to the constructor. - - Returns: - ParticipantsClient: 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: - ParticipantsClient: 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) -> ParticipantsTransport: - """Returns the transport used by the client instance. - - Returns: - ParticipantsTransport: The transport used by the client - instance. - """ - return self._transport - - @staticmethod - def answer_record_path(project: str,answer_record: str,) -> str: - """Returns a fully-qualified answer_record string.""" - return "projects/{project}/answerRecords/{answer_record}".format(project=project, answer_record=answer_record, ) - - @staticmethod - def parse_answer_record_path(path: str) -> Dict[str,str]: - """Parses a answer_record path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/answerRecords/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def context_path(project: str,session: str,context: str,) -> str: - """Returns a fully-qualified context string.""" - return "projects/{project}/agent/sessions/{session}/contexts/{context}".format(project=project, session=session, context=context, ) - - @staticmethod - def parse_context_path(path: str) -> Dict[str,str]: - """Parses a context path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/agent/sessions/(?P.+?)/contexts/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def document_path(project: str,knowledge_base: str,document: str,) -> str: - """Returns a fully-qualified document string.""" - return "projects/{project}/knowledgeBases/{knowledge_base}/documents/{document}".format(project=project, knowledge_base=knowledge_base, document=document, ) - - @staticmethod - def parse_document_path(path: str) -> Dict[str,str]: - """Parses a document path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/knowledgeBases/(?P.+?)/documents/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def intent_path(project: str,intent: str,) -> str: - """Returns a fully-qualified intent string.""" - return "projects/{project}/agent/intents/{intent}".format(project=project, intent=intent, ) - - @staticmethod - def parse_intent_path(path: str) -> Dict[str,str]: - """Parses a intent path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/agent/intents/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def message_path(project: str,conversation: str,message: str,) -> str: - """Returns a fully-qualified message string.""" - return "projects/{project}/conversations/{conversation}/messages/{message}".format(project=project, conversation=conversation, message=message, ) - - @staticmethod - def parse_message_path(path: str) -> Dict[str,str]: - """Parses a message path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/conversations/(?P.+?)/messages/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def participant_path(project: str,conversation: str,participant: str,) -> str: - """Returns a fully-qualified participant string.""" - return "projects/{project}/conversations/{conversation}/participants/{participant}".format(project=project, conversation=conversation, participant=participant, ) - - @staticmethod - def parse_participant_path(path: str) -> Dict[str,str]: - """Parses a participant path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/conversations/(?P.+?)/participants/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def session_entity_type_path(project: str,session: str,entity_type: str,) -> str: - """Returns a fully-qualified session_entity_type string.""" - return "projects/{project}/agent/sessions/{session}/entityTypes/{entity_type}".format(project=project, session=session, entity_type=entity_type, ) - - @staticmethod - def parse_session_entity_type_path(path: str) -> Dict[str,str]: - """Parses a session_entity_type path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/agent/sessions/(?P.+?)/entityTypes/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_billing_account_path(billing_account: str, ) -> str: - """Returns a fully-qualified billing_account string.""" - return "billingAccounts/{billing_account}".format(billing_account=billing_account, ) - - @staticmethod - def parse_common_billing_account_path(path: str) -> Dict[str,str]: - """Parse a billing_account path into its component segments.""" - m = re.match(r"^billingAccounts/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_folder_path(folder: str, ) -> str: - """Returns a fully-qualified folder string.""" - return "folders/{folder}".format(folder=folder, ) - - @staticmethod - def parse_common_folder_path(path: str) -> Dict[str,str]: - """Parse a folder path into its component segments.""" - m = re.match(r"^folders/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_organization_path(organization: str, ) -> str: - """Returns a fully-qualified organization string.""" - return "organizations/{organization}".format(organization=organization, ) - - @staticmethod - def parse_common_organization_path(path: str) -> Dict[str,str]: - """Parse a organization path into its component segments.""" - m = re.match(r"^organizations/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_project_path(project: str, ) -> str: - """Returns a fully-qualified project string.""" - return "projects/{project}".format(project=project, ) - - @staticmethod - def parse_common_project_path(path: str) -> Dict[str,str]: - """Parse a project path into its component segments.""" - m = re.match(r"^projects/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_location_path(project: str, location: str, ) -> str: - """Returns a fully-qualified location string.""" - return "projects/{project}/locations/{location}".format(project=project, location=location, ) - - @staticmethod - def parse_common_location_path(path: str) -> Dict[str,str]: - """Parse a location path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)$", path) - return m.groupdict() if m else {} - - @classmethod - def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[client_options_lib.ClientOptions] = None): - """Return the API endpoint and client cert source for mutual TLS. - - The client cert source is determined in the following order: - (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the - client cert source is None. - (2) if `client_options.client_cert_source` is provided, use the provided one; if the - default client cert source exists, use the default one; otherwise the client cert - source is None. - - The API endpoint is determined in the following order: - (1) if `client_options.api_endpoint` if provided, use the provided one. - (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the - default mTLS endpoint; if the environment variable is "never", use the default API - endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise - use the default API endpoint. - - More details can be found at https://google.aip.dev/auth/4114. - - Args: - client_options (google.api_core.client_options.ClientOptions): Custom options for the - client. Only the `api_endpoint` and `client_cert_source` properties may be used - in this method. - - Returns: - Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the - client cert source to use. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If any errors happen. - """ - if client_options is None: - client_options = client_options_lib.ClientOptions() - use_client_cert = os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false") - use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") - if use_client_cert not in ("true", "false"): - raise ValueError("Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`") - if use_mtls_endpoint not in ("auto", "never", "always"): - raise MutualTLSChannelError("Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`") - - # Figure out the client cert source to use. - client_cert_source = None - if use_client_cert == "true": - if client_options.client_cert_source: - client_cert_source = client_options.client_cert_source - elif mtls.has_default_client_cert_source(): - client_cert_source = mtls.default_client_cert_source() - - # Figure out which api endpoint to use. - if client_options.api_endpoint is not None: - api_endpoint = client_options.api_endpoint - elif use_mtls_endpoint == "always" or (use_mtls_endpoint == "auto" and client_cert_source): - api_endpoint = cls.DEFAULT_MTLS_ENDPOINT - else: - api_endpoint = cls.DEFAULT_ENDPOINT - - return api_endpoint, client_cert_source - - def __init__(self, *, - credentials: Optional[ga_credentials.Credentials] = None, - transport: Optional[Union[str, ParticipantsTransport]] = None, - client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the participants 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, ParticipantsTransport]): The - transport to use. If set to None, a transport is chosen - automatically. - client_options (Optional[Union[google.api_core.client_options.ClientOptions, dict]]): 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() - client_options = cast(client_options_lib.ClientOptions, client_options) - - api_endpoint, client_cert_source_func = self.get_mtls_endpoint_and_cert_source(client_options) - - api_key_value = getattr(client_options, "api_key", None) - if api_key_value and credentials: - raise ValueError("client_options.api_key and credentials are mutually exclusive") - - # 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, ParticipantsTransport): - # transport is a ParticipantsTransport instance. - if credentials or client_options.credentials_file or api_key_value: - 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: - import google.auth._default # type: ignore - - if api_key_value and hasattr(google.auth._default, "get_api_key_credentials"): - credentials = google.auth._default.get_api_key_credentials(api_key_value) - - Transport = type(self).get_transport_class(transport) - self._transport = Transport( - credentials=credentials, - credentials_file=client_options.credentials_file, - host=api_endpoint, - scopes=client_options.scopes, - client_cert_source_for_mtls=client_cert_source_func, - quota_project_id=client_options.quota_project_id, - client_info=client_info, - always_use_jwt_access=True, - api_audience=client_options.api_audience, - ) - - def create_participant(self, - request: Optional[Union[gcd_participant.CreateParticipantRequest, dict]] = None, - *, - parent: Optional[str] = None, - participant: Optional[gcd_participant.Participant] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gcd_participant.Participant: - r"""Creates a new participant in a conversation. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import dialogflow_v2beta1 - - def sample_create_participant(): - # Create a client - client = dialogflow_v2beta1.ParticipantsClient() - - # Initialize request argument(s) - request = dialogflow_v2beta1.CreateParticipantRequest( - parent="parent_value", - ) - - # Make the request - response = client.create_participant(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.dialogflow_v2beta1.types.CreateParticipantRequest, dict]): - The request object. The request message for - [Participants.CreateParticipant][google.cloud.dialogflow.v2beta1.Participants.CreateParticipant]. - parent (str): - Required. Resource identifier of the conversation adding - the participant. Format: - ``projects//locations//conversations/``. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - participant (google.cloud.dialogflow_v2beta1.types.Participant): - Required. The participant to create. - 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. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.dialogflow_v2beta1.types.Participant: - Represents a conversation participant - (human agent, virtual agent, end-user). - - """ - # Create or coerce a protobuf request object. - # Quick 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, participant]) - 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_participant.CreateParticipantRequest. - # There's no risk of modifying the input as we've already verified - # 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: - request.participant = participant - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.create_participant] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def get_participant(self, - request: Optional[Union[participant.GetParticipantRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> participant.Participant: - r"""Retrieves a conversation participant. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import dialogflow_v2beta1 - - def sample_get_participant(): - # Create a client - client = dialogflow_v2beta1.ParticipantsClient() - - # Initialize request argument(s) - request = dialogflow_v2beta1.GetParticipantRequest( - name="name_value", - ) - - # Make the request - response = client.get_participant(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.dialogflow_v2beta1.types.GetParticipantRequest, dict]): - The request object. The request message for - [Participants.GetParticipant][google.cloud.dialogflow.v2beta1.Participants.GetParticipant]. - name (str): - Required. The name of the participant. Format: - ``projects//locations//conversations//participants/``. - - 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.Participant: - Represents a conversation participant - (human agent, virtual agent, end-user). - - """ - # Create or coerce a protobuf request object. - # Quick 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 participant.GetParticipantRequest. - # There's no risk of modifying the input as we've already verified - # 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 - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.get_participant] - - # 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 list_participants(self, - request: Optional[Union[participant.ListParticipantsRequest, dict]] = None, - *, - parent: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListParticipantsPager: - r"""Returns the list of all participants in the specified - conversation. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import dialogflow_v2beta1 - - def sample_list_participants(): - # Create a client - client = dialogflow_v2beta1.ParticipantsClient() - - # Initialize request argument(s) - request = dialogflow_v2beta1.ListParticipantsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_participants(request=request) - - # Handle the response - for response in page_result: - print(response) - - Args: - request (Union[google.cloud.dialogflow_v2beta1.types.ListParticipantsRequest, dict]): - The request object. The request message for - [Participants.ListParticipants][google.cloud.dialogflow.v2beta1.Participants.ListParticipants]. - parent (str): - Required. The conversation to list all participants - from. Format: - ``projects//locations//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. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.dialogflow_v2beta1.services.participants.pagers.ListParticipantsPager: - The response message for - [Participants.ListParticipants][google.cloud.dialogflow.v2beta1.Participants.ListParticipants]. - - Iterating over this object will yield results and - resolve additional pages automatically. - - """ - # Create or coerce a protobuf request object. - # Quick 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 participant.ListParticipantsRequest. - # There's no risk of modifying the input as we've already verified - # 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 - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.list_participants] - - # 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.ListParticipantsPager( - method=rpc, - request=request, - response=response, - metadata=metadata, - ) - - # Done; return the response. - return response - - def update_participant(self, - request: Optional[Union[gcd_participant.UpdateParticipantRequest, dict]] = None, - *, - participant: Optional[gcd_participant.Participant] = None, - update_mask: Optional[field_mask_pb2.FieldMask] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gcd_participant.Participant: - r"""Updates the specified participant. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import dialogflow_v2beta1 - - def sample_update_participant(): - # Create a client - client = dialogflow_v2beta1.ParticipantsClient() - - # Initialize request argument(s) - request = dialogflow_v2beta1.UpdateParticipantRequest( - ) - - # Make the request - response = client.update_participant(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.dialogflow_v2beta1.types.UpdateParticipantRequest, dict]): - The request object. The request message for - [Participants.UpdateParticipant][google.cloud.dialogflow.v2beta1.Participants.UpdateParticipant]. - participant (google.cloud.dialogflow_v2beta1.types.Participant): - Required. The participant to update. - This corresponds to the ``participant`` 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 specify which - fields to update. - - 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.Participant: - Represents a conversation participant - (human agent, virtual agent, end-user). - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([participant, 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_participant.UpdateParticipantRequest. - # There's no risk of modifying the input as we've already verified - # 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: - 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_participant] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("participant.name", request.participant.name), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def analyze_content(self, - request: Optional[Union[gcd_participant.AnalyzeContentRequest, dict]] = None, - *, - participant: Optional[str] = None, - text_input: Optional[session.TextInput] = None, - audio_input: Optional[gcd_participant.AudioInput] = None, - event_input: Optional[session.EventInput] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gcd_participant.AnalyzeContentResponse: - r"""Adds a text (chat, for example), or audio (phone recording, for - example) message from a participant into the conversation. - - Note: Always use agent versions for production traffic sent to - virtual agents. See `Versions and - environments `__. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import dialogflow_v2beta1 - - def sample_analyze_content(): - # Create a client - client = dialogflow_v2beta1.ParticipantsClient() - - # Initialize request argument(s) - request = dialogflow_v2beta1.AnalyzeContentRequest( - participant="participant_value", - ) - - # Make the request - response = client.analyze_content(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.dialogflow_v2beta1.types.AnalyzeContentRequest, dict]): - The request object. The request message for - [Participants.AnalyzeContent][google.cloud.dialogflow.v2beta1.Participants.AnalyzeContent]. - participant (str): - Required. The name of the participant this text comes - from. Format: - ``projects//locations//conversations//participants/``. - - This corresponds to the ``participant`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - text_input (google.cloud.dialogflow_v2beta1.types.TextInput): - The natural language text to be - processed. - - This corresponds to the ``text_input`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - audio_input (google.cloud.dialogflow_v2beta1.types.AudioInput): - The natural language speech audio to - be processed. - - This corresponds to the ``audio_input`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - event_input (google.cloud.dialogflow_v2beta1.types.EventInput): - An input event to send to Dialogflow. - 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. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.dialogflow_v2beta1.types.AnalyzeContentResponse: - The response message for - [Participants.AnalyzeContent][google.cloud.dialogflow.v2beta1.Participants.AnalyzeContent]. - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([participant, text_input, audio_input, event_input]) - 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_participant.AnalyzeContentRequest. - # There's no risk of modifying the input as we've already verified - # 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: - request.text_input = text_input - if audio_input is not None: - request.audio_input = audio_input - if event_input is not None: - request.event_input = event_input - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.analyze_content] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("participant", request.participant), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def streaming_analyze_content(self, - requests: Optional[Iterator[participant.StreamingAnalyzeContentRequest]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> Iterable[participant.StreamingAnalyzeContentResponse]: - r"""Adds a text (e.g., chat) or audio (e.g., phone recording) - message from a participant into the conversation. Note: This - method is only available through the gRPC API (not REST). - - The top-level message sent to the client by the server is - ``StreamingAnalyzeContentResponse``. Multiple response messages - can be returned in order. The first one or more messages contain - the ``recognition_result`` field. Each result represents a more - complete transcript of what the user said. The next message - contains the ``reply_text`` field, and potentially the - ``reply_audio`` and/or the ``automated_agent_reply`` fields. - - Note: Always use agent versions for production traffic sent to - virtual agents. See `Versions and - environments `__. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import dialogflow_v2beta1 - - def sample_streaming_analyze_content(): - # Create a client - client = dialogflow_v2beta1.ParticipantsClient() - - # Initialize request argument(s) - request = dialogflow_v2beta1.StreamingAnalyzeContentRequest( - input_audio=b'input_audio_blob', - participant="participant_value", - ) - - # This method expects an iterator which contains - # 'dialogflow_v2beta1.StreamingAnalyzeContentRequest' objects - # Here we create a generator that yields a single `request` for - # demonstrative purposes. - requests = [request] - - def request_generator(): - for request in requests: - yield request - - # Make the request - stream = client.streaming_analyze_content(requests=request_generator()) - - # Handle the response - for response in stream: - print(response) - - Args: - requests (Iterator[google.cloud.dialogflow_v2beta1.types.StreamingAnalyzeContentRequest]): - The request object iterator. The top-level message sent by the client to the - [Participants.StreamingAnalyzeContent][google.cloud.dialogflow.v2beta1.Participants.StreamingAnalyzeContent] - method. - - Multiple request messages should be sent in order: - - 1. The first message must contain - [participant][google.cloud.dialogflow.v2beta1.StreamingAnalyzeContentRequest.participant], - [config][google.cloud.dialogflow.v2beta1.StreamingAnalyzeContentRequest.config] - and optionally - [query_params][google.cloud.dialogflow.v2beta1.StreamingAnalyzeContentRequest.query_params]. - If you want to receive an audio response, it should - also contain - [reply_audio_config][google.cloud.dialogflow.v2beta1.StreamingAnalyzeContentRequest.reply_audio_config]. - The message must not contain - [input][google.cloud.dialogflow.v2beta1.StreamingAnalyzeContentRequest.input]. - - 2. If - [config][google.cloud.dialogflow.v2beta1.StreamingAnalyzeContentRequest.config] - in the first message was set to - [audio_config][google.cloud.dialogflow.v2beta1.StreamingAnalyzeContentRequest.audio_config], - all subsequent messages must contain - [input_audio][google.cloud.dialogflow.v2beta1.StreamingAnalyzeContentRequest.input_audio] - to continue with Speech recognition. If you decide to - rather analyze text input after you already started - Speech recognition, please send a message with - [StreamingAnalyzeContentRequest.input_text][google.cloud.dialogflow.v2beta1.StreamingAnalyzeContentRequest.input_text]. - - However, note that: - - - Dialogflow will bill you for the audio so far. - - Dialogflow discards all Speech recognition results - in favor of the text input. - - 3. If - [StreamingAnalyzeContentRequest.config][google.cloud.dialogflow.v2beta1.StreamingAnalyzeContentRequest.config] - in the first message was set to - [StreamingAnalyzeContentRequest.text_config][google.cloud.dialogflow.v2beta1.StreamingAnalyzeContentRequest.text_config], - then the second message must contain only - [input_text][google.cloud.dialogflow.v2beta1.StreamingAnalyzeContentRequest.input_text]. - Moreover, you must not send more than two messages. - - After you sent all input, you must half-close or abort - the request stream. - 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: - Iterable[google.cloud.dialogflow_v2beta1.types.StreamingAnalyzeContentResponse]: - The top-level message returned from the - StreamingAnalyzeContent method. - - Multiple response messages can be returned in order: - - 1. If the input was set to streaming audio, the first - one or more messages contain recognition_result. - Each recognition_result represents a more complete - transcript of what the user said. The last - recognition_result has is_final set to true. - 2. In virtual agent stage: if - enable_partial_automated_agent_reply is true, the - following N (currently 1 <= N <= 4) messages - contain automated_agent_reply and optionally - reply_audio returned by the virtual agent. The - first (N-1) automated_agent_replys will have - automated_agent_reply_type set to PARTIAL. The - last automated_agent_reply has - automated_agent_reply_type set to FINAL. If - enable_partial_automated_agent_reply is not - enabled, response stream only contains the final - reply. - - In human assist stage: the following N (N >= 1) - messages contain human_agent_suggestion_results, - end_user_suggestion_results or message. - - """ - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.streaming_analyze_content] - - # Send the request. - response = rpc( - requests, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def suggest_articles(self, - request: Optional[Union[participant.SuggestArticlesRequest, dict]] = None, - *, - parent: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> participant.SuggestArticlesResponse: - r"""Gets suggested articles for a participant based on specific - historical messages. - - Note that - [ListSuggestions][google.cloud.dialogflow.v2beta1.Participants.ListSuggestions] - will only list the auto-generated suggestions, while - [CompileSuggestion][google.cloud.dialogflow.v2beta1.Participants.CompileSuggestion] - will try to compile suggestion based on the provided - conversation context in the real time. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import dialogflow_v2beta1 - - def sample_suggest_articles(): - # Create a client - client = dialogflow_v2beta1.ParticipantsClient() - - # Initialize request argument(s) - request = dialogflow_v2beta1.SuggestArticlesRequest( - parent="parent_value", - ) - - # Make the request - response = client.suggest_articles(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.dialogflow_v2beta1.types.SuggestArticlesRequest, dict]): - The request object. The request message for - [Participants.SuggestArticles][google.cloud.dialogflow.v2beta1.Participants.SuggestArticles]. - parent (str): - Required. The name of the participant to fetch - suggestion for. Format: - ``projects//locations//conversations//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. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.dialogflow_v2beta1.types.SuggestArticlesResponse: - The response message for - [Participants.SuggestArticles][google.cloud.dialogflow.v2beta1.Participants.SuggestArticles]. - - """ - # Create or coerce a protobuf request object. - # Quick 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 participant.SuggestArticlesRequest. - # There's no risk of modifying the input as we've already verified - # 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 - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.suggest_articles] - - # 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 suggest_faq_answers(self, - request: Optional[Union[participant.SuggestFaqAnswersRequest, dict]] = None, - *, - parent: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> participant.SuggestFaqAnswersResponse: - r"""Gets suggested faq answers for a participant based on - specific historical messages. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import dialogflow_v2beta1 - - def sample_suggest_faq_answers(): - # Create a client - client = dialogflow_v2beta1.ParticipantsClient() - - # Initialize request argument(s) - request = dialogflow_v2beta1.SuggestFaqAnswersRequest( - parent="parent_value", - ) - - # Make the request - response = client.suggest_faq_answers(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.dialogflow_v2beta1.types.SuggestFaqAnswersRequest, dict]): - The request object. The request message for - [Participants.SuggestFaqAnswers][google.cloud.dialogflow.v2beta1.Participants.SuggestFaqAnswers]. - parent (str): - Required. The name of the participant to fetch - suggestion for. Format: - ``projects//locations//conversations//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. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.dialogflow_v2beta1.types.SuggestFaqAnswersResponse: - The request message for - [Participants.SuggestFaqAnswers][google.cloud.dialogflow.v2beta1.Participants.SuggestFaqAnswers]. - - """ - # Create or coerce a protobuf request object. - # Quick 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 participant.SuggestFaqAnswersRequest. - # There's no risk of modifying the input as we've already verified - # 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 - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.suggest_faq_answers] - - # 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 suggest_smart_replies(self, - request: Optional[Union[participant.SuggestSmartRepliesRequest, dict]] = None, - *, - parent: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> participant.SuggestSmartRepliesResponse: - r"""Gets smart replies for a participant based on - specific historical messages. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import dialogflow_v2beta1 - - def sample_suggest_smart_replies(): - # Create a client - client = dialogflow_v2beta1.ParticipantsClient() - - # Initialize request argument(s) - request = dialogflow_v2beta1.SuggestSmartRepliesRequest( - parent="parent_value", - ) - - # Make the request - response = client.suggest_smart_replies(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.dialogflow_v2beta1.types.SuggestSmartRepliesRequest, dict]): - The request object. The request message for - [Participants.SuggestSmartReplies][google.cloud.dialogflow.v2beta1.Participants.SuggestSmartReplies]. - parent (str): - Required. The name of the participant to fetch - suggestion for. Format: - ``projects//locations//conversations//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. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.dialogflow_v2beta1.types.SuggestSmartRepliesResponse: - The response message for - [Participants.SuggestSmartReplies][google.cloud.dialogflow.v2beta1.Participants.SuggestSmartReplies]. - - """ - # Create or coerce a protobuf request object. - # Quick 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 participant.SuggestSmartRepliesRequest. - # There's no risk of modifying the input as we've already verified - # 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 - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.suggest_smart_replies] - - # 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 list_suggestions(self, - request: Optional[Union[participant.ListSuggestionsRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListSuggestionsPager: - r"""Deprecated: Use inline suggestion, event based suggestion or - Suggestion\* API instead. See - [HumanAgentAssistantConfig.name][google.cloud.dialogflow.v2beta1.HumanAgentAssistantConfig.name] - for more details. Removal Date: 2020-09-01. - - Retrieves suggestions for live agents. - - This method should be used by human agent client software to - 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 `__ - 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 - descending order. To fetch latest suggestion, just set - ``page_size`` to 1. To fetch new suggestions without - duplication, send request with filter - ``create_time_epoch_microseconds > [first item's create_time of previous request]`` - and empty page_token. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import dialogflow_v2beta1 - - def sample_list_suggestions(): - # Create a client - client = dialogflow_v2beta1.ParticipantsClient() - - # Initialize request argument(s) - request = dialogflow_v2beta1.ListSuggestionsRequest( - ) - - # Make the request - page_result = client.list_suggestions(request=request) - - # Handle the response - for response in page_result: - print(response) - - Args: - request (Union[google.cloud.dialogflow_v2beta1.types.ListSuggestionsRequest, dict]): - 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. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.dialogflow_v2beta1.services.participants.pagers.ListSuggestionsPager: - The response message for - [Participants.ListSuggestions][google.cloud.dialogflow.v2beta1.Participants.ListSuggestions]. - - Iterating over this object will yield results and - resolve additional pages automatically. - - """ - warnings.warn("ParticipantsClient.list_suggestions is deprecated", - DeprecationWarning) - - # 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 - # there are no flattened fields. - if not isinstance(request, participant.ListSuggestionsRequest): - request = participant.ListSuggestionsRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.list_suggestions] - - # 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.ListSuggestionsPager( - method=rpc, - request=request, - response=response, - metadata=metadata, - ) - - # Done; return the response. - return response - - def compile_suggestion(self, - request: Optional[Union[participant.CompileSuggestionRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> participant.CompileSuggestionResponse: - r"""Deprecated. use - [SuggestArticles][google.cloud.dialogflow.v2beta1.Participants.SuggestArticles] - and - [SuggestFaqAnswers][google.cloud.dialogflow.v2beta1.Participants.SuggestFaqAnswers] - instead. - - Gets suggestions for a participant based on specific historical - messages. - - Note that - [ListSuggestions][google.cloud.dialogflow.v2beta1.Participants.ListSuggestions] - will only list the auto-generated suggestions, while - [CompileSuggestion][google.cloud.dialogflow.v2beta1.Participants.CompileSuggestion] - will try to compile suggestion based on the provided - conversation context in the real time. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import dialogflow_v2beta1 - - def sample_compile_suggestion(): - # Create a client - client = dialogflow_v2beta1.ParticipantsClient() - - # Initialize request argument(s) - request = dialogflow_v2beta1.CompileSuggestionRequest( - ) - - # Make the request - response = client.compile_suggestion(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.dialogflow_v2beta1.types.CompileSuggestionRequest, dict]): - 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. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.dialogflow_v2beta1.types.CompileSuggestionResponse: - The response message for - [Participants.CompileSuggestion][google.cloud.dialogflow.v2beta1.Participants.CompileSuggestion]. - - """ - warnings.warn("ParticipantsClient.compile_suggestion is deprecated", - DeprecationWarning) - - # 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 - # there are no flattened fields. - if not isinstance(request, participant.CompileSuggestionRequest): - request = participant.CompileSuggestionRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.compile_suggestion] - - # 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 __enter__(self) -> "ParticipantsClient": - return self - - def __exit__(self, type, value, traceback): - """Releases underlying transport's resources. - - .. warning:: - ONLY use as a context manager if the transport is NOT shared - with other clients! Exiting the with block will CLOSE the transport - and may cause errors in other clients! - """ - self.transport.close() - - def list_operations( - self, - request: Optional[operations_pb2.ListOperationsRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operations_pb2.ListOperationsResponse: - r"""Lists operations that match the specified filter in the request. - - Args: - request (:class:`~.operations_pb2.ListOperationsRequest`): - The request object. Request message for - `ListOperations` method. - 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: - ~.operations_pb2.ListOperationsResponse: - Response message for ``ListOperations`` method. - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = operations_pb2.ListOperationsRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._transport.list_operations, - 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 = rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - def get_operation( - self, - request: Optional[operations_pb2.GetOperationRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operations_pb2.Operation: - r"""Gets the latest state of a long-running operation. - - Args: - request (:class:`~.operations_pb2.GetOperationRequest`): - The request object. Request message for - `GetOperation` method. - 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: - ~.operations_pb2.Operation: - An ``Operation`` object. - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = operations_pb2.GetOperationRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._transport.get_operation, - 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 = rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - def cancel_operation( - self, - request: Optional[operations_pb2.CancelOperationRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> None: - r"""Starts asynchronous cancellation on a long-running operation. - - The server makes a best effort to cancel the operation, but success - is not guaranteed. If the server doesn't support this method, it returns - `google.rpc.Code.UNIMPLEMENTED`. - - Args: - request (:class:`~.operations_pb2.CancelOperationRequest`): - The request object. Request message for - `CancelOperation` method. - 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: - None - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = operations_pb2.CancelOperationRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._transport.cancel_operation, - 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. - rpc(request, retry=retry, timeout=timeout, metadata=metadata,) - - def get_location( - self, - request: Optional[locations_pb2.GetLocationRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> locations_pb2.Location: - r"""Gets information about a location. - - Args: - request (:class:`~.location_pb2.GetLocationRequest`): - The request object. Request message for - `GetLocation` method. - 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: - ~.location_pb2.Location: - Location object. - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = locations_pb2.GetLocationRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._transport.get_location, - 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 = rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - def list_locations( - self, - request: Optional[locations_pb2.ListLocationsRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> locations_pb2.ListLocationsResponse: - r"""Lists information about the supported locations for this service. - - Args: - request (:class:`~.location_pb2.ListLocationsRequest`): - The request object. Request message for - `ListLocations` method. - 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: - ~.location_pb2.ListLocationsResponse: - Response message for ``ListLocations`` method. - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = locations_pb2.ListLocationsRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._transport.list_locations, - 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 = rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) - - -__all__ = ( - "ParticipantsClient", -) diff --git a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/participants/pagers.py b/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/participants/pagers.py deleted file mode 100644 index 84b52149f..000000000 --- a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/participants/pagers.py +++ /dev/null @@ -1,260 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from typing import Any, AsyncIterator, Awaitable, Callable, Sequence, Tuple, Optional, Iterator - -from google.cloud.dialogflow_v2beta1.types import participant - - -class ListParticipantsPager: - """A pager for iterating through ``list_participants`` requests. - - This class thinly wraps an initial - :class:`google.cloud.dialogflow_v2beta1.types.ListParticipantsResponse` object, and - provides an ``__iter__`` method to iterate through its - ``participants`` field. - - If there are more pages, the ``__iter__`` method will make additional - ``ListParticipants`` requests and continue to iterate - through the ``participants`` field on the - corresponding responses. - - All the usual :class:`google.cloud.dialogflow_v2beta1.types.ListParticipantsResponse` - 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[..., participant.ListParticipantsResponse], - request: participant.ListParticipantsRequest, - response: participant.ListParticipantsResponse, - *, - 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.ListParticipantsRequest): - The initial request object. - response (google.cloud.dialogflow_v2beta1.types.ListParticipantsResponse): - 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 = participant.ListParticipantsRequest(request) - self._response = response - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - def pages(self) -> Iterator[participant.ListParticipantsResponse]: - yield self._response - while self._response.next_page_token: - self._request.page_token = self._response.next_page_token - self._response = self._method(self._request, metadata=self._metadata) - yield self._response - - def __iter__(self) -> Iterator[participant.Participant]: - for page in self.pages: - yield from page.participants - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListParticipantsAsyncPager: - """A pager for iterating through ``list_participants`` requests. - - This class thinly wraps an initial - :class:`google.cloud.dialogflow_v2beta1.types.ListParticipantsResponse` object, and - provides an ``__aiter__`` method to iterate through its - ``participants`` field. - - If there are more pages, the ``__aiter__`` method will make additional - ``ListParticipants`` requests and continue to iterate - through the ``participants`` field on the - corresponding responses. - - All the usual :class:`google.cloud.dialogflow_v2beta1.types.ListParticipantsResponse` - 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[participant.ListParticipantsResponse]], - request: participant.ListParticipantsRequest, - response: participant.ListParticipantsResponse, - *, - metadata: Sequence[Tuple[str, str]] = ()): - """Instantiates the pager. - - Args: - method (Callable): The method that was originally called, and - which instantiated this pager. - request (google.cloud.dialogflow_v2beta1.types.ListParticipantsRequest): - The initial request object. - response (google.cloud.dialogflow_v2beta1.types.ListParticipantsResponse): - 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 = participant.ListParticipantsRequest(request) - self._response = response - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - async def pages(self) -> AsyncIterator[participant.ListParticipantsResponse]: - yield self._response - while self._response.next_page_token: - self._request.page_token = self._response.next_page_token - self._response = await self._method(self._request, metadata=self._metadata) - yield self._response - def __aiter__(self) -> AsyncIterator[participant.Participant]: - async def async_generator(): - async for page in self.pages: - for response in page.participants: - yield response - - return async_generator() - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListSuggestionsPager: - """A pager for iterating through ``list_suggestions`` requests. - - This class thinly wraps an initial - :class:`google.cloud.dialogflow_v2beta1.types.ListSuggestionsResponse` object, and - provides an ``__iter__`` method to iterate through its - ``suggestions`` field. - - If there are more pages, the ``__iter__`` method will make additional - ``ListSuggestions`` requests and continue to iterate - through the ``suggestions`` field on the - corresponding responses. - - All the usual :class:`google.cloud.dialogflow_v2beta1.types.ListSuggestionsResponse` - 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[..., participant.ListSuggestionsResponse], - request: participant.ListSuggestionsRequest, - response: participant.ListSuggestionsResponse, - *, - 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.ListSuggestionsRequest): - The initial request object. - response (google.cloud.dialogflow_v2beta1.types.ListSuggestionsResponse): - 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 = participant.ListSuggestionsRequest(request) - self._response = response - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - def pages(self) -> Iterator[participant.ListSuggestionsResponse]: - yield self._response - while self._response.next_page_token: - self._request.page_token = self._response.next_page_token - self._response = self._method(self._request, metadata=self._metadata) - yield self._response - - def __iter__(self) -> Iterator[participant.Suggestion]: - for page in self.pages: - yield from page.suggestions - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListSuggestionsAsyncPager: - """A pager for iterating through ``list_suggestions`` requests. - - This class thinly wraps an initial - :class:`google.cloud.dialogflow_v2beta1.types.ListSuggestionsResponse` object, and - provides an ``__aiter__`` method to iterate through its - ``suggestions`` field. - - If there are more pages, the ``__aiter__`` method will make additional - ``ListSuggestions`` requests and continue to iterate - through the ``suggestions`` field on the - corresponding responses. - - All the usual :class:`google.cloud.dialogflow_v2beta1.types.ListSuggestionsResponse` - 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[participant.ListSuggestionsResponse]], - request: participant.ListSuggestionsRequest, - response: participant.ListSuggestionsResponse, - *, - metadata: Sequence[Tuple[str, str]] = ()): - """Instantiates the pager. - - Args: - method (Callable): The method that was originally called, and - which instantiated this pager. - request (google.cloud.dialogflow_v2beta1.types.ListSuggestionsRequest): - The initial request object. - response (google.cloud.dialogflow_v2beta1.types.ListSuggestionsResponse): - 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 = participant.ListSuggestionsRequest(request) - self._response = response - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - async def pages(self) -> AsyncIterator[participant.ListSuggestionsResponse]: - yield self._response - while self._response.next_page_token: - self._request.page_token = self._response.next_page_token - self._response = await self._method(self._request, metadata=self._metadata) - yield self._response - def __aiter__(self) -> AsyncIterator[participant.Suggestion]: - async def async_generator(): - async for page in self.pages: - for response in page.suggestions: - yield response - - return async_generator() - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) diff --git a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/participants/transports/__init__.py b/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/participants/transports/__init__.py deleted file mode 100644 index 7fedc8d5d..000000000 --- a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/participants/transports/__init__.py +++ /dev/null @@ -1,38 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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 ParticipantsTransport -from .grpc import ParticipantsGrpcTransport -from .grpc_asyncio import ParticipantsGrpcAsyncIOTransport -from .rest import ParticipantsRestTransport -from .rest import ParticipantsRestInterceptor - - -# Compile a registry of transports. -_transport_registry = OrderedDict() # type: Dict[str, Type[ParticipantsTransport]] -_transport_registry['grpc'] = ParticipantsGrpcTransport -_transport_registry['grpc_asyncio'] = ParticipantsGrpcAsyncIOTransport -_transport_registry['rest'] = ParticipantsRestTransport - -__all__ = ( - 'ParticipantsTransport', - 'ParticipantsGrpcTransport', - 'ParticipantsGrpcAsyncIOTransport', - 'ParticipantsRestTransport', - 'ParticipantsRestInterceptor', -) diff --git a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/participants/transports/base.py b/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/participants/transports/base.py deleted file mode 100644 index 684d4bb2a..000000000 --- a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/participants/transports/base.py +++ /dev/null @@ -1,341 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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 - -from google.cloud.dialogflow_v2beta1 import gapic_version as package_version - -import google.auth # type: ignore -import google.api_core -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import retry as retries -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 participant -from google.cloud.dialogflow_v2beta1.types import participant as gcd_participant -from google.cloud.location import locations_pb2 # type: ignore -from google.longrunning import operations_pb2 - -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) - - -class ParticipantsTransport(abc.ABC): - """Abstract transport class for Participants.""" - - 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: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - api_audience: Optional[str] = None, - **kwargs, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. - scopes (Optional[Sequence[str]]): A list of scopes. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - """ - - scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} - - # Save the scopes. - self._scopes = scopes - - # If no credentials are provided, then determine the appropriate - # defaults. - if credentials and credentials_file: - raise core_exceptions.DuplicateCredentialArgs("'credentials_file' and 'credentials' are mutually exclusive") - - if credentials_file is not None: - credentials, _ = google.auth.load_credentials_from_file( - credentials_file, - **scopes_kwargs, - quota_project_id=quota_project_id - ) - elif credentials is None: - credentials, _ = google.auth.default(**scopes_kwargs, quota_project_id=quota_project_id) - # Don't apply audience if the credentials file passed from user. - if hasattr(credentials, "with_gdch_audience"): - credentials = credentials.with_gdch_audience(api_audience if api_audience else host) - - # If the credentials are service account credentials, then always try to use self signed JWT. - if always_use_jwt_access and isinstance(credentials, service_account.Credentials) and hasattr(service_account.Credentials, "with_always_use_jwt_access"): - credentials = credentials.with_always_use_jwt_access(True) - - # Save the credentials. - self._credentials = credentials - - # Save the hostname. Default to port 443 (HTTPS) if none is specified. - if ':' not in host: - host += ':443' - self._host = host - - def _prep_wrapped_messages(self, client_info): - # Precompute the wrapped methods. - self._wrapped_methods = { - self.create_participant: gapic_v1.method.wrap_method( - self.create_participant, - default_timeout=None, - client_info=client_info, - ), - self.get_participant: gapic_v1.method.wrap_method( - self.get_participant, - default_timeout=None, - client_info=client_info, - ), - self.list_participants: gapic_v1.method.wrap_method( - self.list_participants, - default_timeout=None, - client_info=client_info, - ), - self.update_participant: gapic_v1.method.wrap_method( - self.update_participant, - default_timeout=None, - client_info=client_info, - ), - self.analyze_content: gapic_v1.method.wrap_method( - self.analyze_content, - default_retry=retries.Retry( -initial=0.1,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( - core_exceptions.ServiceUnavailable, - ), - deadline=220.0, - ), - default_timeout=220.0, - client_info=client_info, - ), - self.streaming_analyze_content: gapic_v1.method.wrap_method( - self.streaming_analyze_content, - default_timeout=220.0, - client_info=client_info, - ), - self.suggest_articles: gapic_v1.method.wrap_method( - self.suggest_articles, - default_timeout=None, - client_info=client_info, - ), - self.suggest_faq_answers: gapic_v1.method.wrap_method( - self.suggest_faq_answers, - default_timeout=None, - client_info=client_info, - ), - self.suggest_smart_replies: gapic_v1.method.wrap_method( - self.suggest_smart_replies, - default_timeout=None, - client_info=client_info, - ), - self.list_suggestions: gapic_v1.method.wrap_method( - self.list_suggestions, - default_timeout=None, - client_info=client_info, - ), - self.compile_suggestion: gapic_v1.method.wrap_method( - self.compile_suggestion, - default_timeout=None, - client_info=client_info, - ), - } - - def close(self): - """Closes resources associated with the transport. - - .. warning:: - Only call this method if the transport is NOT shared - with other clients - this may cause errors in other clients! - """ - raise NotImplementedError() - - @property - def create_participant(self) -> Callable[ - [gcd_participant.CreateParticipantRequest], - Union[ - gcd_participant.Participant, - Awaitable[gcd_participant.Participant] - ]]: - raise NotImplementedError() - - @property - def get_participant(self) -> Callable[ - [participant.GetParticipantRequest], - Union[ - participant.Participant, - Awaitable[participant.Participant] - ]]: - raise NotImplementedError() - - @property - def list_participants(self) -> Callable[ - [participant.ListParticipantsRequest], - Union[ - participant.ListParticipantsResponse, - Awaitable[participant.ListParticipantsResponse] - ]]: - raise NotImplementedError() - - @property - def update_participant(self) -> Callable[ - [gcd_participant.UpdateParticipantRequest], - Union[ - gcd_participant.Participant, - Awaitable[gcd_participant.Participant] - ]]: - raise NotImplementedError() - - @property - def analyze_content(self) -> Callable[ - [gcd_participant.AnalyzeContentRequest], - Union[ - gcd_participant.AnalyzeContentResponse, - Awaitable[gcd_participant.AnalyzeContentResponse] - ]]: - raise NotImplementedError() - - @property - def streaming_analyze_content(self) -> Callable[ - [participant.StreamingAnalyzeContentRequest], - Union[ - participant.StreamingAnalyzeContentResponse, - Awaitable[participant.StreamingAnalyzeContentResponse] - ]]: - raise NotImplementedError() - - @property - def suggest_articles(self) -> Callable[ - [participant.SuggestArticlesRequest], - Union[ - participant.SuggestArticlesResponse, - Awaitable[participant.SuggestArticlesResponse] - ]]: - raise NotImplementedError() - - @property - def suggest_faq_answers(self) -> Callable[ - [participant.SuggestFaqAnswersRequest], - Union[ - participant.SuggestFaqAnswersResponse, - Awaitable[participant.SuggestFaqAnswersResponse] - ]]: - raise NotImplementedError() - - @property - def suggest_smart_replies(self) -> Callable[ - [participant.SuggestSmartRepliesRequest], - Union[ - participant.SuggestSmartRepliesResponse, - Awaitable[participant.SuggestSmartRepliesResponse] - ]]: - raise NotImplementedError() - - @property - def list_suggestions(self) -> Callable[ - [participant.ListSuggestionsRequest], - Union[ - participant.ListSuggestionsResponse, - Awaitable[participant.ListSuggestionsResponse] - ]]: - raise NotImplementedError() - - @property - def compile_suggestion(self) -> Callable[ - [participant.CompileSuggestionRequest], - Union[ - participant.CompileSuggestionResponse, - Awaitable[participant.CompileSuggestionResponse] - ]]: - raise NotImplementedError() - - @property - def list_operations( - self, - ) -> Callable[ - [operations_pb2.ListOperationsRequest], - Union[operations_pb2.ListOperationsResponse, Awaitable[operations_pb2.ListOperationsResponse]], - ]: - raise NotImplementedError() - - @property - def get_operation( - self, - ) -> Callable[ - [operations_pb2.GetOperationRequest], - Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], - ]: - raise NotImplementedError() - - @property - def cancel_operation( - self, - ) -> Callable[ - [operations_pb2.CancelOperationRequest], - None, - ]: - raise NotImplementedError() - - @property - def get_location(self, - ) -> Callable[ - [locations_pb2.GetLocationRequest], - Union[locations_pb2.Location, Awaitable[locations_pb2.Location]], - ]: - raise NotImplementedError() - - @property - def list_locations(self, - ) -> Callable[ - [locations_pb2.ListLocationsRequest], - Union[locations_pb2.ListLocationsResponse, Awaitable[locations_pb2.ListLocationsResponse]], - ]: - raise NotImplementedError() - - @property - def kind(self) -> str: - raise NotImplementedError() - - -__all__ = ( - 'ParticipantsTransport', -) diff --git a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/participants/transports/grpc.py b/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/participants/transports/grpc.py deleted file mode 100644 index e5979ff7c..000000000 --- a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/participants/transports/grpc.py +++ /dev/null @@ -1,681 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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 -from google.api_core import gapic_v1 -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 google.cloud.location import locations_pb2 # type: ignore -from google.longrunning import operations_pb2 -from .base import ParticipantsTransport, DEFAULT_CLIENT_INFO - - -class ParticipantsGrpcTransport(ParticipantsTransport): - """gRPC backend transport for Participants. - - Service for managing - [Participants][google.cloud.dialogflow.v2beta1.Participant]. - - 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: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - channel: Optional[grpc.Channel] = None, - api_mtls_endpoint: Optional[str] = None, - client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, - ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, - client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - api_audience: Optional[str] = None, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - This argument is ignored if ``channel`` is provided. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional(Sequence[str])): A list of scopes. This argument is - ignored if ``channel`` is provided. - channel (Optional[grpc.Channel]): A ``Channel`` instance through - which to make calls. - api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. - If provided, it overrides the ``host`` argument and tries to create - a mutual TLS channel with client SSL credentials from - ``client_cert_source`` or application default SSL credentials. - client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): - Deprecated. A callback to provide client SSL certificate bytes and - private key bytes, both in PEM format. It is ignored if - ``api_mtls_endpoint`` is None. - ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials - for the grpc channel. It is ignored if ``channel`` is provided. - client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): - A callback to provide client certificate bytes and private key bytes, - both in PEM format. It is used to configure a mutual TLS channel. It is - ignored if ``channel`` or ``ssl_channel_credentials`` is provided. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport - creation failed for any reason. - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - self._grpc_channel = None - self._ssl_channel_credentials = ssl_channel_credentials - self._stubs: Dict[str, Callable] = {} - - if api_mtls_endpoint: - warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) - if client_cert_source: - warnings.warn("client_cert_source is deprecated", DeprecationWarning) - - if channel: - # Ignore credentials if a channel was passed. - credentials = False - # If a channel was explicitly provided, set it. - self._grpc_channel = channel - self._ssl_channel_credentials = None - - else: - if api_mtls_endpoint: - host = api_mtls_endpoint - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - self._ssl_channel_credentials = SslCredentials().ssl_credentials - - else: - if client_cert_source_for_mtls and not ssl_channel_credentials: - cert, key = client_cert_source_for_mtls() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - - # The base transport sets the host, credentials and scopes - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes, - quota_project_id=quota_project_id, - client_info=client_info, - always_use_jwt_access=always_use_jwt_access, - api_audience=api_audience, - ) - - if not self._grpc_channel: - self._grpc_channel = type(self).create_channel( - self._host, - # use the credentials which are saved - credentials=self._credentials, - # Set ``credentials_file`` to ``None`` here as - # the credentials that we saved earlier should be used. - credentials_file=None, - 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: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - **kwargs) -> grpc.Channel: - """Create and return a gRPC channel object. - Args: - host (Optional[str]): The host for the channel to use. - credentials (Optional[~.Credentials]): The - authorization credentials to attach to requests. These - credentials identify this application to the service. If - none are specified, the client will attempt to ascertain - the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - kwargs (Optional[dict]): Keyword arguments, which are passed to the - channel creation. - Returns: - grpc.Channel: A gRPC channel object. - - Raises: - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - - return grpc_helpers.create_channel( - host, - credentials=credentials, - credentials_file=credentials_file, - quota_project_id=quota_project_id, - default_scopes=cls.AUTH_SCOPES, - scopes=scopes, - default_host=cls.DEFAULT_HOST, - **kwargs - ) - - @property - def grpc_channel(self) -> grpc.Channel: - """Return the channel designed to connect to this service. - """ - return self._grpc_channel - - @property - def create_participant(self) -> Callable[ - [gcd_participant.CreateParticipantRequest], - gcd_participant.Participant]: - r"""Return a callable for the create participant method over gRPC. - - Creates a new participant in a conversation. - - Returns: - Callable[[~.CreateParticipantRequest], - ~.Participant]: - 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_participant' not in self._stubs: - self._stubs['create_participant'] = self.grpc_channel.unary_unary( - '/google.cloud.dialogflow.v2beta1.Participants/CreateParticipant', - request_serializer=gcd_participant.CreateParticipantRequest.serialize, - response_deserializer=gcd_participant.Participant.deserialize, - ) - return self._stubs['create_participant'] - - @property - def get_participant(self) -> Callable[ - [participant.GetParticipantRequest], - participant.Participant]: - r"""Return a callable for the get participant method over gRPC. - - Retrieves a conversation participant. - - Returns: - Callable[[~.GetParticipantRequest], - ~.Participant]: - 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_participant' not in self._stubs: - self._stubs['get_participant'] = self.grpc_channel.unary_unary( - '/google.cloud.dialogflow.v2beta1.Participants/GetParticipant', - request_serializer=participant.GetParticipantRequest.serialize, - response_deserializer=participant.Participant.deserialize, - ) - return self._stubs['get_participant'] - - @property - def list_participants(self) -> Callable[ - [participant.ListParticipantsRequest], - participant.ListParticipantsResponse]: - r"""Return a callable for the list participants method over gRPC. - - Returns the list of all participants in the specified - conversation. - - Returns: - Callable[[~.ListParticipantsRequest], - ~.ListParticipantsResponse]: - 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_participants' not in self._stubs: - self._stubs['list_participants'] = self.grpc_channel.unary_unary( - '/google.cloud.dialogflow.v2beta1.Participants/ListParticipants', - request_serializer=participant.ListParticipantsRequest.serialize, - response_deserializer=participant.ListParticipantsResponse.deserialize, - ) - return self._stubs['list_participants'] - - @property - def update_participant(self) -> Callable[ - [gcd_participant.UpdateParticipantRequest], - gcd_participant.Participant]: - r"""Return a callable for the update participant method over gRPC. - - Updates the specified participant. - - Returns: - Callable[[~.UpdateParticipantRequest], - ~.Participant]: - 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_participant' not in self._stubs: - self._stubs['update_participant'] = self.grpc_channel.unary_unary( - '/google.cloud.dialogflow.v2beta1.Participants/UpdateParticipant', - request_serializer=gcd_participant.UpdateParticipantRequest.serialize, - response_deserializer=gcd_participant.Participant.deserialize, - ) - return self._stubs['update_participant'] - - @property - def analyze_content(self) -> Callable[ - [gcd_participant.AnalyzeContentRequest], - gcd_participant.AnalyzeContentResponse]: - r"""Return a callable for the analyze content method over gRPC. - - Adds a text (chat, for example), or audio (phone recording, for - example) message from a participant into the conversation. - - Note: Always use agent versions for production traffic sent to - virtual agents. See `Versions and - environments `__. - - Returns: - Callable[[~.AnalyzeContentRequest], - ~.AnalyzeContentResponse]: - 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 'analyze_content' not in self._stubs: - self._stubs['analyze_content'] = self.grpc_channel.unary_unary( - '/google.cloud.dialogflow.v2beta1.Participants/AnalyzeContent', - request_serializer=gcd_participant.AnalyzeContentRequest.serialize, - response_deserializer=gcd_participant.AnalyzeContentResponse.deserialize, - ) - return self._stubs['analyze_content'] - - @property - def streaming_analyze_content(self) -> Callable[ - [participant.StreamingAnalyzeContentRequest], - participant.StreamingAnalyzeContentResponse]: - r"""Return a callable for the streaming analyze content method over gRPC. - - Adds a text (e.g., chat) or audio (e.g., phone recording) - message from a participant into the conversation. Note: This - method is only available through the gRPC API (not REST). - - The top-level message sent to the client by the server is - ``StreamingAnalyzeContentResponse``. Multiple response messages - can be returned in order. The first one or more messages contain - the ``recognition_result`` field. Each result represents a more - complete transcript of what the user said. The next message - contains the ``reply_text`` field, and potentially the - ``reply_audio`` and/or the ``automated_agent_reply`` fields. - - Note: Always use agent versions for production traffic sent to - virtual agents. See `Versions and - environments `__. - - Returns: - Callable[[~.StreamingAnalyzeContentRequest], - ~.StreamingAnalyzeContentResponse]: - 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 'streaming_analyze_content' not in self._stubs: - self._stubs['streaming_analyze_content'] = self.grpc_channel.stream_stream( - '/google.cloud.dialogflow.v2beta1.Participants/StreamingAnalyzeContent', - request_serializer=participant.StreamingAnalyzeContentRequest.serialize, - response_deserializer=participant.StreamingAnalyzeContentResponse.deserialize, - ) - return self._stubs['streaming_analyze_content'] - - @property - def suggest_articles(self) -> Callable[ - [participant.SuggestArticlesRequest], - participant.SuggestArticlesResponse]: - r"""Return a callable for the suggest articles method over gRPC. - - Gets suggested articles for a participant based on specific - historical messages. - - Note that - [ListSuggestions][google.cloud.dialogflow.v2beta1.Participants.ListSuggestions] - will only list the auto-generated suggestions, while - [CompileSuggestion][google.cloud.dialogflow.v2beta1.Participants.CompileSuggestion] - will try to compile suggestion based on the provided - conversation context in the real time. - - Returns: - Callable[[~.SuggestArticlesRequest], - ~.SuggestArticlesResponse]: - 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 'suggest_articles' not in self._stubs: - self._stubs['suggest_articles'] = self.grpc_channel.unary_unary( - '/google.cloud.dialogflow.v2beta1.Participants/SuggestArticles', - request_serializer=participant.SuggestArticlesRequest.serialize, - response_deserializer=participant.SuggestArticlesResponse.deserialize, - ) - return self._stubs['suggest_articles'] - - @property - def suggest_faq_answers(self) -> Callable[ - [participant.SuggestFaqAnswersRequest], - participant.SuggestFaqAnswersResponse]: - r"""Return a callable for the suggest faq answers method over gRPC. - - Gets suggested faq answers for a participant based on - specific historical messages. - - Returns: - Callable[[~.SuggestFaqAnswersRequest], - ~.SuggestFaqAnswersResponse]: - 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 'suggest_faq_answers' not in self._stubs: - self._stubs['suggest_faq_answers'] = self.grpc_channel.unary_unary( - '/google.cloud.dialogflow.v2beta1.Participants/SuggestFaqAnswers', - request_serializer=participant.SuggestFaqAnswersRequest.serialize, - response_deserializer=participant.SuggestFaqAnswersResponse.deserialize, - ) - return self._stubs['suggest_faq_answers'] - - @property - def suggest_smart_replies(self) -> Callable[ - [participant.SuggestSmartRepliesRequest], - participant.SuggestSmartRepliesResponse]: - r"""Return a callable for the suggest smart replies method over gRPC. - - Gets smart replies for a participant based on - specific historical messages. - - Returns: - Callable[[~.SuggestSmartRepliesRequest], - ~.SuggestSmartRepliesResponse]: - 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 'suggest_smart_replies' not in self._stubs: - self._stubs['suggest_smart_replies'] = self.grpc_channel.unary_unary( - '/google.cloud.dialogflow.v2beta1.Participants/SuggestSmartReplies', - request_serializer=participant.SuggestSmartRepliesRequest.serialize, - response_deserializer=participant.SuggestSmartRepliesResponse.deserialize, - ) - return self._stubs['suggest_smart_replies'] - - @property - def list_suggestions(self) -> Callable[ - [participant.ListSuggestionsRequest], - participant.ListSuggestionsResponse]: - r"""Return a callable for the list suggestions method over gRPC. - - Deprecated: Use inline suggestion, event based suggestion or - Suggestion\* API instead. See - [HumanAgentAssistantConfig.name][google.cloud.dialogflow.v2beta1.HumanAgentAssistantConfig.name] - for more details. Removal Date: 2020-09-01. - - Retrieves suggestions for live agents. - - This method should be used by human agent client software to - 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 `__ - 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 - descending order. To fetch latest suggestion, just set - ``page_size`` to 1. To fetch new suggestions without - duplication, send request with filter - ``create_time_epoch_microseconds > [first item's create_time of previous request]`` - and empty page_token. - - Returns: - Callable[[~.ListSuggestionsRequest], - ~.ListSuggestionsResponse]: - 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_suggestions' not in self._stubs: - self._stubs['list_suggestions'] = self.grpc_channel.unary_unary( - '/google.cloud.dialogflow.v2beta1.Participants/ListSuggestions', - request_serializer=participant.ListSuggestionsRequest.serialize, - response_deserializer=participant.ListSuggestionsResponse.deserialize, - ) - return self._stubs['list_suggestions'] - - @property - def compile_suggestion(self) -> Callable[ - [participant.CompileSuggestionRequest], - participant.CompileSuggestionResponse]: - r"""Return a callable for the compile suggestion method over gRPC. - - Deprecated. use - [SuggestArticles][google.cloud.dialogflow.v2beta1.Participants.SuggestArticles] - and - [SuggestFaqAnswers][google.cloud.dialogflow.v2beta1.Participants.SuggestFaqAnswers] - instead. - - Gets suggestions for a participant based on specific historical - messages. - - Note that - [ListSuggestions][google.cloud.dialogflow.v2beta1.Participants.ListSuggestions] - will only list the auto-generated suggestions, while - [CompileSuggestion][google.cloud.dialogflow.v2beta1.Participants.CompileSuggestion] - will try to compile suggestion based on the provided - conversation context in the real time. - - Returns: - Callable[[~.CompileSuggestionRequest], - ~.CompileSuggestionResponse]: - 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 'compile_suggestion' not in self._stubs: - self._stubs['compile_suggestion'] = self.grpc_channel.unary_unary( - '/google.cloud.dialogflow.v2beta1.Participants/CompileSuggestion', - request_serializer=participant.CompileSuggestionRequest.serialize, - response_deserializer=participant.CompileSuggestionResponse.deserialize, - ) - return self._stubs['compile_suggestion'] - - def close(self): - self.grpc_channel.close() - - @property - def cancel_operation( - self, - ) -> Callable[[operations_pb2.CancelOperationRequest], None]: - r"""Return a callable for the cancel_operation method over gRPC. - """ - # 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 "cancel_operation" not in self._stubs: - self._stubs["cancel_operation"] = self.grpc_channel.unary_unary( - "/google.longrunning.Operations/CancelOperation", - request_serializer=operations_pb2.CancelOperationRequest.SerializeToString, - response_deserializer=None, - ) - return self._stubs["cancel_operation"] - - @property - def get_operation( - self, - ) -> Callable[[operations_pb2.GetOperationRequest], operations_pb2.Operation]: - r"""Return a callable for the get_operation method over gRPC. - """ - # 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_operation" not in self._stubs: - self._stubs["get_operation"] = self.grpc_channel.unary_unary( - "/google.longrunning.Operations/GetOperation", - request_serializer=operations_pb2.GetOperationRequest.SerializeToString, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs["get_operation"] - - @property - def list_operations( - self, - ) -> Callable[[operations_pb2.ListOperationsRequest], operations_pb2.ListOperationsResponse]: - r"""Return a callable for the list_operations method over gRPC. - """ - # 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_operations" not in self._stubs: - self._stubs["list_operations"] = self.grpc_channel.unary_unary( - "/google.longrunning.Operations/ListOperations", - request_serializer=operations_pb2.ListOperationsRequest.SerializeToString, - response_deserializer=operations_pb2.ListOperationsResponse.FromString, - ) - return self._stubs["list_operations"] - - @property - def list_locations( - self, - ) -> Callable[[locations_pb2.ListLocationsRequest], locations_pb2.ListLocationsResponse]: - r"""Return a callable for the list locations method over gRPC. - """ - # 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_locations" not in self._stubs: - self._stubs["list_locations"] = self.grpc_channel.unary_unary( - "/google.cloud.location.Locations/ListLocations", - request_serializer=locations_pb2.ListLocationsRequest.SerializeToString, - response_deserializer=locations_pb2.ListLocationsResponse.FromString, - ) - return self._stubs["list_locations"] - - @property - def get_location( - self, - ) -> Callable[[locations_pb2.GetLocationRequest], locations_pb2.Location]: - r"""Return a callable for the list locations method over gRPC. - """ - # 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_location" not in self._stubs: - self._stubs["get_location"] = self.grpc_channel.unary_unary( - "/google.cloud.location.Locations/GetLocation", - request_serializer=locations_pb2.GetLocationRequest.SerializeToString, - response_deserializer=locations_pb2.Location.FromString, - ) - return self._stubs["get_location"] - - @property - def kind(self) -> str: - return "grpc" - - -__all__ = ( - 'ParticipantsGrpcTransport', -) diff --git a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/participants/transports/grpc_asyncio.py b/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/participants/transports/grpc_asyncio.py deleted file mode 100644 index c25b26c76..000000000 --- a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/participants/transports/grpc_asyncio.py +++ /dev/null @@ -1,680 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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 -from google.api_core import grpc_helpers_async -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore - -import grpc # type: ignore -from grpc.experimental import aio # type: ignore - -from google.cloud.dialogflow_v2beta1.types import participant -from google.cloud.dialogflow_v2beta1.types import participant as gcd_participant -from google.cloud.location import locations_pb2 # type: ignore -from google.longrunning import operations_pb2 -from .base import ParticipantsTransport, DEFAULT_CLIENT_INFO -from .grpc import ParticipantsGrpcTransport - - -class ParticipantsGrpcAsyncIOTransport(ParticipantsTransport): - """gRPC AsyncIO backend transport for Participants. - - Service for managing - [Participants][google.cloud.dialogflow.v2beta1.Participant]. - - 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: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - **kwargs) -> aio.Channel: - """Create and return a gRPC AsyncIO channel object. - Args: - host (Optional[str]): The host for the channel to use. - credentials (Optional[~.Credentials]): The - authorization credentials to attach to requests. These - credentials identify this application to the service. If - none are specified, the client will attempt to ascertain - the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - kwargs (Optional[dict]): Keyword arguments, which are passed to the - channel creation. - Returns: - aio.Channel: A gRPC AsyncIO channel object. - """ - - return grpc_helpers_async.create_channel( - host, - credentials=credentials, - credentials_file=credentials_file, - quota_project_id=quota_project_id, - default_scopes=cls.AUTH_SCOPES, - scopes=scopes, - default_host=cls.DEFAULT_HOST, - **kwargs - ) - - def __init__(self, *, - host: str = 'dialogflow.googleapis.com', - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - channel: Optional[aio.Channel] = None, - api_mtls_endpoint: Optional[str] = None, - client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, - ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, - client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - api_audience: Optional[str] = None, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - This argument is ignored if ``channel`` is provided. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - channel (Optional[aio.Channel]): A ``Channel`` instance through - which to make calls. - api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. - If provided, it overrides the ``host`` argument and tries to create - a mutual TLS channel with client SSL credentials from - ``client_cert_source`` or application default SSL credentials. - client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): - Deprecated. A callback to provide client SSL certificate bytes and - private key bytes, both in PEM format. It is ignored if - ``api_mtls_endpoint`` is None. - ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials - for the grpc channel. It is ignored if ``channel`` is provided. - client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): - A callback to provide client certificate bytes and private key bytes, - both in PEM format. It is used to configure a mutual TLS channel. It is - ignored if ``channel`` or ``ssl_channel_credentials`` is provided. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - - Raises: - google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport - creation failed for any reason. - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - self._grpc_channel = None - self._ssl_channel_credentials = ssl_channel_credentials - self._stubs: Dict[str, Callable] = {} - - if api_mtls_endpoint: - warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) - if client_cert_source: - warnings.warn("client_cert_source is deprecated", DeprecationWarning) - - if channel: - # Ignore credentials if a channel was passed. - credentials = False - # If a channel was explicitly provided, set it. - self._grpc_channel = channel - self._ssl_channel_credentials = None - else: - if api_mtls_endpoint: - host = api_mtls_endpoint - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - self._ssl_channel_credentials = SslCredentials().ssl_credentials - - else: - if client_cert_source_for_mtls and not ssl_channel_credentials: - cert, key = client_cert_source_for_mtls() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - - # The base transport sets the host, credentials and scopes - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes, - quota_project_id=quota_project_id, - client_info=client_info, - always_use_jwt_access=always_use_jwt_access, - api_audience=api_audience, - ) - - if not self._grpc_channel: - self._grpc_channel = type(self).create_channel( - self._host, - # use the credentials which are saved - credentials=self._credentials, - # Set ``credentials_file`` to ``None`` here as - # the credentials that we saved earlier should be used. - credentials_file=None, - 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 create_participant(self) -> Callable[ - [gcd_participant.CreateParticipantRequest], - Awaitable[gcd_participant.Participant]]: - r"""Return a callable for the create participant method over gRPC. - - Creates a new participant in a conversation. - - Returns: - Callable[[~.CreateParticipantRequest], - Awaitable[~.Participant]]: - 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_participant' not in self._stubs: - self._stubs['create_participant'] = self.grpc_channel.unary_unary( - '/google.cloud.dialogflow.v2beta1.Participants/CreateParticipant', - request_serializer=gcd_participant.CreateParticipantRequest.serialize, - response_deserializer=gcd_participant.Participant.deserialize, - ) - return self._stubs['create_participant'] - - @property - def get_participant(self) -> Callable[ - [participant.GetParticipantRequest], - Awaitable[participant.Participant]]: - r"""Return a callable for the get participant method over gRPC. - - Retrieves a conversation participant. - - Returns: - Callable[[~.GetParticipantRequest], - Awaitable[~.Participant]]: - 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_participant' not in self._stubs: - self._stubs['get_participant'] = self.grpc_channel.unary_unary( - '/google.cloud.dialogflow.v2beta1.Participants/GetParticipant', - request_serializer=participant.GetParticipantRequest.serialize, - response_deserializer=participant.Participant.deserialize, - ) - return self._stubs['get_participant'] - - @property - def list_participants(self) -> Callable[ - [participant.ListParticipantsRequest], - Awaitable[participant.ListParticipantsResponse]]: - r"""Return a callable for the list participants method over gRPC. - - Returns the list of all participants in the specified - conversation. - - Returns: - Callable[[~.ListParticipantsRequest], - Awaitable[~.ListParticipantsResponse]]: - 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_participants' not in self._stubs: - self._stubs['list_participants'] = self.grpc_channel.unary_unary( - '/google.cloud.dialogflow.v2beta1.Participants/ListParticipants', - request_serializer=participant.ListParticipantsRequest.serialize, - response_deserializer=participant.ListParticipantsResponse.deserialize, - ) - return self._stubs['list_participants'] - - @property - def update_participant(self) -> Callable[ - [gcd_participant.UpdateParticipantRequest], - Awaitable[gcd_participant.Participant]]: - r"""Return a callable for the update participant method over gRPC. - - Updates the specified participant. - - Returns: - Callable[[~.UpdateParticipantRequest], - Awaitable[~.Participant]]: - 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_participant' not in self._stubs: - self._stubs['update_participant'] = self.grpc_channel.unary_unary( - '/google.cloud.dialogflow.v2beta1.Participants/UpdateParticipant', - request_serializer=gcd_participant.UpdateParticipantRequest.serialize, - response_deserializer=gcd_participant.Participant.deserialize, - ) - return self._stubs['update_participant'] - - @property - def analyze_content(self) -> Callable[ - [gcd_participant.AnalyzeContentRequest], - Awaitable[gcd_participant.AnalyzeContentResponse]]: - r"""Return a callable for the analyze content method over gRPC. - - Adds a text (chat, for example), or audio (phone recording, for - example) message from a participant into the conversation. - - Note: Always use agent versions for production traffic sent to - virtual agents. See `Versions and - environments `__. - - Returns: - Callable[[~.AnalyzeContentRequest], - Awaitable[~.AnalyzeContentResponse]]: - 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 'analyze_content' not in self._stubs: - self._stubs['analyze_content'] = self.grpc_channel.unary_unary( - '/google.cloud.dialogflow.v2beta1.Participants/AnalyzeContent', - request_serializer=gcd_participant.AnalyzeContentRequest.serialize, - response_deserializer=gcd_participant.AnalyzeContentResponse.deserialize, - ) - return self._stubs['analyze_content'] - - @property - def streaming_analyze_content(self) -> Callable[ - [participant.StreamingAnalyzeContentRequest], - Awaitable[participant.StreamingAnalyzeContentResponse]]: - r"""Return a callable for the streaming analyze content method over gRPC. - - Adds a text (e.g., chat) or audio (e.g., phone recording) - message from a participant into the conversation. Note: This - method is only available through the gRPC API (not REST). - - The top-level message sent to the client by the server is - ``StreamingAnalyzeContentResponse``. Multiple response messages - can be returned in order. The first one or more messages contain - the ``recognition_result`` field. Each result represents a more - complete transcript of what the user said. The next message - contains the ``reply_text`` field, and potentially the - ``reply_audio`` and/or the ``automated_agent_reply`` fields. - - Note: Always use agent versions for production traffic sent to - virtual agents. See `Versions and - environments `__. - - Returns: - Callable[[~.StreamingAnalyzeContentRequest], - Awaitable[~.StreamingAnalyzeContentResponse]]: - 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 'streaming_analyze_content' not in self._stubs: - self._stubs['streaming_analyze_content'] = self.grpc_channel.stream_stream( - '/google.cloud.dialogflow.v2beta1.Participants/StreamingAnalyzeContent', - request_serializer=participant.StreamingAnalyzeContentRequest.serialize, - response_deserializer=participant.StreamingAnalyzeContentResponse.deserialize, - ) - return self._stubs['streaming_analyze_content'] - - @property - def suggest_articles(self) -> Callable[ - [participant.SuggestArticlesRequest], - Awaitable[participant.SuggestArticlesResponse]]: - r"""Return a callable for the suggest articles method over gRPC. - - Gets suggested articles for a participant based on specific - historical messages. - - Note that - [ListSuggestions][google.cloud.dialogflow.v2beta1.Participants.ListSuggestions] - will only list the auto-generated suggestions, while - [CompileSuggestion][google.cloud.dialogflow.v2beta1.Participants.CompileSuggestion] - will try to compile suggestion based on the provided - conversation context in the real time. - - Returns: - Callable[[~.SuggestArticlesRequest], - Awaitable[~.SuggestArticlesResponse]]: - 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 'suggest_articles' not in self._stubs: - self._stubs['suggest_articles'] = self.grpc_channel.unary_unary( - '/google.cloud.dialogflow.v2beta1.Participants/SuggestArticles', - request_serializer=participant.SuggestArticlesRequest.serialize, - response_deserializer=participant.SuggestArticlesResponse.deserialize, - ) - return self._stubs['suggest_articles'] - - @property - def suggest_faq_answers(self) -> Callable[ - [participant.SuggestFaqAnswersRequest], - Awaitable[participant.SuggestFaqAnswersResponse]]: - r"""Return a callable for the suggest faq answers method over gRPC. - - Gets suggested faq answers for a participant based on - specific historical messages. - - Returns: - Callable[[~.SuggestFaqAnswersRequest], - Awaitable[~.SuggestFaqAnswersResponse]]: - 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 'suggest_faq_answers' not in self._stubs: - self._stubs['suggest_faq_answers'] = self.grpc_channel.unary_unary( - '/google.cloud.dialogflow.v2beta1.Participants/SuggestFaqAnswers', - request_serializer=participant.SuggestFaqAnswersRequest.serialize, - response_deserializer=participant.SuggestFaqAnswersResponse.deserialize, - ) - return self._stubs['suggest_faq_answers'] - - @property - def suggest_smart_replies(self) -> Callable[ - [participant.SuggestSmartRepliesRequest], - Awaitable[participant.SuggestSmartRepliesResponse]]: - r"""Return a callable for the suggest smart replies method over gRPC. - - Gets smart replies for a participant based on - specific historical messages. - - Returns: - Callable[[~.SuggestSmartRepliesRequest], - Awaitable[~.SuggestSmartRepliesResponse]]: - 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 'suggest_smart_replies' not in self._stubs: - self._stubs['suggest_smart_replies'] = self.grpc_channel.unary_unary( - '/google.cloud.dialogflow.v2beta1.Participants/SuggestSmartReplies', - request_serializer=participant.SuggestSmartRepliesRequest.serialize, - response_deserializer=participant.SuggestSmartRepliesResponse.deserialize, - ) - return self._stubs['suggest_smart_replies'] - - @property - def list_suggestions(self) -> Callable[ - [participant.ListSuggestionsRequest], - Awaitable[participant.ListSuggestionsResponse]]: - r"""Return a callable for the list suggestions method over gRPC. - - Deprecated: Use inline suggestion, event based suggestion or - Suggestion\* API instead. See - [HumanAgentAssistantConfig.name][google.cloud.dialogflow.v2beta1.HumanAgentAssistantConfig.name] - for more details. Removal Date: 2020-09-01. - - Retrieves suggestions for live agents. - - This method should be used by human agent client software to - 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 `__ - 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 - descending order. To fetch latest suggestion, just set - ``page_size`` to 1. To fetch new suggestions without - duplication, send request with filter - ``create_time_epoch_microseconds > [first item's create_time of previous request]`` - and empty page_token. - - Returns: - Callable[[~.ListSuggestionsRequest], - Awaitable[~.ListSuggestionsResponse]]: - 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_suggestions' not in self._stubs: - self._stubs['list_suggestions'] = self.grpc_channel.unary_unary( - '/google.cloud.dialogflow.v2beta1.Participants/ListSuggestions', - request_serializer=participant.ListSuggestionsRequest.serialize, - response_deserializer=participant.ListSuggestionsResponse.deserialize, - ) - return self._stubs['list_suggestions'] - - @property - def compile_suggestion(self) -> Callable[ - [participant.CompileSuggestionRequest], - Awaitable[participant.CompileSuggestionResponse]]: - r"""Return a callable for the compile suggestion method over gRPC. - - Deprecated. use - [SuggestArticles][google.cloud.dialogflow.v2beta1.Participants.SuggestArticles] - and - [SuggestFaqAnswers][google.cloud.dialogflow.v2beta1.Participants.SuggestFaqAnswers] - instead. - - Gets suggestions for a participant based on specific historical - messages. - - Note that - [ListSuggestions][google.cloud.dialogflow.v2beta1.Participants.ListSuggestions] - will only list the auto-generated suggestions, while - [CompileSuggestion][google.cloud.dialogflow.v2beta1.Participants.CompileSuggestion] - will try to compile suggestion based on the provided - conversation context in the real time. - - Returns: - Callable[[~.CompileSuggestionRequest], - Awaitable[~.CompileSuggestionResponse]]: - 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 'compile_suggestion' not in self._stubs: - self._stubs['compile_suggestion'] = self.grpc_channel.unary_unary( - '/google.cloud.dialogflow.v2beta1.Participants/CompileSuggestion', - request_serializer=participant.CompileSuggestionRequest.serialize, - response_deserializer=participant.CompileSuggestionResponse.deserialize, - ) - return self._stubs['compile_suggestion'] - - def close(self): - return self.grpc_channel.close() - - @property - def cancel_operation( - self, - ) -> Callable[[operations_pb2.CancelOperationRequest], None]: - r"""Return a callable for the cancel_operation method over gRPC. - """ - # 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 "cancel_operation" not in self._stubs: - self._stubs["cancel_operation"] = self.grpc_channel.unary_unary( - "/google.longrunning.Operations/CancelOperation", - request_serializer=operations_pb2.CancelOperationRequest.SerializeToString, - response_deserializer=None, - ) - return self._stubs["cancel_operation"] - - @property - def get_operation( - self, - ) -> Callable[[operations_pb2.GetOperationRequest], operations_pb2.Operation]: - r"""Return a callable for the get_operation method over gRPC. - """ - # 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_operation" not in self._stubs: - self._stubs["get_operation"] = self.grpc_channel.unary_unary( - "/google.longrunning.Operations/GetOperation", - request_serializer=operations_pb2.GetOperationRequest.SerializeToString, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs["get_operation"] - - @property - def list_operations( - self, - ) -> Callable[[operations_pb2.ListOperationsRequest], operations_pb2.ListOperationsResponse]: - r"""Return a callable for the list_operations method over gRPC. - """ - # 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_operations" not in self._stubs: - self._stubs["list_operations"] = self.grpc_channel.unary_unary( - "/google.longrunning.Operations/ListOperations", - request_serializer=operations_pb2.ListOperationsRequest.SerializeToString, - response_deserializer=operations_pb2.ListOperationsResponse.FromString, - ) - return self._stubs["list_operations"] - - @property - def list_locations( - self, - ) -> Callable[[locations_pb2.ListLocationsRequest], locations_pb2.ListLocationsResponse]: - r"""Return a callable for the list locations method over gRPC. - """ - # 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_locations" not in self._stubs: - self._stubs["list_locations"] = self.grpc_channel.unary_unary( - "/google.cloud.location.Locations/ListLocations", - request_serializer=locations_pb2.ListLocationsRequest.SerializeToString, - response_deserializer=locations_pb2.ListLocationsResponse.FromString, - ) - return self._stubs["list_locations"] - - @property - def get_location( - self, - ) -> Callable[[locations_pb2.GetLocationRequest], locations_pb2.Location]: - r"""Return a callable for the list locations method over gRPC. - """ - # 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_location" not in self._stubs: - self._stubs["get_location"] = self.grpc_channel.unary_unary( - "/google.cloud.location.Locations/GetLocation", - request_serializer=locations_pb2.GetLocationRequest.SerializeToString, - response_deserializer=locations_pb2.Location.FromString, - ) - return self._stubs["get_location"] - - -__all__ = ( - 'ParticipantsGrpcAsyncIOTransport', -) diff --git a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/participants/transports/rest.py b/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/participants/transports/rest.py deleted file mode 100644 index 29fe4102e..000000000 --- a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/participants/transports/rest.py +++ /dev/null @@ -1,1850 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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 google.auth.transport.requests import AuthorizedSession # type: ignore -import json # type: ignore -import grpc # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore -from google.auth import credentials as ga_credentials # type: ignore -from google.api_core import exceptions as core_exceptions -from google.api_core import retry as retries -from google.api_core import rest_helpers -from google.api_core import rest_streaming -from google.api_core import path_template -from google.api_core import gapic_v1 - -from google.protobuf import json_format -from google.cloud.location import locations_pb2 # type: ignore -from google.longrunning import operations_pb2 -from requests import __version__ as requests_version -import dataclasses -import re -from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union -import warnings - -try: - OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] -except AttributeError: # pragma: NO COVER - OptionalRetry = Union[retries.Retry, object] # 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 as BASE_DEFAULT_CLIENT_INFO - - -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=BASE_DEFAULT_CLIENT_INFO.gapic_version, - grpc_version=None, - rest_version=requests_version, -) - - -class ParticipantsRestInterceptor: - """Interceptor for Participants. - - Interceptors are used to manipulate requests, request metadata, and responses - in arbitrary ways. - Example use cases include: - * Logging - * Verifying requests according to service or custom semantics - * Stripping extraneous information from responses - - These use cases and more can be enabled by injecting an - instance of a custom subclass when constructing the ParticipantsRestTransport. - - .. code-block:: python - class MyCustomParticipantsInterceptor(ParticipantsRestInterceptor): - def pre_analyze_content(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_analyze_content(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_compile_suggestion(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_compile_suggestion(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_create_participant(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_create_participant(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_get_participant(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_get_participant(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_list_participants(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_list_participants(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_list_suggestions(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_list_suggestions(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_suggest_articles(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_suggest_articles(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_suggest_faq_answers(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_suggest_faq_answers(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_suggest_smart_replies(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_suggest_smart_replies(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_update_participant(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_update_participant(self, response): - logging.log(f"Received response: {response}") - return response - - transport = ParticipantsRestTransport(interceptor=MyCustomParticipantsInterceptor()) - client = ParticipantsClient(transport=transport) - - - """ - def pre_analyze_content(self, request: gcd_participant.AnalyzeContentRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[gcd_participant.AnalyzeContentRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for analyze_content - - Override in a subclass to manipulate the request or metadata - before they are sent to the Participants server. - """ - return request, metadata - - def post_analyze_content(self, response: gcd_participant.AnalyzeContentResponse) -> gcd_participant.AnalyzeContentResponse: - """Post-rpc interceptor for analyze_content - - Override in a subclass to manipulate the response - after it is returned by the Participants server but before - it is returned to user code. - """ - return response - def pre_compile_suggestion(self, request: participant.CompileSuggestionRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[participant.CompileSuggestionRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for compile_suggestion - - Override in a subclass to manipulate the request or metadata - before they are sent to the Participants server. - """ - return request, metadata - - def post_compile_suggestion(self, response: participant.CompileSuggestionResponse) -> participant.CompileSuggestionResponse: - """Post-rpc interceptor for compile_suggestion - - Override in a subclass to manipulate the response - after it is returned by the Participants server but before - it is returned to user code. - """ - return response - def pre_create_participant(self, request: gcd_participant.CreateParticipantRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[gcd_participant.CreateParticipantRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for create_participant - - Override in a subclass to manipulate the request or metadata - before they are sent to the Participants server. - """ - return request, metadata - - def post_create_participant(self, response: gcd_participant.Participant) -> gcd_participant.Participant: - """Post-rpc interceptor for create_participant - - Override in a subclass to manipulate the response - after it is returned by the Participants server but before - it is returned to user code. - """ - return response - def pre_get_participant(self, request: participant.GetParticipantRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[participant.GetParticipantRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for get_participant - - Override in a subclass to manipulate the request or metadata - before they are sent to the Participants server. - """ - return request, metadata - - def post_get_participant(self, response: participant.Participant) -> participant.Participant: - """Post-rpc interceptor for get_participant - - Override in a subclass to manipulate the response - after it is returned by the Participants server but before - it is returned to user code. - """ - return response - def pre_list_participants(self, request: participant.ListParticipantsRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[participant.ListParticipantsRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for list_participants - - Override in a subclass to manipulate the request or metadata - before they are sent to the Participants server. - """ - return request, metadata - - def post_list_participants(self, response: participant.ListParticipantsResponse) -> participant.ListParticipantsResponse: - """Post-rpc interceptor for list_participants - - Override in a subclass to manipulate the response - after it is returned by the Participants server but before - it is returned to user code. - """ - return response - def pre_list_suggestions(self, request: participant.ListSuggestionsRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[participant.ListSuggestionsRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for list_suggestions - - Override in a subclass to manipulate the request or metadata - before they are sent to the Participants server. - """ - return request, metadata - - def post_list_suggestions(self, response: participant.ListSuggestionsResponse) -> participant.ListSuggestionsResponse: - """Post-rpc interceptor for list_suggestions - - Override in a subclass to manipulate the response - after it is returned by the Participants server but before - it is returned to user code. - """ - return response - def pre_suggest_articles(self, request: participant.SuggestArticlesRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[participant.SuggestArticlesRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for suggest_articles - - Override in a subclass to manipulate the request or metadata - before they are sent to the Participants server. - """ - return request, metadata - - def post_suggest_articles(self, response: participant.SuggestArticlesResponse) -> participant.SuggestArticlesResponse: - """Post-rpc interceptor for suggest_articles - - Override in a subclass to manipulate the response - after it is returned by the Participants server but before - it is returned to user code. - """ - return response - def pre_suggest_faq_answers(self, request: participant.SuggestFaqAnswersRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[participant.SuggestFaqAnswersRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for suggest_faq_answers - - Override in a subclass to manipulate the request or metadata - before they are sent to the Participants server. - """ - return request, metadata - - def post_suggest_faq_answers(self, response: participant.SuggestFaqAnswersResponse) -> participant.SuggestFaqAnswersResponse: - """Post-rpc interceptor for suggest_faq_answers - - Override in a subclass to manipulate the response - after it is returned by the Participants server but before - it is returned to user code. - """ - return response - def pre_suggest_smart_replies(self, request: participant.SuggestSmartRepliesRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[participant.SuggestSmartRepliesRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for suggest_smart_replies - - Override in a subclass to manipulate the request or metadata - before they are sent to the Participants server. - """ - return request, metadata - - def post_suggest_smart_replies(self, response: participant.SuggestSmartRepliesResponse) -> participant.SuggestSmartRepliesResponse: - """Post-rpc interceptor for suggest_smart_replies - - Override in a subclass to manipulate the response - after it is returned by the Participants server but before - it is returned to user code. - """ - return response - def pre_update_participant(self, request: gcd_participant.UpdateParticipantRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[gcd_participant.UpdateParticipantRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for update_participant - - Override in a subclass to manipulate the request or metadata - before they are sent to the Participants server. - """ - return request, metadata - - def post_update_participant(self, response: gcd_participant.Participant) -> gcd_participant.Participant: - """Post-rpc interceptor for update_participant - - Override in a subclass to manipulate the response - after it is returned by the Participants server but before - it is returned to user code. - """ - return response - - def pre_get_location( - self, request: locations_pb2.GetLocationRequest, metadata: Sequence[Tuple[str, str]] - ) -> Tuple[locations_pb2.GetLocationRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for get_location - - Override in a subclass to manipulate the request or metadata - before they are sent to the Participants server. - """ - return request, metadata - - def post_get_location( - self, response: locations_pb2.Location - ) -> locations_pb2.Location: - """Post-rpc interceptor for get_location - - Override in a subclass to manipulate the response - after it is returned by the Participants server but before - it is returned to user code. - """ - return response - def pre_list_locations( - self, request: locations_pb2.ListLocationsRequest, metadata: Sequence[Tuple[str, str]] - ) -> Tuple[locations_pb2.ListLocationsRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for list_locations - - Override in a subclass to manipulate the request or metadata - before they are sent to the Participants server. - """ - return request, metadata - - def post_list_locations( - self, response: locations_pb2.ListLocationsResponse - ) -> locations_pb2.ListLocationsResponse: - """Post-rpc interceptor for list_locations - - Override in a subclass to manipulate the response - after it is returned by the Participants server but before - it is returned to user code. - """ - return response - def pre_cancel_operation( - self, request: operations_pb2.CancelOperationRequest, metadata: Sequence[Tuple[str, str]] - ) -> Tuple[operations_pb2.CancelOperationRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for cancel_operation - - Override in a subclass to manipulate the request or metadata - before they are sent to the Participants server. - """ - return request, metadata - - def post_cancel_operation( - self, response: None - ) -> None: - """Post-rpc interceptor for cancel_operation - - Override in a subclass to manipulate the response - after it is returned by the Participants server but before - it is returned to user code. - """ - return response - def pre_get_operation( - self, request: operations_pb2.GetOperationRequest, metadata: Sequence[Tuple[str, str]] - ) -> Tuple[operations_pb2.GetOperationRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for get_operation - - Override in a subclass to manipulate the request or metadata - before they are sent to the Participants server. - """ - return request, metadata - - def post_get_operation( - self, response: operations_pb2.Operation - ) -> operations_pb2.Operation: - """Post-rpc interceptor for get_operation - - Override in a subclass to manipulate the response - after it is returned by the Participants server but before - it is returned to user code. - """ - return response - def pre_list_operations( - self, request: operations_pb2.ListOperationsRequest, metadata: Sequence[Tuple[str, str]] - ) -> Tuple[operations_pb2.ListOperationsRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for list_operations - - Override in a subclass to manipulate the request or metadata - before they are sent to the Participants server. - """ - return request, metadata - - def post_list_operations( - self, response: operations_pb2.ListOperationsResponse - ) -> operations_pb2.ListOperationsResponse: - """Post-rpc interceptor for list_operations - - Override in a subclass to manipulate the response - after it is returned by the Participants server but before - it is returned to user code. - """ - return response - - -@dataclasses.dataclass -class ParticipantsRestStub: - _session: AuthorizedSession - _host: str - _interceptor: ParticipantsRestInterceptor - - -class ParticipantsRestTransport(ParticipantsTransport): - """REST backend transport for Participants. - - Service for managing - [Participants][google.cloud.dialogflow.v2beta1.Participant]. - - 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 JSON representations of protocol buffers over HTTP/1.1 - - """ - - def __init__(self, *, - host: str = 'dialogflow.googleapis.com', - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - client_cert_source_for_mtls: Optional[Callable[[ - ], Tuple[bytes, bytes]]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - url_scheme: str = 'https', - interceptor: Optional[ParticipantsRestInterceptor] = None, - api_audience: Optional[str] = None, - ) -> 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 ignored if ``channel`` is provided. - scopes (Optional(Sequence[str])): A list of scopes. This argument is - ignored if ``channel`` is provided. - client_cert_source_for_mtls (Callable[[], Tuple[bytes, bytes]]): Client - certificate to configure mutual TLS HTTP channel. It is ignored - if ``channel`` is provided. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you are developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - url_scheme: the protocol scheme for the API endpoint. Normally - "https", but for testing or local servers, - "http" can be specified. - """ - # Run the base constructor - # TODO(yon-mg): resolve other ctor params i.e. scopes, quota, etc. - # TODO: When custom host (api_endpoint) is set, `scopes` must *also* be set on the - # credentials object - maybe_url_match = re.match("^(?Phttp(?:s)?://)?(?P.*)$", host) - if maybe_url_match is None: - raise ValueError(f"Unexpected hostname structure: {host}") # pragma: NO COVER - - url_match_items = maybe_url_match.groupdict() - - host = f"{url_scheme}://{host}" if not url_match_items["scheme"] else host - - super().__init__( - host=host, - credentials=credentials, - client_info=client_info, - always_use_jwt_access=always_use_jwt_access, - api_audience=api_audience - ) - self._session = AuthorizedSession( - self._credentials, default_host=self.DEFAULT_HOST) - if client_cert_source_for_mtls: - self._session.configure_mtls_channel(client_cert_source_for_mtls) - self._interceptor = interceptor or ParticipantsRestInterceptor() - self._prep_wrapped_messages(client_info) - - class _AnalyzeContent(ParticipantsRestStub): - def __hash__(self): - return hash("AnalyzeContent") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: gcd_participant.AnalyzeContentRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> gcd_participant.AnalyzeContentResponse: - r"""Call the analyze content method over HTTP. - - Args: - request (~.gcd_participant.AnalyzeContentRequest): - The request object. The request message for - [Participants.AnalyzeContent][google.cloud.dialogflow.v2beta1.Participants.AnalyzeContent]. - 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: - ~.gcd_participant.AnalyzeContentResponse: - The response message for - [Participants.AnalyzeContent][google.cloud.dialogflow.v2beta1.Participants.AnalyzeContent]. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'post', - 'uri': '/v2beta1/{participant=projects/*/conversations/*/participants/*}:analyzeContent', - 'body': '*', - }, -{ - 'method': 'post', - 'uri': '/v2beta1/{participant=projects/*/locations/*/conversations/*/participants/*}:analyzeContent', - 'body': '*', - }, - ] - request, metadata = self._interceptor.pre_analyze_content(request, metadata) - pb_request = gcd_participant.AnalyzeContentRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request['body'], - including_default_value_fields=False, - use_integers_for_enums=True - ) - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - including_default_value_fields=False, - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = gcd_participant.AnalyzeContentResponse() - pb_resp = gcd_participant.AnalyzeContentResponse.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_analyze_content(resp) - return resp - - class _CompileSuggestion(ParticipantsRestStub): - def __hash__(self): - return hash("CompileSuggestion") - - def __call__(self, - request: participant.CompileSuggestionRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> participant.CompileSuggestionResponse: - r"""Call the compile suggestion method over HTTP. - - Args: - request (~.participant.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. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.participant.CompileSuggestionResponse: - The response message for - [Participants.CompileSuggestion][google.cloud.dialogflow.v2beta1.Participants.CompileSuggestion]. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'post', - 'uri': '/v2beta1/{parent=projects/*/conversations/*/participants/*}/suggestions:compile', - 'body': '*', - }, - ] - request, metadata = self._interceptor.pre_compile_suggestion(request, metadata) - pb_request = participant.CompileSuggestionRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request['body'], - including_default_value_fields=False, - use_integers_for_enums=True - ) - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - including_default_value_fields=False, - use_integers_for_enums=True, - )) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = participant.CompileSuggestionResponse() - pb_resp = participant.CompileSuggestionResponse.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_compile_suggestion(resp) - return resp - - class _CreateParticipant(ParticipantsRestStub): - def __hash__(self): - return hash("CreateParticipant") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: gcd_participant.CreateParticipantRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> gcd_participant.Participant: - r"""Call the create participant method over HTTP. - - Args: - request (~.gcd_participant.CreateParticipantRequest): - The request object. The request message for - [Participants.CreateParticipant][google.cloud.dialogflow.v2beta1.Participants.CreateParticipant]. - 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: - ~.gcd_participant.Participant: - Represents a conversation participant - (human agent, virtual agent, end-user). - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'post', - 'uri': '/v2beta1/{parent=projects/*/conversations/*}/participants', - 'body': 'participant', - }, -{ - 'method': 'post', - 'uri': '/v2beta1/{parent=projects/*/locations/*/conversations/*}/participants', - 'body': 'participant', - }, - ] - request, metadata = self._interceptor.pre_create_participant(request, metadata) - pb_request = gcd_participant.CreateParticipantRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request['body'], - including_default_value_fields=False, - use_integers_for_enums=True - ) - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - including_default_value_fields=False, - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = gcd_participant.Participant() - pb_resp = gcd_participant.Participant.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_create_participant(resp) - return resp - - class _GetParticipant(ParticipantsRestStub): - def __hash__(self): - return hash("GetParticipant") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: participant.GetParticipantRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> participant.Participant: - r"""Call the get participant method over HTTP. - - Args: - request (~.participant.GetParticipantRequest): - The request object. The request message for - [Participants.GetParticipant][google.cloud.dialogflow.v2beta1.Participants.GetParticipant]. - 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: - ~.participant.Participant: - Represents a conversation participant - (human agent, virtual agent, end-user). - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v2beta1/{name=projects/*/conversations/*/participants/*}', - }, -{ - 'method': 'get', - 'uri': '/v2beta1/{name=projects/*/locations/*/conversations/*/participants/*}', - }, - ] - request, metadata = self._interceptor.pre_get_participant(request, metadata) - pb_request = participant.GetParticipantRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - including_default_value_fields=False, - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = participant.Participant() - pb_resp = participant.Participant.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_get_participant(resp) - return resp - - class _ListParticipants(ParticipantsRestStub): - def __hash__(self): - return hash("ListParticipants") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: participant.ListParticipantsRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> participant.ListParticipantsResponse: - r"""Call the list participants method over HTTP. - - Args: - request (~.participant.ListParticipantsRequest): - The request object. The request message for - [Participants.ListParticipants][google.cloud.dialogflow.v2beta1.Participants.ListParticipants]. - 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: - ~.participant.ListParticipantsResponse: - The response message for - [Participants.ListParticipants][google.cloud.dialogflow.v2beta1.Participants.ListParticipants]. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v2beta1/{parent=projects/*/conversations/*}/participants', - }, -{ - 'method': 'get', - 'uri': '/v2beta1/{parent=projects/*/locations/*/conversations/*}/participants', - }, - ] - request, metadata = self._interceptor.pre_list_participants(request, metadata) - pb_request = participant.ListParticipantsRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - including_default_value_fields=False, - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = participant.ListParticipantsResponse() - pb_resp = participant.ListParticipantsResponse.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_list_participants(resp) - return resp - - class _ListSuggestions(ParticipantsRestStub): - def __hash__(self): - return hash("ListSuggestions") - - def __call__(self, - request: participant.ListSuggestionsRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> participant.ListSuggestionsResponse: - r"""Call the list suggestions method over HTTP. - - Args: - request (~.participant.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. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.participant.ListSuggestionsResponse: - The response message for - [Participants.ListSuggestions][google.cloud.dialogflow.v2beta1.Participants.ListSuggestions]. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v2beta1/{parent=projects/*/conversations/*/participants/*}/suggestions', - }, - ] - request, metadata = self._interceptor.pre_list_suggestions(request, metadata) - pb_request = participant.ListSuggestionsRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - including_default_value_fields=False, - use_integers_for_enums=True, - )) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = participant.ListSuggestionsResponse() - pb_resp = participant.ListSuggestionsResponse.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_list_suggestions(resp) - return resp - - class _StreamingAnalyzeContent(ParticipantsRestStub): - def __hash__(self): - return hash("StreamingAnalyzeContent") - - def __call__(self, - request: participant.StreamingAnalyzeContentRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> rest_streaming.ResponseIterator: - raise NotImplementedError( - "Method StreamingAnalyzeContent is not available over REST transport" - ) - class _SuggestArticles(ParticipantsRestStub): - def __hash__(self): - return hash("SuggestArticles") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: participant.SuggestArticlesRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> participant.SuggestArticlesResponse: - r"""Call the suggest articles method over HTTP. - - Args: - request (~.participant.SuggestArticlesRequest): - The request object. The request message for - [Participants.SuggestArticles][google.cloud.dialogflow.v2beta1.Participants.SuggestArticles]. - 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: - ~.participant.SuggestArticlesResponse: - The response message for - [Participants.SuggestArticles][google.cloud.dialogflow.v2beta1.Participants.SuggestArticles]. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'post', - 'uri': '/v2beta1/{parent=projects/*/conversations/*/participants/*}/suggestions:suggestArticles', - 'body': '*', - }, -{ - 'method': 'post', - 'uri': '/v2beta1/{parent=projects/*/locations/*/conversations/*/participants/*}/suggestions:suggestArticles', - 'body': '*', - }, - ] - request, metadata = self._interceptor.pre_suggest_articles(request, metadata) - pb_request = participant.SuggestArticlesRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request['body'], - including_default_value_fields=False, - use_integers_for_enums=True - ) - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - including_default_value_fields=False, - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = participant.SuggestArticlesResponse() - pb_resp = participant.SuggestArticlesResponse.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_suggest_articles(resp) - return resp - - class _SuggestFaqAnswers(ParticipantsRestStub): - def __hash__(self): - return hash("SuggestFaqAnswers") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: participant.SuggestFaqAnswersRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> participant.SuggestFaqAnswersResponse: - r"""Call the suggest faq answers method over HTTP. - - Args: - request (~.participant.SuggestFaqAnswersRequest): - The request object. The request message for - [Participants.SuggestFaqAnswers][google.cloud.dialogflow.v2beta1.Participants.SuggestFaqAnswers]. - 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: - ~.participant.SuggestFaqAnswersResponse: - The request message for - [Participants.SuggestFaqAnswers][google.cloud.dialogflow.v2beta1.Participants.SuggestFaqAnswers]. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'post', - 'uri': '/v2beta1/{parent=projects/*/conversations/*/participants/*}/suggestions:suggestFaqAnswers', - 'body': '*', - }, -{ - 'method': 'post', - 'uri': '/v2beta1/{parent=projects/*/locations/*/conversations/*/participants/*}/suggestions:suggestFaqAnswers', - 'body': '*', - }, - ] - request, metadata = self._interceptor.pre_suggest_faq_answers(request, metadata) - pb_request = participant.SuggestFaqAnswersRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request['body'], - including_default_value_fields=False, - use_integers_for_enums=True - ) - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - including_default_value_fields=False, - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = participant.SuggestFaqAnswersResponse() - pb_resp = participant.SuggestFaqAnswersResponse.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_suggest_faq_answers(resp) - return resp - - class _SuggestSmartReplies(ParticipantsRestStub): - def __hash__(self): - return hash("SuggestSmartReplies") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: participant.SuggestSmartRepliesRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> participant.SuggestSmartRepliesResponse: - r"""Call the suggest smart replies method over HTTP. - - Args: - request (~.participant.SuggestSmartRepliesRequest): - The request object. The request message for - [Participants.SuggestSmartReplies][google.cloud.dialogflow.v2beta1.Participants.SuggestSmartReplies]. - 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: - ~.participant.SuggestSmartRepliesResponse: - The response message for - [Participants.SuggestSmartReplies][google.cloud.dialogflow.v2beta1.Participants.SuggestSmartReplies]. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'post', - 'uri': '/v2beta1/{parent=projects/*/conversations/*/participants/*}/suggestions:suggestSmartReplies', - 'body': '*', - }, -{ - 'method': 'post', - 'uri': '/v2beta1/{parent=projects/*/locations/*/conversations/*/participants/*}/suggestions:suggestSmartReplies', - 'body': '*', - }, - ] - request, metadata = self._interceptor.pre_suggest_smart_replies(request, metadata) - pb_request = participant.SuggestSmartRepliesRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request['body'], - including_default_value_fields=False, - use_integers_for_enums=True - ) - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - including_default_value_fields=False, - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = participant.SuggestSmartRepliesResponse() - pb_resp = participant.SuggestSmartRepliesResponse.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_suggest_smart_replies(resp) - return resp - - class _UpdateParticipant(ParticipantsRestStub): - def __hash__(self): - return hash("UpdateParticipant") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - "updateMask" : {}, } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: gcd_participant.UpdateParticipantRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> gcd_participant.Participant: - r"""Call the update participant method over HTTP. - - Args: - request (~.gcd_participant.UpdateParticipantRequest): - The request object. The request message for - [Participants.UpdateParticipant][google.cloud.dialogflow.v2beta1.Participants.UpdateParticipant]. - 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: - ~.gcd_participant.Participant: - Represents a conversation participant - (human agent, virtual agent, end-user). - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'patch', - 'uri': '/v2beta1/{participant.name=projects/*/conversations/*/participants/*}', - 'body': 'participant', - }, -{ - 'method': 'patch', - 'uri': '/v2beta1/{participant.name=projects/*/locations/*/conversations/*/participants/*}', - 'body': 'participant', - }, - ] - request, metadata = self._interceptor.pre_update_participant(request, metadata) - pb_request = gcd_participant.UpdateParticipantRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request['body'], - including_default_value_fields=False, - use_integers_for_enums=True - ) - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - including_default_value_fields=False, - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = gcd_participant.Participant() - pb_resp = gcd_participant.Participant.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_update_participant(resp) - return resp - - @property - def analyze_content(self) -> Callable[ - [gcd_participant.AnalyzeContentRequest], - gcd_participant.AnalyzeContentResponse]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._AnalyzeContent(self._session, self._host, self._interceptor) # type: ignore - - @property - def compile_suggestion(self) -> Callable[ - [participant.CompileSuggestionRequest], - participant.CompileSuggestionResponse]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._CompileSuggestion(self._session, self._host, self._interceptor) # type: ignore - - @property - def create_participant(self) -> Callable[ - [gcd_participant.CreateParticipantRequest], - gcd_participant.Participant]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._CreateParticipant(self._session, self._host, self._interceptor) # type: ignore - - @property - def get_participant(self) -> Callable[ - [participant.GetParticipantRequest], - participant.Participant]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._GetParticipant(self._session, self._host, self._interceptor) # type: ignore - - @property - def list_participants(self) -> Callable[ - [participant.ListParticipantsRequest], - participant.ListParticipantsResponse]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._ListParticipants(self._session, self._host, self._interceptor) # type: ignore - - @property - def list_suggestions(self) -> Callable[ - [participant.ListSuggestionsRequest], - participant.ListSuggestionsResponse]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._ListSuggestions(self._session, self._host, self._interceptor) # type: ignore - - @property - def streaming_analyze_content(self) -> Callable[ - [participant.StreamingAnalyzeContentRequest], - participant.StreamingAnalyzeContentResponse]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._StreamingAnalyzeContent(self._session, self._host, self._interceptor) # type: ignore - - @property - def suggest_articles(self) -> Callable[ - [participant.SuggestArticlesRequest], - participant.SuggestArticlesResponse]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._SuggestArticles(self._session, self._host, self._interceptor) # type: ignore - - @property - def suggest_faq_answers(self) -> Callable[ - [participant.SuggestFaqAnswersRequest], - participant.SuggestFaqAnswersResponse]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._SuggestFaqAnswers(self._session, self._host, self._interceptor) # type: ignore - - @property - def suggest_smart_replies(self) -> Callable[ - [participant.SuggestSmartRepliesRequest], - participant.SuggestSmartRepliesResponse]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._SuggestSmartReplies(self._session, self._host, self._interceptor) # type: ignore - - @property - def update_participant(self) -> Callable[ - [gcd_participant.UpdateParticipantRequest], - gcd_participant.Participant]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._UpdateParticipant(self._session, self._host, self._interceptor) # type: ignore - - @property - def get_location(self): - return self._GetLocation(self._session, self._host, self._interceptor) # type: ignore - - class _GetLocation(ParticipantsRestStub): - def __call__(self, - request: locations_pb2.GetLocationRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> locations_pb2.Location: - - r"""Call the get location method over HTTP. - - Args: - request (locations_pb2.GetLocationRequest): - The request object for GetLocation method. - 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: - locations_pb2.Location: Response from GetLocation method. - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v2beta1/{name=projects/*/locations/*}', - }, - ] - - request, metadata = self._interceptor.pre_get_location(request, metadata) - request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode( - http_options, **request_kwargs) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json.dumps(transcoded_request['query_params'])) - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - resp = locations_pb2.Location() - resp = json_format.Parse(response.content.decode("utf-8"), resp) - resp = self._interceptor.post_get_location(resp) - return resp - - @property - def list_locations(self): - return self._ListLocations(self._session, self._host, self._interceptor) # type: ignore - - class _ListLocations(ParticipantsRestStub): - def __call__(self, - request: locations_pb2.ListLocationsRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> locations_pb2.ListLocationsResponse: - - r"""Call the list locations method over HTTP. - - Args: - request (locations_pb2.ListLocationsRequest): - The request object for ListLocations method. - 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: - locations_pb2.ListLocationsResponse: Response from ListLocations method. - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v2beta1/{name=projects/*}/locations', - }, - ] - - request, metadata = self._interceptor.pre_list_locations(request, metadata) - request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode( - http_options, **request_kwargs) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json.dumps(transcoded_request['query_params'])) - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - resp = locations_pb2.ListLocationsResponse() - resp = json_format.Parse(response.content.decode("utf-8"), resp) - resp = self._interceptor.post_list_locations(resp) - return resp - - @property - def cancel_operation(self): - return self._CancelOperation(self._session, self._host, self._interceptor) # type: ignore - - class _CancelOperation(ParticipantsRestStub): - def __call__(self, - request: operations_pb2.CancelOperationRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> None: - - r"""Call the cancel operation method over HTTP. - - Args: - request (operations_pb2.CancelOperationRequest): - The request object for CancelOperation method. - 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. - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'post', - 'uri': '/v2beta1/{name=projects/*/operations/*}:cancel', - }, -{ - 'method': 'post', - 'uri': '/v2beta1/{name=projects/*/locations/*/operations/*}:cancel', - }, - ] - - request, metadata = self._interceptor.pre_cancel_operation(request, metadata) - request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode( - http_options, **request_kwargs) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json.dumps(transcoded_request['query_params'])) - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - return self._interceptor.post_cancel_operation(None) - - @property - def get_operation(self): - return self._GetOperation(self._session, self._host, self._interceptor) # type: ignore - - class _GetOperation(ParticipantsRestStub): - def __call__(self, - request: operations_pb2.GetOperationRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> operations_pb2.Operation: - - r"""Call the get operation method over HTTP. - - Args: - request (operations_pb2.GetOperationRequest): - The request object for GetOperation method. - 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: - operations_pb2.Operation: Response from GetOperation method. - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v2beta1/{name=projects/*/operations/*}', - }, -{ - 'method': 'get', - 'uri': '/v2beta1/{name=projects/*/locations/*/operations/*}', - }, - ] - - request, metadata = self._interceptor.pre_get_operation(request, metadata) - request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode( - http_options, **request_kwargs) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json.dumps(transcoded_request['query_params'])) - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - resp = operations_pb2.Operation() - resp = json_format.Parse(response.content.decode("utf-8"), resp) - resp = self._interceptor.post_get_operation(resp) - return resp - - @property - def list_operations(self): - return self._ListOperations(self._session, self._host, self._interceptor) # type: ignore - - class _ListOperations(ParticipantsRestStub): - def __call__(self, - request: operations_pb2.ListOperationsRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> operations_pb2.ListOperationsResponse: - - r"""Call the list operations method over HTTP. - - Args: - request (operations_pb2.ListOperationsRequest): - The request object for ListOperations method. - 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: - operations_pb2.ListOperationsResponse: Response from ListOperations method. - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v2beta1/{name=projects/*}/operations', - }, -{ - 'method': 'get', - 'uri': '/v2beta1/{name=projects/*/locations/*}/operations', - }, - ] - - request, metadata = self._interceptor.pre_list_operations(request, metadata) - request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode( - http_options, **request_kwargs) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json.dumps(transcoded_request['query_params'])) - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - resp = operations_pb2.ListOperationsResponse() - resp = json_format.Parse(response.content.decode("utf-8"), resp) - resp = self._interceptor.post_list_operations(resp) - return resp - - @property - def kind(self) -> str: - return "rest" - - def close(self): - self._session.close() - - -__all__=( - 'ParticipantsRestTransport', -) diff --git a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/session_entity_types/__init__.py b/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/session_entity_types/__init__.py deleted file mode 100644 index 1a3f965dd..000000000 --- a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/session_entity_types/__init__.py +++ /dev/null @@ -1,22 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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 SessionEntityTypesClient -from .async_client import SessionEntityTypesAsyncClient - -__all__ = ( - 'SessionEntityTypesClient', - 'SessionEntityTypesAsyncClient', -) diff --git a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/session_entity_types/async_client.py b/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/session_entity_types/async_client.py deleted file mode 100644 index bdcb92a1e..000000000 --- a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/session_entity_types/async_client.py +++ /dev/null @@ -1,1067 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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, Mapping, MutableMapping, MutableSequence, Optional, Sequence, Tuple, Type, Union - -from google.cloud.dialogflow_v2beta1 import gapic_version as package_version - -from google.api_core.client_options import ClientOptions -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import retry as retries -from google.auth import credentials as ga_credentials # type: ignore -from google.oauth2 import service_account # type: ignore - -try: - OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] -except AttributeError: # pragma: NO COVER - OptionalRetry = Union[retries.Retry, object] # type: ignore - -from google.cloud.dialogflow_v2beta1.services.session_entity_types import pagers -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.cloud.location import locations_pb2 # type: ignore -from google.longrunning import operations_pb2 -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 - - -class SessionEntityTypesAsyncClient: - """Service for managing - [SessionEntityTypes][google.cloud.dialogflow.v2beta1.SessionEntityType]. - """ - - _client: SessionEntityTypesClient - - DEFAULT_ENDPOINT = SessionEntityTypesClient.DEFAULT_ENDPOINT - DEFAULT_MTLS_ENDPOINT = SessionEntityTypesClient.DEFAULT_MTLS_ENDPOINT - - session_entity_type_path = staticmethod(SessionEntityTypesClient.session_entity_type_path) - 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) - - @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: - SessionEntityTypesAsyncClient: The constructed client. - """ - return SessionEntityTypesClient.from_service_account_info.__func__(SessionEntityTypesAsyncClient, 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: - SessionEntityTypesAsyncClient: The constructed client. - """ - return SessionEntityTypesClient.from_service_account_file.__func__(SessionEntityTypesAsyncClient, filename, *args, **kwargs) # type: ignore - - from_service_account_json = from_service_account_file - - @classmethod - def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[ClientOptions] = None): - """Return the API endpoint and client cert source for mutual TLS. - - The client cert source is determined in the following order: - (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the - client cert source is None. - (2) if `client_options.client_cert_source` is provided, use the provided one; if the - default client cert source exists, use the default one; otherwise the client cert - source is None. - - The API endpoint is determined in the following order: - (1) if `client_options.api_endpoint` if provided, use the provided one. - (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the - default mTLS endpoint; if the environment variable is "never", use the default API - endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise - use the default API endpoint. - - More details can be found at https://google.aip.dev/auth/4114. - - Args: - client_options (google.api_core.client_options.ClientOptions): Custom options for the - client. Only the `api_endpoint` and `client_cert_source` properties may be used - in this method. - - Returns: - Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the - client cert source to use. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If any errors happen. - """ - return SessionEntityTypesClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore - - @property - def transport(self) -> SessionEntityTypesTransport: - """Returns the transport used by the client instance. - - Returns: - SessionEntityTypesTransport: The transport used by the client instance. - """ - return self._client.transport - - get_transport_class = functools.partial(type(SessionEntityTypesClient).get_transport_class, type(SessionEntityTypesClient)) - - def __init__(self, *, - credentials: Optional[ga_credentials.Credentials] = None, - transport: Union[str, SessionEntityTypesTransport] = "grpc_asyncio", - client_options: Optional[ClientOptions] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the session entity types 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, ~.SessionEntityTypesTransport]): 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 = SessionEntityTypesClient( - credentials=credentials, - transport=transport, - client_options=client_options, - client_info=client_info, - - ) - - async def list_session_entity_types(self, - request: Optional[Union[session_entity_type.ListSessionEntityTypesRequest, dict]] = None, - *, - parent: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListSessionEntityTypesAsyncPager: - r"""Returns the list of all session entity types in the - specified session. - This method doesn't work with Google Assistant - integration. Contact Dialogflow support if you need to - use session entities with Google Assistant integration. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import dialogflow_v2beta1 - - async def sample_list_session_entity_types(): - # Create a client - client = dialogflow_v2beta1.SessionEntityTypesAsyncClient() - - # Initialize request argument(s) - request = dialogflow_v2beta1.ListSessionEntityTypesRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_session_entity_types(request=request) - - # Handle the response - async for response in page_result: - print(response) - - Args: - request (Optional[Union[google.cloud.dialogflow_v2beta1.types.ListSessionEntityTypesRequest, dict]]): - The request object. The request message for - [SessionEntityTypes.ListSessionEntityTypes][google.cloud.dialogflow.v2beta1.SessionEntityTypes.ListSessionEntityTypes]. - parent (:class:`str`): - Required. The session to list all session entity types - from. Supported formats: - - - \`projects//agent/sessions/, - - ``projects//locations//agent/sessions/``, - - ``projects//agent/environments//users//sessions/``, - - ``projects//locations//agent/environments//users//sessions/``, - - If ``Location ID`` is not specified we assume default - 'us' location. If ``Environment ID`` is not specified, - we assume default 'draft' environment. If ``User ID`` is - not specified, we assume default '-' user. - - 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.session_entity_types.pagers.ListSessionEntityTypesAsyncPager: - The response message for - [SessionEntityTypes.ListSessionEntityTypes][google.cloud.dialogflow.v2beta1.SessionEntityTypes.ListSessionEntityTypes]. - - Iterating over this object will yield results and - resolve additional pages automatically. - - """ - # Create or coerce a protobuf request object. - # Quick 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 = 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 - - # 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_session_entity_types, - 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.ListSessionEntityTypesAsyncPager( - method=rpc, - request=request, - response=response, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def get_session_entity_type(self, - request: Optional[Union[session_entity_type.GetSessionEntityTypeRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> session_entity_type.SessionEntityType: - r"""Retrieves the specified session entity type. - This method doesn't work with Google Assistant - integration. Contact Dialogflow support if you need to - use session entities with Google Assistant integration. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import dialogflow_v2beta1 - - async def sample_get_session_entity_type(): - # Create a client - client = dialogflow_v2beta1.SessionEntityTypesAsyncClient() - - # Initialize request argument(s) - request = dialogflow_v2beta1.GetSessionEntityTypeRequest( - name="name_value", - ) - - # Make the request - response = await client.get_session_entity_type(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.dialogflow_v2beta1.types.GetSessionEntityTypeRequest, dict]]): - The request object. The request message for - [SessionEntityTypes.GetSessionEntityType][google.cloud.dialogflow.v2beta1.SessionEntityTypes.GetSessionEntityType]. - name (:class:`str`): - Required. The name of the session entity type. Supported - formats: - - - ``projects//agent/sessions//entityTypes/`` - - ``projects//locations//agent/sessions//entityTypes/`` - - ``projects//agent/environments//users//sessions//entityTypes/`` - - ``projects//locations//agent/environments/ /users//sessions//entityTypes/`` - - If ``Location ID`` is not specified we assume default - 'us' location. If ``Environment ID`` is not specified, - we assume default 'draft' environment. If ``User ID`` is - not specified, we assume default '-' user. - - 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.SessionEntityType: - A session represents a conversation between a Dialogflow agent and an - end-user. You can create special entities, called - session entities, during a session. Session entities - can extend or replace custom entity types and only - exist during the session that they were created for. - All session data, including session entities, is - stored by Dialogflow for 20 minutes. - - For more information, see the [session entity - guide](\ https://cloud.google.com/dialogflow/docs/entities-session). - - """ - # Create or coerce a protobuf request object. - # Quick 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 = 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 - - # 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_session_entity_type, - 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_session_entity_type(self, - request: Optional[Union[gcd_session_entity_type.CreateSessionEntityTypeRequest, dict]] = None, - *, - parent: Optional[str] = None, - session_entity_type: Optional[gcd_session_entity_type.SessionEntityType] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gcd_session_entity_type.SessionEntityType: - r"""Creates a session entity type. - If the specified session entity type already exists, - overrides the session entity type. - - This method doesn't work with Google Assistant - integration. Contact Dialogflow support if you need to - use session entities with Google Assistant integration. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import dialogflow_v2beta1 - - async def sample_create_session_entity_type(): - # Create a client - client = dialogflow_v2beta1.SessionEntityTypesAsyncClient() - - # Initialize request argument(s) - request = dialogflow_v2beta1.CreateSessionEntityTypeRequest( - parent="parent_value", - ) - - # Make the request - response = await client.create_session_entity_type(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.dialogflow_v2beta1.types.CreateSessionEntityTypeRequest, dict]]): - The request object. The request message for - [SessionEntityTypes.CreateSessionEntityType][google.cloud.dialogflow.v2beta1.SessionEntityTypes.CreateSessionEntityType]. - parent (:class:`str`): - Required. The session to create a session entity type - for. Supported formats: - - - \`projects//agent/sessions/, - - ``projects//locations//agent/sessions/``, - - ``projects//agent/environments//users//sessions/``, - - ``projects//locations//agent/environments//users//sessions/``, - - If ``Location ID`` is not specified we assume default - 'us' location. If ``Environment ID`` is not specified, - we assume default 'draft' environment. If ``User ID`` is - not specified, we assume default '-' user. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - session_entity_type (:class:`google.cloud.dialogflow_v2beta1.types.SessionEntityType`): - Required. The session entity type to - create. - - 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. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.dialogflow_v2beta1.types.SessionEntityType: - A session represents a conversation between a Dialogflow agent and an - end-user. You can create special entities, called - session entities, during a session. Session entities - can extend or replace custom entity types and only - exist during the session that they were created for. - All session data, including session entities, is - stored by Dialogflow for 20 minutes. - - For more information, see the [session entity - guide](\ https://cloud.google.com/dialogflow/docs/entities-session). - - """ - # Create or coerce a protobuf request object. - # Quick 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, session_entity_type]) - 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_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: - request.session_entity_type = session_entity_type - - # 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_session_entity_type, - 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_session_entity_type(self, - request: Optional[Union[gcd_session_entity_type.UpdateSessionEntityTypeRequest, dict]] = None, - *, - session_entity_type: Optional[gcd_session_entity_type.SessionEntityType] = None, - update_mask: Optional[field_mask_pb2.FieldMask] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gcd_session_entity_type.SessionEntityType: - r"""Updates the specified session entity type. - This method doesn't work with Google Assistant - integration. Contact Dialogflow support if you need to - use session entities with Google Assistant integration. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import dialogflow_v2beta1 - - async def sample_update_session_entity_type(): - # Create a client - client = dialogflow_v2beta1.SessionEntityTypesAsyncClient() - - # Initialize request argument(s) - request = dialogflow_v2beta1.UpdateSessionEntityTypeRequest( - ) - - # Make the request - response = await client.update_session_entity_type(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.dialogflow_v2beta1.types.UpdateSessionEntityTypeRequest, dict]]): - The request object. The request message for - [SessionEntityTypes.UpdateSessionEntityType][google.cloud.dialogflow.v2beta1.SessionEntityTypes.UpdateSessionEntityType]. - session_entity_type (:class:`google.cloud.dialogflow_v2beta1.types.SessionEntityType`): - Required. The session entity type to - update. - - This corresponds to the ``session_entity_type`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - update_mask (:class:`google.protobuf.field_mask_pb2.FieldMask`): - Optional. 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.SessionEntityType: - A session represents a conversation between a Dialogflow agent and an - end-user. You can create special entities, called - session entities, during a session. Session entities - can extend or replace custom entity types and only - exist during the session that they were created for. - All session data, including session entities, is - stored by Dialogflow for 20 minutes. - - For more information, see the [session entity - guide](\ https://cloud.google.com/dialogflow/docs/entities-session). - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([session_entity_type, 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_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: - 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_session_entity_type, - 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(( - ("session_entity_type.name", request.session_entity_type.name), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def delete_session_entity_type(self, - request: Optional[Union[session_entity_type.DeleteSessionEntityTypeRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> None: - r"""Deletes the specified session entity type. - This method doesn't work with Google Assistant - integration. Contact Dialogflow support if you need to - use session entities with Google Assistant integration. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import dialogflow_v2beta1 - - async def sample_delete_session_entity_type(): - # Create a client - client = dialogflow_v2beta1.SessionEntityTypesAsyncClient() - - # Initialize request argument(s) - request = dialogflow_v2beta1.DeleteSessionEntityTypeRequest( - name="name_value", - ) - - # Make the request - await client.delete_session_entity_type(request=request) - - Args: - request (Optional[Union[google.cloud.dialogflow_v2beta1.types.DeleteSessionEntityTypeRequest, dict]]): - The request object. The request message for - [SessionEntityTypes.DeleteSessionEntityType][google.cloud.dialogflow.v2beta1.SessionEntityTypes.DeleteSessionEntityType]. - name (:class:`str`): - Required. The name of the entity type to delete. - Supported formats: - - - ``projects//agent/sessions//entityTypes/`` - - ``projects//locations//agent/sessions//entityTypes/`` - - ``projects//agent/environments//users//sessions//entityTypes/`` - - ``projects//locations//agent/environments/ /users//sessions//entityTypes/`` - - If ``Location ID`` is not specified we assume default - 'us' location. If ``Environment ID`` is not specified, - we assume default 'draft' environment. If ``User ID`` is - not specified, we assume default '-' user. - - 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. - # Quick 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 = 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 - - # 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_session_entity_type, - 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 list_operations( - self, - request: Optional[operations_pb2.ListOperationsRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operations_pb2.ListOperationsResponse: - r"""Lists operations that match the specified filter in the request. - - Args: - request (:class:`~.operations_pb2.ListOperationsRequest`): - The request object. Request message for - `ListOperations` method. - 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: - ~.operations_pb2.ListOperationsResponse: - Response message for ``ListOperations`` method. - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = operations_pb2.ListOperationsRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._client._transport.list_operations, - 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 get_operation( - self, - request: Optional[operations_pb2.GetOperationRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operations_pb2.Operation: - r"""Gets the latest state of a long-running operation. - - Args: - request (:class:`~.operations_pb2.GetOperationRequest`): - The request object. Request message for - `GetOperation` method. - 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: - ~.operations_pb2.Operation: - An ``Operation`` object. - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = operations_pb2.GetOperationRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._client._transport.get_operation, - 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 cancel_operation( - self, - request: Optional[operations_pb2.CancelOperationRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> None: - r"""Starts asynchronous cancellation on a long-running operation. - - The server makes a best effort to cancel the operation, but success - is not guaranteed. If the server doesn't support this method, it returns - `google.rpc.Code.UNIMPLEMENTED`. - - Args: - request (:class:`~.operations_pb2.CancelOperationRequest`): - The request object. Request message for - `CancelOperation` method. - 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: - None - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = operations_pb2.CancelOperationRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._client._transport.cancel_operation, - 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_location( - self, - request: Optional[locations_pb2.GetLocationRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> locations_pb2.Location: - r"""Gets information about a location. - - Args: - request (:class:`~.location_pb2.GetLocationRequest`): - The request object. Request message for - `GetLocation` method. - 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: - ~.location_pb2.Location: - Location object. - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = locations_pb2.GetLocationRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._client._transport.get_location, - 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 list_locations( - self, - request: Optional[locations_pb2.ListLocationsRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> locations_pb2.ListLocationsResponse: - r"""Lists information about the supported locations for this service. - - Args: - request (:class:`~.location_pb2.ListLocationsRequest`): - The request object. Request message for - `ListLocations` method. - 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: - ~.location_pb2.ListLocationsResponse: - Response message for ``ListLocations`` method. - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = locations_pb2.ListLocationsRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._client._transport.list_locations, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("name", request.name),)), - ) - - # Send the request. - response = await rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - async def __aenter__(self): - return self - - async def __aexit__(self, exc_type, exc, tb): - await self.transport.close() - -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) - - -__all__ = ( - "SessionEntityTypesAsyncClient", -) diff --git a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/session_entity_types/client.py b/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/session_entity_types/client.py deleted file mode 100644 index 0a6b77961..000000000 --- a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/session_entity_types/client.py +++ /dev/null @@ -1,1266 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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 os -import re -from typing import Dict, Mapping, MutableMapping, MutableSequence, Optional, Sequence, Tuple, Type, Union, cast - -from google.cloud.dialogflow_v2beta1 import gapic_version as package_version - -from google.api_core import client_options as client_options_lib -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import retry as retries -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 - -try: - OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] -except AttributeError: # pragma: NO COVER - OptionalRetry = Union[retries.Retry, object] # type: ignore - -from google.cloud.dialogflow_v2beta1.services.session_entity_types import pagers -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.cloud.location import locations_pb2 # type: ignore -from google.longrunning import operations_pb2 -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 -from .transports.rest import SessionEntityTypesRestTransport - - -class SessionEntityTypesClientMeta(type): - """Metaclass for the SessionEntityTypes 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[SessionEntityTypesTransport]] - _transport_registry["grpc"] = SessionEntityTypesGrpcTransport - _transport_registry["grpc_asyncio"] = SessionEntityTypesGrpcAsyncIOTransport - _transport_registry["rest"] = SessionEntityTypesRestTransport - - def get_transport_class(cls, - label: Optional[str] = None, - ) -> Type[SessionEntityTypesTransport]: - """Returns an appropriate transport class. - - Args: - label: The name of the desired transport. If none is - provided, then the first transport in the registry is used. - - Returns: - The transport class to use. - """ - # If a specific transport is requested, return that one. - if label: - return cls._transport_registry[label] - - # No transport is requested; return the default (that is, the first one - # in the dictionary). - return next(iter(cls._transport_registry.values())) - - -class SessionEntityTypesClient(metaclass=SessionEntityTypesClientMeta): - """Service for managing - [SessionEntityTypes][google.cloud.dialogflow.v2beta1.SessionEntityType]. - """ - - @staticmethod - def _get_default_mtls_endpoint(api_endpoint): - """Converts api endpoint to mTLS endpoint. - - Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to - "*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively. - Args: - api_endpoint (Optional[str]): the api endpoint to convert. - Returns: - str: converted mTLS api endpoint. - """ - if not api_endpoint: - return api_endpoint - - mtls_endpoint_re = re.compile( - r"(?P[^.]+)(?P\.mtls)?(?P\.sandbox)?(?P\.googleapis\.com)?" - ) - - m = mtls_endpoint_re.match(api_endpoint) - name, mtls, sandbox, googledomain = m.groups() - if mtls or not googledomain: - return api_endpoint - - if sandbox: - return api_endpoint.replace( - "sandbox.googleapis.com", "mtls.sandbox.googleapis.com" - ) - - return api_endpoint.replace(".googleapis.com", ".mtls.googleapis.com") - - DEFAULT_ENDPOINT = "dialogflow.googleapis.com" - DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore - DEFAULT_ENDPOINT - ) - - @classmethod - def from_service_account_info(cls, info: dict, *args, **kwargs): - """Creates an instance of this client using the provided credentials - info. - - Args: - info (dict): The service account private key info. - args: Additional arguments to pass to the constructor. - kwargs: Additional arguments to pass to the constructor. - - Returns: - SessionEntityTypesClient: 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: - SessionEntityTypesClient: 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) -> SessionEntityTypesTransport: - """Returns the transport used by the client instance. - - Returns: - SessionEntityTypesTransport: The transport used by the client - instance. - """ - return self._transport - - @staticmethod - def session_entity_type_path(project: str,session: str,entity_type: str,) -> str: - """Returns a fully-qualified session_entity_type string.""" - return "projects/{project}/agent/sessions/{session}/entityTypes/{entity_type}".format(project=project, session=session, entity_type=entity_type, ) - - @staticmethod - def parse_session_entity_type_path(path: str) -> Dict[str,str]: - """Parses a session_entity_type path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/agent/sessions/(?P.+?)/entityTypes/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_billing_account_path(billing_account: str, ) -> str: - """Returns a fully-qualified billing_account string.""" - return "billingAccounts/{billing_account}".format(billing_account=billing_account, ) - - @staticmethod - def parse_common_billing_account_path(path: str) -> Dict[str,str]: - """Parse a billing_account path into its component segments.""" - m = re.match(r"^billingAccounts/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_folder_path(folder: str, ) -> str: - """Returns a fully-qualified folder string.""" - return "folders/{folder}".format(folder=folder, ) - - @staticmethod - def parse_common_folder_path(path: str) -> Dict[str,str]: - """Parse a folder path into its component segments.""" - m = re.match(r"^folders/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_organization_path(organization: str, ) -> str: - """Returns a fully-qualified organization string.""" - return "organizations/{organization}".format(organization=organization, ) - - @staticmethod - def parse_common_organization_path(path: str) -> Dict[str,str]: - """Parse a organization path into its component segments.""" - m = re.match(r"^organizations/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_project_path(project: str, ) -> str: - """Returns a fully-qualified project string.""" - return "projects/{project}".format(project=project, ) - - @staticmethod - def parse_common_project_path(path: str) -> Dict[str,str]: - """Parse a project path into its component segments.""" - m = re.match(r"^projects/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_location_path(project: str, location: str, ) -> str: - """Returns a fully-qualified location string.""" - return "projects/{project}/locations/{location}".format(project=project, location=location, ) - - @staticmethod - def parse_common_location_path(path: str) -> Dict[str,str]: - """Parse a location path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)$", path) - return m.groupdict() if m else {} - - @classmethod - def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[client_options_lib.ClientOptions] = None): - """Return the API endpoint and client cert source for mutual TLS. - - The client cert source is determined in the following order: - (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the - client cert source is None. - (2) if `client_options.client_cert_source` is provided, use the provided one; if the - default client cert source exists, use the default one; otherwise the client cert - source is None. - - The API endpoint is determined in the following order: - (1) if `client_options.api_endpoint` if provided, use the provided one. - (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the - default mTLS endpoint; if the environment variable is "never", use the default API - endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise - use the default API endpoint. - - More details can be found at https://google.aip.dev/auth/4114. - - Args: - client_options (google.api_core.client_options.ClientOptions): Custom options for the - client. Only the `api_endpoint` and `client_cert_source` properties may be used - in this method. - - Returns: - Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the - client cert source to use. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If any errors happen. - """ - if client_options is None: - client_options = client_options_lib.ClientOptions() - use_client_cert = os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false") - use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") - if use_client_cert not in ("true", "false"): - raise ValueError("Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`") - if use_mtls_endpoint not in ("auto", "never", "always"): - raise MutualTLSChannelError("Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`") - - # Figure out the client cert source to use. - client_cert_source = None - if use_client_cert == "true": - if client_options.client_cert_source: - client_cert_source = client_options.client_cert_source - elif mtls.has_default_client_cert_source(): - client_cert_source = mtls.default_client_cert_source() - - # Figure out which api endpoint to use. - if client_options.api_endpoint is not None: - api_endpoint = client_options.api_endpoint - elif use_mtls_endpoint == "always" or (use_mtls_endpoint == "auto" and client_cert_source): - api_endpoint = cls.DEFAULT_MTLS_ENDPOINT - else: - api_endpoint = cls.DEFAULT_ENDPOINT - - return api_endpoint, client_cert_source - - def __init__(self, *, - credentials: Optional[ga_credentials.Credentials] = None, - transport: Optional[Union[str, SessionEntityTypesTransport]] = None, - client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the session entity types 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, SessionEntityTypesTransport]): The - transport to use. If set to None, a transport is chosen - automatically. - client_options (Optional[Union[google.api_core.client_options.ClientOptions, dict]]): 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() - client_options = cast(client_options_lib.ClientOptions, client_options) - - api_endpoint, client_cert_source_func = self.get_mtls_endpoint_and_cert_source(client_options) - - api_key_value = getattr(client_options, "api_key", None) - if api_key_value and credentials: - raise ValueError("client_options.api_key and credentials are mutually exclusive") - - # 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, SessionEntityTypesTransport): - # transport is a SessionEntityTypesTransport instance. - if credentials or client_options.credentials_file or api_key_value: - 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: - import google.auth._default # type: ignore - - if api_key_value and hasattr(google.auth._default, "get_api_key_credentials"): - credentials = google.auth._default.get_api_key_credentials(api_key_value) - - Transport = type(self).get_transport_class(transport) - self._transport = Transport( - credentials=credentials, - credentials_file=client_options.credentials_file, - host=api_endpoint, - scopes=client_options.scopes, - client_cert_source_for_mtls=client_cert_source_func, - quota_project_id=client_options.quota_project_id, - client_info=client_info, - always_use_jwt_access=True, - api_audience=client_options.api_audience, - ) - - def list_session_entity_types(self, - request: Optional[Union[session_entity_type.ListSessionEntityTypesRequest, dict]] = None, - *, - parent: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListSessionEntityTypesPager: - r"""Returns the list of all session entity types in the - specified session. - This method doesn't work with Google Assistant - integration. Contact Dialogflow support if you need to - use session entities with Google Assistant integration. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import dialogflow_v2beta1 - - def sample_list_session_entity_types(): - # Create a client - client = dialogflow_v2beta1.SessionEntityTypesClient() - - # Initialize request argument(s) - request = dialogflow_v2beta1.ListSessionEntityTypesRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_session_entity_types(request=request) - - # Handle the response - for response in page_result: - print(response) - - Args: - request (Union[google.cloud.dialogflow_v2beta1.types.ListSessionEntityTypesRequest, dict]): - The request object. The request message for - [SessionEntityTypes.ListSessionEntityTypes][google.cloud.dialogflow.v2beta1.SessionEntityTypes.ListSessionEntityTypes]. - parent (str): - Required. The session to list all session entity types - from. Supported formats: - - - \`projects//agent/sessions/, - - ``projects//locations//agent/sessions/``, - - ``projects//agent/environments//users//sessions/``, - - ``projects//locations//agent/environments//users//sessions/``, - - If ``Location ID`` is not specified we assume default - 'us' location. If ``Environment ID`` is not specified, - we assume default 'draft' environment. If ``User ID`` is - not specified, we assume default '-' user. - - 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.session_entity_types.pagers.ListSessionEntityTypesPager: - The response message for - [SessionEntityTypes.ListSessionEntityTypes][google.cloud.dialogflow.v2beta1.SessionEntityTypes.ListSessionEntityTypes]. - - Iterating over this object will yield results and - resolve additional pages automatically. - - """ - # Create or coerce a protobuf request object. - # Quick 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 session_entity_type.ListSessionEntityTypesRequest. - # There's no risk of modifying the input as we've already verified - # 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 - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.list_session_entity_types] - - # 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.ListSessionEntityTypesPager( - method=rpc, - request=request, - response=response, - metadata=metadata, - ) - - # Done; return the response. - return response - - def get_session_entity_type(self, - request: Optional[Union[session_entity_type.GetSessionEntityTypeRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> session_entity_type.SessionEntityType: - r"""Retrieves the specified session entity type. - This method doesn't work with Google Assistant - integration. Contact Dialogflow support if you need to - use session entities with Google Assistant integration. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import dialogflow_v2beta1 - - def sample_get_session_entity_type(): - # Create a client - client = dialogflow_v2beta1.SessionEntityTypesClient() - - # Initialize request argument(s) - request = dialogflow_v2beta1.GetSessionEntityTypeRequest( - name="name_value", - ) - - # Make the request - response = client.get_session_entity_type(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.dialogflow_v2beta1.types.GetSessionEntityTypeRequest, dict]): - The request object. The request message for - [SessionEntityTypes.GetSessionEntityType][google.cloud.dialogflow.v2beta1.SessionEntityTypes.GetSessionEntityType]. - name (str): - Required. The name of the session entity type. Supported - formats: - - - ``projects//agent/sessions//entityTypes/`` - - ``projects//locations//agent/sessions//entityTypes/`` - - ``projects//agent/environments//users//sessions//entityTypes/`` - - ``projects//locations//agent/environments/ /users//sessions//entityTypes/`` - - If ``Location ID`` is not specified we assume default - 'us' location. If ``Environment ID`` is not specified, - we assume default 'draft' environment. If ``User ID`` is - not specified, we assume default '-' user. - - 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.SessionEntityType: - A session represents a conversation between a Dialogflow agent and an - end-user. You can create special entities, called - session entities, during a session. Session entities - can extend or replace custom entity types and only - exist during the session that they were created for. - All session data, including session entities, is - stored by Dialogflow for 20 minutes. - - For more information, see the [session entity - guide](\ https://cloud.google.com/dialogflow/docs/entities-session). - - """ - # Create or coerce a protobuf request object. - # Quick 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 session_entity_type.GetSessionEntityTypeRequest. - # There's no risk of modifying the input as we've already verified - # 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 - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.get_session_entity_type] - - # 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_session_entity_type(self, - request: Optional[Union[gcd_session_entity_type.CreateSessionEntityTypeRequest, dict]] = None, - *, - parent: Optional[str] = None, - session_entity_type: Optional[gcd_session_entity_type.SessionEntityType] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gcd_session_entity_type.SessionEntityType: - r"""Creates a session entity type. - If the specified session entity type already exists, - overrides the session entity type. - - This method doesn't work with Google Assistant - integration. Contact Dialogflow support if you need to - use session entities with Google Assistant integration. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import dialogflow_v2beta1 - - def sample_create_session_entity_type(): - # Create a client - client = dialogflow_v2beta1.SessionEntityTypesClient() - - # Initialize request argument(s) - request = dialogflow_v2beta1.CreateSessionEntityTypeRequest( - parent="parent_value", - ) - - # Make the request - response = client.create_session_entity_type(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.dialogflow_v2beta1.types.CreateSessionEntityTypeRequest, dict]): - The request object. The request message for - [SessionEntityTypes.CreateSessionEntityType][google.cloud.dialogflow.v2beta1.SessionEntityTypes.CreateSessionEntityType]. - parent (str): - Required. The session to create a session entity type - for. Supported formats: - - - \`projects//agent/sessions/, - - ``projects//locations//agent/sessions/``, - - ``projects//agent/environments//users//sessions/``, - - ``projects//locations//agent/environments//users//sessions/``, - - If ``Location ID`` is not specified we assume default - 'us' location. If ``Environment ID`` is not specified, - we assume default 'draft' environment. If ``User ID`` is - not specified, we assume default '-' user. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - session_entity_type (google.cloud.dialogflow_v2beta1.types.SessionEntityType): - Required. The session entity type to - create. - - 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. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.dialogflow_v2beta1.types.SessionEntityType: - A session represents a conversation between a Dialogflow agent and an - end-user. You can create special entities, called - session entities, during a session. Session entities - can extend or replace custom entity types and only - exist during the session that they were created for. - All session data, including session entities, is - stored by Dialogflow for 20 minutes. - - For more information, see the [session entity - guide](\ https://cloud.google.com/dialogflow/docs/entities-session). - - """ - # Create or coerce a protobuf request object. - # Quick 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, session_entity_type]) - 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_session_entity_type.CreateSessionEntityTypeRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(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: - request.session_entity_type = session_entity_type - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.create_session_entity_type] - - # 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_session_entity_type(self, - request: Optional[Union[gcd_session_entity_type.UpdateSessionEntityTypeRequest, dict]] = None, - *, - session_entity_type: Optional[gcd_session_entity_type.SessionEntityType] = None, - update_mask: Optional[field_mask_pb2.FieldMask] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gcd_session_entity_type.SessionEntityType: - r"""Updates the specified session entity type. - This method doesn't work with Google Assistant - integration. Contact Dialogflow support if you need to - use session entities with Google Assistant integration. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import dialogflow_v2beta1 - - def sample_update_session_entity_type(): - # Create a client - client = dialogflow_v2beta1.SessionEntityTypesClient() - - # Initialize request argument(s) - request = dialogflow_v2beta1.UpdateSessionEntityTypeRequest( - ) - - # Make the request - response = client.update_session_entity_type(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.dialogflow_v2beta1.types.UpdateSessionEntityTypeRequest, dict]): - The request object. The request message for - [SessionEntityTypes.UpdateSessionEntityType][google.cloud.dialogflow.v2beta1.SessionEntityTypes.UpdateSessionEntityType]. - session_entity_type (google.cloud.dialogflow_v2beta1.types.SessionEntityType): - Required. The session entity type to - update. - - This corresponds to the ``session_entity_type`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - update_mask (google.protobuf.field_mask_pb2.FieldMask): - Optional. 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.SessionEntityType: - A session represents a conversation between a Dialogflow agent and an - end-user. You can create special entities, called - session entities, during a session. Session entities - can extend or replace custom entity types and only - exist during the session that they were created for. - All session data, including session entities, is - stored by Dialogflow for 20 minutes. - - For more information, see the [session entity - guide](\ https://cloud.google.com/dialogflow/docs/entities-session). - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([session_entity_type, 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_session_entity_type.UpdateSessionEntityTypeRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(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: - 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_session_entity_type] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("session_entity_type.name", request.session_entity_type.name), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def delete_session_entity_type(self, - request: Optional[Union[session_entity_type.DeleteSessionEntityTypeRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> None: - r"""Deletes the specified session entity type. - This method doesn't work with Google Assistant - integration. Contact Dialogflow support if you need to - use session entities with Google Assistant integration. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import dialogflow_v2beta1 - - def sample_delete_session_entity_type(): - # Create a client - client = dialogflow_v2beta1.SessionEntityTypesClient() - - # Initialize request argument(s) - request = dialogflow_v2beta1.DeleteSessionEntityTypeRequest( - name="name_value", - ) - - # Make the request - client.delete_session_entity_type(request=request) - - Args: - request (Union[google.cloud.dialogflow_v2beta1.types.DeleteSessionEntityTypeRequest, dict]): - The request object. The request message for - [SessionEntityTypes.DeleteSessionEntityType][google.cloud.dialogflow.v2beta1.SessionEntityTypes.DeleteSessionEntityType]. - name (str): - Required. The name of the entity type to delete. - Supported formats: - - - ``projects//agent/sessions//entityTypes/`` - - ``projects//locations//agent/sessions//entityTypes/`` - - ``projects//agent/environments//users//sessions//entityTypes/`` - - ``projects//locations//agent/environments/ /users//sessions//entityTypes/`` - - If ``Location ID`` is not specified we assume default - 'us' location. If ``Environment ID`` is not specified, - we assume default 'draft' environment. If ``User ID`` is - not specified, we assume default '-' user. - - 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. - # Quick 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 session_entity_type.DeleteSessionEntityTypeRequest. - # There's no risk of modifying the input as we've already verified - # 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 - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.delete_session_entity_type] - - # 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 __enter__(self) -> "SessionEntityTypesClient": - return self - - def __exit__(self, type, value, traceback): - """Releases underlying transport's resources. - - .. warning:: - ONLY use as a context manager if the transport is NOT shared - with other clients! Exiting the with block will CLOSE the transport - and may cause errors in other clients! - """ - self.transport.close() - - def list_operations( - self, - request: Optional[operations_pb2.ListOperationsRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operations_pb2.ListOperationsResponse: - r"""Lists operations that match the specified filter in the request. - - Args: - request (:class:`~.operations_pb2.ListOperationsRequest`): - The request object. Request message for - `ListOperations` method. - 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: - ~.operations_pb2.ListOperationsResponse: - Response message for ``ListOperations`` method. - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = operations_pb2.ListOperationsRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._transport.list_operations, - 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 = rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - def get_operation( - self, - request: Optional[operations_pb2.GetOperationRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operations_pb2.Operation: - r"""Gets the latest state of a long-running operation. - - Args: - request (:class:`~.operations_pb2.GetOperationRequest`): - The request object. Request message for - `GetOperation` method. - 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: - ~.operations_pb2.Operation: - An ``Operation`` object. - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = operations_pb2.GetOperationRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._transport.get_operation, - 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 = rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - def cancel_operation( - self, - request: Optional[operations_pb2.CancelOperationRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> None: - r"""Starts asynchronous cancellation on a long-running operation. - - The server makes a best effort to cancel the operation, but success - is not guaranteed. If the server doesn't support this method, it returns - `google.rpc.Code.UNIMPLEMENTED`. - - Args: - request (:class:`~.operations_pb2.CancelOperationRequest`): - The request object. Request message for - `CancelOperation` method. - 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: - None - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = operations_pb2.CancelOperationRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._transport.cancel_operation, - 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. - rpc(request, retry=retry, timeout=timeout, metadata=metadata,) - - def get_location( - self, - request: Optional[locations_pb2.GetLocationRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> locations_pb2.Location: - r"""Gets information about a location. - - Args: - request (:class:`~.location_pb2.GetLocationRequest`): - The request object. Request message for - `GetLocation` method. - 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: - ~.location_pb2.Location: - Location object. - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = locations_pb2.GetLocationRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._transport.get_location, - 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 = rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - def list_locations( - self, - request: Optional[locations_pb2.ListLocationsRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> locations_pb2.ListLocationsResponse: - r"""Lists information about the supported locations for this service. - - Args: - request (:class:`~.location_pb2.ListLocationsRequest`): - The request object. Request message for - `ListLocations` method. - 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: - ~.location_pb2.ListLocationsResponse: - Response message for ``ListLocations`` method. - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = locations_pb2.ListLocationsRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._transport.list_locations, - 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 = rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) - - -__all__ = ( - "SessionEntityTypesClient", -) diff --git a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/session_entity_types/pagers.py b/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/session_entity_types/pagers.py deleted file mode 100644 index daa945bb3..000000000 --- a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/session_entity_types/pagers.py +++ /dev/null @@ -1,139 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from typing import Any, AsyncIterator, Awaitable, Callable, Sequence, Tuple, Optional, Iterator - -from google.cloud.dialogflow_v2beta1.types import session_entity_type - - -class ListSessionEntityTypesPager: - """A pager for iterating through ``list_session_entity_types`` requests. - - This class thinly wraps an initial - :class:`google.cloud.dialogflow_v2beta1.types.ListSessionEntityTypesResponse` object, and - provides an ``__iter__`` method to iterate through its - ``session_entity_types`` field. - - If there are more pages, the ``__iter__`` method will make additional - ``ListSessionEntityTypes`` requests and continue to iterate - through the ``session_entity_types`` field on the - corresponding responses. - - All the usual :class:`google.cloud.dialogflow_v2beta1.types.ListSessionEntityTypesResponse` - 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[..., session_entity_type.ListSessionEntityTypesResponse], - request: session_entity_type.ListSessionEntityTypesRequest, - response: session_entity_type.ListSessionEntityTypesResponse, - *, - 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.ListSessionEntityTypesRequest): - The initial request object. - response (google.cloud.dialogflow_v2beta1.types.ListSessionEntityTypesResponse): - 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 = session_entity_type.ListSessionEntityTypesRequest(request) - self._response = response - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - def pages(self) -> Iterator[session_entity_type.ListSessionEntityTypesResponse]: - yield self._response - while self._response.next_page_token: - self._request.page_token = self._response.next_page_token - self._response = self._method(self._request, metadata=self._metadata) - yield self._response - - def __iter__(self) -> Iterator[session_entity_type.SessionEntityType]: - for page in self.pages: - yield from page.session_entity_types - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListSessionEntityTypesAsyncPager: - """A pager for iterating through ``list_session_entity_types`` requests. - - This class thinly wraps an initial - :class:`google.cloud.dialogflow_v2beta1.types.ListSessionEntityTypesResponse` object, and - provides an ``__aiter__`` method to iterate through its - ``session_entity_types`` field. - - If there are more pages, the ``__aiter__`` method will make additional - ``ListSessionEntityTypes`` requests and continue to iterate - through the ``session_entity_types`` field on the - corresponding responses. - - All the usual :class:`google.cloud.dialogflow_v2beta1.types.ListSessionEntityTypesResponse` - 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[session_entity_type.ListSessionEntityTypesResponse]], - request: session_entity_type.ListSessionEntityTypesRequest, - response: session_entity_type.ListSessionEntityTypesResponse, - *, - metadata: Sequence[Tuple[str, str]] = ()): - """Instantiates the pager. - - Args: - method (Callable): The method that was originally called, and - which instantiated this pager. - request (google.cloud.dialogflow_v2beta1.types.ListSessionEntityTypesRequest): - The initial request object. - response (google.cloud.dialogflow_v2beta1.types.ListSessionEntityTypesResponse): - 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 = session_entity_type.ListSessionEntityTypesRequest(request) - self._response = response - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - async def pages(self) -> AsyncIterator[session_entity_type.ListSessionEntityTypesResponse]: - yield self._response - while self._response.next_page_token: - self._request.page_token = self._response.next_page_token - self._response = await self._method(self._request, metadata=self._metadata) - yield self._response - def __aiter__(self) -> AsyncIterator[session_entity_type.SessionEntityType]: - async def async_generator(): - async for page in self.pages: - for response in page.session_entity_types: - yield response - - return async_generator() - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) diff --git a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/session_entity_types/transports/__init__.py b/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/session_entity_types/transports/__init__.py deleted file mode 100644 index 6971010ce..000000000 --- a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/session_entity_types/transports/__init__.py +++ /dev/null @@ -1,38 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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 SessionEntityTypesTransport -from .grpc import SessionEntityTypesGrpcTransport -from .grpc_asyncio import SessionEntityTypesGrpcAsyncIOTransport -from .rest import SessionEntityTypesRestTransport -from .rest import SessionEntityTypesRestInterceptor - - -# Compile a registry of transports. -_transport_registry = OrderedDict() # type: Dict[str, Type[SessionEntityTypesTransport]] -_transport_registry['grpc'] = SessionEntityTypesGrpcTransport -_transport_registry['grpc_asyncio'] = SessionEntityTypesGrpcAsyncIOTransport -_transport_registry['rest'] = SessionEntityTypesRestTransport - -__all__ = ( - 'SessionEntityTypesTransport', - 'SessionEntityTypesGrpcTransport', - 'SessionEntityTypesGrpcAsyncIOTransport', - 'SessionEntityTypesRestTransport', - 'SessionEntityTypesRestInterceptor', -) diff --git a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/session_entity_types/transports/base.py b/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/session_entity_types/transports/base.py deleted file mode 100644 index ccc4bf267..000000000 --- a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/session_entity_types/transports/base.py +++ /dev/null @@ -1,252 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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 - -from google.cloud.dialogflow_v2beta1 import gapic_version as package_version - -import google.auth # type: ignore -import google.api_core -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import retry as retries -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 session_entity_type -from google.cloud.dialogflow_v2beta1.types import session_entity_type as gcd_session_entity_type -from google.cloud.location import locations_pb2 # type: ignore -from google.longrunning import operations_pb2 -from google.protobuf import empty_pb2 # type: ignore - -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) - - -class SessionEntityTypesTransport(abc.ABC): - """Abstract transport class for SessionEntityTypes.""" - - 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: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - api_audience: Optional[str] = None, - **kwargs, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. - scopes (Optional[Sequence[str]]): A list of scopes. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - """ - - scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} - - # Save the scopes. - self._scopes = scopes - - # If no credentials are provided, then determine the appropriate - # defaults. - if credentials and credentials_file: - raise core_exceptions.DuplicateCredentialArgs("'credentials_file' and 'credentials' are mutually exclusive") - - if credentials_file is not None: - credentials, _ = google.auth.load_credentials_from_file( - credentials_file, - **scopes_kwargs, - quota_project_id=quota_project_id - ) - elif credentials is None: - credentials, _ = google.auth.default(**scopes_kwargs, quota_project_id=quota_project_id) - # Don't apply audience if the credentials file passed from user. - if hasattr(credentials, "with_gdch_audience"): - credentials = credentials.with_gdch_audience(api_audience if api_audience else host) - - # If the credentials are service account credentials, then always try to use self signed JWT. - if always_use_jwt_access and isinstance(credentials, service_account.Credentials) and hasattr(service_account.Credentials, "with_always_use_jwt_access"): - credentials = credentials.with_always_use_jwt_access(True) - - # Save the credentials. - self._credentials = credentials - - # Save the hostname. Default to port 443 (HTTPS) if none is specified. - if ':' not in host: - host += ':443' - self._host = host - - def _prep_wrapped_messages(self, client_info): - # Precompute the wrapped methods. - self._wrapped_methods = { - self.list_session_entity_types: gapic_v1.method.wrap_method( - self.list_session_entity_types, - default_timeout=None, - client_info=client_info, - ), - self.get_session_entity_type: gapic_v1.method.wrap_method( - self.get_session_entity_type, - default_timeout=None, - client_info=client_info, - ), - self.create_session_entity_type: gapic_v1.method.wrap_method( - self.create_session_entity_type, - default_timeout=None, - client_info=client_info, - ), - self.update_session_entity_type: gapic_v1.method.wrap_method( - self.update_session_entity_type, - default_timeout=None, - client_info=client_info, - ), - self.delete_session_entity_type: gapic_v1.method.wrap_method( - self.delete_session_entity_type, - default_timeout=None, - client_info=client_info, - ), - } - - def close(self): - """Closes resources associated with the transport. - - .. warning:: - Only call this method if the transport is NOT shared - with other clients - this may cause errors in other clients! - """ - raise NotImplementedError() - - @property - def list_session_entity_types(self) -> Callable[ - [session_entity_type.ListSessionEntityTypesRequest], - Union[ - session_entity_type.ListSessionEntityTypesResponse, - Awaitable[session_entity_type.ListSessionEntityTypesResponse] - ]]: - raise NotImplementedError() - - @property - def get_session_entity_type(self) -> Callable[ - [session_entity_type.GetSessionEntityTypeRequest], - Union[ - session_entity_type.SessionEntityType, - Awaitable[session_entity_type.SessionEntityType] - ]]: - raise NotImplementedError() - - @property - def create_session_entity_type(self) -> Callable[ - [gcd_session_entity_type.CreateSessionEntityTypeRequest], - Union[ - gcd_session_entity_type.SessionEntityType, - Awaitable[gcd_session_entity_type.SessionEntityType] - ]]: - raise NotImplementedError() - - @property - def update_session_entity_type(self) -> Callable[ - [gcd_session_entity_type.UpdateSessionEntityTypeRequest], - Union[ - gcd_session_entity_type.SessionEntityType, - Awaitable[gcd_session_entity_type.SessionEntityType] - ]]: - raise NotImplementedError() - - @property - def delete_session_entity_type(self) -> Callable[ - [session_entity_type.DeleteSessionEntityTypeRequest], - Union[ - empty_pb2.Empty, - Awaitable[empty_pb2.Empty] - ]]: - raise NotImplementedError() - - @property - def list_operations( - self, - ) -> Callable[ - [operations_pb2.ListOperationsRequest], - Union[operations_pb2.ListOperationsResponse, Awaitable[operations_pb2.ListOperationsResponse]], - ]: - raise NotImplementedError() - - @property - def get_operation( - self, - ) -> Callable[ - [operations_pb2.GetOperationRequest], - Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], - ]: - raise NotImplementedError() - - @property - def cancel_operation( - self, - ) -> Callable[ - [operations_pb2.CancelOperationRequest], - None, - ]: - raise NotImplementedError() - - @property - def get_location(self, - ) -> Callable[ - [locations_pb2.GetLocationRequest], - Union[locations_pb2.Location, Awaitable[locations_pb2.Location]], - ]: - raise NotImplementedError() - - @property - def list_locations(self, - ) -> Callable[ - [locations_pb2.ListLocationsRequest], - Union[locations_pb2.ListLocationsResponse, Awaitable[locations_pb2.ListLocationsResponse]], - ]: - raise NotImplementedError() - - @property - def kind(self) -> str: - raise NotImplementedError() - - -__all__ = ( - 'SessionEntityTypesTransport', -) diff --git a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/session_entity_types/transports/grpc.py b/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/session_entity_types/transports/grpc.py deleted file mode 100644 index 0ffa44a5f..000000000 --- a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/session_entity_types/transports/grpc.py +++ /dev/null @@ -1,482 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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 -from google.api_core import gapic_v1 -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_entity_type -from google.cloud.dialogflow_v2beta1.types import session_entity_type as gcd_session_entity_type -from google.cloud.location import locations_pb2 # type: ignore -from google.longrunning import operations_pb2 -from google.protobuf import empty_pb2 # type: ignore -from .base import SessionEntityTypesTransport, DEFAULT_CLIENT_INFO - - -class SessionEntityTypesGrpcTransport(SessionEntityTypesTransport): - """gRPC backend transport for SessionEntityTypes. - - Service for managing - [SessionEntityTypes][google.cloud.dialogflow.v2beta1.SessionEntityType]. - - 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: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - channel: Optional[grpc.Channel] = None, - api_mtls_endpoint: Optional[str] = None, - client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, - ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, - client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - api_audience: Optional[str] = None, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - This argument is ignored if ``channel`` is provided. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional(Sequence[str])): A list of scopes. This argument is - ignored if ``channel`` is provided. - channel (Optional[grpc.Channel]): A ``Channel`` instance through - which to make calls. - api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. - If provided, it overrides the ``host`` argument and tries to create - a mutual TLS channel with client SSL credentials from - ``client_cert_source`` or application default SSL credentials. - client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): - Deprecated. A callback to provide client SSL certificate bytes and - private key bytes, both in PEM format. It is ignored if - ``api_mtls_endpoint`` is None. - ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials - for the grpc channel. It is ignored if ``channel`` is provided. - client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): - A callback to provide client certificate bytes and private key bytes, - both in PEM format. It is used to configure a mutual TLS channel. It is - ignored if ``channel`` or ``ssl_channel_credentials`` is provided. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport - creation failed for any reason. - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - self._grpc_channel = None - self._ssl_channel_credentials = ssl_channel_credentials - self._stubs: Dict[str, Callable] = {} - - if api_mtls_endpoint: - warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) - if client_cert_source: - warnings.warn("client_cert_source is deprecated", DeprecationWarning) - - if channel: - # Ignore credentials if a channel was passed. - credentials = False - # If a channel was explicitly provided, set it. - self._grpc_channel = channel - self._ssl_channel_credentials = None - - else: - if api_mtls_endpoint: - host = api_mtls_endpoint - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - self._ssl_channel_credentials = SslCredentials().ssl_credentials - - else: - if client_cert_source_for_mtls and not ssl_channel_credentials: - cert, key = client_cert_source_for_mtls() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - - # The base transport sets the host, credentials and scopes - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes, - quota_project_id=quota_project_id, - client_info=client_info, - always_use_jwt_access=always_use_jwt_access, - api_audience=api_audience, - ) - - if not self._grpc_channel: - self._grpc_channel = type(self).create_channel( - self._host, - # use the credentials which are saved - credentials=self._credentials, - # Set ``credentials_file`` to ``None`` here as - # the credentials that we saved earlier should be used. - credentials_file=None, - 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: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - **kwargs) -> grpc.Channel: - """Create and return a gRPC channel object. - Args: - host (Optional[str]): The host for the channel to use. - credentials (Optional[~.Credentials]): The - authorization credentials to attach to requests. These - credentials identify this application to the service. If - none are specified, the client will attempt to ascertain - the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - kwargs (Optional[dict]): Keyword arguments, which are passed to the - channel creation. - Returns: - grpc.Channel: A gRPC channel object. - - Raises: - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - - return grpc_helpers.create_channel( - host, - credentials=credentials, - credentials_file=credentials_file, - quota_project_id=quota_project_id, - default_scopes=cls.AUTH_SCOPES, - scopes=scopes, - default_host=cls.DEFAULT_HOST, - **kwargs - ) - - @property - def grpc_channel(self) -> grpc.Channel: - """Return the channel designed to connect to this service. - """ - return self._grpc_channel - - @property - def list_session_entity_types(self) -> Callable[ - [session_entity_type.ListSessionEntityTypesRequest], - session_entity_type.ListSessionEntityTypesResponse]: - r"""Return a callable for the list session entity types method over gRPC. - - Returns the list of all session entity types in the - specified session. - This method doesn't work with Google Assistant - integration. Contact Dialogflow support if you need to - use session entities with Google Assistant integration. - - Returns: - Callable[[~.ListSessionEntityTypesRequest], - ~.ListSessionEntityTypesResponse]: - 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_session_entity_types' not in self._stubs: - self._stubs['list_session_entity_types'] = self.grpc_channel.unary_unary( - '/google.cloud.dialogflow.v2beta1.SessionEntityTypes/ListSessionEntityTypes', - request_serializer=session_entity_type.ListSessionEntityTypesRequest.serialize, - response_deserializer=session_entity_type.ListSessionEntityTypesResponse.deserialize, - ) - return self._stubs['list_session_entity_types'] - - @property - def get_session_entity_type(self) -> Callable[ - [session_entity_type.GetSessionEntityTypeRequest], - session_entity_type.SessionEntityType]: - r"""Return a callable for the get session entity type method over gRPC. - - Retrieves the specified session entity type. - This method doesn't work with Google Assistant - integration. Contact Dialogflow support if you need to - use session entities with Google Assistant integration. - - Returns: - Callable[[~.GetSessionEntityTypeRequest], - ~.SessionEntityType]: - 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_session_entity_type' not in self._stubs: - self._stubs['get_session_entity_type'] = self.grpc_channel.unary_unary( - '/google.cloud.dialogflow.v2beta1.SessionEntityTypes/GetSessionEntityType', - request_serializer=session_entity_type.GetSessionEntityTypeRequest.serialize, - response_deserializer=session_entity_type.SessionEntityType.deserialize, - ) - return self._stubs['get_session_entity_type'] - - @property - def create_session_entity_type(self) -> Callable[ - [gcd_session_entity_type.CreateSessionEntityTypeRequest], - gcd_session_entity_type.SessionEntityType]: - r"""Return a callable for the create session entity type method over gRPC. - - Creates a session entity type. - If the specified session entity type already exists, - overrides the session entity type. - - This method doesn't work with Google Assistant - integration. Contact Dialogflow support if you need to - use session entities with Google Assistant integration. - - Returns: - Callable[[~.CreateSessionEntityTypeRequest], - ~.SessionEntityType]: - 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_session_entity_type' not in self._stubs: - self._stubs['create_session_entity_type'] = self.grpc_channel.unary_unary( - '/google.cloud.dialogflow.v2beta1.SessionEntityTypes/CreateSessionEntityType', - request_serializer=gcd_session_entity_type.CreateSessionEntityTypeRequest.serialize, - response_deserializer=gcd_session_entity_type.SessionEntityType.deserialize, - ) - return self._stubs['create_session_entity_type'] - - @property - def update_session_entity_type(self) -> Callable[ - [gcd_session_entity_type.UpdateSessionEntityTypeRequest], - gcd_session_entity_type.SessionEntityType]: - r"""Return a callable for the update session entity type method over gRPC. - - Updates the specified session entity type. - This method doesn't work with Google Assistant - integration. Contact Dialogflow support if you need to - use session entities with Google Assistant integration. - - Returns: - Callable[[~.UpdateSessionEntityTypeRequest], - ~.SessionEntityType]: - 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_session_entity_type' not in self._stubs: - self._stubs['update_session_entity_type'] = self.grpc_channel.unary_unary( - '/google.cloud.dialogflow.v2beta1.SessionEntityTypes/UpdateSessionEntityType', - request_serializer=gcd_session_entity_type.UpdateSessionEntityTypeRequest.serialize, - response_deserializer=gcd_session_entity_type.SessionEntityType.deserialize, - ) - return self._stubs['update_session_entity_type'] - - @property - def delete_session_entity_type(self) -> 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. - This method doesn't work with Google Assistant - integration. Contact Dialogflow support if you need to - use session entities with Google Assistant integration. - - Returns: - Callable[[~.DeleteSessionEntityTypeRequest], - ~.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_session_entity_type' not in self._stubs: - 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_pb2.Empty.FromString, - ) - return self._stubs['delete_session_entity_type'] - - def close(self): - self.grpc_channel.close() - - @property - def cancel_operation( - self, - ) -> Callable[[operations_pb2.CancelOperationRequest], None]: - r"""Return a callable for the cancel_operation method over gRPC. - """ - # 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 "cancel_operation" not in self._stubs: - self._stubs["cancel_operation"] = self.grpc_channel.unary_unary( - "/google.longrunning.Operations/CancelOperation", - request_serializer=operations_pb2.CancelOperationRequest.SerializeToString, - response_deserializer=None, - ) - return self._stubs["cancel_operation"] - - @property - def get_operation( - self, - ) -> Callable[[operations_pb2.GetOperationRequest], operations_pb2.Operation]: - r"""Return a callable for the get_operation method over gRPC. - """ - # 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_operation" not in self._stubs: - self._stubs["get_operation"] = self.grpc_channel.unary_unary( - "/google.longrunning.Operations/GetOperation", - request_serializer=operations_pb2.GetOperationRequest.SerializeToString, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs["get_operation"] - - @property - def list_operations( - self, - ) -> Callable[[operations_pb2.ListOperationsRequest], operations_pb2.ListOperationsResponse]: - r"""Return a callable for the list_operations method over gRPC. - """ - # 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_operations" not in self._stubs: - self._stubs["list_operations"] = self.grpc_channel.unary_unary( - "/google.longrunning.Operations/ListOperations", - request_serializer=operations_pb2.ListOperationsRequest.SerializeToString, - response_deserializer=operations_pb2.ListOperationsResponse.FromString, - ) - return self._stubs["list_operations"] - - @property - def list_locations( - self, - ) -> Callable[[locations_pb2.ListLocationsRequest], locations_pb2.ListLocationsResponse]: - r"""Return a callable for the list locations method over gRPC. - """ - # 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_locations" not in self._stubs: - self._stubs["list_locations"] = self.grpc_channel.unary_unary( - "/google.cloud.location.Locations/ListLocations", - request_serializer=locations_pb2.ListLocationsRequest.SerializeToString, - response_deserializer=locations_pb2.ListLocationsResponse.FromString, - ) - return self._stubs["list_locations"] - - @property - def get_location( - self, - ) -> Callable[[locations_pb2.GetLocationRequest], locations_pb2.Location]: - r"""Return a callable for the list locations method over gRPC. - """ - # 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_location" not in self._stubs: - self._stubs["get_location"] = self.grpc_channel.unary_unary( - "/google.cloud.location.Locations/GetLocation", - request_serializer=locations_pb2.GetLocationRequest.SerializeToString, - response_deserializer=locations_pb2.Location.FromString, - ) - return self._stubs["get_location"] - - @property - def kind(self) -> str: - return "grpc" - - -__all__ = ( - 'SessionEntityTypesGrpcTransport', -) diff --git a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/session_entity_types/transports/grpc_asyncio.py b/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/session_entity_types/transports/grpc_asyncio.py deleted file mode 100644 index 7564e2405..000000000 --- a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/session_entity_types/transports/grpc_asyncio.py +++ /dev/null @@ -1,481 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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 -from google.api_core import grpc_helpers_async -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore - -import grpc # type: ignore -from grpc.experimental import aio # type: ignore - -from google.cloud.dialogflow_v2beta1.types import session_entity_type -from google.cloud.dialogflow_v2beta1.types import session_entity_type as gcd_session_entity_type -from google.cloud.location import locations_pb2 # type: ignore -from google.longrunning import operations_pb2 -from google.protobuf import empty_pb2 # type: ignore -from .base import SessionEntityTypesTransport, DEFAULT_CLIENT_INFO -from .grpc import SessionEntityTypesGrpcTransport - - -class SessionEntityTypesGrpcAsyncIOTransport(SessionEntityTypesTransport): - """gRPC AsyncIO backend transport for SessionEntityTypes. - - Service for managing - [SessionEntityTypes][google.cloud.dialogflow.v2beta1.SessionEntityType]. - - 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: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - **kwargs) -> aio.Channel: - """Create and return a gRPC AsyncIO channel object. - Args: - host (Optional[str]): The host for the channel to use. - credentials (Optional[~.Credentials]): The - authorization credentials to attach to requests. These - credentials identify this application to the service. If - none are specified, the client will attempt to ascertain - the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - kwargs (Optional[dict]): Keyword arguments, which are passed to the - channel creation. - Returns: - aio.Channel: A gRPC AsyncIO channel object. - """ - - return grpc_helpers_async.create_channel( - host, - credentials=credentials, - credentials_file=credentials_file, - quota_project_id=quota_project_id, - default_scopes=cls.AUTH_SCOPES, - scopes=scopes, - default_host=cls.DEFAULT_HOST, - **kwargs - ) - - def __init__(self, *, - host: str = 'dialogflow.googleapis.com', - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - channel: Optional[aio.Channel] = None, - api_mtls_endpoint: Optional[str] = None, - client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, - ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, - client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - api_audience: Optional[str] = None, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - This argument is ignored if ``channel`` is provided. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - channel (Optional[aio.Channel]): A ``Channel`` instance through - which to make calls. - api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. - If provided, it overrides the ``host`` argument and tries to create - a mutual TLS channel with client SSL credentials from - ``client_cert_source`` or application default SSL credentials. - client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): - Deprecated. A callback to provide client SSL certificate bytes and - private key bytes, both in PEM format. It is ignored if - ``api_mtls_endpoint`` is None. - ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials - for the grpc channel. It is ignored if ``channel`` is provided. - client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): - A callback to provide client certificate bytes and private key bytes, - both in PEM format. It is used to configure a mutual TLS channel. It is - ignored if ``channel`` or ``ssl_channel_credentials`` is provided. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - - Raises: - google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport - creation failed for any reason. - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - self._grpc_channel = None - self._ssl_channel_credentials = ssl_channel_credentials - self._stubs: Dict[str, Callable] = {} - - if api_mtls_endpoint: - warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) - if client_cert_source: - warnings.warn("client_cert_source is deprecated", DeprecationWarning) - - if channel: - # Ignore credentials if a channel was passed. - credentials = False - # If a channel was explicitly provided, set it. - self._grpc_channel = channel - self._ssl_channel_credentials = None - else: - if api_mtls_endpoint: - host = api_mtls_endpoint - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - self._ssl_channel_credentials = SslCredentials().ssl_credentials - - else: - if client_cert_source_for_mtls and not ssl_channel_credentials: - cert, key = client_cert_source_for_mtls() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - - # The base transport sets the host, credentials and scopes - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes, - quota_project_id=quota_project_id, - client_info=client_info, - always_use_jwt_access=always_use_jwt_access, - api_audience=api_audience, - ) - - if not self._grpc_channel: - self._grpc_channel = type(self).create_channel( - self._host, - # use the credentials which are saved - credentials=self._credentials, - # Set ``credentials_file`` to ``None`` here as - # the credentials that we saved earlier should be used. - credentials_file=None, - 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_session_entity_types(self) -> Callable[ - [session_entity_type.ListSessionEntityTypesRequest], - Awaitable[session_entity_type.ListSessionEntityTypesResponse]]: - r"""Return a callable for the list session entity types method over gRPC. - - Returns the list of all session entity types in the - specified session. - This method doesn't work with Google Assistant - integration. Contact Dialogflow support if you need to - use session entities with Google Assistant integration. - - Returns: - Callable[[~.ListSessionEntityTypesRequest], - Awaitable[~.ListSessionEntityTypesResponse]]: - 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_session_entity_types' not in self._stubs: - self._stubs['list_session_entity_types'] = self.grpc_channel.unary_unary( - '/google.cloud.dialogflow.v2beta1.SessionEntityTypes/ListSessionEntityTypes', - request_serializer=session_entity_type.ListSessionEntityTypesRequest.serialize, - response_deserializer=session_entity_type.ListSessionEntityTypesResponse.deserialize, - ) - return self._stubs['list_session_entity_types'] - - @property - def get_session_entity_type(self) -> Callable[ - [session_entity_type.GetSessionEntityTypeRequest], - Awaitable[session_entity_type.SessionEntityType]]: - r"""Return a callable for the get session entity type method over gRPC. - - Retrieves the specified session entity type. - This method doesn't work with Google Assistant - integration. Contact Dialogflow support if you need to - use session entities with Google Assistant integration. - - Returns: - Callable[[~.GetSessionEntityTypeRequest], - Awaitable[~.SessionEntityType]]: - 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_session_entity_type' not in self._stubs: - self._stubs['get_session_entity_type'] = self.grpc_channel.unary_unary( - '/google.cloud.dialogflow.v2beta1.SessionEntityTypes/GetSessionEntityType', - request_serializer=session_entity_type.GetSessionEntityTypeRequest.serialize, - response_deserializer=session_entity_type.SessionEntityType.deserialize, - ) - return self._stubs['get_session_entity_type'] - - @property - def create_session_entity_type(self) -> Callable[ - [gcd_session_entity_type.CreateSessionEntityTypeRequest], - Awaitable[gcd_session_entity_type.SessionEntityType]]: - r"""Return a callable for the create session entity type method over gRPC. - - Creates a session entity type. - If the specified session entity type already exists, - overrides the session entity type. - - This method doesn't work with Google Assistant - integration. Contact Dialogflow support if you need to - use session entities with Google Assistant integration. - - Returns: - Callable[[~.CreateSessionEntityTypeRequest], - Awaitable[~.SessionEntityType]]: - 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_session_entity_type' not in self._stubs: - self._stubs['create_session_entity_type'] = self.grpc_channel.unary_unary( - '/google.cloud.dialogflow.v2beta1.SessionEntityTypes/CreateSessionEntityType', - request_serializer=gcd_session_entity_type.CreateSessionEntityTypeRequest.serialize, - response_deserializer=gcd_session_entity_type.SessionEntityType.deserialize, - ) - return self._stubs['create_session_entity_type'] - - @property - def update_session_entity_type(self) -> Callable[ - [gcd_session_entity_type.UpdateSessionEntityTypeRequest], - Awaitable[gcd_session_entity_type.SessionEntityType]]: - r"""Return a callable for the update session entity type method over gRPC. - - Updates the specified session entity type. - This method doesn't work with Google Assistant - integration. Contact Dialogflow support if you need to - use session entities with Google Assistant integration. - - Returns: - Callable[[~.UpdateSessionEntityTypeRequest], - Awaitable[~.SessionEntityType]]: - 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_session_entity_type' not in self._stubs: - self._stubs['update_session_entity_type'] = self.grpc_channel.unary_unary( - '/google.cloud.dialogflow.v2beta1.SessionEntityTypes/UpdateSessionEntityType', - request_serializer=gcd_session_entity_type.UpdateSessionEntityTypeRequest.serialize, - response_deserializer=gcd_session_entity_type.SessionEntityType.deserialize, - ) - return self._stubs['update_session_entity_type'] - - @property - def delete_session_entity_type(self) -> Callable[ - [session_entity_type.DeleteSessionEntityTypeRequest], - Awaitable[empty_pb2.Empty]]: - r"""Return a callable for the delete session entity type method over gRPC. - - Deletes the specified session entity type. - This method doesn't work with Google Assistant - integration. Contact Dialogflow support if you need to - use session entities with Google Assistant integration. - - Returns: - Callable[[~.DeleteSessionEntityTypeRequest], - 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_session_entity_type' not in self._stubs: - 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_pb2.Empty.FromString, - ) - return self._stubs['delete_session_entity_type'] - - def close(self): - return self.grpc_channel.close() - - @property - def cancel_operation( - self, - ) -> Callable[[operations_pb2.CancelOperationRequest], None]: - r"""Return a callable for the cancel_operation method over gRPC. - """ - # 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 "cancel_operation" not in self._stubs: - self._stubs["cancel_operation"] = self.grpc_channel.unary_unary( - "/google.longrunning.Operations/CancelOperation", - request_serializer=operations_pb2.CancelOperationRequest.SerializeToString, - response_deserializer=None, - ) - return self._stubs["cancel_operation"] - - @property - def get_operation( - self, - ) -> Callable[[operations_pb2.GetOperationRequest], operations_pb2.Operation]: - r"""Return a callable for the get_operation method over gRPC. - """ - # 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_operation" not in self._stubs: - self._stubs["get_operation"] = self.grpc_channel.unary_unary( - "/google.longrunning.Operations/GetOperation", - request_serializer=operations_pb2.GetOperationRequest.SerializeToString, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs["get_operation"] - - @property - def list_operations( - self, - ) -> Callable[[operations_pb2.ListOperationsRequest], operations_pb2.ListOperationsResponse]: - r"""Return a callable for the list_operations method over gRPC. - """ - # 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_operations" not in self._stubs: - self._stubs["list_operations"] = self.grpc_channel.unary_unary( - "/google.longrunning.Operations/ListOperations", - request_serializer=operations_pb2.ListOperationsRequest.SerializeToString, - response_deserializer=operations_pb2.ListOperationsResponse.FromString, - ) - return self._stubs["list_operations"] - - @property - def list_locations( - self, - ) -> Callable[[locations_pb2.ListLocationsRequest], locations_pb2.ListLocationsResponse]: - r"""Return a callable for the list locations method over gRPC. - """ - # 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_locations" not in self._stubs: - self._stubs["list_locations"] = self.grpc_channel.unary_unary( - "/google.cloud.location.Locations/ListLocations", - request_serializer=locations_pb2.ListLocationsRequest.SerializeToString, - response_deserializer=locations_pb2.ListLocationsResponse.FromString, - ) - return self._stubs["list_locations"] - - @property - def get_location( - self, - ) -> Callable[[locations_pb2.GetLocationRequest], locations_pb2.Location]: - r"""Return a callable for the list locations method over gRPC. - """ - # 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_location" not in self._stubs: - self._stubs["get_location"] = self.grpc_channel.unary_unary( - "/google.cloud.location.Locations/GetLocation", - request_serializer=locations_pb2.GetLocationRequest.SerializeToString, - response_deserializer=locations_pb2.Location.FromString, - ) - return self._stubs["get_location"] - - -__all__ = ( - 'SessionEntityTypesGrpcAsyncIOTransport', -) diff --git a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/session_entity_types/transports/rest.py b/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/session_entity_types/transports/rest.py deleted file mode 100644 index 3d97acd53..000000000 --- a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/session_entity_types/transports/rest.py +++ /dev/null @@ -1,1265 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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 google.auth.transport.requests import AuthorizedSession # type: ignore -import json # type: ignore -import grpc # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore -from google.auth import credentials as ga_credentials # type: ignore -from google.api_core import exceptions as core_exceptions -from google.api_core import retry as retries -from google.api_core import rest_helpers -from google.api_core import rest_streaming -from google.api_core import path_template -from google.api_core import gapic_v1 - -from google.protobuf import json_format -from google.cloud.location import locations_pb2 # type: ignore -from google.longrunning import operations_pb2 -from requests import __version__ as requests_version -import dataclasses -import re -from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union -import warnings - -try: - OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] -except AttributeError: # pragma: NO COVER - OptionalRetry = Union[retries.Retry, object] # 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 # type: ignore - -from .base import SessionEntityTypesTransport, DEFAULT_CLIENT_INFO as BASE_DEFAULT_CLIENT_INFO - - -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=BASE_DEFAULT_CLIENT_INFO.gapic_version, - grpc_version=None, - rest_version=requests_version, -) - - -class SessionEntityTypesRestInterceptor: - """Interceptor for SessionEntityTypes. - - Interceptors are used to manipulate requests, request metadata, and responses - in arbitrary ways. - Example use cases include: - * Logging - * Verifying requests according to service or custom semantics - * Stripping extraneous information from responses - - These use cases and more can be enabled by injecting an - instance of a custom subclass when constructing the SessionEntityTypesRestTransport. - - .. code-block:: python - class MyCustomSessionEntityTypesInterceptor(SessionEntityTypesRestInterceptor): - def pre_create_session_entity_type(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_create_session_entity_type(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_delete_session_entity_type(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def pre_get_session_entity_type(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_get_session_entity_type(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_list_session_entity_types(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_list_session_entity_types(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_update_session_entity_type(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_update_session_entity_type(self, response): - logging.log(f"Received response: {response}") - return response - - transport = SessionEntityTypesRestTransport(interceptor=MyCustomSessionEntityTypesInterceptor()) - client = SessionEntityTypesClient(transport=transport) - - - """ - def pre_create_session_entity_type(self, request: gcd_session_entity_type.CreateSessionEntityTypeRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[gcd_session_entity_type.CreateSessionEntityTypeRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for create_session_entity_type - - Override in a subclass to manipulate the request or metadata - before they are sent to the SessionEntityTypes server. - """ - return request, metadata - - def post_create_session_entity_type(self, response: gcd_session_entity_type.SessionEntityType) -> gcd_session_entity_type.SessionEntityType: - """Post-rpc interceptor for create_session_entity_type - - Override in a subclass to manipulate the response - after it is returned by the SessionEntityTypes server but before - it is returned to user code. - """ - return response - def pre_delete_session_entity_type(self, request: session_entity_type.DeleteSessionEntityTypeRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[session_entity_type.DeleteSessionEntityTypeRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for delete_session_entity_type - - Override in a subclass to manipulate the request or metadata - before they are sent to the SessionEntityTypes server. - """ - return request, metadata - - def pre_get_session_entity_type(self, request: session_entity_type.GetSessionEntityTypeRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[session_entity_type.GetSessionEntityTypeRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for get_session_entity_type - - Override in a subclass to manipulate the request or metadata - before they are sent to the SessionEntityTypes server. - """ - return request, metadata - - def post_get_session_entity_type(self, response: session_entity_type.SessionEntityType) -> session_entity_type.SessionEntityType: - """Post-rpc interceptor for get_session_entity_type - - Override in a subclass to manipulate the response - after it is returned by the SessionEntityTypes server but before - it is returned to user code. - """ - return response - def pre_list_session_entity_types(self, request: session_entity_type.ListSessionEntityTypesRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[session_entity_type.ListSessionEntityTypesRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for list_session_entity_types - - Override in a subclass to manipulate the request or metadata - before they are sent to the SessionEntityTypes server. - """ - return request, metadata - - def post_list_session_entity_types(self, response: session_entity_type.ListSessionEntityTypesResponse) -> session_entity_type.ListSessionEntityTypesResponse: - """Post-rpc interceptor for list_session_entity_types - - Override in a subclass to manipulate the response - after it is returned by the SessionEntityTypes server but before - it is returned to user code. - """ - return response - def pre_update_session_entity_type(self, request: gcd_session_entity_type.UpdateSessionEntityTypeRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[gcd_session_entity_type.UpdateSessionEntityTypeRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for update_session_entity_type - - Override in a subclass to manipulate the request or metadata - before they are sent to the SessionEntityTypes server. - """ - return request, metadata - - def post_update_session_entity_type(self, response: gcd_session_entity_type.SessionEntityType) -> gcd_session_entity_type.SessionEntityType: - """Post-rpc interceptor for update_session_entity_type - - Override in a subclass to manipulate the response - after it is returned by the SessionEntityTypes server but before - it is returned to user code. - """ - return response - - def pre_get_location( - self, request: locations_pb2.GetLocationRequest, metadata: Sequence[Tuple[str, str]] - ) -> Tuple[locations_pb2.GetLocationRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for get_location - - Override in a subclass to manipulate the request or metadata - before they are sent to the SessionEntityTypes server. - """ - return request, metadata - - def post_get_location( - self, response: locations_pb2.Location - ) -> locations_pb2.Location: - """Post-rpc interceptor for get_location - - Override in a subclass to manipulate the response - after it is returned by the SessionEntityTypes server but before - it is returned to user code. - """ - return response - def pre_list_locations( - self, request: locations_pb2.ListLocationsRequest, metadata: Sequence[Tuple[str, str]] - ) -> Tuple[locations_pb2.ListLocationsRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for list_locations - - Override in a subclass to manipulate the request or metadata - before they are sent to the SessionEntityTypes server. - """ - return request, metadata - - def post_list_locations( - self, response: locations_pb2.ListLocationsResponse - ) -> locations_pb2.ListLocationsResponse: - """Post-rpc interceptor for list_locations - - Override in a subclass to manipulate the response - after it is returned by the SessionEntityTypes server but before - it is returned to user code. - """ - return response - def pre_cancel_operation( - self, request: operations_pb2.CancelOperationRequest, metadata: Sequence[Tuple[str, str]] - ) -> Tuple[operations_pb2.CancelOperationRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for cancel_operation - - Override in a subclass to manipulate the request or metadata - before they are sent to the SessionEntityTypes server. - """ - return request, metadata - - def post_cancel_operation( - self, response: None - ) -> None: - """Post-rpc interceptor for cancel_operation - - Override in a subclass to manipulate the response - after it is returned by the SessionEntityTypes server but before - it is returned to user code. - """ - return response - def pre_get_operation( - self, request: operations_pb2.GetOperationRequest, metadata: Sequence[Tuple[str, str]] - ) -> Tuple[operations_pb2.GetOperationRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for get_operation - - Override in a subclass to manipulate the request or metadata - before they are sent to the SessionEntityTypes server. - """ - return request, metadata - - def post_get_operation( - self, response: operations_pb2.Operation - ) -> operations_pb2.Operation: - """Post-rpc interceptor for get_operation - - Override in a subclass to manipulate the response - after it is returned by the SessionEntityTypes server but before - it is returned to user code. - """ - return response - def pre_list_operations( - self, request: operations_pb2.ListOperationsRequest, metadata: Sequence[Tuple[str, str]] - ) -> Tuple[operations_pb2.ListOperationsRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for list_operations - - Override in a subclass to manipulate the request or metadata - before they are sent to the SessionEntityTypes server. - """ - return request, metadata - - def post_list_operations( - self, response: operations_pb2.ListOperationsResponse - ) -> operations_pb2.ListOperationsResponse: - """Post-rpc interceptor for list_operations - - Override in a subclass to manipulate the response - after it is returned by the SessionEntityTypes server but before - it is returned to user code. - """ - return response - - -@dataclasses.dataclass -class SessionEntityTypesRestStub: - _session: AuthorizedSession - _host: str - _interceptor: SessionEntityTypesRestInterceptor - - -class SessionEntityTypesRestTransport(SessionEntityTypesTransport): - """REST backend transport for SessionEntityTypes. - - Service for managing - [SessionEntityTypes][google.cloud.dialogflow.v2beta1.SessionEntityType]. - - 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 JSON representations of protocol buffers over HTTP/1.1 - - """ - - def __init__(self, *, - host: str = 'dialogflow.googleapis.com', - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - client_cert_source_for_mtls: Optional[Callable[[ - ], Tuple[bytes, bytes]]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - url_scheme: str = 'https', - interceptor: Optional[SessionEntityTypesRestInterceptor] = None, - api_audience: Optional[str] = None, - ) -> 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 ignored if ``channel`` is provided. - scopes (Optional(Sequence[str])): A list of scopes. This argument is - ignored if ``channel`` is provided. - client_cert_source_for_mtls (Callable[[], Tuple[bytes, bytes]]): Client - certificate to configure mutual TLS HTTP channel. It is ignored - if ``channel`` is provided. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you are developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - url_scheme: the protocol scheme for the API endpoint. Normally - "https", but for testing or local servers, - "http" can be specified. - """ - # Run the base constructor - # TODO(yon-mg): resolve other ctor params i.e. scopes, quota, etc. - # TODO: When custom host (api_endpoint) is set, `scopes` must *also* be set on the - # credentials object - maybe_url_match = re.match("^(?Phttp(?:s)?://)?(?P.*)$", host) - if maybe_url_match is None: - raise ValueError(f"Unexpected hostname structure: {host}") # pragma: NO COVER - - url_match_items = maybe_url_match.groupdict() - - host = f"{url_scheme}://{host}" if not url_match_items["scheme"] else host - - super().__init__( - host=host, - credentials=credentials, - client_info=client_info, - always_use_jwt_access=always_use_jwt_access, - api_audience=api_audience - ) - self._session = AuthorizedSession( - self._credentials, default_host=self.DEFAULT_HOST) - if client_cert_source_for_mtls: - self._session.configure_mtls_channel(client_cert_source_for_mtls) - self._interceptor = interceptor or SessionEntityTypesRestInterceptor() - self._prep_wrapped_messages(client_info) - - class _CreateSessionEntityType(SessionEntityTypesRestStub): - def __hash__(self): - return hash("CreateSessionEntityType") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: gcd_session_entity_type.CreateSessionEntityTypeRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> gcd_session_entity_type.SessionEntityType: - r"""Call the create session entity - type method over HTTP. - - Args: - request (~.gcd_session_entity_type.CreateSessionEntityTypeRequest): - The request object. The request message for - [SessionEntityTypes.CreateSessionEntityType][google.cloud.dialogflow.v2beta1.SessionEntityTypes.CreateSessionEntityType]. - 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: - ~.gcd_session_entity_type.SessionEntityType: - A session represents a conversation between a Dialogflow - agent and an end-user. You can create special entities, - called session entities, during a session. Session - entities can extend or replace custom entity types and - only exist during the session that they were created - for. All session data, including session entities, is - stored by Dialogflow for 20 minutes. - - For more information, see the `session entity - guide `__. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'post', - 'uri': '/v2beta1/{parent=projects/*/agent/sessions/*}/entityTypes', - 'body': 'session_entity_type', - }, -{ - 'method': 'post', - 'uri': '/v2beta1/{parent=projects/*/agent/environments/*/users/*/sessions/*}/entityTypes', - 'body': 'session_entity_type', - }, -{ - 'method': 'post', - 'uri': '/v2beta1/{parent=projects/*/locations/*/agent/sessions/*}/entityTypes', - 'body': 'session_entity_type', - }, -{ - 'method': 'post', - 'uri': '/v2beta1/{parent=projects/*/locations/*/agent/environments/*/users/*/sessions/*}/entityTypes', - 'body': 'session_entity_type', - }, - ] - request, metadata = self._interceptor.pre_create_session_entity_type(request, metadata) - pb_request = gcd_session_entity_type.CreateSessionEntityTypeRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request['body'], - including_default_value_fields=False, - use_integers_for_enums=True - ) - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - including_default_value_fields=False, - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = gcd_session_entity_type.SessionEntityType() - pb_resp = gcd_session_entity_type.SessionEntityType.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_create_session_entity_type(resp) - return resp - - class _DeleteSessionEntityType(SessionEntityTypesRestStub): - def __hash__(self): - return hash("DeleteSessionEntityType") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: session_entity_type.DeleteSessionEntityTypeRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ): - r"""Call the delete session entity - type method over HTTP. - - Args: - request (~.session_entity_type.DeleteSessionEntityTypeRequest): - The request object. The request message for - [SessionEntityTypes.DeleteSessionEntityType][google.cloud.dialogflow.v2beta1.SessionEntityTypes.DeleteSessionEntityType]. - 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. - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'delete', - 'uri': '/v2beta1/{name=projects/*/agent/sessions/*/entityTypes/*}', - }, -{ - 'method': 'delete', - 'uri': '/v2beta1/{name=projects/*/agent/environments/*/users/*/sessions/*/entityTypes/*}', - }, -{ - 'method': 'delete', - 'uri': '/v2beta1/{name=projects/*/locations/*/agent/sessions/*/entityTypes/*}', - }, -{ - 'method': 'delete', - 'uri': '/v2beta1/{name=projects/*/locations/*/agent/environments/*/users/*/sessions/*/entityTypes/*}', - }, - ] - request, metadata = self._interceptor.pre_delete_session_entity_type(request, metadata) - pb_request = session_entity_type.DeleteSessionEntityTypeRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - including_default_value_fields=False, - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - class _GetSessionEntityType(SessionEntityTypesRestStub): - def __hash__(self): - return hash("GetSessionEntityType") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: session_entity_type.GetSessionEntityTypeRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> session_entity_type.SessionEntityType: - r"""Call the get session entity type method over HTTP. - - Args: - request (~.session_entity_type.GetSessionEntityTypeRequest): - The request object. The request message for - [SessionEntityTypes.GetSessionEntityType][google.cloud.dialogflow.v2beta1.SessionEntityTypes.GetSessionEntityType]. - 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: - ~.session_entity_type.SessionEntityType: - A session represents a conversation between a Dialogflow - agent and an end-user. You can create special entities, - called session entities, during a session. Session - entities can extend or replace custom entity types and - only exist during the session that they were created - for. All session data, including session entities, is - stored by Dialogflow for 20 minutes. - - For more information, see the `session entity - guide `__. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v2beta1/{name=projects/*/agent/sessions/*/entityTypes/*}', - }, -{ - 'method': 'get', - 'uri': '/v2beta1/{name=projects/*/agent/environments/*/users/*/sessions/*/entityTypes/*}', - }, -{ - 'method': 'get', - 'uri': '/v2beta1/{name=projects/*/locations/*/agent/sessions/*/entityTypes/*}', - }, -{ - 'method': 'get', - 'uri': '/v2beta1/{name=projects/*/locations/*/agent/environments/*/users/*/sessions/*/entityTypes/*}', - }, - ] - request, metadata = self._interceptor.pre_get_session_entity_type(request, metadata) - pb_request = session_entity_type.GetSessionEntityTypeRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - including_default_value_fields=False, - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = session_entity_type.SessionEntityType() - pb_resp = session_entity_type.SessionEntityType.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_get_session_entity_type(resp) - return resp - - class _ListSessionEntityTypes(SessionEntityTypesRestStub): - def __hash__(self): - return hash("ListSessionEntityTypes") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: session_entity_type.ListSessionEntityTypesRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> session_entity_type.ListSessionEntityTypesResponse: - r"""Call the list session entity types method over HTTP. - - Args: - request (~.session_entity_type.ListSessionEntityTypesRequest): - The request object. The request message for - [SessionEntityTypes.ListSessionEntityTypes][google.cloud.dialogflow.v2beta1.SessionEntityTypes.ListSessionEntityTypes]. - 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: - ~.session_entity_type.ListSessionEntityTypesResponse: - The response message for - [SessionEntityTypes.ListSessionEntityTypes][google.cloud.dialogflow.v2beta1.SessionEntityTypes.ListSessionEntityTypes]. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v2beta1/{parent=projects/*/agent/sessions/*}/entityTypes', - }, -{ - 'method': 'get', - 'uri': '/v2beta1/{parent=projects/*/agent/environments/*/users/*/sessions/*}/entityTypes', - }, -{ - 'method': 'get', - 'uri': '/v2beta1/{parent=projects/*/locations/*/agent/sessions/*}/entityTypes', - }, -{ - 'method': 'get', - 'uri': '/v2beta1/{parent=projects/*/locations/*/agent/environments/*/users/*/sessions/*}/entityTypes', - }, - ] - request, metadata = self._interceptor.pre_list_session_entity_types(request, metadata) - pb_request = session_entity_type.ListSessionEntityTypesRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - including_default_value_fields=False, - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = session_entity_type.ListSessionEntityTypesResponse() - pb_resp = session_entity_type.ListSessionEntityTypesResponse.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_list_session_entity_types(resp) - return resp - - class _UpdateSessionEntityType(SessionEntityTypesRestStub): - def __hash__(self): - return hash("UpdateSessionEntityType") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: gcd_session_entity_type.UpdateSessionEntityTypeRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> gcd_session_entity_type.SessionEntityType: - r"""Call the update session entity - type method over HTTP. - - Args: - request (~.gcd_session_entity_type.UpdateSessionEntityTypeRequest): - The request object. The request message for - [SessionEntityTypes.UpdateSessionEntityType][google.cloud.dialogflow.v2beta1.SessionEntityTypes.UpdateSessionEntityType]. - 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: - ~.gcd_session_entity_type.SessionEntityType: - A session represents a conversation between a Dialogflow - agent and an end-user. You can create special entities, - called session entities, during a session. Session - entities can extend or replace custom entity types and - only exist during the session that they were created - for. All session data, including session entities, is - stored by Dialogflow for 20 minutes. - - For more information, see the `session entity - guide `__. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'patch', - 'uri': '/v2beta1/{session_entity_type.name=projects/*/agent/sessions/*/entityTypes/*}', - 'body': 'session_entity_type', - }, -{ - 'method': 'patch', - 'uri': '/v2beta1/{session_entity_type.name=projects/*/agent/environments/*/users/*/sessions/*/entityTypes/*}', - 'body': 'session_entity_type', - }, -{ - 'method': 'patch', - 'uri': '/v2beta1/{session_entity_type.name=projects/*/locations/*/agent/sessions/*/entityTypes/*}', - 'body': 'session_entity_type', - }, -{ - 'method': 'patch', - 'uri': '/v2beta1/{session_entity_type.name=projects/*/locations/*/agent/environments/*/users/*/sessions/*/entityTypes/*}', - 'body': 'session_entity_type', - }, - ] - request, metadata = self._interceptor.pre_update_session_entity_type(request, metadata) - pb_request = gcd_session_entity_type.UpdateSessionEntityTypeRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request['body'], - including_default_value_fields=False, - use_integers_for_enums=True - ) - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - including_default_value_fields=False, - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = gcd_session_entity_type.SessionEntityType() - pb_resp = gcd_session_entity_type.SessionEntityType.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_update_session_entity_type(resp) - return resp - - @property - def create_session_entity_type(self) -> Callable[ - [gcd_session_entity_type.CreateSessionEntityTypeRequest], - gcd_session_entity_type.SessionEntityType]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._CreateSessionEntityType(self._session, self._host, self._interceptor) # type: ignore - - @property - def delete_session_entity_type(self) -> Callable[ - [session_entity_type.DeleteSessionEntityTypeRequest], - empty_pb2.Empty]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._DeleteSessionEntityType(self._session, self._host, self._interceptor) # type: ignore - - @property - def get_session_entity_type(self) -> Callable[ - [session_entity_type.GetSessionEntityTypeRequest], - session_entity_type.SessionEntityType]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._GetSessionEntityType(self._session, self._host, self._interceptor) # type: ignore - - @property - def list_session_entity_types(self) -> Callable[ - [session_entity_type.ListSessionEntityTypesRequest], - session_entity_type.ListSessionEntityTypesResponse]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._ListSessionEntityTypes(self._session, self._host, self._interceptor) # type: ignore - - @property - def update_session_entity_type(self) -> Callable[ - [gcd_session_entity_type.UpdateSessionEntityTypeRequest], - gcd_session_entity_type.SessionEntityType]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._UpdateSessionEntityType(self._session, self._host, self._interceptor) # type: ignore - - @property - def get_location(self): - return self._GetLocation(self._session, self._host, self._interceptor) # type: ignore - - class _GetLocation(SessionEntityTypesRestStub): - def __call__(self, - request: locations_pb2.GetLocationRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> locations_pb2.Location: - - r"""Call the get location method over HTTP. - - Args: - request (locations_pb2.GetLocationRequest): - The request object for GetLocation method. - 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: - locations_pb2.Location: Response from GetLocation method. - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v2beta1/{name=projects/*/locations/*}', - }, - ] - - request, metadata = self._interceptor.pre_get_location(request, metadata) - request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode( - http_options, **request_kwargs) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json.dumps(transcoded_request['query_params'])) - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - resp = locations_pb2.Location() - resp = json_format.Parse(response.content.decode("utf-8"), resp) - resp = self._interceptor.post_get_location(resp) - return resp - - @property - def list_locations(self): - return self._ListLocations(self._session, self._host, self._interceptor) # type: ignore - - class _ListLocations(SessionEntityTypesRestStub): - def __call__(self, - request: locations_pb2.ListLocationsRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> locations_pb2.ListLocationsResponse: - - r"""Call the list locations method over HTTP. - - Args: - request (locations_pb2.ListLocationsRequest): - The request object for ListLocations method. - 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: - locations_pb2.ListLocationsResponse: Response from ListLocations method. - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v2beta1/{name=projects/*}/locations', - }, - ] - - request, metadata = self._interceptor.pre_list_locations(request, metadata) - request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode( - http_options, **request_kwargs) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json.dumps(transcoded_request['query_params'])) - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - resp = locations_pb2.ListLocationsResponse() - resp = json_format.Parse(response.content.decode("utf-8"), resp) - resp = self._interceptor.post_list_locations(resp) - return resp - - @property - def cancel_operation(self): - return self._CancelOperation(self._session, self._host, self._interceptor) # type: ignore - - class _CancelOperation(SessionEntityTypesRestStub): - def __call__(self, - request: operations_pb2.CancelOperationRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> None: - - r"""Call the cancel operation method over HTTP. - - Args: - request (operations_pb2.CancelOperationRequest): - The request object for CancelOperation method. - 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. - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'post', - 'uri': '/v2beta1/{name=projects/*/operations/*}:cancel', - }, -{ - 'method': 'post', - 'uri': '/v2beta1/{name=projects/*/locations/*/operations/*}:cancel', - }, - ] - - request, metadata = self._interceptor.pre_cancel_operation(request, metadata) - request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode( - http_options, **request_kwargs) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json.dumps(transcoded_request['query_params'])) - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - return self._interceptor.post_cancel_operation(None) - - @property - def get_operation(self): - return self._GetOperation(self._session, self._host, self._interceptor) # type: ignore - - class _GetOperation(SessionEntityTypesRestStub): - def __call__(self, - request: operations_pb2.GetOperationRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> operations_pb2.Operation: - - r"""Call the get operation method over HTTP. - - Args: - request (operations_pb2.GetOperationRequest): - The request object for GetOperation method. - 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: - operations_pb2.Operation: Response from GetOperation method. - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v2beta1/{name=projects/*/operations/*}', - }, -{ - 'method': 'get', - 'uri': '/v2beta1/{name=projects/*/locations/*/operations/*}', - }, - ] - - request, metadata = self._interceptor.pre_get_operation(request, metadata) - request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode( - http_options, **request_kwargs) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json.dumps(transcoded_request['query_params'])) - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - resp = operations_pb2.Operation() - resp = json_format.Parse(response.content.decode("utf-8"), resp) - resp = self._interceptor.post_get_operation(resp) - return resp - - @property - def list_operations(self): - return self._ListOperations(self._session, self._host, self._interceptor) # type: ignore - - class _ListOperations(SessionEntityTypesRestStub): - def __call__(self, - request: operations_pb2.ListOperationsRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> operations_pb2.ListOperationsResponse: - - r"""Call the list operations method over HTTP. - - Args: - request (operations_pb2.ListOperationsRequest): - The request object for ListOperations method. - 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: - operations_pb2.ListOperationsResponse: Response from ListOperations method. - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v2beta1/{name=projects/*}/operations', - }, -{ - 'method': 'get', - 'uri': '/v2beta1/{name=projects/*/locations/*}/operations', - }, - ] - - request, metadata = self._interceptor.pre_list_operations(request, metadata) - request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode( - http_options, **request_kwargs) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json.dumps(transcoded_request['query_params'])) - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - resp = operations_pb2.ListOperationsResponse() - resp = json_format.Parse(response.content.decode("utf-8"), resp) - resp = self._interceptor.post_list_operations(resp) - return resp - - @property - def kind(self) -> str: - return "rest" - - def close(self): - self._session.close() - - -__all__=( - 'SessionEntityTypesRestTransport', -) diff --git a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/sessions/__init__.py b/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/sessions/__init__.py deleted file mode 100644 index b1e28f0e8..000000000 --- a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/sessions/__init__.py +++ /dev/null @@ -1,22 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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 SessionsClient -from .async_client import SessionsAsyncClient - -__all__ = ( - 'SessionsClient', - 'SessionsAsyncClient', -) diff --git a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/sessions/async_client.py b/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/sessions/async_client.py deleted file mode 100644 index 8b669811e..000000000 --- a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/sessions/async_client.py +++ /dev/null @@ -1,780 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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, Mapping, MutableMapping, MutableSequence, Optional, AsyncIterable, Awaitable, AsyncIterator, Sequence, Tuple, Type, Union - -from google.cloud.dialogflow_v2beta1 import gapic_version as package_version - -from google.api_core.client_options import ClientOptions -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import retry as retries -from google.auth import credentials as ga_credentials # type: ignore -from google.oauth2 import service_account # type: ignore - -try: - OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] -except AttributeError: # pragma: NO COVER - OptionalRetry = Union[retries.Retry, object] # 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.cloud.location import locations_pb2 # type: ignore -from google.longrunning import operations_pb2 -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 - - -class SessionsAsyncClient: - """A service used for session interactions. - - For more information, see the `API interactions - guide `__. - """ - - _client: SessionsClient - - DEFAULT_ENDPOINT = SessionsClient.DEFAULT_ENDPOINT - DEFAULT_MTLS_ENDPOINT = SessionsClient.DEFAULT_MTLS_ENDPOINT - - context_path = staticmethod(SessionsClient.context_path) - parse_context_path = staticmethod(SessionsClient.parse_context_path) - document_path = staticmethod(SessionsClient.document_path) - parse_document_path = staticmethod(SessionsClient.parse_document_path) - intent_path = staticmethod(SessionsClient.intent_path) - parse_intent_path = staticmethod(SessionsClient.parse_intent_path) - session_path = staticmethod(SessionsClient.session_path) - parse_session_path = staticmethod(SessionsClient.parse_session_path) - session_entity_type_path = staticmethod(SessionsClient.session_entity_type_path) - 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) - - @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: - SessionsAsyncClient: The constructed client. - """ - return SessionsClient.from_service_account_info.__func__(SessionsAsyncClient, 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: - SessionsAsyncClient: The constructed client. - """ - return SessionsClient.from_service_account_file.__func__(SessionsAsyncClient, filename, *args, **kwargs) # type: ignore - - from_service_account_json = from_service_account_file - - @classmethod - def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[ClientOptions] = None): - """Return the API endpoint and client cert source for mutual TLS. - - The client cert source is determined in the following order: - (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the - client cert source is None. - (2) if `client_options.client_cert_source` is provided, use the provided one; if the - default client cert source exists, use the default one; otherwise the client cert - source is None. - - The API endpoint is determined in the following order: - (1) if `client_options.api_endpoint` if provided, use the provided one. - (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the - default mTLS endpoint; if the environment variable is "never", use the default API - endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise - use the default API endpoint. - - More details can be found at https://google.aip.dev/auth/4114. - - Args: - client_options (google.api_core.client_options.ClientOptions): Custom options for the - client. Only the `api_endpoint` and `client_cert_source` properties may be used - in this method. - - Returns: - Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the - client cert source to use. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If any errors happen. - """ - return SessionsClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore - - @property - def transport(self) -> SessionsTransport: - """Returns the transport used by the client instance. - - Returns: - SessionsTransport: The transport used by the client instance. - """ - return self._client.transport - - get_transport_class = functools.partial(type(SessionsClient).get_transport_class, type(SessionsClient)) - - def __init__(self, *, - credentials: Optional[ga_credentials.Credentials] = None, - transport: Union[str, SessionsTransport] = "grpc_asyncio", - client_options: Optional[ClientOptions] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the sessions 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, ~.SessionsTransport]): 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 = SessionsClient( - credentials=credentials, - transport=transport, - client_options=client_options, - client_info=client_info, - - ) - - async def detect_intent(self, - request: Optional[Union[gcd_session.DetectIntentRequest, dict]] = None, - *, - session: Optional[str] = None, - query_input: Optional[gcd_session.QueryInput] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gcd_session.DetectIntentResponse: - r"""Processes a natural language query and returns structured, - actionable data as a result. This method is not idempotent, - because it may cause contexts and session entity types to be - updated, which in turn might affect results of future queries. - - If you might use `Agent - Assist `__ or - other CCAI products now or in the future, consider using - [AnalyzeContent][google.cloud.dialogflow.v2beta1.Participants.AnalyzeContent] - instead of ``DetectIntent``. ``AnalyzeContent`` has additional - functionality for Agent Assist and other CCAI products. - - Note: Always use agent versions for production traffic. See - `Versions and - environments `__. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import dialogflow_v2beta1 - - async def sample_detect_intent(): - # Create a client - client = dialogflow_v2beta1.SessionsAsyncClient() - - # Initialize request argument(s) - request = dialogflow_v2beta1.DetectIntentRequest( - session="session_value", - ) - - # Make the request - response = await client.detect_intent(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.dialogflow_v2beta1.types.DetectIntentRequest, dict]]): - The request object. The request to detect user's intent. - session (:class:`str`): - Required. The name of the session this query is sent to. - Supported formats: - - - \`projects//agent/sessions/, - - ``projects//locations//agent/sessions/``, - - ``projects//agent/environments//users//sessions/``, - - ``projects//locations//agent/environments//users//sessions/``, - - If ``Location ID`` is not specified we assume default - 'us' location. If ``Environment ID`` is not specified, - we assume default 'draft' environment - (``Environment ID`` might be referred to as environment - name at some places). If ``User ID`` is not specified, - we are using "-". It's up to the API caller to choose an - appropriate ``Session ID`` and ``User Id``. They can be - a random number or some type of user and session - identifiers (preferably hashed). The length of the - ``Session ID`` and ``User ID`` must not exceed 36 - characters. For more information, see the `API - interactions - guide `__. - - Note: Always use agent versions for production traffic. - See `Versions and - environments `__. - - This corresponds to the ``session`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - query_input (:class:`google.cloud.dialogflow_v2beta1.types.QueryInput`): - Required. The input specification. It - can be set to: - 1. an audio config - which instructs the speech - recognizer how to process the speech - audio, - 2. a conversational query in the form - of text, or - 3. an event that specifies which intent - to trigger. - - 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. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.dialogflow_v2beta1.types.DetectIntentResponse: - The message returned from the - DetectIntent method. - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([session, query_input]) - 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_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: - request.query_input = query_input - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.detect_intent, - default_retry=retries.Retry( -initial=0.1,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( - core_exceptions.ServiceUnavailable, - ), - deadline=220.0, - ), - default_timeout=220.0, - 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(( - ("session", request.session), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def streaming_detect_intent(self, - requests: Optional[AsyncIterator[session.StreamingDetectIntentRequest]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> Awaitable[AsyncIterable[session.StreamingDetectIntentResponse]]: - r"""Processes a natural language query in audio format in a - streaming fashion and returns structured, actionable data as a - result. This method is only available via the gRPC API (not - REST). - - If you might use `Agent - Assist `__ or - other CCAI products now or in the future, consider using - [StreamingAnalyzeContent][google.cloud.dialogflow.v2beta1.Participants.StreamingAnalyzeContent] - instead of ``StreamingDetectIntent``. - ``StreamingAnalyzeContent`` has additional functionality for - Agent Assist and other CCAI products. - - Note: Always use agent versions for production traffic. See - `Versions and - environments `__. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import dialogflow_v2beta1 - - async def sample_streaming_detect_intent(): - # Create a client - client = dialogflow_v2beta1.SessionsAsyncClient() - - # Initialize request argument(s) - request = dialogflow_v2beta1.StreamingDetectIntentRequest( - session="session_value", - ) - - # This method expects an iterator which contains - # 'dialogflow_v2beta1.StreamingDetectIntentRequest' objects - # Here we create a generator that yields a single `request` for - # demonstrative purposes. - requests = [request] - - def request_generator(): - for request in requests: - yield request - - # Make the request - stream = await client.streaming_detect_intent(requests=request_generator()) - - # Handle the response - async for response in stream: - print(response) - - Args: - requests (AsyncIterator[`google.cloud.dialogflow_v2beta1.types.StreamingDetectIntentRequest`]): - The request object AsyncIterator. The top-level message sent by the client to the - [Sessions.StreamingDetectIntent][google.cloud.dialogflow.v2beta1.Sessions.StreamingDetectIntent] - method. - - Multiple request messages should be sent in order: - - 1. The first message must contain - [session][google.cloud.dialogflow.v2beta1.StreamingDetectIntentRequest.session], - [query_input][google.cloud.dialogflow.v2beta1.StreamingDetectIntentRequest.query_input] - plus optionally - [query_params][google.cloud.dialogflow.v2beta1.StreamingDetectIntentRequest.query_params]. - If the client wants to receive an audio response, it - should also contain - [output_audio_config][google.cloud.dialogflow.v2beta1.StreamingDetectIntentRequest.output_audio_config]. - The message must not contain - [input_audio][google.cloud.dialogflow.v2beta1.StreamingDetectIntentRequest.input_audio]. - - 2. If - [query_input][google.cloud.dialogflow.v2beta1.StreamingDetectIntentRequest.query_input] - was set to - [query_input.audio_config][google.cloud.dialogflow.v2beta1.InputAudioConfig], - all subsequent messages must contain - [input_audio][google.cloud.dialogflow.v2beta1.StreamingDetectIntentRequest.input_audio] - to continue with Speech recognition. If you decide to - rather detect an intent from text input after you - already started Speech recognition, please send a - message with - [query_input.text][google.cloud.dialogflow.v2beta1.QueryInput.text]. - - However, note that: - - - Dialogflow will bill you for the audio duration so - far. - - Dialogflow discards all Speech recognition results - in favor of the input text. - - Dialogflow will use the language code from the - first message. - - After you sent all input, you must half-close or abort - the request stream. - 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: - AsyncIterable[google.cloud.dialogflow_v2beta1.types.StreamingDetectIntentResponse]: - The top-level message returned from the - StreamingDetectIntent method. - - Multiple response messages can be returned in order: - - 1. If the StreamingDetectIntentRequest.input_audio - field was set, the recognition_result field is - populated for one or more messages. See the - [StreamingRecognitionResult][google.cloud.dialogflow.v2beta1.StreamingRecognitionResult] - message for details about the result message - sequence. - 2. The next message contains response_id, - query_result, alternative_query_results and - optionally webhook_status if a WebHook was called. - 3. If output_audio_config was specified in the - request or agent-level speech synthesizer is - configured, all subsequent messages contain - output_audio and output_audio_config. - - """ - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.streaming_detect_intent, - default_timeout=220.0, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Send the request. - response = rpc( - requests, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def list_operations( - self, - request: Optional[operations_pb2.ListOperationsRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operations_pb2.ListOperationsResponse: - r"""Lists operations that match the specified filter in the request. - - Args: - request (:class:`~.operations_pb2.ListOperationsRequest`): - The request object. Request message for - `ListOperations` method. - 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: - ~.operations_pb2.ListOperationsResponse: - Response message for ``ListOperations`` method. - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = operations_pb2.ListOperationsRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._client._transport.list_operations, - 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 get_operation( - self, - request: Optional[operations_pb2.GetOperationRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operations_pb2.Operation: - r"""Gets the latest state of a long-running operation. - - Args: - request (:class:`~.operations_pb2.GetOperationRequest`): - The request object. Request message for - `GetOperation` method. - 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: - ~.operations_pb2.Operation: - An ``Operation`` object. - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = operations_pb2.GetOperationRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._client._transport.get_operation, - 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 cancel_operation( - self, - request: Optional[operations_pb2.CancelOperationRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> None: - r"""Starts asynchronous cancellation on a long-running operation. - - The server makes a best effort to cancel the operation, but success - is not guaranteed. If the server doesn't support this method, it returns - `google.rpc.Code.UNIMPLEMENTED`. - - Args: - request (:class:`~.operations_pb2.CancelOperationRequest`): - The request object. Request message for - `CancelOperation` method. - 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: - None - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = operations_pb2.CancelOperationRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._client._transport.cancel_operation, - 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_location( - self, - request: Optional[locations_pb2.GetLocationRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> locations_pb2.Location: - r"""Gets information about a location. - - Args: - request (:class:`~.location_pb2.GetLocationRequest`): - The request object. Request message for - `GetLocation` method. - 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: - ~.location_pb2.Location: - Location object. - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = locations_pb2.GetLocationRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._client._transport.get_location, - 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 list_locations( - self, - request: Optional[locations_pb2.ListLocationsRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> locations_pb2.ListLocationsResponse: - r"""Lists information about the supported locations for this service. - - Args: - request (:class:`~.location_pb2.ListLocationsRequest`): - The request object. Request message for - `ListLocations` method. - 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: - ~.location_pb2.ListLocationsResponse: - Response message for ``ListLocations`` method. - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = locations_pb2.ListLocationsRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._client._transport.list_locations, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("name", request.name),)), - ) - - # Send the request. - response = await rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - async def __aenter__(self): - return self - - async def __aexit__(self, exc_type, exc, tb): - await self.transport.close() - -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) - - -__all__ = ( - "SessionsAsyncClient", -) diff --git a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/sessions/client.py b/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/sessions/client.py deleted file mode 100644 index 746689db0..000000000 --- a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/sessions/client.py +++ /dev/null @@ -1,1005 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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 os -import re -from typing import Dict, Mapping, MutableMapping, MutableSequence, Optional, Iterable, Iterator, Sequence, Tuple, Type, Union, cast - -from google.cloud.dialogflow_v2beta1 import gapic_version as package_version - -from google.api_core import client_options as client_options_lib -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import retry as retries -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 - -try: - OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] -except AttributeError: # pragma: NO COVER - OptionalRetry = Union[retries.Retry, object] # 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.cloud.location import locations_pb2 # type: ignore -from google.longrunning import operations_pb2 -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 -from .transports.rest import SessionsRestTransport - - -class SessionsClientMeta(type): - """Metaclass for the Sessions 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[SessionsTransport]] - _transport_registry["grpc"] = SessionsGrpcTransport - _transport_registry["grpc_asyncio"] = SessionsGrpcAsyncIOTransport - _transport_registry["rest"] = SessionsRestTransport - - def get_transport_class(cls, - label: Optional[str] = None, - ) -> Type[SessionsTransport]: - """Returns an appropriate transport class. - - Args: - label: The name of the desired transport. If none is - provided, then the first transport in the registry is used. - - Returns: - The transport class to use. - """ - # If a specific transport is requested, return that one. - if label: - return cls._transport_registry[label] - - # No transport is requested; return the default (that is, the first one - # in the dictionary). - return next(iter(cls._transport_registry.values())) - - -class SessionsClient(metaclass=SessionsClientMeta): - """A service used for session interactions. - - For more information, see the `API interactions - guide `__. - """ - - @staticmethod - def _get_default_mtls_endpoint(api_endpoint): - """Converts api endpoint to mTLS endpoint. - - Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to - "*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively. - Args: - api_endpoint (Optional[str]): the api endpoint to convert. - Returns: - str: converted mTLS api endpoint. - """ - if not api_endpoint: - return api_endpoint - - mtls_endpoint_re = re.compile( - r"(?P[^.]+)(?P\.mtls)?(?P\.sandbox)?(?P\.googleapis\.com)?" - ) - - m = mtls_endpoint_re.match(api_endpoint) - name, mtls, sandbox, googledomain = m.groups() - if mtls or not googledomain: - return api_endpoint - - if sandbox: - return api_endpoint.replace( - "sandbox.googleapis.com", "mtls.sandbox.googleapis.com" - ) - - return api_endpoint.replace(".googleapis.com", ".mtls.googleapis.com") - - DEFAULT_ENDPOINT = "dialogflow.googleapis.com" - DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore - DEFAULT_ENDPOINT - ) - - @classmethod - def from_service_account_info(cls, info: dict, *args, **kwargs): - """Creates an instance of this client using the provided credentials - info. - - Args: - info (dict): The service account private key info. - args: Additional arguments to pass to the constructor. - kwargs: Additional arguments to pass to the constructor. - - Returns: - SessionsClient: 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: - SessionsClient: 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) -> SessionsTransport: - """Returns the transport used by the client instance. - - Returns: - SessionsTransport: The transport used by the client - instance. - """ - return self._transport - - @staticmethod - def context_path(project: str,session: str,context: str,) -> str: - """Returns a fully-qualified context string.""" - return "projects/{project}/agent/sessions/{session}/contexts/{context}".format(project=project, session=session, context=context, ) - - @staticmethod - def parse_context_path(path: str) -> Dict[str,str]: - """Parses a context path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/agent/sessions/(?P.+?)/contexts/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def document_path(project: str,knowledge_base: str,document: str,) -> str: - """Returns a fully-qualified document string.""" - return "projects/{project}/knowledgeBases/{knowledge_base}/documents/{document}".format(project=project, knowledge_base=knowledge_base, document=document, ) - - @staticmethod - def parse_document_path(path: str) -> Dict[str,str]: - """Parses a document path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/knowledgeBases/(?P.+?)/documents/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def intent_path(project: str,intent: str,) -> str: - """Returns a fully-qualified intent string.""" - return "projects/{project}/agent/intents/{intent}".format(project=project, intent=intent, ) - - @staticmethod - def parse_intent_path(path: str) -> Dict[str,str]: - """Parses a intent path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/agent/intents/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def session_path(project: str,session: str,) -> str: - """Returns a fully-qualified session string.""" - return "projects/{project}/agent/sessions/{session}".format(project=project, session=session, ) - - @staticmethod - def parse_session_path(path: str) -> Dict[str,str]: - """Parses a session path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/agent/sessions/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def session_entity_type_path(project: str,session: str,entity_type: str,) -> str: - """Returns a fully-qualified session_entity_type string.""" - return "projects/{project}/agent/sessions/{session}/entityTypes/{entity_type}".format(project=project, session=session, entity_type=entity_type, ) - - @staticmethod - def parse_session_entity_type_path(path: str) -> Dict[str,str]: - """Parses a session_entity_type path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/agent/sessions/(?P.+?)/entityTypes/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_billing_account_path(billing_account: str, ) -> str: - """Returns a fully-qualified billing_account string.""" - return "billingAccounts/{billing_account}".format(billing_account=billing_account, ) - - @staticmethod - def parse_common_billing_account_path(path: str) -> Dict[str,str]: - """Parse a billing_account path into its component segments.""" - m = re.match(r"^billingAccounts/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_folder_path(folder: str, ) -> str: - """Returns a fully-qualified folder string.""" - return "folders/{folder}".format(folder=folder, ) - - @staticmethod - def parse_common_folder_path(path: str) -> Dict[str,str]: - """Parse a folder path into its component segments.""" - m = re.match(r"^folders/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_organization_path(organization: str, ) -> str: - """Returns a fully-qualified organization string.""" - return "organizations/{organization}".format(organization=organization, ) - - @staticmethod - def parse_common_organization_path(path: str) -> Dict[str,str]: - """Parse a organization path into its component segments.""" - m = re.match(r"^organizations/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_project_path(project: str, ) -> str: - """Returns a fully-qualified project string.""" - return "projects/{project}".format(project=project, ) - - @staticmethod - def parse_common_project_path(path: str) -> Dict[str,str]: - """Parse a project path into its component segments.""" - m = re.match(r"^projects/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_location_path(project: str, location: str, ) -> str: - """Returns a fully-qualified location string.""" - return "projects/{project}/locations/{location}".format(project=project, location=location, ) - - @staticmethod - def parse_common_location_path(path: str) -> Dict[str,str]: - """Parse a location path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)$", path) - return m.groupdict() if m else {} - - @classmethod - def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[client_options_lib.ClientOptions] = None): - """Return the API endpoint and client cert source for mutual TLS. - - The client cert source is determined in the following order: - (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the - client cert source is None. - (2) if `client_options.client_cert_source` is provided, use the provided one; if the - default client cert source exists, use the default one; otherwise the client cert - source is None. - - The API endpoint is determined in the following order: - (1) if `client_options.api_endpoint` if provided, use the provided one. - (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the - default mTLS endpoint; if the environment variable is "never", use the default API - endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise - use the default API endpoint. - - More details can be found at https://google.aip.dev/auth/4114. - - Args: - client_options (google.api_core.client_options.ClientOptions): Custom options for the - client. Only the `api_endpoint` and `client_cert_source` properties may be used - in this method. - - Returns: - Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the - client cert source to use. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If any errors happen. - """ - if client_options is None: - client_options = client_options_lib.ClientOptions() - use_client_cert = os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false") - use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") - if use_client_cert not in ("true", "false"): - raise ValueError("Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`") - if use_mtls_endpoint not in ("auto", "never", "always"): - raise MutualTLSChannelError("Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`") - - # Figure out the client cert source to use. - client_cert_source = None - if use_client_cert == "true": - if client_options.client_cert_source: - client_cert_source = client_options.client_cert_source - elif mtls.has_default_client_cert_source(): - client_cert_source = mtls.default_client_cert_source() - - # Figure out which api endpoint to use. - if client_options.api_endpoint is not None: - api_endpoint = client_options.api_endpoint - elif use_mtls_endpoint == "always" or (use_mtls_endpoint == "auto" and client_cert_source): - api_endpoint = cls.DEFAULT_MTLS_ENDPOINT - else: - api_endpoint = cls.DEFAULT_ENDPOINT - - return api_endpoint, client_cert_source - - def __init__(self, *, - credentials: Optional[ga_credentials.Credentials] = None, - transport: Optional[Union[str, SessionsTransport]] = None, - client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the sessions 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, SessionsTransport]): The - transport to use. If set to None, a transport is chosen - automatically. - client_options (Optional[Union[google.api_core.client_options.ClientOptions, dict]]): 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() - client_options = cast(client_options_lib.ClientOptions, client_options) - - api_endpoint, client_cert_source_func = self.get_mtls_endpoint_and_cert_source(client_options) - - api_key_value = getattr(client_options, "api_key", None) - if api_key_value and credentials: - raise ValueError("client_options.api_key and credentials are mutually exclusive") - - # 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, SessionsTransport): - # transport is a SessionsTransport instance. - if credentials or client_options.credentials_file or api_key_value: - 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: - import google.auth._default # type: ignore - - if api_key_value and hasattr(google.auth._default, "get_api_key_credentials"): - credentials = google.auth._default.get_api_key_credentials(api_key_value) - - Transport = type(self).get_transport_class(transport) - self._transport = Transport( - credentials=credentials, - credentials_file=client_options.credentials_file, - host=api_endpoint, - scopes=client_options.scopes, - client_cert_source_for_mtls=client_cert_source_func, - quota_project_id=client_options.quota_project_id, - client_info=client_info, - always_use_jwt_access=True, - api_audience=client_options.api_audience, - ) - - def detect_intent(self, - request: Optional[Union[gcd_session.DetectIntentRequest, dict]] = None, - *, - session: Optional[str] = None, - query_input: Optional[gcd_session.QueryInput] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gcd_session.DetectIntentResponse: - r"""Processes a natural language query and returns structured, - actionable data as a result. This method is not idempotent, - because it may cause contexts and session entity types to be - updated, which in turn might affect results of future queries. - - If you might use `Agent - Assist `__ or - other CCAI products now or in the future, consider using - [AnalyzeContent][google.cloud.dialogflow.v2beta1.Participants.AnalyzeContent] - instead of ``DetectIntent``. ``AnalyzeContent`` has additional - functionality for Agent Assist and other CCAI products. - - Note: Always use agent versions for production traffic. See - `Versions and - environments `__. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import dialogflow_v2beta1 - - def sample_detect_intent(): - # Create a client - client = dialogflow_v2beta1.SessionsClient() - - # Initialize request argument(s) - request = dialogflow_v2beta1.DetectIntentRequest( - session="session_value", - ) - - # Make the request - response = client.detect_intent(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.dialogflow_v2beta1.types.DetectIntentRequest, dict]): - The request object. The request to detect user's intent. - session (str): - Required. The name of the session this query is sent to. - Supported formats: - - - \`projects//agent/sessions/, - - ``projects//locations//agent/sessions/``, - - ``projects//agent/environments//users//sessions/``, - - ``projects//locations//agent/environments//users//sessions/``, - - If ``Location ID`` is not specified we assume default - 'us' location. If ``Environment ID`` is not specified, - we assume default 'draft' environment - (``Environment ID`` might be referred to as environment - name at some places). If ``User ID`` is not specified, - we are using "-". It's up to the API caller to choose an - appropriate ``Session ID`` and ``User Id``. They can be - a random number or some type of user and session - identifiers (preferably hashed). The length of the - ``Session ID`` and ``User ID`` must not exceed 36 - characters. For more information, see the `API - interactions - guide `__. - - Note: Always use agent versions for production traffic. - See `Versions and - environments `__. - - This corresponds to the ``session`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - query_input (google.cloud.dialogflow_v2beta1.types.QueryInput): - Required. The input specification. It - can be set to: - 1. an audio config - which instructs the speech - recognizer how to process the speech - audio, - 2. a conversational query in the form - of text, or - 3. an event that specifies which intent - to trigger. - - 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. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.dialogflow_v2beta1.types.DetectIntentResponse: - The message returned from the - DetectIntent method. - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([session, query_input]) - 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_session.DetectIntentRequest. - # There's no risk of modifying the input as we've already verified - # 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: - request.query_input = query_input - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.detect_intent] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("session", request.session), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def streaming_detect_intent(self, - requests: Optional[Iterator[session.StreamingDetectIntentRequest]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> Iterable[session.StreamingDetectIntentResponse]: - r"""Processes a natural language query in audio format in a - streaming fashion and returns structured, actionable data as a - result. This method is only available via the gRPC API (not - REST). - - If you might use `Agent - Assist `__ or - other CCAI products now or in the future, consider using - [StreamingAnalyzeContent][google.cloud.dialogflow.v2beta1.Participants.StreamingAnalyzeContent] - instead of ``StreamingDetectIntent``. - ``StreamingAnalyzeContent`` has additional functionality for - Agent Assist and other CCAI products. - - Note: Always use agent versions for production traffic. See - `Versions and - environments `__. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import dialogflow_v2beta1 - - def sample_streaming_detect_intent(): - # Create a client - client = dialogflow_v2beta1.SessionsClient() - - # Initialize request argument(s) - request = dialogflow_v2beta1.StreamingDetectIntentRequest( - session="session_value", - ) - - # This method expects an iterator which contains - # 'dialogflow_v2beta1.StreamingDetectIntentRequest' objects - # Here we create a generator that yields a single `request` for - # demonstrative purposes. - requests = [request] - - def request_generator(): - for request in requests: - yield request - - # Make the request - stream = client.streaming_detect_intent(requests=request_generator()) - - # Handle the response - for response in stream: - print(response) - - Args: - requests (Iterator[google.cloud.dialogflow_v2beta1.types.StreamingDetectIntentRequest]): - The request object iterator. The top-level message sent by the client to the - [Sessions.StreamingDetectIntent][google.cloud.dialogflow.v2beta1.Sessions.StreamingDetectIntent] - method. - - Multiple request messages should be sent in order: - - 1. The first message must contain - [session][google.cloud.dialogflow.v2beta1.StreamingDetectIntentRequest.session], - [query_input][google.cloud.dialogflow.v2beta1.StreamingDetectIntentRequest.query_input] - plus optionally - [query_params][google.cloud.dialogflow.v2beta1.StreamingDetectIntentRequest.query_params]. - If the client wants to receive an audio response, it - should also contain - [output_audio_config][google.cloud.dialogflow.v2beta1.StreamingDetectIntentRequest.output_audio_config]. - The message must not contain - [input_audio][google.cloud.dialogflow.v2beta1.StreamingDetectIntentRequest.input_audio]. - - 2. If - [query_input][google.cloud.dialogflow.v2beta1.StreamingDetectIntentRequest.query_input] - was set to - [query_input.audio_config][google.cloud.dialogflow.v2beta1.InputAudioConfig], - all subsequent messages must contain - [input_audio][google.cloud.dialogflow.v2beta1.StreamingDetectIntentRequest.input_audio] - to continue with Speech recognition. If you decide to - rather detect an intent from text input after you - already started Speech recognition, please send a - message with - [query_input.text][google.cloud.dialogflow.v2beta1.QueryInput.text]. - - However, note that: - - - Dialogflow will bill you for the audio duration so - far. - - Dialogflow discards all Speech recognition results - in favor of the input text. - - Dialogflow will use the language code from the - first message. - - After you sent all input, you must half-close or abort - the request stream. - 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: - Iterable[google.cloud.dialogflow_v2beta1.types.StreamingDetectIntentResponse]: - The top-level message returned from the - StreamingDetectIntent method. - - Multiple response messages can be returned in order: - - 1. If the StreamingDetectIntentRequest.input_audio - field was set, the recognition_result field is - populated for one or more messages. See the - [StreamingRecognitionResult][google.cloud.dialogflow.v2beta1.StreamingRecognitionResult] - message for details about the result message - sequence. - 2. The next message contains response_id, - query_result, alternative_query_results and - optionally webhook_status if a WebHook was called. - 3. If output_audio_config was specified in the - request or agent-level speech synthesizer is - configured, all subsequent messages contain - output_audio and output_audio_config. - - """ - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.streaming_detect_intent] - - # Send the request. - response = rpc( - requests, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def __enter__(self) -> "SessionsClient": - return self - - def __exit__(self, type, value, traceback): - """Releases underlying transport's resources. - - .. warning:: - ONLY use as a context manager if the transport is NOT shared - with other clients! Exiting the with block will CLOSE the transport - and may cause errors in other clients! - """ - self.transport.close() - - def list_operations( - self, - request: Optional[operations_pb2.ListOperationsRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operations_pb2.ListOperationsResponse: - r"""Lists operations that match the specified filter in the request. - - Args: - request (:class:`~.operations_pb2.ListOperationsRequest`): - The request object. Request message for - `ListOperations` method. - 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: - ~.operations_pb2.ListOperationsResponse: - Response message for ``ListOperations`` method. - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = operations_pb2.ListOperationsRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._transport.list_operations, - 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 = rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - def get_operation( - self, - request: Optional[operations_pb2.GetOperationRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operations_pb2.Operation: - r"""Gets the latest state of a long-running operation. - - Args: - request (:class:`~.operations_pb2.GetOperationRequest`): - The request object. Request message for - `GetOperation` method. - 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: - ~.operations_pb2.Operation: - An ``Operation`` object. - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = operations_pb2.GetOperationRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._transport.get_operation, - 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 = rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - def cancel_operation( - self, - request: Optional[operations_pb2.CancelOperationRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> None: - r"""Starts asynchronous cancellation on a long-running operation. - - The server makes a best effort to cancel the operation, but success - is not guaranteed. If the server doesn't support this method, it returns - `google.rpc.Code.UNIMPLEMENTED`. - - Args: - request (:class:`~.operations_pb2.CancelOperationRequest`): - The request object. Request message for - `CancelOperation` method. - 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: - None - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = operations_pb2.CancelOperationRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._transport.cancel_operation, - 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. - rpc(request, retry=retry, timeout=timeout, metadata=metadata,) - - def get_location( - self, - request: Optional[locations_pb2.GetLocationRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> locations_pb2.Location: - r"""Gets information about a location. - - Args: - request (:class:`~.location_pb2.GetLocationRequest`): - The request object. Request message for - `GetLocation` method. - 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: - ~.location_pb2.Location: - Location object. - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = locations_pb2.GetLocationRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._transport.get_location, - 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 = rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - def list_locations( - self, - request: Optional[locations_pb2.ListLocationsRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> locations_pb2.ListLocationsResponse: - r"""Lists information about the supported locations for this service. - - Args: - request (:class:`~.location_pb2.ListLocationsRequest`): - The request object. Request message for - `ListLocations` method. - 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: - ~.location_pb2.ListLocationsResponse: - Response message for ``ListLocations`` method. - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = locations_pb2.ListLocationsRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._transport.list_locations, - 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 = rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) - - -__all__ = ( - "SessionsClient", -) diff --git a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/sessions/transports/__init__.py b/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/sessions/transports/__init__.py deleted file mode 100644 index 62897c27a..000000000 --- a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/sessions/transports/__init__.py +++ /dev/null @@ -1,38 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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 SessionsTransport -from .grpc import SessionsGrpcTransport -from .grpc_asyncio import SessionsGrpcAsyncIOTransport -from .rest import SessionsRestTransport -from .rest import SessionsRestInterceptor - - -# Compile a registry of transports. -_transport_registry = OrderedDict() # type: Dict[str, Type[SessionsTransport]] -_transport_registry['grpc'] = SessionsGrpcTransport -_transport_registry['grpc_asyncio'] = SessionsGrpcAsyncIOTransport -_transport_registry['rest'] = SessionsRestTransport - -__all__ = ( - 'SessionsTransport', - 'SessionsGrpcTransport', - 'SessionsGrpcAsyncIOTransport', - 'SessionsRestTransport', - 'SessionsRestInterceptor', -) diff --git a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/sessions/transports/base.py b/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/sessions/transports/base.py deleted file mode 100644 index 3a44e935f..000000000 --- a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/sessions/transports/base.py +++ /dev/null @@ -1,215 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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 - -from google.cloud.dialogflow_v2beta1 import gapic_version as package_version - -import google.auth # type: ignore -import google.api_core -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import retry as retries -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 session -from google.cloud.dialogflow_v2beta1.types import session as gcd_session -from google.cloud.location import locations_pb2 # type: ignore -from google.longrunning import operations_pb2 - -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) - - -class SessionsTransport(abc.ABC): - """Abstract transport class for Sessions.""" - - 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: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - api_audience: Optional[str] = None, - **kwargs, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. - scopes (Optional[Sequence[str]]): A list of scopes. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - """ - - scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} - - # Save the scopes. - self._scopes = scopes - - # If no credentials are provided, then determine the appropriate - # defaults. - if credentials and credentials_file: - raise core_exceptions.DuplicateCredentialArgs("'credentials_file' and 'credentials' are mutually exclusive") - - if credentials_file is not None: - credentials, _ = google.auth.load_credentials_from_file( - credentials_file, - **scopes_kwargs, - quota_project_id=quota_project_id - ) - elif credentials is None: - credentials, _ = google.auth.default(**scopes_kwargs, quota_project_id=quota_project_id) - # Don't apply audience if the credentials file passed from user. - if hasattr(credentials, "with_gdch_audience"): - credentials = credentials.with_gdch_audience(api_audience if api_audience else host) - - # If the credentials are service account credentials, then always try to use self signed JWT. - if always_use_jwt_access and isinstance(credentials, service_account.Credentials) and hasattr(service_account.Credentials, "with_always_use_jwt_access"): - credentials = credentials.with_always_use_jwt_access(True) - - # Save the credentials. - self._credentials = credentials - - # Save the hostname. Default to port 443 (HTTPS) if none is specified. - if ':' not in host: - host += ':443' - self._host = host - - def _prep_wrapped_messages(self, client_info): - # Precompute the wrapped methods. - self._wrapped_methods = { - self.detect_intent: gapic_v1.method.wrap_method( - self.detect_intent, - default_retry=retries.Retry( -initial=0.1,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( - core_exceptions.ServiceUnavailable, - ), - deadline=220.0, - ), - default_timeout=220.0, - client_info=client_info, - ), - self.streaming_detect_intent: gapic_v1.method.wrap_method( - self.streaming_detect_intent, - default_timeout=220.0, - client_info=client_info, - ), - } - - def close(self): - """Closes resources associated with the transport. - - .. warning:: - Only call this method if the transport is NOT shared - with other clients - this may cause errors in other clients! - """ - raise NotImplementedError() - - @property - def detect_intent(self) -> Callable[ - [gcd_session.DetectIntentRequest], - Union[ - gcd_session.DetectIntentResponse, - Awaitable[gcd_session.DetectIntentResponse] - ]]: - raise NotImplementedError() - - @property - def streaming_detect_intent(self) -> Callable[ - [session.StreamingDetectIntentRequest], - Union[ - session.StreamingDetectIntentResponse, - Awaitable[session.StreamingDetectIntentResponse] - ]]: - raise NotImplementedError() - - @property - def list_operations( - self, - ) -> Callable[ - [operations_pb2.ListOperationsRequest], - Union[operations_pb2.ListOperationsResponse, Awaitable[operations_pb2.ListOperationsResponse]], - ]: - raise NotImplementedError() - - @property - def get_operation( - self, - ) -> Callable[ - [operations_pb2.GetOperationRequest], - Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], - ]: - raise NotImplementedError() - - @property - def cancel_operation( - self, - ) -> Callable[ - [operations_pb2.CancelOperationRequest], - None, - ]: - raise NotImplementedError() - - @property - def get_location(self, - ) -> Callable[ - [locations_pb2.GetLocationRequest], - Union[locations_pb2.Location, Awaitable[locations_pb2.Location]], - ]: - raise NotImplementedError() - - @property - def list_locations(self, - ) -> Callable[ - [locations_pb2.ListLocationsRequest], - Union[locations_pb2.ListLocationsResponse, Awaitable[locations_pb2.ListLocationsResponse]], - ]: - raise NotImplementedError() - - @property - def kind(self) -> str: - raise NotImplementedError() - - -__all__ = ( - 'SessionsTransport', -) diff --git a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/sessions/transports/grpc.py b/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/sessions/transports/grpc.py deleted file mode 100644 index 727aca215..000000000 --- a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/sessions/transports/grpc.py +++ /dev/null @@ -1,415 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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 -from google.api_core import gapic_v1 -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 google.cloud.location import locations_pb2 # type: ignore -from google.longrunning import operations_pb2 -from .base import SessionsTransport, DEFAULT_CLIENT_INFO - - -class SessionsGrpcTransport(SessionsTransport): - """gRPC backend transport for Sessions. - - A service used for session interactions. - - For more information, see the `API interactions - guide `__. - - 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: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - channel: Optional[grpc.Channel] = None, - api_mtls_endpoint: Optional[str] = None, - client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, - ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, - client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - api_audience: Optional[str] = None, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - This argument is ignored if ``channel`` is provided. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional(Sequence[str])): A list of scopes. This argument is - ignored if ``channel`` is provided. - channel (Optional[grpc.Channel]): A ``Channel`` instance through - which to make calls. - api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. - If provided, it overrides the ``host`` argument and tries to create - a mutual TLS channel with client SSL credentials from - ``client_cert_source`` or application default SSL credentials. - client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): - Deprecated. A callback to provide client SSL certificate bytes and - private key bytes, both in PEM format. It is ignored if - ``api_mtls_endpoint`` is None. - ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials - for the grpc channel. It is ignored if ``channel`` is provided. - client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): - A callback to provide client certificate bytes and private key bytes, - both in PEM format. It is used to configure a mutual TLS channel. It is - ignored if ``channel`` or ``ssl_channel_credentials`` is provided. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport - creation failed for any reason. - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - self._grpc_channel = None - self._ssl_channel_credentials = ssl_channel_credentials - self._stubs: Dict[str, Callable] = {} - - if api_mtls_endpoint: - warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) - if client_cert_source: - warnings.warn("client_cert_source is deprecated", DeprecationWarning) - - if channel: - # Ignore credentials if a channel was passed. - credentials = False - # If a channel was explicitly provided, set it. - self._grpc_channel = channel - self._ssl_channel_credentials = None - - else: - if api_mtls_endpoint: - host = api_mtls_endpoint - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - self._ssl_channel_credentials = SslCredentials().ssl_credentials - - else: - if client_cert_source_for_mtls and not ssl_channel_credentials: - cert, key = client_cert_source_for_mtls() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - - # The base transport sets the host, credentials and scopes - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes, - quota_project_id=quota_project_id, - client_info=client_info, - always_use_jwt_access=always_use_jwt_access, - api_audience=api_audience, - ) - - if not self._grpc_channel: - self._grpc_channel = type(self).create_channel( - self._host, - # use the credentials which are saved - credentials=self._credentials, - # Set ``credentials_file`` to ``None`` here as - # the credentials that we saved earlier should be used. - credentials_file=None, - 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: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - **kwargs) -> grpc.Channel: - """Create and return a gRPC channel object. - Args: - host (Optional[str]): The host for the channel to use. - credentials (Optional[~.Credentials]): The - authorization credentials to attach to requests. These - credentials identify this application to the service. If - none are specified, the client will attempt to ascertain - the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - kwargs (Optional[dict]): Keyword arguments, which are passed to the - channel creation. - Returns: - grpc.Channel: A gRPC channel object. - - Raises: - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - - return grpc_helpers.create_channel( - host, - credentials=credentials, - credentials_file=credentials_file, - quota_project_id=quota_project_id, - default_scopes=cls.AUTH_SCOPES, - scopes=scopes, - default_host=cls.DEFAULT_HOST, - **kwargs - ) - - @property - def grpc_channel(self) -> grpc.Channel: - """Return the channel designed to connect to this service. - """ - return self._grpc_channel - - @property - def detect_intent(self) -> Callable[ - [gcd_session.DetectIntentRequest], - gcd_session.DetectIntentResponse]: - r"""Return a callable for the detect intent method over gRPC. - - Processes a natural language query and returns structured, - actionable data as a result. This method is not idempotent, - because it may cause contexts and session entity types to be - updated, which in turn might affect results of future queries. - - If you might use `Agent - Assist `__ or - other CCAI products now or in the future, consider using - [AnalyzeContent][google.cloud.dialogflow.v2beta1.Participants.AnalyzeContent] - instead of ``DetectIntent``. ``AnalyzeContent`` has additional - functionality for Agent Assist and other CCAI products. - - Note: Always use agent versions for production traffic. See - `Versions and - environments `__. - - Returns: - Callable[[~.DetectIntentRequest], - ~.DetectIntentResponse]: - 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 'detect_intent' not in self._stubs: - self._stubs['detect_intent'] = self.grpc_channel.unary_unary( - '/google.cloud.dialogflow.v2beta1.Sessions/DetectIntent', - request_serializer=gcd_session.DetectIntentRequest.serialize, - response_deserializer=gcd_session.DetectIntentResponse.deserialize, - ) - return self._stubs['detect_intent'] - - @property - def streaming_detect_intent(self) -> Callable[ - [session.StreamingDetectIntentRequest], - session.StreamingDetectIntentResponse]: - r"""Return a callable for the streaming detect intent method over gRPC. - - Processes a natural language query in audio format in a - streaming fashion and returns structured, actionable data as a - result. This method is only available via the gRPC API (not - REST). - - If you might use `Agent - Assist `__ or - other CCAI products now or in the future, consider using - [StreamingAnalyzeContent][google.cloud.dialogflow.v2beta1.Participants.StreamingAnalyzeContent] - instead of ``StreamingDetectIntent``. - ``StreamingAnalyzeContent`` has additional functionality for - Agent Assist and other CCAI products. - - Note: Always use agent versions for production traffic. See - `Versions and - environments `__. - - Returns: - Callable[[~.StreamingDetectIntentRequest], - ~.StreamingDetectIntentResponse]: - 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 'streaming_detect_intent' not in self._stubs: - self._stubs['streaming_detect_intent'] = self.grpc_channel.stream_stream( - '/google.cloud.dialogflow.v2beta1.Sessions/StreamingDetectIntent', - request_serializer=session.StreamingDetectIntentRequest.serialize, - response_deserializer=session.StreamingDetectIntentResponse.deserialize, - ) - return self._stubs['streaming_detect_intent'] - - def close(self): - self.grpc_channel.close() - - @property - def cancel_operation( - self, - ) -> Callable[[operations_pb2.CancelOperationRequest], None]: - r"""Return a callable for the cancel_operation method over gRPC. - """ - # 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 "cancel_operation" not in self._stubs: - self._stubs["cancel_operation"] = self.grpc_channel.unary_unary( - "/google.longrunning.Operations/CancelOperation", - request_serializer=operations_pb2.CancelOperationRequest.SerializeToString, - response_deserializer=None, - ) - return self._stubs["cancel_operation"] - - @property - def get_operation( - self, - ) -> Callable[[operations_pb2.GetOperationRequest], operations_pb2.Operation]: - r"""Return a callable for the get_operation method over gRPC. - """ - # 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_operation" not in self._stubs: - self._stubs["get_operation"] = self.grpc_channel.unary_unary( - "/google.longrunning.Operations/GetOperation", - request_serializer=operations_pb2.GetOperationRequest.SerializeToString, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs["get_operation"] - - @property - def list_operations( - self, - ) -> Callable[[operations_pb2.ListOperationsRequest], operations_pb2.ListOperationsResponse]: - r"""Return a callable for the list_operations method over gRPC. - """ - # 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_operations" not in self._stubs: - self._stubs["list_operations"] = self.grpc_channel.unary_unary( - "/google.longrunning.Operations/ListOperations", - request_serializer=operations_pb2.ListOperationsRequest.SerializeToString, - response_deserializer=operations_pb2.ListOperationsResponse.FromString, - ) - return self._stubs["list_operations"] - - @property - def list_locations( - self, - ) -> Callable[[locations_pb2.ListLocationsRequest], locations_pb2.ListLocationsResponse]: - r"""Return a callable for the list locations method over gRPC. - """ - # 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_locations" not in self._stubs: - self._stubs["list_locations"] = self.grpc_channel.unary_unary( - "/google.cloud.location.Locations/ListLocations", - request_serializer=locations_pb2.ListLocationsRequest.SerializeToString, - response_deserializer=locations_pb2.ListLocationsResponse.FromString, - ) - return self._stubs["list_locations"] - - @property - def get_location( - self, - ) -> Callable[[locations_pb2.GetLocationRequest], locations_pb2.Location]: - r"""Return a callable for the list locations method over gRPC. - """ - # 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_location" not in self._stubs: - self._stubs["get_location"] = self.grpc_channel.unary_unary( - "/google.cloud.location.Locations/GetLocation", - request_serializer=locations_pb2.GetLocationRequest.SerializeToString, - response_deserializer=locations_pb2.Location.FromString, - ) - return self._stubs["get_location"] - - @property - def kind(self) -> str: - return "grpc" - - -__all__ = ( - 'SessionsGrpcTransport', -) diff --git a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/sessions/transports/grpc_asyncio.py b/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/sessions/transports/grpc_asyncio.py deleted file mode 100644 index 137c76454..000000000 --- a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/sessions/transports/grpc_asyncio.py +++ /dev/null @@ -1,414 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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 -from google.api_core import grpc_helpers_async -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore - -import grpc # type: ignore -from grpc.experimental import aio # type: ignore - -from google.cloud.dialogflow_v2beta1.types import session -from google.cloud.dialogflow_v2beta1.types import session as gcd_session -from google.cloud.location import locations_pb2 # type: ignore -from google.longrunning import operations_pb2 -from .base import SessionsTransport, DEFAULT_CLIENT_INFO -from .grpc import SessionsGrpcTransport - - -class SessionsGrpcAsyncIOTransport(SessionsTransport): - """gRPC AsyncIO backend transport for Sessions. - - A service used for session interactions. - - For more information, see the `API interactions - guide `__. - - 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: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - **kwargs) -> aio.Channel: - """Create and return a gRPC AsyncIO channel object. - Args: - host (Optional[str]): The host for the channel to use. - credentials (Optional[~.Credentials]): The - authorization credentials to attach to requests. These - credentials identify this application to the service. If - none are specified, the client will attempt to ascertain - the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - kwargs (Optional[dict]): Keyword arguments, which are passed to the - channel creation. - Returns: - aio.Channel: A gRPC AsyncIO channel object. - """ - - return grpc_helpers_async.create_channel( - host, - credentials=credentials, - credentials_file=credentials_file, - quota_project_id=quota_project_id, - default_scopes=cls.AUTH_SCOPES, - scopes=scopes, - default_host=cls.DEFAULT_HOST, - **kwargs - ) - - def __init__(self, *, - host: str = 'dialogflow.googleapis.com', - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - channel: Optional[aio.Channel] = None, - api_mtls_endpoint: Optional[str] = None, - client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, - ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, - client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - api_audience: Optional[str] = None, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - This argument is ignored if ``channel`` is provided. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - channel (Optional[aio.Channel]): A ``Channel`` instance through - which to make calls. - api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. - If provided, it overrides the ``host`` argument and tries to create - a mutual TLS channel with client SSL credentials from - ``client_cert_source`` or application default SSL credentials. - client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): - Deprecated. A callback to provide client SSL certificate bytes and - private key bytes, both in PEM format. It is ignored if - ``api_mtls_endpoint`` is None. - ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials - for the grpc channel. It is ignored if ``channel`` is provided. - client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): - A callback to provide client certificate bytes and private key bytes, - both in PEM format. It is used to configure a mutual TLS channel. It is - ignored if ``channel`` or ``ssl_channel_credentials`` is provided. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - - Raises: - google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport - creation failed for any reason. - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - self._grpc_channel = None - self._ssl_channel_credentials = ssl_channel_credentials - self._stubs: Dict[str, Callable] = {} - - if api_mtls_endpoint: - warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) - if client_cert_source: - warnings.warn("client_cert_source is deprecated", DeprecationWarning) - - if channel: - # Ignore credentials if a channel was passed. - credentials = False - # If a channel was explicitly provided, set it. - self._grpc_channel = channel - self._ssl_channel_credentials = None - else: - if api_mtls_endpoint: - host = api_mtls_endpoint - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - self._ssl_channel_credentials = SslCredentials().ssl_credentials - - else: - if client_cert_source_for_mtls and not ssl_channel_credentials: - cert, key = client_cert_source_for_mtls() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - - # The base transport sets the host, credentials and scopes - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes, - quota_project_id=quota_project_id, - client_info=client_info, - always_use_jwt_access=always_use_jwt_access, - api_audience=api_audience, - ) - - if not self._grpc_channel: - self._grpc_channel = type(self).create_channel( - self._host, - # use the credentials which are saved - credentials=self._credentials, - # Set ``credentials_file`` to ``None`` here as - # the credentials that we saved earlier should be used. - credentials_file=None, - 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 detect_intent(self) -> Callable[ - [gcd_session.DetectIntentRequest], - Awaitable[gcd_session.DetectIntentResponse]]: - r"""Return a callable for the detect intent method over gRPC. - - Processes a natural language query and returns structured, - actionable data as a result. This method is not idempotent, - because it may cause contexts and session entity types to be - updated, which in turn might affect results of future queries. - - If you might use `Agent - Assist `__ or - other CCAI products now or in the future, consider using - [AnalyzeContent][google.cloud.dialogflow.v2beta1.Participants.AnalyzeContent] - instead of ``DetectIntent``. ``AnalyzeContent`` has additional - functionality for Agent Assist and other CCAI products. - - Note: Always use agent versions for production traffic. See - `Versions and - environments `__. - - Returns: - Callable[[~.DetectIntentRequest], - Awaitable[~.DetectIntentResponse]]: - 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 'detect_intent' not in self._stubs: - self._stubs['detect_intent'] = self.grpc_channel.unary_unary( - '/google.cloud.dialogflow.v2beta1.Sessions/DetectIntent', - request_serializer=gcd_session.DetectIntentRequest.serialize, - response_deserializer=gcd_session.DetectIntentResponse.deserialize, - ) - return self._stubs['detect_intent'] - - @property - def streaming_detect_intent(self) -> Callable[ - [session.StreamingDetectIntentRequest], - Awaitable[session.StreamingDetectIntentResponse]]: - r"""Return a callable for the streaming detect intent method over gRPC. - - Processes a natural language query in audio format in a - streaming fashion and returns structured, actionable data as a - result. This method is only available via the gRPC API (not - REST). - - If you might use `Agent - Assist `__ or - other CCAI products now or in the future, consider using - [StreamingAnalyzeContent][google.cloud.dialogflow.v2beta1.Participants.StreamingAnalyzeContent] - instead of ``StreamingDetectIntent``. - ``StreamingAnalyzeContent`` has additional functionality for - Agent Assist and other CCAI products. - - Note: Always use agent versions for production traffic. See - `Versions and - environments `__. - - Returns: - Callable[[~.StreamingDetectIntentRequest], - Awaitable[~.StreamingDetectIntentResponse]]: - 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 'streaming_detect_intent' not in self._stubs: - self._stubs['streaming_detect_intent'] = self.grpc_channel.stream_stream( - '/google.cloud.dialogflow.v2beta1.Sessions/StreamingDetectIntent', - request_serializer=session.StreamingDetectIntentRequest.serialize, - response_deserializer=session.StreamingDetectIntentResponse.deserialize, - ) - return self._stubs['streaming_detect_intent'] - - def close(self): - return self.grpc_channel.close() - - @property - def cancel_operation( - self, - ) -> Callable[[operations_pb2.CancelOperationRequest], None]: - r"""Return a callable for the cancel_operation method over gRPC. - """ - # 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 "cancel_operation" not in self._stubs: - self._stubs["cancel_operation"] = self.grpc_channel.unary_unary( - "/google.longrunning.Operations/CancelOperation", - request_serializer=operations_pb2.CancelOperationRequest.SerializeToString, - response_deserializer=None, - ) - return self._stubs["cancel_operation"] - - @property - def get_operation( - self, - ) -> Callable[[operations_pb2.GetOperationRequest], operations_pb2.Operation]: - r"""Return a callable for the get_operation method over gRPC. - """ - # 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_operation" not in self._stubs: - self._stubs["get_operation"] = self.grpc_channel.unary_unary( - "/google.longrunning.Operations/GetOperation", - request_serializer=operations_pb2.GetOperationRequest.SerializeToString, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs["get_operation"] - - @property - def list_operations( - self, - ) -> Callable[[operations_pb2.ListOperationsRequest], operations_pb2.ListOperationsResponse]: - r"""Return a callable for the list_operations method over gRPC. - """ - # 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_operations" not in self._stubs: - self._stubs["list_operations"] = self.grpc_channel.unary_unary( - "/google.longrunning.Operations/ListOperations", - request_serializer=operations_pb2.ListOperationsRequest.SerializeToString, - response_deserializer=operations_pb2.ListOperationsResponse.FromString, - ) - return self._stubs["list_operations"] - - @property - def list_locations( - self, - ) -> Callable[[locations_pb2.ListLocationsRequest], locations_pb2.ListLocationsResponse]: - r"""Return a callable for the list locations method over gRPC. - """ - # 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_locations" not in self._stubs: - self._stubs["list_locations"] = self.grpc_channel.unary_unary( - "/google.cloud.location.Locations/ListLocations", - request_serializer=locations_pb2.ListLocationsRequest.SerializeToString, - response_deserializer=locations_pb2.ListLocationsResponse.FromString, - ) - return self._stubs["list_locations"] - - @property - def get_location( - self, - ) -> Callable[[locations_pb2.GetLocationRequest], locations_pb2.Location]: - r"""Return a callable for the list locations method over gRPC. - """ - # 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_location" not in self._stubs: - self._stubs["get_location"] = self.grpc_channel.unary_unary( - "/google.cloud.location.Locations/GetLocation", - request_serializer=locations_pb2.GetLocationRequest.SerializeToString, - response_deserializer=locations_pb2.Location.FromString, - ) - return self._stubs["get_location"] - - -__all__ = ( - 'SessionsGrpcAsyncIOTransport', -) diff --git a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/sessions/transports/rest.py b/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/sessions/transports/rest.py deleted file mode 100644 index a72342ab6..000000000 --- a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/sessions/transports/rest.py +++ /dev/null @@ -1,774 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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 google.auth.transport.requests import AuthorizedSession # type: ignore -import json # type: ignore -import grpc # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore -from google.auth import credentials as ga_credentials # type: ignore -from google.api_core import exceptions as core_exceptions -from google.api_core import retry as retries -from google.api_core import rest_helpers -from google.api_core import rest_streaming -from google.api_core import path_template -from google.api_core import gapic_v1 - -from google.protobuf import json_format -from google.cloud.location import locations_pb2 # type: ignore -from google.longrunning import operations_pb2 -from requests import __version__ as requests_version -import dataclasses -import re -from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union -import warnings - -try: - OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] -except AttributeError: # pragma: NO COVER - OptionalRetry = Union[retries.Retry, object] # 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 as BASE_DEFAULT_CLIENT_INFO - - -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=BASE_DEFAULT_CLIENT_INFO.gapic_version, - grpc_version=None, - rest_version=requests_version, -) - - -class SessionsRestInterceptor: - """Interceptor for Sessions. - - Interceptors are used to manipulate requests, request metadata, and responses - in arbitrary ways. - Example use cases include: - * Logging - * Verifying requests according to service or custom semantics - * Stripping extraneous information from responses - - These use cases and more can be enabled by injecting an - instance of a custom subclass when constructing the SessionsRestTransport. - - .. code-block:: python - class MyCustomSessionsInterceptor(SessionsRestInterceptor): - def pre_detect_intent(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_detect_intent(self, response): - logging.log(f"Received response: {response}") - return response - - transport = SessionsRestTransport(interceptor=MyCustomSessionsInterceptor()) - client = SessionsClient(transport=transport) - - - """ - def pre_detect_intent(self, request: gcd_session.DetectIntentRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[gcd_session.DetectIntentRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for detect_intent - - Override in a subclass to manipulate the request or metadata - before they are sent to the Sessions server. - """ - return request, metadata - - def post_detect_intent(self, response: gcd_session.DetectIntentResponse) -> gcd_session.DetectIntentResponse: - """Post-rpc interceptor for detect_intent - - Override in a subclass to manipulate the response - after it is returned by the Sessions server but before - it is returned to user code. - """ - return response - - def pre_get_location( - self, request: locations_pb2.GetLocationRequest, metadata: Sequence[Tuple[str, str]] - ) -> Tuple[locations_pb2.GetLocationRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for get_location - - Override in a subclass to manipulate the request or metadata - before they are sent to the Sessions server. - """ - return request, metadata - - def post_get_location( - self, response: locations_pb2.Location - ) -> locations_pb2.Location: - """Post-rpc interceptor for get_location - - Override in a subclass to manipulate the response - after it is returned by the Sessions server but before - it is returned to user code. - """ - return response - def pre_list_locations( - self, request: locations_pb2.ListLocationsRequest, metadata: Sequence[Tuple[str, str]] - ) -> Tuple[locations_pb2.ListLocationsRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for list_locations - - Override in a subclass to manipulate the request or metadata - before they are sent to the Sessions server. - """ - return request, metadata - - def post_list_locations( - self, response: locations_pb2.ListLocationsResponse - ) -> locations_pb2.ListLocationsResponse: - """Post-rpc interceptor for list_locations - - Override in a subclass to manipulate the response - after it is returned by the Sessions server but before - it is returned to user code. - """ - return response - def pre_cancel_operation( - self, request: operations_pb2.CancelOperationRequest, metadata: Sequence[Tuple[str, str]] - ) -> Tuple[operations_pb2.CancelOperationRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for cancel_operation - - Override in a subclass to manipulate the request or metadata - before they are sent to the Sessions server. - """ - return request, metadata - - def post_cancel_operation( - self, response: None - ) -> None: - """Post-rpc interceptor for cancel_operation - - Override in a subclass to manipulate the response - after it is returned by the Sessions server but before - it is returned to user code. - """ - return response - def pre_get_operation( - self, request: operations_pb2.GetOperationRequest, metadata: Sequence[Tuple[str, str]] - ) -> Tuple[operations_pb2.GetOperationRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for get_operation - - Override in a subclass to manipulate the request or metadata - before they are sent to the Sessions server. - """ - return request, metadata - - def post_get_operation( - self, response: operations_pb2.Operation - ) -> operations_pb2.Operation: - """Post-rpc interceptor for get_operation - - Override in a subclass to manipulate the response - after it is returned by the Sessions server but before - it is returned to user code. - """ - return response - def pre_list_operations( - self, request: operations_pb2.ListOperationsRequest, metadata: Sequence[Tuple[str, str]] - ) -> Tuple[operations_pb2.ListOperationsRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for list_operations - - Override in a subclass to manipulate the request or metadata - before they are sent to the Sessions server. - """ - return request, metadata - - def post_list_operations( - self, response: operations_pb2.ListOperationsResponse - ) -> operations_pb2.ListOperationsResponse: - """Post-rpc interceptor for list_operations - - Override in a subclass to manipulate the response - after it is returned by the Sessions server but before - it is returned to user code. - """ - return response - - -@dataclasses.dataclass -class SessionsRestStub: - _session: AuthorizedSession - _host: str - _interceptor: SessionsRestInterceptor - - -class SessionsRestTransport(SessionsTransport): - """REST backend transport for Sessions. - - A service used for session interactions. - - For more information, see the `API interactions - guide `__. - - 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 JSON representations of protocol buffers over HTTP/1.1 - - """ - - def __init__(self, *, - host: str = 'dialogflow.googleapis.com', - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - client_cert_source_for_mtls: Optional[Callable[[ - ], Tuple[bytes, bytes]]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - url_scheme: str = 'https', - interceptor: Optional[SessionsRestInterceptor] = None, - api_audience: Optional[str] = None, - ) -> 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 ignored if ``channel`` is provided. - scopes (Optional(Sequence[str])): A list of scopes. This argument is - ignored if ``channel`` is provided. - client_cert_source_for_mtls (Callable[[], Tuple[bytes, bytes]]): Client - certificate to configure mutual TLS HTTP channel. It is ignored - if ``channel`` is provided. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you are developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - url_scheme: the protocol scheme for the API endpoint. Normally - "https", but for testing or local servers, - "http" can be specified. - """ - # Run the base constructor - # TODO(yon-mg): resolve other ctor params i.e. scopes, quota, etc. - # TODO: When custom host (api_endpoint) is set, `scopes` must *also* be set on the - # credentials object - maybe_url_match = re.match("^(?Phttp(?:s)?://)?(?P.*)$", host) - if maybe_url_match is None: - raise ValueError(f"Unexpected hostname structure: {host}") # pragma: NO COVER - - url_match_items = maybe_url_match.groupdict() - - host = f"{url_scheme}://{host}" if not url_match_items["scheme"] else host - - super().__init__( - host=host, - credentials=credentials, - client_info=client_info, - always_use_jwt_access=always_use_jwt_access, - api_audience=api_audience - ) - self._session = AuthorizedSession( - self._credentials, default_host=self.DEFAULT_HOST) - if client_cert_source_for_mtls: - self._session.configure_mtls_channel(client_cert_source_for_mtls) - self._interceptor = interceptor or SessionsRestInterceptor() - self._prep_wrapped_messages(client_info) - - class _DetectIntent(SessionsRestStub): - def __hash__(self): - return hash("DetectIntent") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: gcd_session.DetectIntentRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> gcd_session.DetectIntentResponse: - r"""Call the detect intent method over HTTP. - - Args: - request (~.gcd_session.DetectIntentRequest): - The request object. The request to detect user's intent. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.gcd_session.DetectIntentResponse: - The message returned from the - DetectIntent method. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'post', - 'uri': '/v2beta1/{session=projects/*/agent/sessions/*}:detectIntent', - 'body': '*', - }, -{ - 'method': 'post', - 'uri': '/v2beta1/{session=projects/*/agent/environments/*/users/*/sessions/*}:detectIntent', - 'body': '*', - }, -{ - 'method': 'post', - 'uri': '/v2beta1/{session=projects/*/locations/*/agent/sessions/*}:detectIntent', - 'body': '*', - }, -{ - 'method': 'post', - 'uri': '/v2beta1/{session=projects/*/locations/*/agent/environments/*/users/*/sessions/*}:detectIntent', - 'body': '*', - }, - ] - request, metadata = self._interceptor.pre_detect_intent(request, metadata) - pb_request = gcd_session.DetectIntentRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request['body'], - including_default_value_fields=False, - use_integers_for_enums=True - ) - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - including_default_value_fields=False, - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = gcd_session.DetectIntentResponse() - pb_resp = gcd_session.DetectIntentResponse.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_detect_intent(resp) - return resp - - class _StreamingDetectIntent(SessionsRestStub): - def __hash__(self): - return hash("StreamingDetectIntent") - - def __call__(self, - request: session.StreamingDetectIntentRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> rest_streaming.ResponseIterator: - raise NotImplementedError( - "Method StreamingDetectIntent is not available over REST transport" - ) - - @property - def detect_intent(self) -> Callable[ - [gcd_session.DetectIntentRequest], - gcd_session.DetectIntentResponse]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._DetectIntent(self._session, self._host, self._interceptor) # type: ignore - - @property - def streaming_detect_intent(self) -> Callable[ - [session.StreamingDetectIntentRequest], - session.StreamingDetectIntentResponse]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._StreamingDetectIntent(self._session, self._host, self._interceptor) # type: ignore - - @property - def get_location(self): - return self._GetLocation(self._session, self._host, self._interceptor) # type: ignore - - class _GetLocation(SessionsRestStub): - def __call__(self, - request: locations_pb2.GetLocationRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> locations_pb2.Location: - - r"""Call the get location method over HTTP. - - Args: - request (locations_pb2.GetLocationRequest): - The request object for GetLocation method. - 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: - locations_pb2.Location: Response from GetLocation method. - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v2beta1/{name=projects/*/locations/*}', - }, - ] - - request, metadata = self._interceptor.pre_get_location(request, metadata) - request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode( - http_options, **request_kwargs) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json.dumps(transcoded_request['query_params'])) - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - resp = locations_pb2.Location() - resp = json_format.Parse(response.content.decode("utf-8"), resp) - resp = self._interceptor.post_get_location(resp) - return resp - - @property - def list_locations(self): - return self._ListLocations(self._session, self._host, self._interceptor) # type: ignore - - class _ListLocations(SessionsRestStub): - def __call__(self, - request: locations_pb2.ListLocationsRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> locations_pb2.ListLocationsResponse: - - r"""Call the list locations method over HTTP. - - Args: - request (locations_pb2.ListLocationsRequest): - The request object for ListLocations method. - 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: - locations_pb2.ListLocationsResponse: Response from ListLocations method. - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v2beta1/{name=projects/*}/locations', - }, - ] - - request, metadata = self._interceptor.pre_list_locations(request, metadata) - request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode( - http_options, **request_kwargs) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json.dumps(transcoded_request['query_params'])) - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - resp = locations_pb2.ListLocationsResponse() - resp = json_format.Parse(response.content.decode("utf-8"), resp) - resp = self._interceptor.post_list_locations(resp) - return resp - - @property - def cancel_operation(self): - return self._CancelOperation(self._session, self._host, self._interceptor) # type: ignore - - class _CancelOperation(SessionsRestStub): - def __call__(self, - request: operations_pb2.CancelOperationRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> None: - - r"""Call the cancel operation method over HTTP. - - Args: - request (operations_pb2.CancelOperationRequest): - The request object for CancelOperation method. - 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. - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'post', - 'uri': '/v2beta1/{name=projects/*/operations/*}:cancel', - }, -{ - 'method': 'post', - 'uri': '/v2beta1/{name=projects/*/locations/*/operations/*}:cancel', - }, - ] - - request, metadata = self._interceptor.pre_cancel_operation(request, metadata) - request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode( - http_options, **request_kwargs) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json.dumps(transcoded_request['query_params'])) - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - return self._interceptor.post_cancel_operation(None) - - @property - def get_operation(self): - return self._GetOperation(self._session, self._host, self._interceptor) # type: ignore - - class _GetOperation(SessionsRestStub): - def __call__(self, - request: operations_pb2.GetOperationRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> operations_pb2.Operation: - - r"""Call the get operation method over HTTP. - - Args: - request (operations_pb2.GetOperationRequest): - The request object for GetOperation method. - 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: - operations_pb2.Operation: Response from GetOperation method. - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v2beta1/{name=projects/*/operations/*}', - }, -{ - 'method': 'get', - 'uri': '/v2beta1/{name=projects/*/locations/*/operations/*}', - }, - ] - - request, metadata = self._interceptor.pre_get_operation(request, metadata) - request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode( - http_options, **request_kwargs) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json.dumps(transcoded_request['query_params'])) - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - resp = operations_pb2.Operation() - resp = json_format.Parse(response.content.decode("utf-8"), resp) - resp = self._interceptor.post_get_operation(resp) - return resp - - @property - def list_operations(self): - return self._ListOperations(self._session, self._host, self._interceptor) # type: ignore - - class _ListOperations(SessionsRestStub): - def __call__(self, - request: operations_pb2.ListOperationsRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> operations_pb2.ListOperationsResponse: - - r"""Call the list operations method over HTTP. - - Args: - request (operations_pb2.ListOperationsRequest): - The request object for ListOperations method. - 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: - operations_pb2.ListOperationsResponse: Response from ListOperations method. - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v2beta1/{name=projects/*}/operations', - }, -{ - 'method': 'get', - 'uri': '/v2beta1/{name=projects/*/locations/*}/operations', - }, - ] - - request, metadata = self._interceptor.pre_list_operations(request, metadata) - request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode( - http_options, **request_kwargs) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json.dumps(transcoded_request['query_params'])) - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - resp = operations_pb2.ListOperationsResponse() - resp = json_format.Parse(response.content.decode("utf-8"), resp) - resp = self._interceptor.post_list_operations(resp) - return resp - - @property - def kind(self) -> str: - return "rest" - - def close(self): - self._session.close() - - -__all__=( - 'SessionsRestTransport', -) diff --git a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/versions/__init__.py b/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/versions/__init__.py deleted file mode 100644 index 8f339fd03..000000000 --- a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/versions/__init__.py +++ /dev/null @@ -1,22 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/versions/async_client.py b/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/versions/async_client.py deleted file mode 100644 index 2e3d22e04..000000000 --- a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/versions/async_client.py +++ /dev/null @@ -1,1059 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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, Mapping, MutableMapping, MutableSequence, Optional, Sequence, Tuple, Type, Union - -from google.cloud.dialogflow_v2beta1 import gapic_version as package_version - -from google.api_core.client_options import ClientOptions -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import retry as retries -from google.auth import credentials as ga_credentials # type: ignore -from google.oauth2 import service_account # type: ignore - -try: - OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] -except AttributeError: # pragma: NO COVER - OptionalRetry = Union[retries.Retry, object] # 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.cloud.location import locations_pb2 # type: ignore -from google.longrunning import operations_pb2 -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 - - @classmethod - def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[ClientOptions] = None): - """Return the API endpoint and client cert source for mutual TLS. - - The client cert source is determined in the following order: - (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the - client cert source is None. - (2) if `client_options.client_cert_source` is provided, use the provided one; if the - default client cert source exists, use the default one; otherwise the client cert - source is None. - - The API endpoint is determined in the following order: - (1) if `client_options.api_endpoint` if provided, use the provided one. - (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the - default mTLS endpoint; if the environment variable is "never", use the default API - endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise - use the default API endpoint. - - More details can be found at https://google.aip.dev/auth/4114. - - Args: - client_options (google.api_core.client_options.ClientOptions): Custom options for the - client. Only the `api_endpoint` and `client_cert_source` properties may be used - in this method. - - Returns: - Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the - client cert source to use. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If any errors happen. - """ - return VersionsClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore - - @property - def transport(self) -> VersionsTransport: - """Returns 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: Optional[ga_credentials.Credentials] = None, - transport: Union[str, VersionsTransport] = "grpc_asyncio", - client_options: Optional[ClientOptions] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates 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: Optional[Union[version.ListVersionsRequest, dict]] = None, - *, - parent: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListVersionsAsyncPager: - r"""Returns the list of all versions of the specified - agent. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import dialogflow_v2beta1 - - async def sample_list_versions(): - # Create a client - client = dialogflow_v2beta1.VersionsAsyncClient() - - # Initialize request argument(s) - request = dialogflow_v2beta1.ListVersionsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_versions(request=request) - - # Handle the response - async for response in page_result: - print(response) - - Args: - request (Optional[Union[google.cloud.dialogflow_v2beta1.types.ListVersionsRequest, dict]]): - 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. - # Quick 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: Optional[Union[version.GetVersionRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> version.Version: - r"""Retrieves the specified agent version. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import dialogflow_v2beta1 - - async def sample_get_version(): - # Create a client - client = dialogflow_v2beta1.VersionsAsyncClient() - - # Initialize request argument(s) - request = dialogflow_v2beta1.GetVersionRequest( - name="name_value", - ) - - # Make the request - response = await client.get_version(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.dialogflow_v2beta1.types.GetVersionRequest, dict]]): - 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. - # Quick 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: Optional[Union[gcd_version.CreateVersionRequest, dict]] = None, - *, - parent: Optional[str] = None, - version: Optional[gcd_version.Version] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - 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. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import dialogflow_v2beta1 - - async def sample_create_version(): - # Create a client - client = dialogflow_v2beta1.VersionsAsyncClient() - - # Initialize request argument(s) - request = dialogflow_v2beta1.CreateVersionRequest( - parent="parent_value", - ) - - # Make the request - response = await client.create_version(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.dialogflow_v2beta1.types.CreateVersionRequest, dict]]): - 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. - # Quick 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: Optional[Union[gcd_version.UpdateVersionRequest, dict]] = None, - *, - version: Optional[gcd_version.Version] = None, - update_mask: Optional[field_mask_pb2.FieldMask] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - 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. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import dialogflow_v2beta1 - - async def sample_update_version(): - # Create a client - client = dialogflow_v2beta1.VersionsAsyncClient() - - # Initialize request argument(s) - request = dialogflow_v2beta1.UpdateVersionRequest( - ) - - # Make the request - response = await client.update_version(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.dialogflow_v2beta1.types.UpdateVersionRequest, dict]]): - 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. - # Quick 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: Optional[Union[version.DeleteVersionRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> None: - r"""Delete the specified agent version. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import dialogflow_v2beta1 - - async def sample_delete_version(): - # Create a client - client = dialogflow_v2beta1.VersionsAsyncClient() - - # Initialize request argument(s) - request = dialogflow_v2beta1.DeleteVersionRequest( - name="name_value", - ) - - # Make the request - await client.delete_version(request=request) - - Args: - request (Optional[Union[google.cloud.dialogflow_v2beta1.types.DeleteVersionRequest, dict]]): - 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. - # Quick 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, - ) - - async def list_operations( - self, - request: Optional[operations_pb2.ListOperationsRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operations_pb2.ListOperationsResponse: - r"""Lists operations that match the specified filter in the request. - - Args: - request (:class:`~.operations_pb2.ListOperationsRequest`): - The request object. Request message for - `ListOperations` method. - 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: - ~.operations_pb2.ListOperationsResponse: - Response message for ``ListOperations`` method. - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = operations_pb2.ListOperationsRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._client._transport.list_operations, - 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 get_operation( - self, - request: Optional[operations_pb2.GetOperationRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operations_pb2.Operation: - r"""Gets the latest state of a long-running operation. - - Args: - request (:class:`~.operations_pb2.GetOperationRequest`): - The request object. Request message for - `GetOperation` method. - 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: - ~.operations_pb2.Operation: - An ``Operation`` object. - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = operations_pb2.GetOperationRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._client._transport.get_operation, - 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 cancel_operation( - self, - request: Optional[operations_pb2.CancelOperationRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> None: - r"""Starts asynchronous cancellation on a long-running operation. - - The server makes a best effort to cancel the operation, but success - is not guaranteed. If the server doesn't support this method, it returns - `google.rpc.Code.UNIMPLEMENTED`. - - Args: - request (:class:`~.operations_pb2.CancelOperationRequest`): - The request object. Request message for - `CancelOperation` method. - 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: - None - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = operations_pb2.CancelOperationRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._client._transport.cancel_operation, - 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_location( - self, - request: Optional[locations_pb2.GetLocationRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> locations_pb2.Location: - r"""Gets information about a location. - - Args: - request (:class:`~.location_pb2.GetLocationRequest`): - The request object. Request message for - `GetLocation` method. - 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: - ~.location_pb2.Location: - Location object. - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = locations_pb2.GetLocationRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._client._transport.get_location, - 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 list_locations( - self, - request: Optional[locations_pb2.ListLocationsRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> locations_pb2.ListLocationsResponse: - r"""Lists information about the supported locations for this service. - - Args: - request (:class:`~.location_pb2.ListLocationsRequest`): - The request object. Request message for - `ListLocations` method. - 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: - ~.location_pb2.ListLocationsResponse: - Response message for ``ListLocations`` method. - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = locations_pb2.ListLocationsRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._client._transport.list_locations, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("name", request.name),)), - ) - - # Send the request. - response = await rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - async def __aenter__(self): - return self - - async def __aexit__(self, exc_type, exc, tb): - await self.transport.close() - -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) - - -__all__ = ( - "VersionsAsyncClient", -) diff --git a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/versions/client.py b/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/versions/client.py deleted file mode 100644 index bfec6c30c..000000000 --- a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/versions/client.py +++ /dev/null @@ -1,1258 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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 os -import re -from typing import Dict, Mapping, MutableMapping, MutableSequence, Optional, Sequence, Tuple, Type, Union, cast - -from google.cloud.dialogflow_v2beta1 import gapic_version as package_version - -from google.api_core import client_options as client_options_lib -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import retry as retries -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 - -try: - OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] -except AttributeError: # pragma: NO COVER - OptionalRetry = Union[retries.Retry, object] # 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.cloud.location import locations_pb2 # type: ignore -from google.longrunning import operations_pb2 -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 -from .transports.rest import VersionsRestTransport - - -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 - _transport_registry["rest"] = VersionsRestTransport - - def get_transport_class(cls, - label: Optional[str] = None, - ) -> Type[VersionsTransport]: - """Returns an appropriate transport class. - - Args: - label: The name of the desired transport. If none is - provided, then the first transport in the registry is used. - - Returns: - The transport class to use. - """ - # If a specific transport is requested, return that one. - if label: - return cls._transport_registry[label] - - # No transport is requested; return the default (that is, the first one - # in the dictionary). - return next(iter(cls._transport_registry.values())) - - -class VersionsClient(metaclass=VersionsClientMeta): - """Service for managing - [Versions][google.cloud.dialogflow.v2beta1.Version]. - """ - - @staticmethod - def _get_default_mtls_endpoint(api_endpoint): - """Converts api endpoint to mTLS endpoint. - - Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to - "*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively. - Args: - api_endpoint (Optional[str]): the api endpoint to convert. - Returns: - str: converted mTLS api endpoint. - """ - if not api_endpoint: - return api_endpoint - - mtls_endpoint_re = re.compile( - r"(?P[^.]+)(?P\.mtls)?(?P\.sandbox)?(?P\.googleapis\.com)?" - ) - - m = mtls_endpoint_re.match(api_endpoint) - name, mtls, sandbox, googledomain = m.groups() - if mtls or not googledomain: - return api_endpoint - - if sandbox: - return api_endpoint.replace( - "sandbox.googleapis.com", "mtls.sandbox.googleapis.com" - ) - - return api_endpoint.replace(".googleapis.com", ".mtls.googleapis.com") - - DEFAULT_ENDPOINT = "dialogflow.googleapis.com" - DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore - DEFAULT_ENDPOINT - ) - - @classmethod - def from_service_account_info(cls, info: dict, *args, **kwargs): - """Creates an instance of this client using the provided credentials - info. - - Args: - info (dict): The service account private key info. - args: Additional arguments to pass to the constructor. - kwargs: Additional arguments to pass to the constructor. - - Returns: - 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: - """Returns 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: - """Returns 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]: - """Parses 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: - """Returns a fully-qualified billing_account string.""" - return "billingAccounts/{billing_account}".format(billing_account=billing_account, ) - - @staticmethod - def parse_common_billing_account_path(path: str) -> Dict[str,str]: - """Parse a billing_account path into its component segments.""" - m = re.match(r"^billingAccounts/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_folder_path(folder: str, ) -> str: - """Returns a fully-qualified folder string.""" - return "folders/{folder}".format(folder=folder, ) - - @staticmethod - def parse_common_folder_path(path: str) -> Dict[str,str]: - """Parse a folder path into its component segments.""" - m = re.match(r"^folders/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_organization_path(organization: str, ) -> str: - """Returns a fully-qualified organization string.""" - return "organizations/{organization}".format(organization=organization, ) - - @staticmethod - def parse_common_organization_path(path: str) -> Dict[str,str]: - """Parse a organization path into its component segments.""" - m = re.match(r"^organizations/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_project_path(project: str, ) -> str: - """Returns a fully-qualified project string.""" - return "projects/{project}".format(project=project, ) - - @staticmethod - def parse_common_project_path(path: str) -> Dict[str,str]: - """Parse a project path into its component segments.""" - m = re.match(r"^projects/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_location_path(project: str, location: str, ) -> str: - """Returns a fully-qualified location string.""" - return "projects/{project}/locations/{location}".format(project=project, location=location, ) - - @staticmethod - def parse_common_location_path(path: str) -> Dict[str,str]: - """Parse a location path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)$", path) - return m.groupdict() if m else {} - - @classmethod - def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[client_options_lib.ClientOptions] = None): - """Return the API endpoint and client cert source for mutual TLS. - - The client cert source is determined in the following order: - (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the - client cert source is None. - (2) if `client_options.client_cert_source` is provided, use the provided one; if the - default client cert source exists, use the default one; otherwise the client cert - source is None. - - The API endpoint is determined in the following order: - (1) if `client_options.api_endpoint` if provided, use the provided one. - (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the - default mTLS endpoint; if the environment variable is "never", use the default API - endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise - use the default API endpoint. - - More details can be found at https://google.aip.dev/auth/4114. - - Args: - client_options (google.api_core.client_options.ClientOptions): Custom options for the - client. Only the `api_endpoint` and `client_cert_source` properties may be used - in this method. - - Returns: - Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the - client cert source to use. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If any errors happen. - """ - if client_options is None: - client_options = client_options_lib.ClientOptions() - use_client_cert = os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false") - use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") - if use_client_cert not in ("true", "false"): - raise ValueError("Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`") - if use_mtls_endpoint not in ("auto", "never", "always"): - raise MutualTLSChannelError("Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`") - - # Figure out the client cert source to use. - client_cert_source = None - if use_client_cert == "true": - if client_options.client_cert_source: - client_cert_source = client_options.client_cert_source - elif mtls.has_default_client_cert_source(): - client_cert_source = mtls.default_client_cert_source() - - # Figure out which api endpoint to use. - if client_options.api_endpoint is not None: - api_endpoint = client_options.api_endpoint - elif use_mtls_endpoint == "always" or (use_mtls_endpoint == "auto" and client_cert_source): - api_endpoint = cls.DEFAULT_MTLS_ENDPOINT - else: - api_endpoint = cls.DEFAULT_ENDPOINT - - return api_endpoint, client_cert_source - - def __init__(self, *, - credentials: Optional[ga_credentials.Credentials] = None, - transport: Optional[Union[str, VersionsTransport]] = None, - client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates 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 (Optional[Union[google.api_core.client_options.ClientOptions, dict]]): 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() - client_options = cast(client_options_lib.ClientOptions, client_options) - - api_endpoint, client_cert_source_func = self.get_mtls_endpoint_and_cert_source(client_options) - - api_key_value = getattr(client_options, "api_key", None) - if api_key_value and credentials: - raise ValueError("client_options.api_key and credentials are mutually exclusive") - - # 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 or api_key_value: - 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: - import google.auth._default # type: ignore - - if api_key_value and hasattr(google.auth._default, "get_api_key_credentials"): - credentials = google.auth._default.get_api_key_credentials(api_key_value) - - Transport = type(self).get_transport_class(transport) - self._transport = Transport( - credentials=credentials, - credentials_file=client_options.credentials_file, - host=api_endpoint, - scopes=client_options.scopes, - client_cert_source_for_mtls=client_cert_source_func, - quota_project_id=client_options.quota_project_id, - client_info=client_info, - always_use_jwt_access=True, - api_audience=client_options.api_audience, - ) - - def list_versions(self, - request: Optional[Union[version.ListVersionsRequest, dict]] = None, - *, - parent: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListVersionsPager: - r"""Returns the list of all versions of the specified - agent. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import dialogflow_v2beta1 - - def sample_list_versions(): - # Create a client - client = dialogflow_v2beta1.VersionsClient() - - # Initialize request argument(s) - request = dialogflow_v2beta1.ListVersionsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_versions(request=request) - - # Handle the response - for response in page_result: - print(response) - - Args: - request (Union[google.cloud.dialogflow_v2beta1.types.ListVersionsRequest, dict]): - 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. - # Quick 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: Optional[Union[version.GetVersionRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> version.Version: - r"""Retrieves the specified agent version. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import dialogflow_v2beta1 - - def sample_get_version(): - # Create a client - client = dialogflow_v2beta1.VersionsClient() - - # Initialize request argument(s) - request = dialogflow_v2beta1.GetVersionRequest( - name="name_value", - ) - - # Make the request - response = client.get_version(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.dialogflow_v2beta1.types.GetVersionRequest, dict]): - 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. - # Quick 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: Optional[Union[gcd_version.CreateVersionRequest, dict]] = None, - *, - parent: Optional[str] = None, - version: Optional[gcd_version.Version] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - 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. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import dialogflow_v2beta1 - - def sample_create_version(): - # Create a client - client = dialogflow_v2beta1.VersionsClient() - - # Initialize request argument(s) - request = dialogflow_v2beta1.CreateVersionRequest( - parent="parent_value", - ) - - # Make the request - response = client.create_version(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.dialogflow_v2beta1.types.CreateVersionRequest, dict]): - 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. - # Quick 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: Optional[Union[gcd_version.UpdateVersionRequest, dict]] = None, - *, - version: Optional[gcd_version.Version] = None, - update_mask: Optional[field_mask_pb2.FieldMask] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - 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. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import dialogflow_v2beta1 - - def sample_update_version(): - # Create a client - client = dialogflow_v2beta1.VersionsClient() - - # Initialize request argument(s) - request = dialogflow_v2beta1.UpdateVersionRequest( - ) - - # Make the request - response = client.update_version(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.dialogflow_v2beta1.types.UpdateVersionRequest, dict]): - 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. - # Quick 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: Optional[Union[version.DeleteVersionRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> None: - r"""Delete the specified agent version. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import dialogflow_v2beta1 - - def sample_delete_version(): - # Create a client - client = dialogflow_v2beta1.VersionsClient() - - # Initialize request argument(s) - request = dialogflow_v2beta1.DeleteVersionRequest( - name="name_value", - ) - - # Make the request - client.delete_version(request=request) - - Args: - request (Union[google.cloud.dialogflow_v2beta1.types.DeleteVersionRequest, dict]): - 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. - # Quick 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, - ) - - def __enter__(self) -> "VersionsClient": - return self - - def __exit__(self, type, value, traceback): - """Releases underlying transport's resources. - - .. warning:: - ONLY use as a context manager if the transport is NOT shared - with other clients! Exiting the with block will CLOSE the transport - and may cause errors in other clients! - """ - self.transport.close() - - def list_operations( - self, - request: Optional[operations_pb2.ListOperationsRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operations_pb2.ListOperationsResponse: - r"""Lists operations that match the specified filter in the request. - - Args: - request (:class:`~.operations_pb2.ListOperationsRequest`): - The request object. Request message for - `ListOperations` method. - 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: - ~.operations_pb2.ListOperationsResponse: - Response message for ``ListOperations`` method. - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = operations_pb2.ListOperationsRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._transport.list_operations, - 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 = rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - def get_operation( - self, - request: Optional[operations_pb2.GetOperationRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operations_pb2.Operation: - r"""Gets the latest state of a long-running operation. - - Args: - request (:class:`~.operations_pb2.GetOperationRequest`): - The request object. Request message for - `GetOperation` method. - 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: - ~.operations_pb2.Operation: - An ``Operation`` object. - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = operations_pb2.GetOperationRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._transport.get_operation, - 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 = rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - def cancel_operation( - self, - request: Optional[operations_pb2.CancelOperationRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> None: - r"""Starts asynchronous cancellation on a long-running operation. - - The server makes a best effort to cancel the operation, but success - is not guaranteed. If the server doesn't support this method, it returns - `google.rpc.Code.UNIMPLEMENTED`. - - Args: - request (:class:`~.operations_pb2.CancelOperationRequest`): - The request object. Request message for - `CancelOperation` method. - 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: - None - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = operations_pb2.CancelOperationRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._transport.cancel_operation, - 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. - rpc(request, retry=retry, timeout=timeout, metadata=metadata,) - - def get_location( - self, - request: Optional[locations_pb2.GetLocationRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> locations_pb2.Location: - r"""Gets information about a location. - - Args: - request (:class:`~.location_pb2.GetLocationRequest`): - The request object. Request message for - `GetLocation` method. - 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: - ~.location_pb2.Location: - Location object. - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = locations_pb2.GetLocationRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._transport.get_location, - 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 = rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - def list_locations( - self, - request: Optional[locations_pb2.ListLocationsRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> locations_pb2.ListLocationsResponse: - r"""Lists information about the supported locations for this service. - - Args: - request (:class:`~.location_pb2.ListLocationsRequest`): - The request object. Request message for - `ListLocations` method. - 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: - ~.location_pb2.ListLocationsResponse: - Response message for ``ListLocations`` method. - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = locations_pb2.ListLocationsRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._transport.list_locations, - 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 = rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) - - -__all__ = ( - "VersionsClient", -) diff --git a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/versions/pagers.py b/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/versions/pagers.py deleted file mode 100644 index 688ae8721..000000000 --- a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/versions/pagers.py +++ /dev/null @@ -1,139 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from typing import Any, AsyncIterator, Awaitable, Callable, Sequence, Tuple, Optional, Iterator - -from google.cloud.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) -> Iterator[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) -> Iterator[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]] = ()): - """Instantiates 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) -> AsyncIterator[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) -> AsyncIterator[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/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/versions/transports/__init__.py b/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/versions/transports/__init__.py deleted file mode 100644 index 778af6195..000000000 --- a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/versions/transports/__init__.py +++ /dev/null @@ -1,38 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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 -from .rest import VersionsRestTransport -from .rest import VersionsRestInterceptor - - -# Compile a registry of transports. -_transport_registry = OrderedDict() # type: Dict[str, Type[VersionsTransport]] -_transport_registry['grpc'] = VersionsGrpcTransport -_transport_registry['grpc_asyncio'] = VersionsGrpcAsyncIOTransport -_transport_registry['rest'] = VersionsRestTransport - -__all__ = ( - 'VersionsTransport', - 'VersionsGrpcTransport', - 'VersionsGrpcAsyncIOTransport', - 'VersionsRestTransport', - 'VersionsRestInterceptor', -) diff --git a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/versions/transports/base.py b/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/versions/transports/base.py deleted file mode 100644 index 106aa97ef..000000000 --- a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/versions/transports/base.py +++ /dev/null @@ -1,252 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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 - -from google.cloud.dialogflow_v2beta1 import gapic_version as package_version - -import google.auth # type: ignore -import google.api_core -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import retry as retries -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 version -from google.cloud.dialogflow_v2beta1.types import version as gcd_version -from google.cloud.location import locations_pb2 # type: ignore -from google.longrunning import operations_pb2 -from google.protobuf import empty_pb2 # type: ignore - -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__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: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - api_audience: Optional[str] = None, - **kwargs, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. - scopes (Optional[Sequence[str]]): A list of scopes. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - """ - - scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} - - # Save the scopes. - self._scopes = scopes - - # If no credentials are provided, then determine the appropriate - # defaults. - if credentials and credentials_file: - raise core_exceptions.DuplicateCredentialArgs("'credentials_file' and 'credentials' are mutually exclusive") - - if credentials_file is not None: - credentials, _ = google.auth.load_credentials_from_file( - credentials_file, - **scopes_kwargs, - quota_project_id=quota_project_id - ) - elif credentials is None: - credentials, _ = google.auth.default(**scopes_kwargs, quota_project_id=quota_project_id) - # Don't apply audience if the credentials file passed from user. - if hasattr(credentials, "with_gdch_audience"): - credentials = credentials.with_gdch_audience(api_audience if api_audience else host) - - # If the credentials are service account credentials, then always try to use self signed JWT. - if always_use_jwt_access and isinstance(credentials, service_account.Credentials) and hasattr(service_account.Credentials, "with_always_use_jwt_access"): - credentials = credentials.with_always_use_jwt_access(True) - - # Save the credentials. - self._credentials = credentials - - # Save the hostname. Default to port 443 (HTTPS) if none is specified. - if ':' not in host: - host += ':443' - self._host = host - - 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, - ), - } - - def close(self): - """Closes resources associated with the transport. - - .. warning:: - Only call this method if the transport is NOT shared - with other clients - this may cause errors in other clients! - """ - raise NotImplementedError() - - @property - def list_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() - - @property - def list_operations( - self, - ) -> Callable[ - [operations_pb2.ListOperationsRequest], - Union[operations_pb2.ListOperationsResponse, Awaitable[operations_pb2.ListOperationsResponse]], - ]: - raise NotImplementedError() - - @property - def get_operation( - self, - ) -> Callable[ - [operations_pb2.GetOperationRequest], - Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], - ]: - raise NotImplementedError() - - @property - def cancel_operation( - self, - ) -> Callable[ - [operations_pb2.CancelOperationRequest], - None, - ]: - raise NotImplementedError() - - @property - def get_location(self, - ) -> Callable[ - [locations_pb2.GetLocationRequest], - Union[locations_pb2.Location, Awaitable[locations_pb2.Location]], - ]: - raise NotImplementedError() - - @property - def list_locations(self, - ) -> Callable[ - [locations_pb2.ListLocationsRequest], - Union[locations_pb2.ListLocationsResponse, Awaitable[locations_pb2.ListLocationsResponse]], - ]: - raise NotImplementedError() - - @property - def kind(self) -> str: - raise NotImplementedError() - - -__all__ = ( - 'VersionsTransport', -) diff --git a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/versions/transports/grpc.py b/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/versions/transports/grpc.py deleted file mode 100644 index c77958ef7..000000000 --- a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/versions/transports/grpc.py +++ /dev/null @@ -1,470 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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 -from google.api_core import gapic_v1 -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.cloud.location import locations_pb2 # type: ignore -from google.longrunning import operations_pb2 -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: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - channel: Optional[grpc.Channel] = None, - api_mtls_endpoint: Optional[str] = None, - client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, - ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, - client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - api_audience: Optional[str] = None, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - This argument is ignored if ``channel`` is provided. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional(Sequence[str])): A list of scopes. This argument is - ignored if ``channel`` is provided. - channel (Optional[grpc.Channel]): A ``Channel`` instance through - which to make calls. - api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. - If provided, it overrides the ``host`` argument and tries to create - a mutual TLS channel with client SSL credentials from - ``client_cert_source`` or application default SSL credentials. - client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): - Deprecated. A callback to provide client SSL certificate bytes and - private key bytes, both in PEM format. It is ignored if - ``api_mtls_endpoint`` is None. - ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials - for the grpc channel. It is ignored if ``channel`` is provided. - client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): - A callback to provide client certificate bytes and private key bytes, - both in PEM format. It is used to configure a mutual TLS channel. It is - ignored if ``channel`` or ``ssl_channel_credentials`` is provided. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport - creation failed for any reason. - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - self._grpc_channel = None - self._ssl_channel_credentials = ssl_channel_credentials - self._stubs: Dict[str, Callable] = {} - - if api_mtls_endpoint: - warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) - if client_cert_source: - warnings.warn("client_cert_source is deprecated", DeprecationWarning) - - if channel: - # Ignore credentials if a channel was passed. - credentials = False - # If a channel was explicitly provided, set it. - self._grpc_channel = channel - self._ssl_channel_credentials = None - - else: - if api_mtls_endpoint: - host = api_mtls_endpoint - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - self._ssl_channel_credentials = SslCredentials().ssl_credentials - - else: - if client_cert_source_for_mtls and not ssl_channel_credentials: - cert, key = client_cert_source_for_mtls() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - - # The base transport sets the host, credentials and scopes - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes, - quota_project_id=quota_project_id, - client_info=client_info, - always_use_jwt_access=always_use_jwt_access, - api_audience=api_audience, - ) - - if not self._grpc_channel: - self._grpc_channel = type(self).create_channel( - self._host, - # use the credentials which are saved - credentials=self._credentials, - # Set ``credentials_file`` to ``None`` here as - # the credentials that we saved earlier should be used. - credentials_file=None, - 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: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - **kwargs) -> grpc.Channel: - """Create and return a gRPC channel object. - Args: - host (Optional[str]): The host for the channel to use. - credentials (Optional[~.Credentials]): The - authorization credentials to attach to requests. These - credentials identify this application to the service. If - none are specified, the client will attempt to ascertain - the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - kwargs (Optional[dict]): Keyword arguments, which are passed to the - channel creation. - Returns: - grpc.Channel: A gRPC channel object. - - Raises: - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - - return grpc_helpers.create_channel( - host, - credentials=credentials, - credentials_file=credentials_file, - quota_project_id=quota_project_id, - default_scopes=cls.AUTH_SCOPES, - scopes=scopes, - default_host=cls.DEFAULT_HOST, - **kwargs - ) - - @property - def grpc_channel(self) -> grpc.Channel: - """Return the channel designed to connect to this service. - """ - return self._grpc_channel - - @property - def list_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'] - - def close(self): - self.grpc_channel.close() - - @property - def cancel_operation( - self, - ) -> Callable[[operations_pb2.CancelOperationRequest], None]: - r"""Return a callable for the cancel_operation method over gRPC. - """ - # 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 "cancel_operation" not in self._stubs: - self._stubs["cancel_operation"] = self.grpc_channel.unary_unary( - "/google.longrunning.Operations/CancelOperation", - request_serializer=operations_pb2.CancelOperationRequest.SerializeToString, - response_deserializer=None, - ) - return self._stubs["cancel_operation"] - - @property - def get_operation( - self, - ) -> Callable[[operations_pb2.GetOperationRequest], operations_pb2.Operation]: - r"""Return a callable for the get_operation method over gRPC. - """ - # 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_operation" not in self._stubs: - self._stubs["get_operation"] = self.grpc_channel.unary_unary( - "/google.longrunning.Operations/GetOperation", - request_serializer=operations_pb2.GetOperationRequest.SerializeToString, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs["get_operation"] - - @property - def list_operations( - self, - ) -> Callable[[operations_pb2.ListOperationsRequest], operations_pb2.ListOperationsResponse]: - r"""Return a callable for the list_operations method over gRPC. - """ - # 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_operations" not in self._stubs: - self._stubs["list_operations"] = self.grpc_channel.unary_unary( - "/google.longrunning.Operations/ListOperations", - request_serializer=operations_pb2.ListOperationsRequest.SerializeToString, - response_deserializer=operations_pb2.ListOperationsResponse.FromString, - ) - return self._stubs["list_operations"] - - @property - def list_locations( - self, - ) -> Callable[[locations_pb2.ListLocationsRequest], locations_pb2.ListLocationsResponse]: - r"""Return a callable for the list locations method over gRPC. - """ - # 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_locations" not in self._stubs: - self._stubs["list_locations"] = self.grpc_channel.unary_unary( - "/google.cloud.location.Locations/ListLocations", - request_serializer=locations_pb2.ListLocationsRequest.SerializeToString, - response_deserializer=locations_pb2.ListLocationsResponse.FromString, - ) - return self._stubs["list_locations"] - - @property - def get_location( - self, - ) -> Callable[[locations_pb2.GetLocationRequest], locations_pb2.Location]: - r"""Return a callable for the list locations method over gRPC. - """ - # 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_location" not in self._stubs: - self._stubs["get_location"] = self.grpc_channel.unary_unary( - "/google.cloud.location.Locations/GetLocation", - request_serializer=locations_pb2.GetLocationRequest.SerializeToString, - response_deserializer=locations_pb2.Location.FromString, - ) - return self._stubs["get_location"] - - @property - def kind(self) -> str: - return "grpc" - - -__all__ = ( - 'VersionsGrpcTransport', -) diff --git a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/versions/transports/grpc_asyncio.py b/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/versions/transports/grpc_asyncio.py deleted file mode 100644 index 667d070fe..000000000 --- a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/versions/transports/grpc_asyncio.py +++ /dev/null @@ -1,469 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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 -from google.api_core import grpc_helpers_async -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore - -import grpc # type: ignore -from grpc.experimental import aio # type: ignore - -from google.cloud.dialogflow_v2beta1.types import version -from google.cloud.dialogflow_v2beta1.types import version as gcd_version -from google.cloud.location import locations_pb2 # type: ignore -from google.longrunning import operations_pb2 -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: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - **kwargs) -> aio.Channel: - """Create and return a gRPC AsyncIO channel object. - Args: - host (Optional[str]): The host for the channel to use. - credentials (Optional[~.Credentials]): The - authorization credentials to attach to requests. These - credentials identify this application to the service. If - none are specified, the client will attempt to ascertain - the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - kwargs (Optional[dict]): Keyword arguments, which are passed to the - channel creation. - Returns: - aio.Channel: A gRPC AsyncIO channel object. - """ - - return grpc_helpers_async.create_channel( - host, - credentials=credentials, - credentials_file=credentials_file, - quota_project_id=quota_project_id, - default_scopes=cls.AUTH_SCOPES, - scopes=scopes, - default_host=cls.DEFAULT_HOST, - **kwargs - ) - - def __init__(self, *, - host: str = 'dialogflow.googleapis.com', - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - channel: Optional[aio.Channel] = None, - api_mtls_endpoint: Optional[str] = None, - client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, - ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, - client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - api_audience: Optional[str] = None, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - This argument is ignored if ``channel`` is provided. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - channel (Optional[aio.Channel]): A ``Channel`` instance through - which to make calls. - api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. - If provided, it overrides the ``host`` argument and tries to create - a mutual TLS channel with client SSL credentials from - ``client_cert_source`` or application default SSL credentials. - client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): - Deprecated. A callback to provide client SSL certificate bytes and - private key bytes, both in PEM format. It is ignored if - ``api_mtls_endpoint`` is None. - ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials - for the grpc channel. It is ignored if ``channel`` is provided. - client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): - A callback to provide client certificate bytes and private key bytes, - both in PEM format. It is used to configure a mutual TLS channel. It is - ignored if ``channel`` or ``ssl_channel_credentials`` is provided. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - - Raises: - google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport - creation failed for any reason. - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - self._grpc_channel = None - self._ssl_channel_credentials = ssl_channel_credentials - self._stubs: Dict[str, Callable] = {} - - if api_mtls_endpoint: - warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) - if client_cert_source: - warnings.warn("client_cert_source is deprecated", DeprecationWarning) - - if channel: - # Ignore credentials if a channel was passed. - credentials = False - # If a channel was explicitly provided, set it. - self._grpc_channel = channel - self._ssl_channel_credentials = None - else: - if api_mtls_endpoint: - host = api_mtls_endpoint - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - self._ssl_channel_credentials = SslCredentials().ssl_credentials - - else: - if client_cert_source_for_mtls and not ssl_channel_credentials: - cert, key = client_cert_source_for_mtls() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - - # The base transport sets the host, credentials and scopes - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes, - quota_project_id=quota_project_id, - client_info=client_info, - always_use_jwt_access=always_use_jwt_access, - api_audience=api_audience, - ) - - if not self._grpc_channel: - self._grpc_channel = type(self).create_channel( - self._host, - # use the credentials which are saved - credentials=self._credentials, - # Set ``credentials_file`` to ``None`` here as - # the credentials that we saved earlier should be used. - credentials_file=None, - 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'] - - def close(self): - return self.grpc_channel.close() - - @property - def cancel_operation( - self, - ) -> Callable[[operations_pb2.CancelOperationRequest], None]: - r"""Return a callable for the cancel_operation method over gRPC. - """ - # 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 "cancel_operation" not in self._stubs: - self._stubs["cancel_operation"] = self.grpc_channel.unary_unary( - "/google.longrunning.Operations/CancelOperation", - request_serializer=operations_pb2.CancelOperationRequest.SerializeToString, - response_deserializer=None, - ) - return self._stubs["cancel_operation"] - - @property - def get_operation( - self, - ) -> Callable[[operations_pb2.GetOperationRequest], operations_pb2.Operation]: - r"""Return a callable for the get_operation method over gRPC. - """ - # 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_operation" not in self._stubs: - self._stubs["get_operation"] = self.grpc_channel.unary_unary( - "/google.longrunning.Operations/GetOperation", - request_serializer=operations_pb2.GetOperationRequest.SerializeToString, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs["get_operation"] - - @property - def list_operations( - self, - ) -> Callable[[operations_pb2.ListOperationsRequest], operations_pb2.ListOperationsResponse]: - r"""Return a callable for the list_operations method over gRPC. - """ - # 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_operations" not in self._stubs: - self._stubs["list_operations"] = self.grpc_channel.unary_unary( - "/google.longrunning.Operations/ListOperations", - request_serializer=operations_pb2.ListOperationsRequest.SerializeToString, - response_deserializer=operations_pb2.ListOperationsResponse.FromString, - ) - return self._stubs["list_operations"] - - @property - def list_locations( - self, - ) -> Callable[[locations_pb2.ListLocationsRequest], locations_pb2.ListLocationsResponse]: - r"""Return a callable for the list locations method over gRPC. - """ - # 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_locations" not in self._stubs: - self._stubs["list_locations"] = self.grpc_channel.unary_unary( - "/google.cloud.location.Locations/ListLocations", - request_serializer=locations_pb2.ListLocationsRequest.SerializeToString, - response_deserializer=locations_pb2.ListLocationsResponse.FromString, - ) - return self._stubs["list_locations"] - - @property - def get_location( - self, - ) -> Callable[[locations_pb2.GetLocationRequest], locations_pb2.Location]: - r"""Return a callable for the list locations method over gRPC. - """ - # 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_location" not in self._stubs: - self._stubs["get_location"] = self.grpc_channel.unary_unary( - "/google.cloud.location.Locations/GetLocation", - request_serializer=locations_pb2.GetLocationRequest.SerializeToString, - response_deserializer=locations_pb2.Location.FromString, - ) - return self._stubs["get_location"] - - -__all__ = ( - 'VersionsGrpcAsyncIOTransport', -) diff --git a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/versions/transports/rest.py b/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/versions/transports/rest.py deleted file mode 100644 index bb4f388cd..000000000 --- a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/services/versions/transports/rest.py +++ /dev/null @@ -1,1245 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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 google.auth.transport.requests import AuthorizedSession # type: ignore -import json # type: ignore -import grpc # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore -from google.auth import credentials as ga_credentials # type: ignore -from google.api_core import exceptions as core_exceptions -from google.api_core import retry as retries -from google.api_core import rest_helpers -from google.api_core import rest_streaming -from google.api_core import path_template -from google.api_core import gapic_v1 - -from google.protobuf import json_format -from google.cloud.location import locations_pb2 # type: ignore -from google.longrunning import operations_pb2 -from requests import __version__ as requests_version -import dataclasses -import re -from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union -import warnings - -try: - OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] -except AttributeError: # pragma: NO COVER - OptionalRetry = Union[retries.Retry, object] # 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 as BASE_DEFAULT_CLIENT_INFO - - -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=BASE_DEFAULT_CLIENT_INFO.gapic_version, - grpc_version=None, - rest_version=requests_version, -) - - -class VersionsRestInterceptor: - """Interceptor for Versions. - - Interceptors are used to manipulate requests, request metadata, and responses - in arbitrary ways. - Example use cases include: - * Logging - * Verifying requests according to service or custom semantics - * Stripping extraneous information from responses - - These use cases and more can be enabled by injecting an - instance of a custom subclass when constructing the VersionsRestTransport. - - .. code-block:: python - class MyCustomVersionsInterceptor(VersionsRestInterceptor): - def pre_create_version(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_create_version(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_delete_version(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def pre_get_version(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_get_version(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_list_versions(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_list_versions(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_update_version(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_update_version(self, response): - logging.log(f"Received response: {response}") - return response - - transport = VersionsRestTransport(interceptor=MyCustomVersionsInterceptor()) - client = VersionsClient(transport=transport) - - - """ - def pre_create_version(self, request: gcd_version.CreateVersionRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[gcd_version.CreateVersionRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for create_version - - Override in a subclass to manipulate the request or metadata - before they are sent to the Versions server. - """ - return request, metadata - - def post_create_version(self, response: gcd_version.Version) -> gcd_version.Version: - """Post-rpc interceptor for create_version - - Override in a subclass to manipulate the response - after it is returned by the Versions server but before - it is returned to user code. - """ - return response - def pre_delete_version(self, request: version.DeleteVersionRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[version.DeleteVersionRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for delete_version - - Override in a subclass to manipulate the request or metadata - before they are sent to the Versions server. - """ - return request, metadata - - def pre_get_version(self, request: version.GetVersionRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[version.GetVersionRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for get_version - - Override in a subclass to manipulate the request or metadata - before they are sent to the Versions server. - """ - return request, metadata - - def post_get_version(self, response: version.Version) -> version.Version: - """Post-rpc interceptor for get_version - - Override in a subclass to manipulate the response - after it is returned by the Versions server but before - it is returned to user code. - """ - return response - def pre_list_versions(self, request: version.ListVersionsRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[version.ListVersionsRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for list_versions - - Override in a subclass to manipulate the request or metadata - before they are sent to the Versions server. - """ - return request, metadata - - def post_list_versions(self, response: version.ListVersionsResponse) -> version.ListVersionsResponse: - """Post-rpc interceptor for list_versions - - Override in a subclass to manipulate the response - after it is returned by the Versions server but before - it is returned to user code. - """ - return response - def pre_update_version(self, request: gcd_version.UpdateVersionRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[gcd_version.UpdateVersionRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for update_version - - Override in a subclass to manipulate the request or metadata - before they are sent to the Versions server. - """ - return request, metadata - - def post_update_version(self, response: gcd_version.Version) -> gcd_version.Version: - """Post-rpc interceptor for update_version - - Override in a subclass to manipulate the response - after it is returned by the Versions server but before - it is returned to user code. - """ - return response - - def pre_get_location( - self, request: locations_pb2.GetLocationRequest, metadata: Sequence[Tuple[str, str]] - ) -> Tuple[locations_pb2.GetLocationRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for get_location - - Override in a subclass to manipulate the request or metadata - before they are sent to the Versions server. - """ - return request, metadata - - def post_get_location( - self, response: locations_pb2.Location - ) -> locations_pb2.Location: - """Post-rpc interceptor for get_location - - Override in a subclass to manipulate the response - after it is returned by the Versions server but before - it is returned to user code. - """ - return response - def pre_list_locations( - self, request: locations_pb2.ListLocationsRequest, metadata: Sequence[Tuple[str, str]] - ) -> Tuple[locations_pb2.ListLocationsRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for list_locations - - Override in a subclass to manipulate the request or metadata - before they are sent to the Versions server. - """ - return request, metadata - - def post_list_locations( - self, response: locations_pb2.ListLocationsResponse - ) -> locations_pb2.ListLocationsResponse: - """Post-rpc interceptor for list_locations - - Override in a subclass to manipulate the response - after it is returned by the Versions server but before - it is returned to user code. - """ - return response - def pre_cancel_operation( - self, request: operations_pb2.CancelOperationRequest, metadata: Sequence[Tuple[str, str]] - ) -> Tuple[operations_pb2.CancelOperationRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for cancel_operation - - Override in a subclass to manipulate the request or metadata - before they are sent to the Versions server. - """ - return request, metadata - - def post_cancel_operation( - self, response: None - ) -> None: - """Post-rpc interceptor for cancel_operation - - Override in a subclass to manipulate the response - after it is returned by the Versions server but before - it is returned to user code. - """ - return response - def pre_get_operation( - self, request: operations_pb2.GetOperationRequest, metadata: Sequence[Tuple[str, str]] - ) -> Tuple[operations_pb2.GetOperationRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for get_operation - - Override in a subclass to manipulate the request or metadata - before they are sent to the Versions server. - """ - return request, metadata - - def post_get_operation( - self, response: operations_pb2.Operation - ) -> operations_pb2.Operation: - """Post-rpc interceptor for get_operation - - Override in a subclass to manipulate the response - after it is returned by the Versions server but before - it is returned to user code. - """ - return response - def pre_list_operations( - self, request: operations_pb2.ListOperationsRequest, metadata: Sequence[Tuple[str, str]] - ) -> Tuple[operations_pb2.ListOperationsRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for list_operations - - Override in a subclass to manipulate the request or metadata - before they are sent to the Versions server. - """ - return request, metadata - - def post_list_operations( - self, response: operations_pb2.ListOperationsResponse - ) -> operations_pb2.ListOperationsResponse: - """Post-rpc interceptor for list_operations - - Override in a subclass to manipulate the response - after it is returned by the Versions server but before - it is returned to user code. - """ - return response - - -@dataclasses.dataclass -class VersionsRestStub: - _session: AuthorizedSession - _host: str - _interceptor: VersionsRestInterceptor - - -class VersionsRestTransport(VersionsTransport): - """REST 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 JSON representations of protocol buffers over HTTP/1.1 - - """ - - def __init__(self, *, - host: str = 'dialogflow.googleapis.com', - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - client_cert_source_for_mtls: Optional[Callable[[ - ], Tuple[bytes, bytes]]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - url_scheme: str = 'https', - interceptor: Optional[VersionsRestInterceptor] = None, - api_audience: Optional[str] = None, - ) -> 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 ignored if ``channel`` is provided. - scopes (Optional(Sequence[str])): A list of scopes. This argument is - ignored if ``channel`` is provided. - client_cert_source_for_mtls (Callable[[], Tuple[bytes, bytes]]): Client - certificate to configure mutual TLS HTTP channel. It is ignored - if ``channel`` is provided. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you are developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - url_scheme: the protocol scheme for the API endpoint. Normally - "https", but for testing or local servers, - "http" can be specified. - """ - # Run the base constructor - # TODO(yon-mg): resolve other ctor params i.e. scopes, quota, etc. - # TODO: When custom host (api_endpoint) is set, `scopes` must *also* be set on the - # credentials object - maybe_url_match = re.match("^(?Phttp(?:s)?://)?(?P.*)$", host) - if maybe_url_match is None: - raise ValueError(f"Unexpected hostname structure: {host}") # pragma: NO COVER - - url_match_items = maybe_url_match.groupdict() - - host = f"{url_scheme}://{host}" if not url_match_items["scheme"] else host - - super().__init__( - host=host, - credentials=credentials, - client_info=client_info, - always_use_jwt_access=always_use_jwt_access, - api_audience=api_audience - ) - self._session = AuthorizedSession( - self._credentials, default_host=self.DEFAULT_HOST) - if client_cert_source_for_mtls: - self._session.configure_mtls_channel(client_cert_source_for_mtls) - self._interceptor = interceptor or VersionsRestInterceptor() - self._prep_wrapped_messages(client_info) - - class _CreateVersion(VersionsRestStub): - def __hash__(self): - return hash("CreateVersion") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: gcd_version.CreateVersionRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> gcd_version.Version: - r"""Call the create version method over HTTP. - - Args: - request (~.gcd_version.CreateVersionRequest): - The request object. The request message for - [Versions.CreateVersion][google.cloud.dialogflow.v2beta1.Versions.CreateVersion]. - 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: - ~.gcd_version.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 `__. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'post', - 'uri': '/v2beta1/{parent=projects/*/agent}/versions', - 'body': 'version', - }, -{ - 'method': 'post', - 'uri': '/v2beta1/{parent=projects/*/locations/*/agent}/versions', - 'body': 'version', - }, - ] - request, metadata = self._interceptor.pre_create_version(request, metadata) - pb_request = gcd_version.CreateVersionRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request['body'], - including_default_value_fields=False, - use_integers_for_enums=True - ) - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - including_default_value_fields=False, - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = gcd_version.Version() - pb_resp = gcd_version.Version.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_create_version(resp) - return resp - - class _DeleteVersion(VersionsRestStub): - def __hash__(self): - return hash("DeleteVersion") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: version.DeleteVersionRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ): - r"""Call the delete version method over HTTP. - - Args: - request (~.version.DeleteVersionRequest): - The request object. The request message for - [Versions.DeleteVersion][google.cloud.dialogflow.v2beta1.Versions.DeleteVersion]. - 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. - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'delete', - 'uri': '/v2beta1/{name=projects/*/agent/versions/*}', - }, -{ - 'method': 'delete', - 'uri': '/v2beta1/{name=projects/*/locations/*/agent/versions/*}', - }, - ] - request, metadata = self._interceptor.pre_delete_version(request, metadata) - pb_request = version.DeleteVersionRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - including_default_value_fields=False, - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - class _GetVersion(VersionsRestStub): - def __hash__(self): - return hash("GetVersion") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: version.GetVersionRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> version.Version: - r"""Call the get version method over HTTP. - - Args: - request (~.version.GetVersionRequest): - The request object. The request message for - [Versions.GetVersion][google.cloud.dialogflow.v2beta1.Versions.GetVersion]. - 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: - ~.version.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 `__. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v2beta1/{name=projects/*/agent/versions/*}', - }, -{ - 'method': 'get', - 'uri': '/v2beta1/{name=projects/*/locations/*/agent/versions/*}', - }, - ] - request, metadata = self._interceptor.pre_get_version(request, metadata) - pb_request = version.GetVersionRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - including_default_value_fields=False, - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = version.Version() - pb_resp = version.Version.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_get_version(resp) - return resp - - class _ListVersions(VersionsRestStub): - def __hash__(self): - return hash("ListVersions") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: version.ListVersionsRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> version.ListVersionsResponse: - r"""Call the list versions method over HTTP. - - Args: - request (~.version.ListVersionsRequest): - The request object. The request message for - [Versions.ListVersions][google.cloud.dialogflow.v2beta1.Versions.ListVersions]. - 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: - ~.version.ListVersionsResponse: - The response message for - [Versions.ListVersions][google.cloud.dialogflow.v2beta1.Versions.ListVersions]. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v2beta1/{parent=projects/*/agent}/versions', - }, -{ - 'method': 'get', - 'uri': '/v2beta1/{parent=projects/*/locations/*/agent}/versions', - }, - ] - request, metadata = self._interceptor.pre_list_versions(request, metadata) - pb_request = version.ListVersionsRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - including_default_value_fields=False, - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = version.ListVersionsResponse() - pb_resp = version.ListVersionsResponse.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_list_versions(resp) - return resp - - class _UpdateVersion(VersionsRestStub): - def __hash__(self): - return hash("UpdateVersion") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - "updateMask" : {}, } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: gcd_version.UpdateVersionRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> gcd_version.Version: - r"""Call the update version method over HTTP. - - Args: - request (~.gcd_version.UpdateVersionRequest): - The request object. The request message for - [Versions.UpdateVersion][google.cloud.dialogflow.v2beta1.Versions.UpdateVersion]. - 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: - ~.gcd_version.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 `__. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'patch', - 'uri': '/v2beta1/{version.name=projects/*/agent/versions/*}', - 'body': 'version', - }, -{ - 'method': 'patch', - 'uri': '/v2beta1/{version.name=projects/*/locations/*/agent/versions/*}', - 'body': 'version', - }, - ] - request, metadata = self._interceptor.pre_update_version(request, metadata) - pb_request = gcd_version.UpdateVersionRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request['body'], - including_default_value_fields=False, - use_integers_for_enums=True - ) - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - including_default_value_fields=False, - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = gcd_version.Version() - pb_resp = gcd_version.Version.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_update_version(resp) - return resp - - @property - def create_version(self) -> Callable[ - [gcd_version.CreateVersionRequest], - gcd_version.Version]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._CreateVersion(self._session, self._host, self._interceptor) # type: ignore - - @property - def delete_version(self) -> Callable[ - [version.DeleteVersionRequest], - empty_pb2.Empty]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._DeleteVersion(self._session, self._host, self._interceptor) # type: ignore - - @property - def get_version(self) -> Callable[ - [version.GetVersionRequest], - version.Version]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._GetVersion(self._session, self._host, self._interceptor) # type: ignore - - @property - def list_versions(self) -> Callable[ - [version.ListVersionsRequest], - version.ListVersionsResponse]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._ListVersions(self._session, self._host, self._interceptor) # type: ignore - - @property - def update_version(self) -> Callable[ - [gcd_version.UpdateVersionRequest], - gcd_version.Version]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._UpdateVersion(self._session, self._host, self._interceptor) # type: ignore - - @property - def get_location(self): - return self._GetLocation(self._session, self._host, self._interceptor) # type: ignore - - class _GetLocation(VersionsRestStub): - def __call__(self, - request: locations_pb2.GetLocationRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> locations_pb2.Location: - - r"""Call the get location method over HTTP. - - Args: - request (locations_pb2.GetLocationRequest): - The request object for GetLocation method. - 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: - locations_pb2.Location: Response from GetLocation method. - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v2beta1/{name=projects/*/locations/*}', - }, - ] - - request, metadata = self._interceptor.pre_get_location(request, metadata) - request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode( - http_options, **request_kwargs) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json.dumps(transcoded_request['query_params'])) - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - resp = locations_pb2.Location() - resp = json_format.Parse(response.content.decode("utf-8"), resp) - resp = self._interceptor.post_get_location(resp) - return resp - - @property - def list_locations(self): - return self._ListLocations(self._session, self._host, self._interceptor) # type: ignore - - class _ListLocations(VersionsRestStub): - def __call__(self, - request: locations_pb2.ListLocationsRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> locations_pb2.ListLocationsResponse: - - r"""Call the list locations method over HTTP. - - Args: - request (locations_pb2.ListLocationsRequest): - The request object for ListLocations method. - 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: - locations_pb2.ListLocationsResponse: Response from ListLocations method. - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v2beta1/{name=projects/*}/locations', - }, - ] - - request, metadata = self._interceptor.pre_list_locations(request, metadata) - request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode( - http_options, **request_kwargs) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json.dumps(transcoded_request['query_params'])) - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - resp = locations_pb2.ListLocationsResponse() - resp = json_format.Parse(response.content.decode("utf-8"), resp) - resp = self._interceptor.post_list_locations(resp) - return resp - - @property - def cancel_operation(self): - return self._CancelOperation(self._session, self._host, self._interceptor) # type: ignore - - class _CancelOperation(VersionsRestStub): - def __call__(self, - request: operations_pb2.CancelOperationRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> None: - - r"""Call the cancel operation method over HTTP. - - Args: - request (operations_pb2.CancelOperationRequest): - The request object for CancelOperation method. - 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. - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'post', - 'uri': '/v2beta1/{name=projects/*/operations/*}:cancel', - }, -{ - 'method': 'post', - 'uri': '/v2beta1/{name=projects/*/locations/*/operations/*}:cancel', - }, - ] - - request, metadata = self._interceptor.pre_cancel_operation(request, metadata) - request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode( - http_options, **request_kwargs) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json.dumps(transcoded_request['query_params'])) - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - return self._interceptor.post_cancel_operation(None) - - @property - def get_operation(self): - return self._GetOperation(self._session, self._host, self._interceptor) # type: ignore - - class _GetOperation(VersionsRestStub): - def __call__(self, - request: operations_pb2.GetOperationRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> operations_pb2.Operation: - - r"""Call the get operation method over HTTP. - - Args: - request (operations_pb2.GetOperationRequest): - The request object for GetOperation method. - 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: - operations_pb2.Operation: Response from GetOperation method. - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v2beta1/{name=projects/*/operations/*}', - }, -{ - 'method': 'get', - 'uri': '/v2beta1/{name=projects/*/locations/*/operations/*}', - }, - ] - - request, metadata = self._interceptor.pre_get_operation(request, metadata) - request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode( - http_options, **request_kwargs) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json.dumps(transcoded_request['query_params'])) - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - resp = operations_pb2.Operation() - resp = json_format.Parse(response.content.decode("utf-8"), resp) - resp = self._interceptor.post_get_operation(resp) - return resp - - @property - def list_operations(self): - return self._ListOperations(self._session, self._host, self._interceptor) # type: ignore - - class _ListOperations(VersionsRestStub): - def __call__(self, - request: operations_pb2.ListOperationsRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> operations_pb2.ListOperationsResponse: - - r"""Call the list operations method over HTTP. - - Args: - request (operations_pb2.ListOperationsRequest): - The request object for ListOperations method. - 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: - operations_pb2.ListOperationsResponse: Response from ListOperations method. - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v2beta1/{name=projects/*}/operations', - }, -{ - 'method': 'get', - 'uri': '/v2beta1/{name=projects/*/locations/*}/operations', - }, - ] - - request, metadata = self._interceptor.pre_list_operations(request, metadata) - request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode( - http_options, **request_kwargs) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json.dumps(transcoded_request['query_params'])) - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - resp = operations_pb2.ListOperationsResponse() - resp = json_format.Parse(response.content.decode("utf-8"), resp) - resp = self._interceptor.post_list_operations(resp) - return resp - - @property - def kind(self) -> str: - return "rest" - - def close(self): - self._session.close() - - -__all__=( - 'VersionsRestTransport', -) diff --git a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/types/__init__.py b/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/types/__init__.py deleted file mode 100644 index 3bd3a4b97..000000000 --- a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/types/__init__.py +++ /dev/null @@ -1,472 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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 .agent import ( - Agent, - DeleteAgentRequest, - ExportAgentRequest, - ExportAgentResponse, - GetAgentRequest, - GetValidationResultRequest, - ImportAgentRequest, - RestoreAgentRequest, - SearchAgentsRequest, - SearchAgentsResponse, - SetAgentRequest, - SubAgent, - TrainAgentRequest, -) -from .answer_record import ( - AgentAssistantFeedback, - AgentAssistantRecord, - AnswerFeedback, - AnswerRecord, - GetAnswerRecordRequest, - ListAnswerRecordsRequest, - ListAnswerRecordsResponse, - UpdateAnswerRecordRequest, -) -from .audio_config import ( - BargeInConfig, - InputAudioConfig, - OutputAudioConfig, - SpeechContext, - SpeechToTextConfig, - SpeechWordInfo, - SynthesizeSpeechConfig, - TelephonyDtmfEvents, - VoiceSelectionParams, - AudioEncoding, - OutputAudioEncoding, - SpeechModelVariant, - SsmlVoiceGender, - TelephonyDtmf, -) -from .context import ( - Context, - CreateContextRequest, - DeleteAllContextsRequest, - DeleteContextRequest, - GetContextRequest, - ListContextsRequest, - ListContextsResponse, - UpdateContextRequest, -) -from .conversation import ( - BatchCreateMessagesRequest, - BatchCreateMessagesResponse, - CompleteConversationRequest, - Conversation, - ConversationPhoneNumber, - CreateConversationRequest, - CreateMessageRequest, - GetConversationRequest, - ListConversationsRequest, - ListConversationsResponse, - ListMessagesRequest, - ListMessagesResponse, - SuggestConversationSummaryRequest, - SuggestConversationSummaryResponse, -) -from .conversation_event import ( - ConversationEvent, -) -from .conversation_profile import ( - AutomatedAgentConfig, - ClearSuggestionFeatureConfigOperationMetadata, - ClearSuggestionFeatureConfigRequest, - ConversationProfile, - CreateConversationProfileRequest, - DeleteConversationProfileRequest, - GetConversationProfileRequest, - HumanAgentAssistantConfig, - HumanAgentHandoffConfig, - ListConversationProfilesRequest, - ListConversationProfilesResponse, - LoggingConfig, - NotificationConfig, - SetSuggestionFeatureConfigOperationMetadata, - SetSuggestionFeatureConfigRequest, - UpdateConversationProfileRequest, -) -from .document import ( - CreateDocumentRequest, - DeleteDocumentRequest, - Document, - ExportOperationMetadata, - GetDocumentRequest, - ImportDocumentsRequest, - ImportDocumentsResponse, - ImportDocumentTemplate, - KnowledgeOperationMetadata, - ListDocumentsRequest, - ListDocumentsResponse, - ReloadDocumentRequest, - UpdateDocumentRequest, -) -from .entity_type import ( - BatchCreateEntitiesRequest, - BatchDeleteEntitiesRequest, - BatchDeleteEntityTypesRequest, - BatchUpdateEntitiesRequest, - BatchUpdateEntityTypesRequest, - BatchUpdateEntityTypesResponse, - CreateEntityTypeRequest, - DeleteEntityTypeRequest, - EntityType, - EntityTypeBatch, - GetEntityTypeRequest, - ListEntityTypesRequest, - ListEntityTypesResponse, - UpdateEntityTypeRequest, -) -from .environment import ( - CreateEnvironmentRequest, - DeleteEnvironmentRequest, - Environment, - EnvironmentHistory, - GetEnvironmentHistoryRequest, - GetEnvironmentRequest, - ListEnvironmentsRequest, - ListEnvironmentsResponse, - TextToSpeechSettings, - UpdateEnvironmentRequest, -) -from .fulfillment import ( - Fulfillment, - GetFulfillmentRequest, - UpdateFulfillmentRequest, -) -from .gcs import ( - GcsDestination, - GcsSource, - GcsSources, -) -from .human_agent_assistant_event import ( - HumanAgentAssistantEvent, -) -from .intent import ( - BatchDeleteIntentsRequest, - BatchUpdateIntentsRequest, - BatchUpdateIntentsResponse, - CreateIntentRequest, - DeleteIntentRequest, - GetIntentRequest, - Intent, - IntentBatch, - ListIntentsRequest, - ListIntentsResponse, - UpdateIntentRequest, - IntentView, -) -from .knowledge_base import ( - CreateKnowledgeBaseRequest, - DeleteKnowledgeBaseRequest, - GetKnowledgeBaseRequest, - KnowledgeBase, - ListKnowledgeBasesRequest, - ListKnowledgeBasesResponse, - UpdateKnowledgeBaseRequest, -) -from .participant import ( - AnalyzeContentRequest, - AnalyzeContentResponse, - AnnotatedMessagePart, - ArticleAnswer, - AssistQueryParameters, - AudioInput, - AutomatedAgentReply, - CompileSuggestionRequest, - CompileSuggestionResponse, - CreateParticipantRequest, - DtmfParameters, - FaqAnswer, - GetParticipantRequest, - InputTextConfig, - ListParticipantsRequest, - ListParticipantsResponse, - ListSuggestionsRequest, - ListSuggestionsResponse, - Message, - MessageAnnotation, - OutputAudio, - Participant, - ResponseMessage, - SmartReplyAnswer, - StreamingAnalyzeContentRequest, - StreamingAnalyzeContentResponse, - SuggestArticlesRequest, - SuggestArticlesResponse, - SuggestFaqAnswersRequest, - SuggestFaqAnswersResponse, - Suggestion, - SuggestionFeature, - SuggestionResult, - SuggestSmartRepliesRequest, - SuggestSmartRepliesResponse, - UpdateParticipantRequest, -) -from .session import ( - DetectIntentRequest, - DetectIntentResponse, - EventInput, - KnowledgeAnswers, - QueryInput, - QueryParameters, - QueryResult, - Sentiment, - SentimentAnalysisRequestConfig, - SentimentAnalysisResult, - StreamingDetectIntentRequest, - StreamingDetectIntentResponse, - StreamingRecognitionResult, - TextInput, -) -from .session_entity_type import ( - CreateSessionEntityTypeRequest, - DeleteSessionEntityTypeRequest, - GetSessionEntityTypeRequest, - ListSessionEntityTypesRequest, - ListSessionEntityTypesResponse, - SessionEntityType, - UpdateSessionEntityTypeRequest, -) -from .validation_result import ( - ValidationError, - ValidationResult, -) -from .version import ( - CreateVersionRequest, - DeleteVersionRequest, - GetVersionRequest, - ListVersionsRequest, - ListVersionsResponse, - UpdateVersionRequest, - Version, -) -from .webhook import ( - OriginalDetectIntentRequest, - WebhookRequest, - WebhookResponse, -) - -__all__ = ( - 'Agent', - 'DeleteAgentRequest', - 'ExportAgentRequest', - 'ExportAgentResponse', - 'GetAgentRequest', - 'GetValidationResultRequest', - 'ImportAgentRequest', - 'RestoreAgentRequest', - 'SearchAgentsRequest', - 'SearchAgentsResponse', - 'SetAgentRequest', - 'SubAgent', - 'TrainAgentRequest', - 'AgentAssistantFeedback', - 'AgentAssistantRecord', - 'AnswerFeedback', - 'AnswerRecord', - 'GetAnswerRecordRequest', - 'ListAnswerRecordsRequest', - 'ListAnswerRecordsResponse', - 'UpdateAnswerRecordRequest', - 'BargeInConfig', - 'InputAudioConfig', - 'OutputAudioConfig', - 'SpeechContext', - 'SpeechToTextConfig', - 'SpeechWordInfo', - 'SynthesizeSpeechConfig', - 'TelephonyDtmfEvents', - 'VoiceSelectionParams', - 'AudioEncoding', - 'OutputAudioEncoding', - 'SpeechModelVariant', - 'SsmlVoiceGender', - 'TelephonyDtmf', - 'Context', - 'CreateContextRequest', - 'DeleteAllContextsRequest', - 'DeleteContextRequest', - 'GetContextRequest', - 'ListContextsRequest', - 'ListContextsResponse', - 'UpdateContextRequest', - 'BatchCreateMessagesRequest', - 'BatchCreateMessagesResponse', - 'CompleteConversationRequest', - 'Conversation', - 'ConversationPhoneNumber', - 'CreateConversationRequest', - 'CreateMessageRequest', - 'GetConversationRequest', - 'ListConversationsRequest', - 'ListConversationsResponse', - 'ListMessagesRequest', - 'ListMessagesResponse', - 'SuggestConversationSummaryRequest', - 'SuggestConversationSummaryResponse', - 'ConversationEvent', - 'AutomatedAgentConfig', - 'ClearSuggestionFeatureConfigOperationMetadata', - 'ClearSuggestionFeatureConfigRequest', - 'ConversationProfile', - 'CreateConversationProfileRequest', - 'DeleteConversationProfileRequest', - 'GetConversationProfileRequest', - 'HumanAgentAssistantConfig', - 'HumanAgentHandoffConfig', - 'ListConversationProfilesRequest', - 'ListConversationProfilesResponse', - 'LoggingConfig', - 'NotificationConfig', - 'SetSuggestionFeatureConfigOperationMetadata', - 'SetSuggestionFeatureConfigRequest', - 'UpdateConversationProfileRequest', - 'CreateDocumentRequest', - 'DeleteDocumentRequest', - 'Document', - 'ExportOperationMetadata', - 'GetDocumentRequest', - 'ImportDocumentsRequest', - 'ImportDocumentsResponse', - 'ImportDocumentTemplate', - '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', - 'GcsDestination', - 'GcsSource', - 'GcsSources', - 'HumanAgentAssistantEvent', - 'BatchDeleteIntentsRequest', - 'BatchUpdateIntentsRequest', - 'BatchUpdateIntentsResponse', - 'CreateIntentRequest', - 'DeleteIntentRequest', - 'GetIntentRequest', - 'Intent', - 'IntentBatch', - 'ListIntentsRequest', - 'ListIntentsResponse', - 'UpdateIntentRequest', - 'IntentView', - 'CreateKnowledgeBaseRequest', - 'DeleteKnowledgeBaseRequest', - 'GetKnowledgeBaseRequest', - 'KnowledgeBase', - 'ListKnowledgeBasesRequest', - 'ListKnowledgeBasesResponse', - 'UpdateKnowledgeBaseRequest', - 'AnalyzeContentRequest', - 'AnalyzeContentResponse', - 'AnnotatedMessagePart', - 'ArticleAnswer', - 'AssistQueryParameters', - 'AudioInput', - 'AutomatedAgentReply', - 'CompileSuggestionRequest', - 'CompileSuggestionResponse', - 'CreateParticipantRequest', - 'DtmfParameters', - 'FaqAnswer', - 'GetParticipantRequest', - 'InputTextConfig', - 'ListParticipantsRequest', - 'ListParticipantsResponse', - 'ListSuggestionsRequest', - 'ListSuggestionsResponse', - 'Message', - 'MessageAnnotation', - 'OutputAudio', - 'Participant', - 'ResponseMessage', - 'SmartReplyAnswer', - 'StreamingAnalyzeContentRequest', - 'StreamingAnalyzeContentResponse', - 'SuggestArticlesRequest', - 'SuggestArticlesResponse', - 'SuggestFaqAnswersRequest', - 'SuggestFaqAnswersResponse', - 'Suggestion', - 'SuggestionFeature', - 'SuggestionResult', - 'SuggestSmartRepliesRequest', - 'SuggestSmartRepliesResponse', - 'UpdateParticipantRequest', - 'DetectIntentRequest', - 'DetectIntentResponse', - 'EventInput', - 'KnowledgeAnswers', - 'QueryInput', - 'QueryParameters', - 'QueryResult', - 'Sentiment', - 'SentimentAnalysisRequestConfig', - 'SentimentAnalysisResult', - 'StreamingDetectIntentRequest', - 'StreamingDetectIntentResponse', - 'StreamingRecognitionResult', - 'TextInput', - 'CreateSessionEntityTypeRequest', - 'DeleteSessionEntityTypeRequest', - 'GetSessionEntityTypeRequest', - 'ListSessionEntityTypesRequest', - 'ListSessionEntityTypesResponse', - 'SessionEntityType', - 'UpdateSessionEntityTypeRequest', - 'ValidationError', - 'ValidationResult', - 'CreateVersionRequest', - 'DeleteVersionRequest', - 'GetVersionRequest', - 'ListVersionsRequest', - 'ListVersionsResponse', - 'UpdateVersionRequest', - 'Version', - 'OriginalDetectIntentRequest', - 'WebhookRequest', - 'WebhookResponse', -) diff --git a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/types/agent.py b/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/types/agent.py deleted file mode 100644 index d1d4ff0c7..000000000 --- a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/types/agent.py +++ /dev/null @@ -1,584 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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 __future__ import annotations - -from typing import MutableMapping, MutableSequence - -import proto # type: ignore - -from google.protobuf import field_mask_pb2 # type: ignore - - -__protobuf__ = proto.module( - package='google.cloud.dialogflow.v2beta1', - manifest={ - 'Agent', - 'GetAgentRequest', - 'SetAgentRequest', - 'DeleteAgentRequest', - 'SubAgent', - 'SearchAgentsRequest', - 'SearchAgentsResponse', - 'TrainAgentRequest', - 'ExportAgentRequest', - 'ExportAgentResponse', - 'ImportAgentRequest', - 'RestoreAgentRequest', - 'GetValidationResultRequest', - }, -) - - -class Agent(proto.Message): - r"""A Dialogflow agent is a virtual agent that handles conversations - with your end-users. It is a natural language understanding module - that understands the nuances of human language. Dialogflow - translates end-user text or audio during a conversation to - structured data that your apps and services can understand. You - design and build a Dialogflow agent to handle the types of - conversations required for your system. - - For more information about agents, see the `Agent - guide `__. - - Attributes: - parent (str): - Required. The project of this agent. Format: - ``projects/`` or - ``projects//locations/`` - display_name (str): - Required. The name of this agent. - default_language_code (str): - Required. The default language of the agent as a language - tag. See `Language - Support `__ - for a list of the currently supported language codes. This - field cannot be set by the ``Update`` method. - supported_language_codes (MutableSequence[str]): - Optional. The list of all languages supported by this agent - (except for the ``default_language_code``). - time_zone (str): - Required. The time zone of this agent from the `time zone - database `__, e.g., - America/New_York, Europe/Paris. - description (str): - Optional. The description of this agent. - The maximum length is 500 characters. If - exceeded, the request is rejected. - avatar_uri (str): - Optional. The URI of the agent's avatar. Avatars are used - throughout the Dialogflow console and in the self-hosted - `Web - Demo `__ - integration. - enable_logging (bool): - Optional. Determines whether this agent - should log conversation queries. - match_mode (google.cloud.dialogflow_v2beta1.types.Agent.MatchMode): - Optional. Determines how intents are detected - from user queries. - classification_threshold (float): - Optional. To filter out false positive - results and still get variety in matched natural - language inputs for your agent, you can tune the - machine learning classification threshold. If - the returned score value is less than the - threshold value, then a fallback intent will be - triggered or, if there are no fallback intents - defined, no intent will be triggered. The score - values range from 0.0 (completely uncertain) to - 1.0 (completely certain). If set to 0.0, the - default of 0.3 is used. - api_version (google.cloud.dialogflow_v2beta1.types.Agent.ApiVersion): - Optional. API version displayed in Dialogflow - console. If not specified, V2 API is assumed. - Clients are free to query different service - endpoints for different API versions. However, - bots connectors and webhook calls will follow - the specified API version. - tier (google.cloud.dialogflow_v2beta1.types.Agent.Tier): - Optional. The agent tier. If not specified, TIER_STANDARD is - assumed. - """ - class MatchMode(proto.Enum): - r"""Match mode determines how intents are detected from user - queries. - - Values: - MATCH_MODE_UNSPECIFIED (0): - Not specified. - MATCH_MODE_HYBRID (1): - Best for agents with a small number of - examples in intents and/or wide use of templates - syntax and composite entities. - MATCH_MODE_ML_ONLY (2): - Can be used for agents with a large number of - examples in intents, especially the ones using - @sys.any or very large custom entities. - """ - MATCH_MODE_UNSPECIFIED = 0 - MATCH_MODE_HYBRID = 1 - MATCH_MODE_ML_ONLY = 2 - - class ApiVersion(proto.Enum): - r"""API version for the agent. - - Values: - API_VERSION_UNSPECIFIED (0): - Not specified. - API_VERSION_V1 (1): - Legacy V1 API. - API_VERSION_V2 (2): - V2 API. - API_VERSION_V2_BETA_1 (3): - V2beta1 API. - """ - API_VERSION_UNSPECIFIED = 0 - API_VERSION_V1 = 1 - API_VERSION_V2 = 2 - API_VERSION_V2_BETA_1 = 3 - - class Tier(proto.Enum): - r"""Represents the agent tier. - - Values: - TIER_UNSPECIFIED (0): - Not specified. This value should never be - used. - TIER_STANDARD (1): - Trial Edition, previously known as Standard - Edition. - TIER_ENTERPRISE (2): - Essentials Edition, previously known as - Enterprise Essential Edition. - TIER_ENTERPRISE_PLUS (3): - Essentials Edition (same as TIER_ENTERPRISE), previously - known as Enterprise Plus Edition. - """ - TIER_UNSPECIFIED = 0 - TIER_STANDARD = 1 - TIER_ENTERPRISE = 2 - TIER_ENTERPRISE_PLUS = 3 - - parent: str = proto.Field( - proto.STRING, - number=1, - ) - display_name: str = proto.Field( - proto.STRING, - number=2, - ) - default_language_code: str = proto.Field( - proto.STRING, - number=3, - ) - supported_language_codes: MutableSequence[str] = proto.RepeatedField( - proto.STRING, - number=4, - ) - time_zone: str = proto.Field( - proto.STRING, - number=5, - ) - description: str = proto.Field( - proto.STRING, - number=6, - ) - avatar_uri: str = proto.Field( - proto.STRING, - number=7, - ) - enable_logging: bool = proto.Field( - proto.BOOL, - number=8, - ) - match_mode: MatchMode = proto.Field( - proto.ENUM, - number=9, - enum=MatchMode, - ) - classification_threshold: float = proto.Field( - proto.FLOAT, - number=10, - ) - api_version: ApiVersion = proto.Field( - proto.ENUM, - number=14, - enum=ApiVersion, - ) - tier: Tier = proto.Field( - proto.ENUM, - number=15, - enum=Tier, - ) - - -class GetAgentRequest(proto.Message): - r"""The request message for - [Agents.GetAgent][google.cloud.dialogflow.v2beta1.Agents.GetAgent]. - - Attributes: - parent (str): - Required. The project that the agent to fetch is associated - with. Format: ``projects/`` or - ``projects//locations/``. - """ - - parent: str = proto.Field( - proto.STRING, - number=1, - ) - - -class SetAgentRequest(proto.Message): - r"""The request message for - [Agents.SetAgent][google.cloud.dialogflow.v2beta1.Agents.SetAgent]. - - Attributes: - agent (google.cloud.dialogflow_v2beta1.types.Agent): - Required. The agent to update. - update_mask (google.protobuf.field_mask_pb2.FieldMask): - Optional. The mask to control which fields - get updated. - """ - - agent: 'Agent' = proto.Field( - proto.MESSAGE, - number=1, - message='Agent', - ) - update_mask: field_mask_pb2.FieldMask = proto.Field( - proto.MESSAGE, - number=2, - message=field_mask_pb2.FieldMask, - ) - - -class DeleteAgentRequest(proto.Message): - r"""The request message for - [Agents.DeleteAgent][google.cloud.dialogflow.v2beta1.Agents.DeleteAgent]. - - Attributes: - parent (str): - Required. The project that the agent to delete is associated - with. Format: ``projects/`` or - ``projects//locations/``. - """ - - parent: str = 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: - ``projects/`` or - ``projects//locations/``. - environment (str): - Optional. The unique identifier (``environment name`` in - dialogflow console) of this sub-agent environment. Assumes - draft environment if ``environment`` is not set. - """ - - project: str = proto.Field( - proto.STRING, - number=1, - ) - environment: str = proto.Field( - proto.STRING, - number=2, - ) - - -class SearchAgentsRequest(proto.Message): - r"""The request message for - [Agents.SearchAgents][google.cloud.dialogflow.v2beta1.Agents.SearchAgents]. - - Attributes: - parent (str): - Required. The project to list agents from. Format: - ``projects/`` or - ``projects//locations/``. - 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: str = proto.Field( - proto.STRING, - number=1, - ) - page_size: int = proto.Field( - proto.INT32, - number=2, - ) - page_token: str = proto.Field( - proto.STRING, - number=3, - ) - - -class SearchAgentsResponse(proto.Message): - r"""The response message for - [Agents.SearchAgents][google.cloud.dialogflow.v2beta1.Agents.SearchAgents]. - - Attributes: - agents (MutableSequence[google.cloud.dialogflow_v2beta1.types.Agent]): - The list of agents. 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 - - agents: MutableSequence['Agent'] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message='Agent', - ) - next_page_token: str = proto.Field( - proto.STRING, - number=2, - ) - - -class TrainAgentRequest(proto.Message): - r"""The request message for - [Agents.TrainAgent][google.cloud.dialogflow.v2beta1.Agents.TrainAgent]. - - Attributes: - parent (str): - Required. The project that the agent to train is associated - with. Format: ``projects/`` or - ``projects//locations/``. - """ - - parent: str = proto.Field( - proto.STRING, - number=1, - ) - - -class ExportAgentRequest(proto.Message): - r"""The request message for - [Agents.ExportAgent][google.cloud.dialogflow.v2beta1.Agents.ExportAgent]. - - Attributes: - parent (str): - Required. The project that the agent to export is associated - with. Format: ``projects/`` or - ``projects//locations/``. - agent_uri (str): - Optional. The `Google Cloud - Storage `__ URI to - export the agent to. The format of this URI must be - ``gs:///``. If left unspecified, - the serialized agent is returned inline. - - Dialogflow performs a write operation for the Cloud Storage - object on the caller's behalf, so your request - authentication must have write permissions for the object. - For more information, see `Dialogflow access - control `__. - """ - - parent: str = proto.Field( - proto.STRING, - number=1, - ) - agent_uri: str = proto.Field( - proto.STRING, - number=2, - ) - - -class ExportAgentResponse(proto.Message): - r"""The response message for - [Agents.ExportAgent][google.cloud.dialogflow.v2beta1.Agents.ExportAgent]. - - This message has `oneof`_ fields (mutually exclusive fields). - For each oneof, at most one member field can be set at the same time. - Setting any member of the oneof automatically clears all other - members. - - .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields - - Attributes: - agent_uri (str): - The URI to a file containing the exported agent. This field - is populated only if ``agent_uri`` is specified in - ``ExportAgentRequest``. - - This field is a member of `oneof`_ ``agent``. - agent_content (bytes): - Zip compressed raw byte content for agent. - - This field is a member of `oneof`_ ``agent``. - """ - - agent_uri: str = proto.Field( - proto.STRING, - number=1, - oneof='agent', - ) - agent_content: bytes = proto.Field( - proto.BYTES, - number=2, - oneof='agent', - ) - - -class ImportAgentRequest(proto.Message): - r"""The request message for - [Agents.ImportAgent][google.cloud.dialogflow.v2beta1.Agents.ImportAgent]. - - This message has `oneof`_ fields (mutually exclusive fields). - For each oneof, at most one member field can be set at the same time. - Setting any member of the oneof automatically clears all other - members. - - .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields - - Attributes: - parent (str): - Required. The project that the agent to import is associated - with. Format: ``projects/`` or - ``projects//locations/``. - agent_uri (str): - The URI to a Google Cloud Storage file containing the agent - to import. Note: The URI must start with "gs://". - - Dialogflow performs a read operation for the Cloud Storage - object on the caller's behalf, so your request - authentication must have read permissions for the object. - For more information, see `Dialogflow access - control `__. - - This field is a member of `oneof`_ ``agent``. - agent_content (bytes): - Zip compressed raw byte content for agent. - - This field is a member of `oneof`_ ``agent``. - """ - - parent: str = proto.Field( - proto.STRING, - number=1, - ) - agent_uri: str = proto.Field( - proto.STRING, - number=2, - oneof='agent', - ) - agent_content: bytes = proto.Field( - proto.BYTES, - number=3, - oneof='agent', - ) - - -class RestoreAgentRequest(proto.Message): - r"""The request message for - [Agents.RestoreAgent][google.cloud.dialogflow.v2beta1.Agents.RestoreAgent]. - - This message has `oneof`_ fields (mutually exclusive fields). - For each oneof, at most one member field can be set at the same time. - Setting any member of the oneof automatically clears all other - members. - - .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields - - Attributes: - parent (str): - Required. The project that the agent to restore is - associated with. Format: ``projects/`` or - ``projects//locations/``. - agent_uri (str): - The URI to a Google Cloud Storage file containing the agent - to restore. Note: The URI must start with "gs://". - - Dialogflow performs a read operation for the Cloud Storage - object on the caller's behalf, so your request - authentication must have read permissions for the object. - For more information, see `Dialogflow access - control `__. - - This field is a member of `oneof`_ ``agent``. - agent_content (bytes): - Zip compressed raw byte content for agent. - - This field is a member of `oneof`_ ``agent``. - """ - - parent: str = proto.Field( - proto.STRING, - number=1, - ) - agent_uri: str = proto.Field( - proto.STRING, - number=2, - oneof='agent', - ) - agent_content: bytes = proto.Field( - proto.BYTES, - number=3, - oneof='agent', - ) - - -class GetValidationResultRequest(proto.Message): - r"""The request message for - [Agents.GetValidationResult][google.cloud.dialogflow.v2beta1.Agents.GetValidationResult]. - - Attributes: - parent (str): - Required. The project that the agent is associated with. - Format: ``projects/`` or - ``projects//locations/``. - language_code (str): - Optional. The language for which you want a validation - result. If not specified, the agent's default language is - used. `Many - languages `__ - are supported. Note: languages must be enabled in the agent - before they can be used. - """ - - parent: str = proto.Field( - proto.STRING, - number=1, - ) - language_code: str = proto.Field( - proto.STRING, - number=3, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/types/answer_record.py b/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/types/answer_record.py deleted file mode 100644 index 9269697d1..000000000 --- a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/types/answer_record.py +++ /dev/null @@ -1,468 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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 __future__ import annotations - -from typing import MutableMapping, MutableSequence - -import proto # type: ignore - -from google.cloud.dialogflow_v2beta1.types import participant -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={ - 'AnswerRecord', - 'AgentAssistantRecord', - 'AnswerFeedback', - 'AgentAssistantFeedback', - 'GetAnswerRecordRequest', - 'ListAnswerRecordsRequest', - 'ListAnswerRecordsResponse', - 'UpdateAnswerRecordRequest', - }, -) - - -class AnswerRecord(proto.Message): - r"""Answer records are records to manage answer history and feedbacks - for Dialogflow. - - Currently, answer record includes: - - - human agent assistant article suggestion - - human agent assistant faq article - - It doesn't include: - - - ``DetectIntent`` intent matching - - ``DetectIntent`` knowledge - - Answer records are not related to the conversation history in the - Dialogflow Console. A Record is generated even when the end-user - disables conversation history in the console. Records are created - when there's a human agent assistant suggestion generated. - - A typical workflow for customers provide feedback to an answer is: - - 1. For human agent assistant, customers get suggestion via - ListSuggestions API. Together with 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. - - - .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields - - Attributes: - name (str): - The unique identifier of this answer record. Required for - [AnswerRecords.UpdateAnswerRecord][google.cloud.dialogflow.v2beta1.AnswerRecords.UpdateAnswerRecord] - method. Format: - ``projects//locations//answerRecords/``. - answer_feedback (google.cloud.dialogflow_v2beta1.types.AnswerFeedback): - Optional. The AnswerFeedback for this record. You can set - this with - [AnswerRecords.UpdateAnswerRecord][google.cloud.dialogflow.v2beta1.AnswerRecords.UpdateAnswerRecord] - in order to give us feedback about this answer. - agent_assistant_record (google.cloud.dialogflow_v2beta1.types.AgentAssistantRecord): - Output only. The record for human agent - assistant. - - This field is a member of `oneof`_ ``record``. - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - answer_feedback: 'AnswerFeedback' = proto.Field( - proto.MESSAGE, - number=3, - message='AnswerFeedback', - ) - agent_assistant_record: 'AgentAssistantRecord' = proto.Field( - proto.MESSAGE, - number=4, - oneof='record', - message='AgentAssistantRecord', - ) - - -class AgentAssistantRecord(proto.Message): - r"""Represents a record of a human agent assistant answer. - - This message has `oneof`_ fields (mutually exclusive fields). - For each oneof, at most one member field can be set at the same time. - Setting any member of the oneof automatically clears all other - members. - - .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields - - Attributes: - article_suggestion_answer (google.cloud.dialogflow_v2beta1.types.ArticleAnswer): - Output only. The article suggestion answer. - - This field is a member of `oneof`_ ``answer``. - faq_answer (google.cloud.dialogflow_v2beta1.types.FaqAnswer): - Output only. The FAQ answer. - - This field is a member of `oneof`_ ``answer``. - """ - - article_suggestion_answer: participant.ArticleAnswer = proto.Field( - proto.MESSAGE, - number=5, - oneof='answer', - message=participant.ArticleAnswer, - ) - faq_answer: participant.FaqAnswer = proto.Field( - proto.MESSAGE, - number=6, - oneof='answer', - message=participant.FaqAnswer, - ) - - -class AnswerFeedback(proto.Message): - r"""Represents feedback the customer has about the quality & - correctness of a certain answer in a conversation. - - - .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields - - Attributes: - correctness_level (google.cloud.dialogflow_v2beta1.types.AnswerFeedback.CorrectnessLevel): - The correctness level of the specific answer. - agent_assistant_detail_feedback (google.cloud.dialogflow_v2beta1.types.AgentAssistantFeedback): - Optional. Detail feedback of agent assistant - suggestions. - - This field is a member of `oneof`_ ``detail_feedback``. - clicked (bool): - Indicates whether the answer/item was clicked - by the human agent or not. Default to false. - click_time (google.protobuf.timestamp_pb2.Timestamp): - Time when the answer/item was clicked. - displayed (bool): - Indicates whether the answer/item was - displayed to the human agent in the agent - desktop UI. Default to false. - display_time (google.protobuf.timestamp_pb2.Timestamp): - Time when the answer/item was displayed. - """ - class CorrectnessLevel(proto.Enum): - r"""The correctness level of an answer. - - Values: - CORRECTNESS_LEVEL_UNSPECIFIED (0): - Correctness level unspecified. - NOT_CORRECT (1): - Answer is totally wrong. - PARTIALLY_CORRECT (2): - Answer is partially correct. - FULLY_CORRECT (3): - Answer is fully correct. - """ - CORRECTNESS_LEVEL_UNSPECIFIED = 0 - NOT_CORRECT = 1 - PARTIALLY_CORRECT = 2 - FULLY_CORRECT = 3 - - correctness_level: CorrectnessLevel = proto.Field( - proto.ENUM, - number=1, - enum=CorrectnessLevel, - ) - agent_assistant_detail_feedback: 'AgentAssistantFeedback' = proto.Field( - proto.MESSAGE, - number=2, - oneof='detail_feedback', - message='AgentAssistantFeedback', - ) - clicked: bool = proto.Field( - proto.BOOL, - number=3, - ) - click_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=5, - message=timestamp_pb2.Timestamp, - ) - displayed: bool = proto.Field( - proto.BOOL, - number=4, - ) - display_time: timestamp_pb2.Timestamp = 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. - - For example: - - - Query: "Can I change my mailing address?" - - Suggested document says: "Items must be - returned/exchanged within 60 days of the purchase date." - - [answer_relevance][google.cloud.dialogflow.v2beta1.AgentAssistantFeedback.answer_relevance]: - [AnswerRelevance.IRRELEVANT][google.cloud.dialogflow.v2beta1.AgentAssistantFeedback.AnswerRelevance.IRRELEVANT] - document_correctness (google.cloud.dialogflow_v2beta1.types.AgentAssistantFeedback.DocumentCorrectness): - Optional. Whether or not the information in the document is - correct. - - For example: - - - Query: "Can I return the package in 2 days once - received?" - - Suggested document says: "Items must be - returned/exchanged within 60 days of the purchase date." - - Ground truth: "No return or exchange is allowed." - - - document_efficiency (google.cloud.dialogflow_v2beta1.types.AgentAssistantFeedback.DocumentEfficiency): - Optional. Whether or not the suggested document is - efficient. For example, if the document is poorly written, - hard to understand, hard to use or too long to find useful - information, - [document_efficiency][google.cloud.dialogflow.v2beta1.AgentAssistantFeedback.document_efficiency] - is - [DocumentEfficiency.INEFFICIENT][google.cloud.dialogflow.v2beta1.AgentAssistantFeedback.DocumentEfficiency.INEFFICIENT]. - summarization_feedback (google.cloud.dialogflow_v2beta1.types.AgentAssistantFeedback.SummarizationFeedback): - Feedback for conversation summarization. - """ - class AnswerRelevance(proto.Enum): - r"""Relevance of an answer. - - Values: - ANSWER_RELEVANCE_UNSPECIFIED (0): - Answer relevance unspecified. - IRRELEVANT (1): - Answer is irrelevant to query. - RELEVANT (2): - Answer is relevant to query. - """ - ANSWER_RELEVANCE_UNSPECIFIED = 0 - IRRELEVANT = 1 - RELEVANT = 2 - - class DocumentCorrectness(proto.Enum): - r"""Correctness of document. - - Values: - DOCUMENT_CORRECTNESS_UNSPECIFIED (0): - Document correctness unspecified. - INCORRECT (1): - Information in document is incorrect. - CORRECT (2): - Information in document is correct. - """ - DOCUMENT_CORRECTNESS_UNSPECIFIED = 0 - INCORRECT = 1 - CORRECT = 2 - - class DocumentEfficiency(proto.Enum): - r"""Efficiency of document. - - Values: - DOCUMENT_EFFICIENCY_UNSPECIFIED (0): - Document efficiency unspecified. - INEFFICIENT (1): - Document is inefficient. - EFFICIENT (2): - Document is efficient. - """ - DOCUMENT_EFFICIENCY_UNSPECIFIED = 0 - INEFFICIENT = 1 - EFFICIENT = 2 - - class SummarizationFeedback(proto.Message): - r"""Feedback for conversation summarization. - - Attributes: - start_timestamp (google.protobuf.timestamp_pb2.Timestamp): - Timestamp when composing of the summary - starts. - submit_timestamp (google.protobuf.timestamp_pb2.Timestamp): - Timestamp when the summary was submitted. - summary_text (str): - Text of actual submitted summary. - """ - - start_timestamp: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=1, - message=timestamp_pb2.Timestamp, - ) - submit_timestamp: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=2, - message=timestamp_pb2.Timestamp, - ) - summary_text: str = proto.Field( - proto.STRING, - number=3, - ) - - answer_relevance: AnswerRelevance = proto.Field( - proto.ENUM, - number=1, - enum=AnswerRelevance, - ) - document_correctness: DocumentCorrectness = proto.Field( - proto.ENUM, - number=2, - enum=DocumentCorrectness, - ) - document_efficiency: DocumentEfficiency = proto.Field( - proto.ENUM, - number=3, - enum=DocumentEfficiency, - ) - summarization_feedback: SummarizationFeedback = proto.Field( - proto.MESSAGE, - number=4, - message=SummarizationFeedback, - ) - - -class GetAnswerRecordRequest(proto.Message): - r"""Request message for - [AnswerRecords.GetAnswerRecord][google.cloud.dialogflow.v2beta1.AnswerRecords.GetAnswerRecord]. - - Attributes: - name (str): - Required. The name of the answer record to retrieve. Format: - ``projects//locations//answerRecords/``. - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - - -class ListAnswerRecordsRequest(proto.Message): - r"""Request message for - [AnswerRecords.ListAnswerRecords][google.cloud.dialogflow.v2beta1.AnswerRecords.ListAnswerRecords]. - - Attributes: - parent (str): - Required. The project to list all answer records for in - reverse chronological order. Format: - ``projects//locations/``. - filter (str): - Optional. Filters to restrict results to specific answer - records. - - For more information about filtering, see `API - Filtering `__. - page_size (int): - Optional. The maximum number of records to - return in a single page. The server may return - fewer records than this. If unspecified, we use - 10. The maximum is 100. - page_token (str): - Optional. The - [ListAnswerRecordsResponse.next_page_token][google.cloud.dialogflow.v2beta1.ListAnswerRecordsResponse.next_page_token] - value returned from a previous list request used to continue - listing on the next page. - """ - - parent: str = proto.Field( - proto.STRING, - number=1, - ) - filter: str = proto.Field( - proto.STRING, - number=2, - ) - page_size: int = proto.Field( - proto.INT32, - number=3, - ) - page_token: str = proto.Field( - proto.STRING, - number=4, - ) - - -class ListAnswerRecordsResponse(proto.Message): - r"""Response message for - [AnswerRecords.ListAnswerRecords][google.cloud.dialogflow.v2beta1.AnswerRecords.ListAnswerRecords]. - - Attributes: - answer_records (MutableSequence[google.cloud.dialogflow_v2beta1.types.AnswerRecord]): - The list of answer records. - next_page_token (str): - A token to retrieve next page of results. Or empty if there - are no more results. Pass this value in the - [ListAnswerRecordsRequest.page_token][google.cloud.dialogflow.v2beta1.ListAnswerRecordsRequest.page_token] - field in the subsequent call to ``ListAnswerRecords`` method - to retrieve the next page of results. - """ - - @property - def raw_page(self): - return self - - answer_records: MutableSequence['AnswerRecord'] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message='AnswerRecord', - ) - next_page_token: str = proto.Field( - proto.STRING, - number=2, - ) - - -class UpdateAnswerRecordRequest(proto.Message): - r"""Request message for - [AnswerRecords.UpdateAnswerRecord][google.cloud.dialogflow.v2beta1.AnswerRecords.UpdateAnswerRecord]. - - Attributes: - answer_record (google.cloud.dialogflow_v2beta1.types.AnswerRecord): - Required. Answer record to update. - update_mask (google.protobuf.field_mask_pb2.FieldMask): - Required. The mask to control which fields - get updated. - """ - - answer_record: 'AnswerRecord' = proto.Field( - proto.MESSAGE, - number=1, - message='AnswerRecord', - ) - update_mask: field_mask_pb2.FieldMask = proto.Field( - proto.MESSAGE, - number=2, - message=field_mask_pb2.FieldMask, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/types/audio_config.py b/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/types/audio_config.py deleted file mode 100644 index 565a95249..000000000 --- a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/types/audio_config.py +++ /dev/null @@ -1,736 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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 __future__ import annotations - -from typing import MutableMapping, MutableSequence - -import proto # type: ignore - -from google.protobuf import duration_pb2 # type: ignore - - -__protobuf__ = proto.module( - package='google.cloud.dialogflow.v2beta1', - manifest={ - 'AudioEncoding', - 'SpeechModelVariant', - 'SsmlVoiceGender', - 'OutputAudioEncoding', - 'TelephonyDtmf', - 'SpeechContext', - 'SpeechWordInfo', - 'BargeInConfig', - 'InputAudioConfig', - 'VoiceSelectionParams', - 'SynthesizeSpeechConfig', - 'OutputAudioConfig', - 'TelephonyDtmfEvents', - 'SpeechToTextConfig', - }, -) - - -class AudioEncoding(proto.Enum): - r"""Audio encoding of the audio content sent in the conversational query - request. Refer to the `Cloud Speech API - documentation `__ - for more details. - - Values: - AUDIO_ENCODING_UNSPECIFIED (0): - Not specified. - AUDIO_ENCODING_LINEAR_16 (1): - Uncompressed 16-bit signed little-endian - samples (Linear PCM). - AUDIO_ENCODING_FLAC (2): - ```FLAC`` `__ - (Free Lossless Audio Codec) is the recommended encoding - because it is lossless (therefore recognition is not - compromised) and requires only about half the bandwidth of - ``LINEAR16``. ``FLAC`` stream encoding supports 16-bit and - 24-bit samples, however, not all fields in ``STREAMINFO`` - are supported. - AUDIO_ENCODING_MULAW (3): - 8-bit samples that compand 14-bit audio - samples using G.711 PCMU/mu-law. - AUDIO_ENCODING_AMR (4): - Adaptive Multi-Rate Narrowband codec. ``sample_rate_hertz`` - must be 8000. - AUDIO_ENCODING_AMR_WB (5): - Adaptive Multi-Rate Wideband codec. ``sample_rate_hertz`` - must be 16000. - AUDIO_ENCODING_OGG_OPUS (6): - Opus encoded audio frames in Ogg container - (`OggOpus `__). - ``sample_rate_hertz`` must be 16000. - AUDIO_ENCODING_SPEEX_WITH_HEADER_BYTE (7): - Although the use of lossy encodings is not recommended, if a - very low bitrate encoding is required, ``OGG_OPUS`` is - highly preferred over Speex encoding. The - `Speex `__ encoding supported by - Dialogflow API has a header byte in each block, as in MIME - type ``audio/x-speex-with-header-byte``. It is a variant of - the RTP Speex encoding defined in `RFC - 5574 `__. The stream is - a sequence of blocks, one block per RTP packet. Each block - starts with a byte containing the length of the block, in - bytes, followed by one or more frames of Speex data, padded - to an integral number of bytes (octets) as specified in RFC - 5574. In other words, each RTP header is replaced with a - single byte containing the block length. Only Speex wideband - is supported. ``sample_rate_hertz`` must be 16000. - """ - AUDIO_ENCODING_UNSPECIFIED = 0 - AUDIO_ENCODING_LINEAR_16 = 1 - AUDIO_ENCODING_FLAC = 2 - AUDIO_ENCODING_MULAW = 3 - AUDIO_ENCODING_AMR = 4 - AUDIO_ENCODING_AMR_WB = 5 - AUDIO_ENCODING_OGG_OPUS = 6 - AUDIO_ENCODING_SPEEX_WITH_HEADER_BYTE = 7 - - -class SpeechModelVariant(proto.Enum): - r"""Variant of the specified [Speech - model][google.cloud.dialogflow.v2beta1.InputAudioConfig.model] to - use. - - See the `Cloud Speech - documentation `__ - for which models have different variants. For example, the - "phone_call" model has both a standard and an enhanced variant. When - you use an enhanced model, you will generally receive higher quality - results than for a standard model. - - Values: - SPEECH_MODEL_VARIANT_UNSPECIFIED (0): - No model variant specified. In this case Dialogflow defaults - to USE_BEST_AVAILABLE. - USE_BEST_AVAILABLE (1): - Use the best available variant of the [Speech - model][InputAudioConfig.model] that the caller is eligible - for. - - Please see the `Dialogflow - docs `__ - for how to make your project eligible for enhanced models. - USE_STANDARD (2): - Use standard model variant even if an enhanced model is - available. See the `Cloud Speech - documentation `__ - for details about enhanced models. - USE_ENHANCED (3): - Use an enhanced model variant: - - - If an enhanced variant does not exist for the given - [model][google.cloud.dialogflow.v2beta1.InputAudioConfig.model] - and request language, Dialogflow falls back to the - standard variant. - - The `Cloud Speech - documentation `__ - describes which models have enhanced variants. - - - If the API caller isn't eligible for enhanced models, - Dialogflow returns an error. Please see the `Dialogflow - docs `__ - for how to make your project eligible. - """ - SPEECH_MODEL_VARIANT_UNSPECIFIED = 0 - USE_BEST_AVAILABLE = 1 - USE_STANDARD = 2 - USE_ENHANCED = 3 - - -class SsmlVoiceGender(proto.Enum): - r"""Gender of the voice as described in `SSML voice - element `__. - - Values: - SSML_VOICE_GENDER_UNSPECIFIED (0): - An unspecified gender, which means that the - client doesn't care which gender the selected - voice will have. - SSML_VOICE_GENDER_MALE (1): - A male voice. - SSML_VOICE_GENDER_FEMALE (2): - A female voice. - SSML_VOICE_GENDER_NEUTRAL (3): - A gender-neutral voice. - """ - SSML_VOICE_GENDER_UNSPECIFIED = 0 - SSML_VOICE_GENDER_MALE = 1 - SSML_VOICE_GENDER_FEMALE = 2 - SSML_VOICE_GENDER_NEUTRAL = 3 - - -class OutputAudioEncoding(proto.Enum): - r"""Audio encoding of the output audio format in Text-To-Speech. - - Values: - OUTPUT_AUDIO_ENCODING_UNSPECIFIED (0): - Not specified. - OUTPUT_AUDIO_ENCODING_LINEAR_16 (1): - Uncompressed 16-bit signed little-endian - samples (Linear PCM). Audio content returned as - LINEAR16 also contains a WAV header. - OUTPUT_AUDIO_ENCODING_MP3 (2): - MP3 audio at 32kbps. - OUTPUT_AUDIO_ENCODING_MP3_64_KBPS (4): - MP3 audio at 64kbps. - OUTPUT_AUDIO_ENCODING_OGG_OPUS (3): - Opus encoded audio wrapped in an ogg - container. The result will be a file which can - be played natively on Android, and in browsers - (at least Chrome and Firefox). The quality of - the encoding is considerably higher than MP3 - while using approximately the same bitrate. - OUTPUT_AUDIO_ENCODING_MULAW (5): - 8-bit samples that compand 14-bit audio - samples using G.711 PCMU/mu-law. - """ - OUTPUT_AUDIO_ENCODING_UNSPECIFIED = 0 - OUTPUT_AUDIO_ENCODING_LINEAR_16 = 1 - OUTPUT_AUDIO_ENCODING_MP3 = 2 - OUTPUT_AUDIO_ENCODING_MP3_64_KBPS = 4 - OUTPUT_AUDIO_ENCODING_OGG_OPUS = 3 - OUTPUT_AUDIO_ENCODING_MULAW = 5 - - -class TelephonyDtmf(proto.Enum): - r"""`DTMF `__ - digit in Telephony Gateway. - - Values: - TELEPHONY_DTMF_UNSPECIFIED (0): - Not specified. This value may be used to - indicate an absent digit. - DTMF_ONE (1): - Number: '1'. - DTMF_TWO (2): - Number: '2'. - DTMF_THREE (3): - Number: '3'. - DTMF_FOUR (4): - Number: '4'. - DTMF_FIVE (5): - Number: '5'. - DTMF_SIX (6): - Number: '6'. - DTMF_SEVEN (7): - Number: '7'. - DTMF_EIGHT (8): - Number: '8'. - DTMF_NINE (9): - Number: '9'. - DTMF_ZERO (10): - Number: '0'. - DTMF_A (11): - Letter: 'A'. - DTMF_B (12): - Letter: 'B'. - DTMF_C (13): - Letter: 'C'. - DTMF_D (14): - Letter: 'D'. - DTMF_STAR (15): - Asterisk/star: '*'. - DTMF_POUND (16): - Pound/diamond/hash/square/gate/octothorpe: - '#'. - """ - TELEPHONY_DTMF_UNSPECIFIED = 0 - DTMF_ONE = 1 - DTMF_TWO = 2 - DTMF_THREE = 3 - DTMF_FOUR = 4 - DTMF_FIVE = 5 - DTMF_SIX = 6 - DTMF_SEVEN = 7 - DTMF_EIGHT = 8 - DTMF_NINE = 9 - DTMF_ZERO = 10 - DTMF_A = 11 - DTMF_B = 12 - DTMF_C = 13 - DTMF_D = 14 - DTMF_STAR = 15 - DTMF_POUND = 16 - - -class SpeechContext(proto.Message): - r"""Hints for the speech recognizer to help with recognition in a - specific conversation state. - - Attributes: - phrases (MutableSequence[str]): - Optional. A list of strings containing words and phrases - that the speech recognizer should recognize with higher - likelihood. - - This list can be used to: - - - improve accuracy for words and phrases you expect the - user to say, e.g. typical commands for your Dialogflow - agent - - add additional words to the speech recognizer vocabulary - - ... - - See the `Cloud Speech - documentation `__ - for usage limits. - boost (float): - Optional. Boost for this context compared to other contexts: - - - If the boost is positive, Dialogflow will increase the - probability that the phrases in this context are - recognized over similar sounding phrases. - - If the boost is unspecified or non-positive, Dialogflow - will not apply any boost. - - Dialogflow recommends that you use boosts in the range (0, - 20] and that you find a value that fits your use case with - binary search. - """ - - phrases: MutableSequence[str] = proto.RepeatedField( - proto.STRING, - number=1, - ) - boost: float = 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. - start_offset (google.protobuf.duration_pb2.Duration): - Time offset relative to the beginning of the - audio that corresponds to the start of the - spoken word. This is an experimental feature and - the accuracy of the time offset can vary. - end_offset (google.protobuf.duration_pb2.Duration): - Time offset relative to the beginning of the - audio that corresponds to the end of the spoken - word. This is an experimental feature and the - accuracy of the time offset can vary. - confidence (float): - The Speech confidence between 0.0 and 1.0 for - this word. A higher number indicates an - estimated greater likelihood that the recognized - word is correct. The default of 0.0 is a - sentinel value indicating that confidence was - not set. - - This field is not guaranteed to be fully stable - over time for the same audio input. Users should - also not rely on it to always be provided. - """ - - word: str = proto.Field( - proto.STRING, - number=3, - ) - start_offset: duration_pb2.Duration = proto.Field( - proto.MESSAGE, - number=1, - message=duration_pb2.Duration, - ) - end_offset: duration_pb2.Duration = proto.Field( - proto.MESSAGE, - number=2, - message=duration_pb2.Duration, - ) - confidence: float = proto.Field( - proto.FLOAT, - number=4, - ) - - -class BargeInConfig(proto.Message): - r"""Configuration of the barge-in behavior. Barge-in instructs the API - to return a detected utterance at a proper time while the client is - playing back the response audio from a previous request. When the - client sees the utterance, it should stop the playback and - immediately get ready for receiving the responses for the current - request. - - The barge-in handling requires the client to start streaming audio - input as soon as it starts playing back the audio from the previous - response. The playback is modeled into two phases: - - - No barge-in phase: which goes first and during which speech - detection should not be carried out. - - - Barge-in phase: which follows the no barge-in phase and during - which the API starts speech detection and may inform the client - that an utterance has been detected. Note that no-speech event is - not expected in this phase. - - The client provides this configuration in terms of the durations of - those two phases. The durations are measured in terms of the audio - length fromt the the start of the input audio. - - No-speech event is a response with END_OF_UTTERANCE without any - transcript following up. - - Attributes: - no_barge_in_duration (google.protobuf.duration_pb2.Duration): - Duration that is not eligible for barge-in at - the beginning of the input audio. - total_duration (google.protobuf.duration_pb2.Duration): - Total duration for the playback at the - beginning of the input audio. - """ - - no_barge_in_duration: duration_pb2.Duration = proto.Field( - proto.MESSAGE, - number=1, - message=duration_pb2.Duration, - ) - total_duration: duration_pb2.Duration = proto.Field( - proto.MESSAGE, - number=2, - message=duration_pb2.Duration, - ) - - -class InputAudioConfig(proto.Message): - r"""Instructs the speech recognizer on how to process the audio - content. - - Attributes: - audio_encoding (google.cloud.dialogflow_v2beta1.types.AudioEncoding): - Required. Audio encoding of the audio content - to process. - sample_rate_hertz (int): - Required. Sample rate (in Hertz) of the audio content sent - in the query. Refer to `Cloud Speech API - documentation `__ - for more details. - language_code (str): - Required. The language of the supplied audio. Dialogflow - does not do translations. See `Language - Support `__ - for a list of the currently supported language codes. Note - that queries in the same session do not necessarily need to - specify the same language. - enable_word_info (bool): - If ``true``, Dialogflow returns - [SpeechWordInfo][google.cloud.dialogflow.v2beta1.SpeechWordInfo] - in - [StreamingRecognitionResult][google.cloud.dialogflow.v2beta1.StreamingRecognitionResult] - with information about the recognized speech words, e.g. - start and end time offsets. If false or unspecified, Speech - doesn't return any word-level information. - phrase_hints (MutableSequence[str]): - A list of strings containing words and phrases that the - speech recognizer should recognize with higher likelihood. - - See `the Cloud Speech - documentation `__ - for more details. - - This field is deprecated. Please use `speech_contexts <>`__ - instead. If you specify both `phrase_hints <>`__ and - `speech_contexts <>`__, Dialogflow will treat the - `phrase_hints <>`__ as a single additional - `SpeechContext <>`__. - speech_contexts (MutableSequence[google.cloud.dialogflow_v2beta1.types.SpeechContext]): - Context information to assist speech recognition. - - See `the Cloud Speech - documentation `__ - for more details. - model (str): - Which Speech model to select for the given request. Select - the model best suited to your domain to get best results. If - a model is not explicitly specified, then we auto-select a - model based on the parameters in the InputAudioConfig. If - enhanced speech model is enabled for the agent and an - enhanced version of the specified model for the language - does not exist, then the speech is recognized using the - standard version of the specified model. Refer to `Cloud - Speech API - documentation `__ - for more details. - model_variant (google.cloud.dialogflow_v2beta1.types.SpeechModelVariant): - Which variant of the [Speech - model][google.cloud.dialogflow.v2beta1.InputAudioConfig.model] - to use. - single_utterance (bool): - If ``false`` (default), recognition does not cease until the - client closes the stream. If ``true``, the recognizer will - detect a single spoken utterance in input audio. Recognition - ceases when it detects the audio's voice has stopped or - paused. In this case, once a detected intent is received, - the client should close the stream and start a new request - with a new stream as needed. Note: This setting is relevant - only for streaming methods. Note: When specified, - InputAudioConfig.single_utterance takes precedence over - StreamingDetectIntentRequest.single_utterance. - disable_no_speech_recognized_event (bool): - Only used in - [Participants.AnalyzeContent][google.cloud.dialogflow.v2beta1.Participants.AnalyzeContent] - and - [Participants.StreamingAnalyzeContent][google.cloud.dialogflow.v2beta1.Participants.StreamingAnalyzeContent]. - If ``false`` and recognition doesn't return any result, - trigger ``NO_SPEECH_RECOGNIZED`` event to Dialogflow agent. - barge_in_config (google.cloud.dialogflow_v2beta1.types.BargeInConfig): - Configuration of barge-in behavior during the - streaming of input audio. - """ - - audio_encoding: 'AudioEncoding' = proto.Field( - proto.ENUM, - number=1, - enum='AudioEncoding', - ) - sample_rate_hertz: int = proto.Field( - proto.INT32, - number=2, - ) - language_code: str = proto.Field( - proto.STRING, - number=3, - ) - enable_word_info: bool = proto.Field( - proto.BOOL, - number=13, - ) - phrase_hints: MutableSequence[str] = proto.RepeatedField( - proto.STRING, - number=4, - ) - speech_contexts: MutableSequence['SpeechContext'] = proto.RepeatedField( - proto.MESSAGE, - number=11, - message='SpeechContext', - ) - model: str = proto.Field( - proto.STRING, - number=7, - ) - model_variant: 'SpeechModelVariant' = proto.Field( - proto.ENUM, - number=10, - enum='SpeechModelVariant', - ) - single_utterance: bool = proto.Field( - proto.BOOL, - number=8, - ) - disable_no_speech_recognized_event: bool = proto.Field( - proto.BOOL, - number=14, - ) - barge_in_config: 'BargeInConfig' = proto.Field( - proto.MESSAGE, - number=15, - message='BargeInConfig', - ) - - -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 - will choose a voice based on the other parameters such as - language_code and - [ssml_gender][google.cloud.dialogflow.v2beta1.VoiceSelectionParams.ssml_gender]. - - For the list of available voices, please refer to `Supported - voices and - languages `__. - ssml_gender (google.cloud.dialogflow_v2beta1.types.SsmlVoiceGender): - Optional. The preferred gender of the voice. If not set, the - service will choose a voice based on the other parameters - such as language_code and - [name][google.cloud.dialogflow.v2beta1.VoiceSelectionParams.name]. - Note that this is only a preference, not requirement. If a - voice of the appropriate gender is not available, the - synthesizer should substitute a voice with a different - gender rather than failing the request. - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - ssml_gender: 'SsmlVoiceGender' = 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 - is the normal native speed supported by the specific voice. - 2.0 is twice as fast, and 0.5 is half as fast. If - unset(0.0), defaults to the native 1.0 speed. Any other - values < 0.25 or > 4.0 will return an error. - pitch (float): - Optional. Speaking pitch, in the range [-20.0, 20.0]. 20 - means increase 20 semitones from the original pitch. -20 - means decrease 20 semitones from the original pitch. - volume_gain_db (float): - Optional. Volume gain (in dB) of the normal native volume - supported by the specific voice, in the range [-96.0, 16.0]. - If unset, or set to a value of 0.0 (dB), will play at normal - native signal amplitude. A value of -6.0 (dB) will play at - approximately half the amplitude of the normal native signal - amplitude. A value of +6.0 (dB) will play at approximately - twice the amplitude of the normal native signal amplitude. - We strongly recommend not to exceed +10 (dB) as there's - usually no effective increase in loudness for any value - greater than that. - effects_profile_id (MutableSequence[str]): - Optional. An identifier which selects 'audio - effects' profiles that are applied on (post - synthesized) text to speech. Effects are applied - on top of each other in the order they are - given. - voice (google.cloud.dialogflow_v2beta1.types.VoiceSelectionParams): - Optional. The desired voice of the - synthesized audio. - """ - - speaking_rate: float = proto.Field( - proto.DOUBLE, - number=1, - ) - pitch: float = proto.Field( - proto.DOUBLE, - number=2, - ) - volume_gain_db: float = proto.Field( - proto.DOUBLE, - number=3, - ) - effects_profile_id: MutableSequence[str] = proto.RepeatedField( - proto.STRING, - number=5, - ) - voice: 'VoiceSelectionParams' = proto.Field( - proto.MESSAGE, - number=4, - message='VoiceSelectionParams', - ) - - -class OutputAudioConfig(proto.Message): - r"""Instructs the speech synthesizer how to generate the output - audio content. If this audio config is supplied in a request, it - overrides all existing text-to-speech settings applied to the - agent. - - Attributes: - audio_encoding (google.cloud.dialogflow_v2beta1.types.OutputAudioEncoding): - Required. Audio encoding of the synthesized - audio content. - sample_rate_hertz (int): - 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_config (google.cloud.dialogflow_v2beta1.types.SynthesizeSpeechConfig): - Configuration of how speech should be - synthesized. - """ - - audio_encoding: 'OutputAudioEncoding' = proto.Field( - proto.ENUM, - number=1, - enum='OutputAudioEncoding', - ) - sample_rate_hertz: int = proto.Field( - proto.INT32, - number=2, - ) - synthesize_speech_config: 'SynthesizeSpeechConfig' = proto.Field( - proto.MESSAGE, - number=3, - message='SynthesizeSpeechConfig', - ) - - -class TelephonyDtmfEvents(proto.Message): - r"""A wrapper of repeated TelephonyDtmf digits. - - Attributes: - dtmf_events (MutableSequence[google.cloud.dialogflow_v2beta1.types.TelephonyDtmf]): - A sequence of TelephonyDtmf digits. - """ - - dtmf_events: MutableSequence['TelephonyDtmf'] = proto.RepeatedField( - proto.ENUM, - number=1, - enum='TelephonyDtmf', - ) - - -class SpeechToTextConfig(proto.Message): - r"""Configures speech transcription for - [ConversationProfile][google.cloud.dialogflow.v2beta1.ConversationProfile]. - - Attributes: - speech_model_variant (google.cloud.dialogflow_v2beta1.types.SpeechModelVariant): - The speech model used in speech to text. - ``SPEECH_MODEL_VARIANT_UNSPECIFIED``, ``USE_BEST_AVAILABLE`` - will be treated as ``USE_ENHANCED``. It can be overridden in - [AnalyzeContentRequest][google.cloud.dialogflow.v2beta1.AnalyzeContentRequest] - and - [StreamingAnalyzeContentRequest][google.cloud.dialogflow.v2beta1.StreamingAnalyzeContentRequest] - request. If enhanced model variant is specified and an - enhanced version of the specified model for the language - does not exist, then it would emit an error. - model (str): - Which Speech model to select. Select the model best suited - to your domain to get best results. If a model is not - explicitly specified, then a default model is used. Refer to - `Cloud Speech API - documentation `__ - for more details. - """ - - speech_model_variant: 'SpeechModelVariant' = proto.Field( - proto.ENUM, - number=1, - enum='SpeechModelVariant', - ) - model: str = proto.Field( - proto.STRING, - number=2, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/types/context.py b/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/types/context.py deleted file mode 100644 index 7502e1350..000000000 --- a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/types/context.py +++ /dev/null @@ -1,331 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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 __future__ import annotations - -from typing import MutableMapping, MutableSequence - -import proto # type: ignore - -from google.protobuf import field_mask_pb2 # type: ignore -from google.protobuf import struct_pb2 # type: ignore - - -__protobuf__ = proto.module( - package='google.cloud.dialogflow.v2beta1', - manifest={ - 'Context', - 'ListContextsRequest', - 'ListContextsResponse', - 'GetContextRequest', - 'CreateContextRequest', - 'UpdateContextRequest', - 'DeleteContextRequest', - 'DeleteAllContextsRequest', - }, -) - - -class Context(proto.Message): - r"""Dialogflow contexts are similar to natural language context. If a - person says to you "they are orange", you need context in order to - understand what "they" is referring to. Similarly, for Dialogflow to - handle an end-user expression like that, it needs to be provided - with context in order to correctly match an intent. - - Using contexts, you can control the flow of a conversation. You can - configure contexts for an intent by setting input and output - contexts, which are identified by string names. When an intent is - matched, any configured output contexts for that intent become - active. While any contexts are active, Dialogflow is more likely to - match intents that are configured with input contexts that - correspond to the currently active contexts. - - For more information about context, see the `Contexts - guide `__. - - Attributes: - name (str): - Required. The unique identifier of the context. Supported - formats: - - - ``projects//agent/sessions//contexts/``, - - ``projects//locations//agent/sessions//contexts/``, - - ``projects//agent/environments//users//sessions//contexts/``, - - ``projects//locations//agent/environments//users//sessions//contexts/``, - - The ``Context ID`` is always converted to lowercase, may - only contain characters in a-zA-Z0-9_-% and may be at most - 250 bytes long. - - If ``Environment ID`` is not specified, we assume default - 'draft' environment. If ``User ID`` is not specified, we - assume default '-' user. - - The following context names are reserved for internal use by - Dialogflow. You should not use these contexts or create - contexts with these names: - - - ``__system_counters__`` - - ``*_id_dialog_context`` - - ``*_dialog_params_size`` - lifespan_count (int): - Optional. The number of conversational query requests after - which the context expires. The default is ``0``. If set to - ``0``, the context expires immediately. Contexts expire - automatically after 20 minutes if there are no matching - queries. - parameters (google.protobuf.struct_pb2.Struct): - Optional. The collection of parameters - associated with this context. - Depending on your protocol or client library - language, this is a map, associative array, - symbol table, dictionary, or JSON object - composed of a collection of (MapKey, MapValue) - pairs: - - MapKey type: string - - MapKey value: parameter name - - MapValue type: - - If parameter's entity type is a - composite entity: map - Else: depending on - parameter value type, could be one of string, - number, boolean, null, list or map - - MapValue value: - - If parameter's entity type is a - composite entity: map from composite - entity property names to property values - - Else: parameter value - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - lifespan_count: int = proto.Field( - proto.INT32, - number=2, - ) - parameters: struct_pb2.Struct = proto.Field( - proto.MESSAGE, - number=3, - message=struct_pb2.Struct, - ) - - -class ListContextsRequest(proto.Message): - r"""The request message for - [Contexts.ListContexts][google.cloud.dialogflow.v2beta1.Contexts.ListContexts]. - - Attributes: - parent (str): - Required. The session to list all contexts from. Supported - formats: - - - \`projects//agent/sessions/, - - ``projects//locations//agent/sessions/``, - - ``projects//agent/environments//users//sessions/``, - - ``projects//locations//agent/environments//users//sessions/``, - - If ``Location ID`` is not specified we assume default 'us' - location. If ``Environment ID`` is not specified, we assume - default 'draft' environment. If ``User ID`` is not - specified, we assume default '-' user. - 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: str = proto.Field( - proto.STRING, - number=1, - ) - page_size: int = proto.Field( - proto.INT32, - number=2, - ) - page_token: str = proto.Field( - proto.STRING, - number=3, - ) - - -class ListContextsResponse(proto.Message): - r"""The response message for - [Contexts.ListContexts][google.cloud.dialogflow.v2beta1.Contexts.ListContexts]. - - Attributes: - contexts (MutableSequence[google.cloud.dialogflow_v2beta1.types.Context]): - The list of contexts. 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 - - contexts: MutableSequence['Context'] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message='Context', - ) - next_page_token: str = proto.Field( - proto.STRING, - number=2, - ) - - -class GetContextRequest(proto.Message): - r"""The request message for - [Contexts.GetContext][google.cloud.dialogflow.v2beta1.Contexts.GetContext]. - - Attributes: - name (str): - Required. The name of the context. Supported formats: - - - ``projects//agent/sessions//contexts/``, - - ``projects//locations//agent/sessions//contexts/``, - - ``projects//agent/environments//users//sessions//contexts/``, - - ``projects//locations//agent/environments//users//sessions//contexts/``, - - If ``Location ID`` is not specified we assume default 'us' - location. If ``Environment ID`` is not specified, we assume - default 'draft' environment. If ``User ID`` is not - specified, we assume default '-' user. - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - - -class CreateContextRequest(proto.Message): - r"""The request message for - [Contexts.CreateContext][google.cloud.dialogflow.v2beta1.Contexts.CreateContext]. - - Attributes: - parent (str): - Required. The session to create a context for. Supported - formats: - - - \`projects//agent/sessions/, - - ``projects//locations//agent/sessions/``, - - ``projects//agent/environments//users//sessions/``, - - ``projects//locations//agent/environments//users//sessions/``, - - If ``Location ID`` is not specified we assume default 'us' - location. If ``Environment ID`` is not specified, we assume - default 'draft' environment. If ``User ID`` is not - specified, we assume default '-' user. - context (google.cloud.dialogflow_v2beta1.types.Context): - Required. The context to create. - """ - - parent: str = proto.Field( - proto.STRING, - number=1, - ) - context: 'Context' = proto.Field( - proto.MESSAGE, - number=2, - message='Context', - ) - - -class UpdateContextRequest(proto.Message): - r"""The request message for - [Contexts.UpdateContext][google.cloud.dialogflow.v2beta1.Contexts.UpdateContext]. - - Attributes: - context (google.cloud.dialogflow_v2beta1.types.Context): - Required. The context to update. - update_mask (google.protobuf.field_mask_pb2.FieldMask): - Optional. The mask to control which fields - get updated. - """ - - context: 'Context' = proto.Field( - proto.MESSAGE, - number=1, - message='Context', - ) - update_mask: field_mask_pb2.FieldMask = proto.Field( - proto.MESSAGE, - number=2, - message=field_mask_pb2.FieldMask, - ) - - -class DeleteContextRequest(proto.Message): - r"""The request message for - [Contexts.DeleteContext][google.cloud.dialogflow.v2beta1.Contexts.DeleteContext]. - - Attributes: - name (str): - Required. The name of the context to delete. Supported - formats: - - - ``projects//agent/sessions//contexts/``, - - ``projects//locations//agent/sessions//contexts/``, - - ``projects//agent/environments//users//sessions//contexts/``, - - ``projects//locations//agent/environments//users//sessions//contexts/``, - - If ``Location ID`` is not specified we assume default 'us' - location. If ``Environment ID`` is not specified, we assume - default 'draft' environment. If ``User ID`` is not - specified, we assume default '-' user. - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - - -class DeleteAllContextsRequest(proto.Message): - r"""The request message for - [Contexts.DeleteAllContexts][google.cloud.dialogflow.v2beta1.Contexts.DeleteAllContexts]. - - Attributes: - parent (str): - Required. The name of the session to delete all contexts - from. Supported formats: - - - \`projects//agent/sessions/, - - ``projects//locations//agent/sessions/``, - - ``projects//agent/environments//users//sessions/``, - - ``projects//locations//agent/environments//users//sessions/``, - - If ``Location ID`` is not specified we assume default 'us' - location. If ``Environment ID`` is not specified we assume - default 'draft' environment. If ``User ID`` is not - specified, we assume default '-' user. - """ - - parent: str = proto.Field( - proto.STRING, - number=1, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/types/conversation.py b/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/types/conversation.py deleted file mode 100644 index dd7d08b7f..000000000 --- a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/types/conversation.py +++ /dev/null @@ -1,598 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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 __future__ import annotations - -from typing import MutableMapping, MutableSequence - -import proto # type: ignore - -from google.cloud.dialogflow_v2beta1.types import participant -from google.protobuf import timestamp_pb2 # type: ignore - - -__protobuf__ = proto.module( - package='google.cloud.dialogflow.v2beta1', - manifest={ - 'Conversation', - 'ConversationPhoneNumber', - 'CreateConversationRequest', - 'ListConversationsRequest', - 'ListConversationsResponse', - 'GetConversationRequest', - 'CompleteConversationRequest', - 'CreateMessageRequest', - 'BatchCreateMessagesRequest', - 'BatchCreateMessagesResponse', - 'ListMessagesRequest', - 'ListMessagesResponse', - 'SuggestConversationSummaryRequest', - 'SuggestConversationSummaryResponse', - }, -) - - -class Conversation(proto.Message): - r"""Represents a conversation. - A conversation is an interaction between an agent, including - live agents and Dialogflow agents, and a support customer. - Conversations can include phone calls and text-based chat - sessions. - - Attributes: - name (str): - Output only. The unique identifier of this conversation. - Format: - ``projects//locations//conversations/``. - lifecycle_state (google.cloud.dialogflow_v2beta1.types.Conversation.LifecycleState): - Output only. The current state of the - Conversation. - conversation_profile (str): - Required. The Conversation Profile to be used to configure - this Conversation. This field cannot be updated. Format: - ``projects//locations//conversationProfiles/``. - phone_number (google.cloud.dialogflow_v2beta1.types.ConversationPhoneNumber): - Output only. Required if the conversation is - to be connected over telephony. - conversation_stage (google.cloud.dialogflow_v2beta1.types.Conversation.ConversationStage): - The stage of a conversation. It indicates whether the - virtual agent or a human agent is handling the conversation. - - If the conversation is created with the conversation profile - that has Dialogflow config set, defaults to - [ConversationStage.VIRTUAL_AGENT_STAGE][google.cloud.dialogflow.v2beta1.Conversation.ConversationStage.VIRTUAL_AGENT_STAGE]; - Otherwise, defaults to - [ConversationStage.HUMAN_ASSIST_STAGE][google.cloud.dialogflow.v2beta1.Conversation.ConversationStage.HUMAN_ASSIST_STAGE]. - - If the conversation is created with the conversation profile - that has Dialogflow config set but explicitly sets - conversation_stage to - [ConversationStage.HUMAN_ASSIST_STAGE][google.cloud.dialogflow.v2beta1.Conversation.ConversationStage.HUMAN_ASSIST_STAGE], - it skips - [ConversationStage.VIRTUAL_AGENT_STAGE][google.cloud.dialogflow.v2beta1.Conversation.ConversationStage.VIRTUAL_AGENT_STAGE] - stage and directly goes to - [ConversationStage.HUMAN_ASSIST_STAGE][google.cloud.dialogflow.v2beta1.Conversation.ConversationStage.HUMAN_ASSIST_STAGE]. - start_time (google.protobuf.timestamp_pb2.Timestamp): - Output only. The time the conversation was - started. - end_time (google.protobuf.timestamp_pb2.Timestamp): - Output only. The time the conversation was - finished. - """ - class LifecycleState(proto.Enum): - r"""Enumeration of the completion status of the conversation. - - Values: - LIFECYCLE_STATE_UNSPECIFIED (0): - Unknown. - IN_PROGRESS (1): - Conversation is currently open for media - analysis. - COMPLETED (2): - Conversation has been completed. - """ - LIFECYCLE_STATE_UNSPECIFIED = 0 - IN_PROGRESS = 1 - COMPLETED = 2 - - class ConversationStage(proto.Enum): - r"""Enumeration of the different conversation stages a - conversation can be in. Reference: - https://cloud.google.com/dialogflow/priv/docs/contact-center/basics#stages - - Values: - CONVERSATION_STAGE_UNSPECIFIED (0): - Unknown. Should never be used after a - conversation is successfully created. - VIRTUAL_AGENT_STAGE (1): - The conversation should return virtual agent - responses into the conversation. - HUMAN_ASSIST_STAGE (2): - The conversation should not provide - responses, just listen and provide suggestions. - """ - CONVERSATION_STAGE_UNSPECIFIED = 0 - VIRTUAL_AGENT_STAGE = 1 - HUMAN_ASSIST_STAGE = 2 - - name: str = proto.Field( - proto.STRING, - number=1, - ) - lifecycle_state: LifecycleState = proto.Field( - proto.ENUM, - number=2, - enum=LifecycleState, - ) - conversation_profile: str = proto.Field( - proto.STRING, - number=3, - ) - phone_number: 'ConversationPhoneNumber' = proto.Field( - proto.MESSAGE, - number=4, - message='ConversationPhoneNumber', - ) - conversation_stage: ConversationStage = proto.Field( - proto.ENUM, - number=7, - enum=ConversationStage, - ) - start_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=5, - message=timestamp_pb2.Timestamp, - ) - end_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=6, - message=timestamp_pb2.Timestamp, - ) - - -class ConversationPhoneNumber(proto.Message): - r"""Represents a phone number for telephony integration. It - allows for connecting a particular conversation over telephony. - - Attributes: - phone_number (str): - Output only. The phone number to connect to - this conversation. - """ - - phone_number: str = proto.Field( - proto.STRING, - number=3, - ) - - -class CreateConversationRequest(proto.Message): - r"""The request message for - [Conversations.CreateConversation][google.cloud.dialogflow.v2beta1.Conversations.CreateConversation]. - - Attributes: - parent (str): - Required. Resource identifier of the project creating the - conversation. Format: - ``projects//locations/``. - conversation (google.cloud.dialogflow_v2beta1.types.Conversation): - Required. The conversation to create. - conversation_id (str): - Optional. Identifier of the conversation. Generally it's - auto generated by Google. Only set it if you cannot wait for - the response to return a auto-generated one to you. - - The conversation ID must be compliant with the regression - fomula "[a-zA-Z][a-zA-Z0-9_-]*" with the characters length - in range of [3,64]. If the field is provided, the caller is - resposible for - - 1. the uniqueness of the ID, otherwise the request will be - rejected. - 2. the consistency for whether to use custom ID or not under - a project to better ensure uniqueness. - """ - - parent: str = proto.Field( - proto.STRING, - number=1, - ) - conversation: 'Conversation' = proto.Field( - proto.MESSAGE, - number=2, - message='Conversation', - ) - conversation_id: str = proto.Field( - proto.STRING, - number=3, - ) - - -class ListConversationsRequest(proto.Message): - r"""The request message for - [Conversations.ListConversations][google.cloud.dialogflow.v2beta1.Conversations.ListConversations]. - - Attributes: - parent (str): - Required. The project from which to list all conversation. - Format: ``projects//locations/``. - 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. - filter (str): - A filter expression that filters conversations listed in the - response. In general, the expression must specify the field - name, a comparison operator, and the value to use for - filtering: - - .. raw:: html - -
    -
  • The value must be a string, a number, or a boolean.
  • -
  • The comparison operator must be either `=`,`!=`, `>`, or `<`.
  • -
  • To filter on multiple expressions, separate the - expressions with `AND` or `OR` (omitting both implies `AND`).
  • -
  • For clarity, expressions can be enclosed in parentheses.
  • -
- Only `lifecycle_state` can be filtered on in this way. For example, - the following expression only returns `COMPLETED` conversations: - - ``lifecycle_state = "COMPLETED"`` - - For more information about filtering, see `API - Filtering `__. - """ - - parent: str = proto.Field( - proto.STRING, - number=1, - ) - page_size: int = proto.Field( - proto.INT32, - number=2, - ) - page_token: str = proto.Field( - proto.STRING, - number=3, - ) - filter: str = proto.Field( - proto.STRING, - number=4, - ) - - -class ListConversationsResponse(proto.Message): - r"""The response message for - [Conversations.ListConversations][google.cloud.dialogflow.v2beta1.Conversations.ListConversations]. - - Attributes: - conversations (MutableSequence[google.cloud.dialogflow_v2beta1.types.Conversation]): - The list of conversations. 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 - - conversations: MutableSequence['Conversation'] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message='Conversation', - ) - next_page_token: str = proto.Field( - proto.STRING, - number=2, - ) - - -class GetConversationRequest(proto.Message): - r"""The request message for - [Conversations.GetConversation][google.cloud.dialogflow.v2beta1.Conversations.GetConversation]. - - Attributes: - name (str): - Required. The name of the conversation. Format: - ``projects//locations//conversations/``. - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - - -class CompleteConversationRequest(proto.Message): - r"""The request message for - [Conversations.CompleteConversation][google.cloud.dialogflow.v2beta1.Conversations.CompleteConversation]. - - Attributes: - name (str): - Required. Resource identifier of the conversation to close. - Format: - ``projects//locations//conversations/``. - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - - -class CreateMessageRequest(proto.Message): - r"""The request message to create one Message. Currently it is - only used in BatchCreateMessagesRequest. - - Attributes: - parent (str): - Required. Resource identifier of the conversation to create - message. Format: - ``projects//locations//conversations/``. - message (google.cloud.dialogflow_v2beta1.types.Message): - Required. The message to create. - [Message.participant][google.cloud.dialogflow.v2beta1.Message.participant] - is required. - """ - - parent: str = proto.Field( - proto.STRING, - number=1, - ) - message: participant.Message = proto.Field( - proto.MESSAGE, - number=2, - message=participant.Message, - ) - - -class BatchCreateMessagesRequest(proto.Message): - r"""The request message for - [Conversations.BatchCreateMessagesRequest][]. - - Attributes: - parent (str): - Required. Resource identifier of the conversation to create - message. Format: - ``projects//locations//conversations/``. - requests (MutableSequence[google.cloud.dialogflow_v2beta1.types.CreateMessageRequest]): - Required. A maximum of 1000 Messages can be created in a - batch. [CreateMessageRequest.message.send_time][] is - required. All created messages will have identical - [Message.create_time][google.cloud.dialogflow.v2beta1.Message.create_time]. - """ - - parent: str = proto.Field( - proto.STRING, - number=1, - ) - requests: MutableSequence['CreateMessageRequest'] = proto.RepeatedField( - proto.MESSAGE, - number=2, - message='CreateMessageRequest', - ) - - -class BatchCreateMessagesResponse(proto.Message): - r"""The request message for - [Conversations.BatchCreateMessagesResponse][]. - - Attributes: - messages (MutableSequence[google.cloud.dialogflow_v2beta1.types.Message]): - Messages created. - """ - - messages: MutableSequence[participant.Message] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message=participant.Message, - ) - - -class ListMessagesRequest(proto.Message): - r"""The request message for - [Conversations.ListMessages][google.cloud.dialogflow.v2beta1.Conversations.ListMessages]. - - Attributes: - parent (str): - Required. The name of the conversation to list messages for. - Format: - ``projects//locations//conversations/`` - filter (str): - Optional. Filter on message fields. Currently predicates on - ``create_time`` and ``create_time_epoch_microseconds`` are - supported. ``create_time`` only support milliseconds - accuracy. E.g., - ``create_time_epoch_microseconds > 1551790877964485`` or - ``create_time > "2017-01-15T01:30:15.01Z"``. - - For more information about filtering, see `API - Filtering `__. - 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: str = proto.Field( - proto.STRING, - number=1, - ) - filter: str = proto.Field( - proto.STRING, - number=4, - ) - page_size: int = proto.Field( - proto.INT32, - number=2, - ) - page_token: str = proto.Field( - proto.STRING, - number=3, - ) - - -class ListMessagesResponse(proto.Message): - r"""The response message for - [Conversations.ListMessages][google.cloud.dialogflow.v2beta1.Conversations.ListMessages]. - - Attributes: - messages (MutableSequence[google.cloud.dialogflow_v2beta1.types.Message]): - Required. The list of messages. There will be a maximum - number of items returned based on the page_size field in the - request. ``messages`` is sorted by ``create_time`` in - descending order. - next_page_token (str): - Optional. 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 - - messages: MutableSequence[participant.Message] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message=participant.Message, - ) - next_page_token: str = proto.Field( - proto.STRING, - number=2, - ) - - -class SuggestConversationSummaryRequest(proto.Message): - r"""The request message for - [Conversations.SuggestConversationSummary][google.cloud.dialogflow.v2beta1.Conversations.SuggestConversationSummary]. - - Attributes: - conversation (str): - Required. The conversation to fetch suggestion for. Format: - ``projects//locations//conversations/``. - latest_message (str): - The name of the latest conversation message used as context - for compiling suggestion. If empty, the latest message of - the conversation will be used. - - Format: - ``projects//locations//conversations//messages/``. - context_size (int): - Max number of messages prior to and including - [latest_message] to use as context when compiling the - suggestion. By default 500 and at most 1000. - assist_query_params (google.cloud.dialogflow_v2beta1.types.AssistQueryParameters): - Parameters for a human assist query. - """ - - conversation: str = proto.Field( - proto.STRING, - number=1, - ) - latest_message: str = proto.Field( - proto.STRING, - number=3, - ) - context_size: int = proto.Field( - proto.INT32, - number=4, - ) - assist_query_params: participant.AssistQueryParameters = proto.Field( - proto.MESSAGE, - number=5, - message=participant.AssistQueryParameters, - ) - - -class SuggestConversationSummaryResponse(proto.Message): - r"""The response message for - [Conversations.SuggestConversationSummary][google.cloud.dialogflow.v2beta1.Conversations.SuggestConversationSummary]. - - Attributes: - summary (google.cloud.dialogflow_v2beta1.types.SuggestConversationSummaryResponse.Summary): - Generated summary. - latest_message (str): - The name of the latest conversation message used as context - for compiling suggestion. - - Format: - ``projects//locations//conversations//messages/``. - context_size (int): - Number of messages prior to and including - [last_conversation_message][] used to compile the - suggestion. It may be smaller than the - [SuggestSummaryRequest.context_size][] field in the request - if there weren't that many messages in the conversation. - """ - - class Summary(proto.Message): - r"""Generated summary for a conversation. - - Attributes: - text (str): - The summary content that is concatenated into - one string. - text_sections (MutableMapping[str, str]): - The summary content that is divided into - sections. The key is the section's name and the - value is the section's content. There is no - specific format for the key or value. - answer_record (str): - The name of the answer record. Format: - "projects//answerRecords/". - """ - - text: str = proto.Field( - proto.STRING, - number=1, - ) - text_sections: MutableMapping[str, str] = proto.MapField( - proto.STRING, - proto.STRING, - number=4, - ) - answer_record: str = proto.Field( - proto.STRING, - number=3, - ) - - summary: Summary = proto.Field( - proto.MESSAGE, - number=1, - message=Summary, - ) - latest_message: str = proto.Field( - proto.STRING, - number=2, - ) - context_size: int = proto.Field( - proto.INT32, - number=3, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/types/conversation_event.py b/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/types/conversation_event.py deleted file mode 100644 index 44fac8deb..000000000 --- a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/types/conversation_event.py +++ /dev/null @@ -1,122 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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 __future__ import annotations - -from typing import MutableMapping, MutableSequence - -import proto # type: ignore - -from google.cloud.dialogflow_v2beta1.types import participant -from google.rpc import status_pb2 # type: ignore - - -__protobuf__ = proto.module( - package='google.cloud.dialogflow.v2beta1', - manifest={ - 'ConversationEvent', - }, -) - - -class ConversationEvent(proto.Message): - r"""Represents a notification sent to Pub/Sub subscribers for - conversation lifecycle events. - - - .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields - - Attributes: - conversation (str): - Required. The unique identifier of the conversation this - notification refers to. Format: - ``projects//conversations/``. - type_ (google.cloud.dialogflow_v2beta1.types.ConversationEvent.Type): - Required. The type of the event that this - notification refers to. - error_status (google.rpc.status_pb2.Status): - Optional. More detailed information about an error. Only set - for type UNRECOVERABLE_ERROR_IN_PHONE_CALL. - new_message_payload (google.cloud.dialogflow_v2beta1.types.Message): - Payload of NEW_MESSAGE event. - - This field is a member of `oneof`_ ``payload``. - """ - class Type(proto.Enum): - r"""Enumeration of the types of events available. - - Values: - TYPE_UNSPECIFIED (0): - Type not set. - CONVERSATION_STARTED (1): - A new conversation has been opened. This is - fired when a telephone call is answered, or a - conversation is created via the API. - CONVERSATION_FINISHED (2): - An existing conversation has closed. This is - fired when a telephone call is terminated, or a - conversation is closed via the API. - HUMAN_INTERVENTION_NEEDED (3): - An existing conversation has received - notification from Dialogflow that human - intervention is required. - NEW_MESSAGE (5): - An existing conversation has received a new message, either - from API or telephony. It is configured in - [ConversationProfile.new_message_event_notification_config][google.cloud.dialogflow.v2beta1.ConversationProfile.new_message_event_notification_config] - UNRECOVERABLE_ERROR (4): - Unrecoverable error during a telephone call. - - In general non-recoverable errors only occur if something - was misconfigured in the ConversationProfile corresponding - to the call. After a non-recoverable error, Dialogflow may - stop responding. - - We don't fire this event: - - - in an API call because we can directly return the error, - or, - - when we can recover from an error. - """ - TYPE_UNSPECIFIED = 0 - CONVERSATION_STARTED = 1 - CONVERSATION_FINISHED = 2 - HUMAN_INTERVENTION_NEEDED = 3 - NEW_MESSAGE = 5 - UNRECOVERABLE_ERROR = 4 - - conversation: str = proto.Field( - proto.STRING, - number=1, - ) - type_: Type = proto.Field( - proto.ENUM, - number=2, - enum=Type, - ) - error_status: status_pb2.Status = proto.Field( - proto.MESSAGE, - number=3, - message=status_pb2.Status, - ) - new_message_payload: participant.Message = proto.Field( - proto.MESSAGE, - number=4, - oneof='payload', - message=participant.Message, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/types/conversation_profile.py b/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/types/conversation_profile.py deleted file mode 100644 index 35cd748fd..000000000 --- a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/types/conversation_profile.py +++ /dev/null @@ -1,1072 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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 __future__ import annotations - -from typing import MutableMapping, MutableSequence - -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 # type: ignore -from google.protobuf import timestamp_pb2 # type: ignore - - -__protobuf__ = proto.module( - package='google.cloud.dialogflow.v2beta1', - manifest={ - 'ConversationProfile', - 'AutomatedAgentConfig', - 'HumanAgentAssistantConfig', - 'HumanAgentHandoffConfig', - 'NotificationConfig', - 'LoggingConfig', - 'ListConversationProfilesRequest', - 'ListConversationProfilesResponse', - 'GetConversationProfileRequest', - 'CreateConversationProfileRequest', - 'UpdateConversationProfileRequest', - 'DeleteConversationProfileRequest', - 'SetSuggestionFeatureConfigRequest', - 'ClearSuggestionFeatureConfigRequest', - 'SetSuggestionFeatureConfigOperationMetadata', - 'ClearSuggestionFeatureConfigOperationMetadata', - }, -) - - -class ConversationProfile(proto.Message): - r"""Defines the services to connect to incoming Dialogflow - conversations. - - Attributes: - name (str): - The unique identifier of this conversation profile. Format: - ``projects//locations//conversationProfiles/``. - display_name (str): - Required. Human readable name for this - profile. Max length 1024 bytes. - create_time (google.protobuf.timestamp_pb2.Timestamp): - Output only. Create time of the conversation - profile. - update_time (google.protobuf.timestamp_pb2.Timestamp): - Output only. Update time of the conversation - profile. - automated_agent_config (google.cloud.dialogflow_v2beta1.types.AutomatedAgentConfig): - Configuration for an automated agent to use - with this profile. - human_agent_assistant_config (google.cloud.dialogflow_v2beta1.types.HumanAgentAssistantConfig): - Configuration for agent assistance to use - 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. - logging_config (google.cloud.dialogflow_v2beta1.types.LoggingConfig): - Configuration for logging conversation - lifecycle events. - new_message_event_notification_config (google.cloud.dialogflow_v2beta1.types.NotificationConfig): - Configuration for publishing new message events. Event will - be sent in format of - [ConversationEvent][google.cloud.dialogflow.v2beta1.ConversationEvent] - stt_config (google.cloud.dialogflow_v2beta1.types.SpeechToTextConfig): - Settings for speech transcription. - language_code (str): - Language code for the conversation profile. If not - specified, the language is en-US. Language at - ConversationProfile should be set for all non en-us - languages. This should be a - `BCP-47 `__ - language tag. Example: "en-US". - time_zone (str): - The time zone of this conversational profile from the `time - zone database `__, e.g., - America/New_York, Europe/Paris. Defaults to - America/New_York. - security_settings (str): - Name of the CX SecuritySettings reference for the agent. - Format: - ``projects//locations//securitySettings/``. - tts_config (google.cloud.dialogflow_v2beta1.types.SynthesizeSpeechConfig): - Configuration for Text-to-Speech - synthesization. - Used by Phone Gateway to specify synthesization - options. If agent defines synthesization options - as well, agent settings overrides the option - here. - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - display_name: str = proto.Field( - proto.STRING, - number=2, - ) - create_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=11, - message=timestamp_pb2.Timestamp, - ) - update_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=12, - message=timestamp_pb2.Timestamp, - ) - automated_agent_config: 'AutomatedAgentConfig' = proto.Field( - proto.MESSAGE, - number=3, - message='AutomatedAgentConfig', - ) - human_agent_assistant_config: 'HumanAgentAssistantConfig' = proto.Field( - proto.MESSAGE, - number=4, - message='HumanAgentAssistantConfig', - ) - human_agent_handoff_config: 'HumanAgentHandoffConfig' = proto.Field( - proto.MESSAGE, - number=5, - message='HumanAgentHandoffConfig', - ) - notification_config: 'NotificationConfig' = proto.Field( - proto.MESSAGE, - number=6, - message='NotificationConfig', - ) - logging_config: 'LoggingConfig' = proto.Field( - proto.MESSAGE, - number=7, - message='LoggingConfig', - ) - new_message_event_notification_config: 'NotificationConfig' = proto.Field( - proto.MESSAGE, - number=8, - message='NotificationConfig', - ) - stt_config: audio_config.SpeechToTextConfig = proto.Field( - proto.MESSAGE, - number=9, - message=audio_config.SpeechToTextConfig, - ) - language_code: str = proto.Field( - proto.STRING, - number=10, - ) - time_zone: str = proto.Field( - proto.STRING, - number=14, - ) - security_settings: str = proto.Field( - proto.STRING, - number=13, - ) - tts_config: audio_config.SynthesizeSpeechConfig = proto.Field( - proto.MESSAGE, - number=18, - message=audio_config.SynthesizeSpeechConfig, - ) - - -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. - - This project needs to either be the same project as the - conversation or you need to grant - ``service-@gcp-sa-dialogflow.iam.gserviceaccount.com`` - the ``Dialogflow API Service Agent`` role in this project. - - - For ES agents, use format: - ``projects//locations//agent/environments/``. - If environment is not specified, the default ``draft`` - environment is used. Refer to - `DetectIntentRequest `__ - for more details. - - - For CX agents, use format - ``projects//locations//agents//environments/``. - If environment is not specified, the default ``draft`` - environment is used. - """ - - agent: str = proto.Field( - proto.STRING, - number=1, - ) - - -class HumanAgentAssistantConfig(proto.Message): - r"""Defines the Human Agent Assistant to connect to a - conversation. - - Attributes: - notification_config (google.cloud.dialogflow_v2beta1.types.NotificationConfig): - Pub/Sub topic on which to publish new agent - assistant events. - human_agent_suggestion_config (google.cloud.dialogflow_v2beta1.types.HumanAgentAssistantConfig.SuggestionConfig): - Configuration for agent assistance of human - agent participant. - 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 - talk. - only_end_user (bool): - Only trigger suggestion if participant role of last - utterance is END_USER. - """ - - no_small_talk: bool = proto.Field( - proto.BOOL, - number=1, - ) - only_end_user: bool = 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. - enable_event_based_suggestion (bool): - Automatically iterates all participants and tries to compile - suggestions. - - Supported features: ARTICLE_SUGGESTION, FAQ, - DIALOGFLOW_ASSIST. - suggestion_trigger_settings (google.cloud.dialogflow_v2beta1.types.HumanAgentAssistantConfig.SuggestionTriggerSettings): - Settings of suggestion trigger. - - Currently, only ARTICLE_SUGGESTION, FAQ, and - DIALOGFLOW_ASSIST will use this field. - query_config (google.cloud.dialogflow_v2beta1.types.HumanAgentAssistantConfig.SuggestionQueryConfig): - Configs of query. - conversation_model_config (google.cloud.dialogflow_v2beta1.types.HumanAgentAssistantConfig.ConversationModelConfig): - Configs of custom conversation model. - conversation_process_config (google.cloud.dialogflow_v2beta1.types.HumanAgentAssistantConfig.ConversationProcessConfig): - Configs for processing conversation. - """ - - suggestion_feature: participant.SuggestionFeature = proto.Field( - proto.MESSAGE, - number=5, - message=participant.SuggestionFeature, - ) - enable_event_based_suggestion: bool = proto.Field( - proto.BOOL, - number=3, - ) - suggestion_trigger_settings: 'HumanAgentAssistantConfig.SuggestionTriggerSettings' = proto.Field( - proto.MESSAGE, - number=10, - message='HumanAgentAssistantConfig.SuggestionTriggerSettings', - ) - query_config: 'HumanAgentAssistantConfig.SuggestionQueryConfig' = proto.Field( - proto.MESSAGE, - number=6, - message='HumanAgentAssistantConfig.SuggestionQueryConfig', - ) - conversation_model_config: 'HumanAgentAssistantConfig.ConversationModelConfig' = proto.Field( - proto.MESSAGE, - number=7, - message='HumanAgentAssistantConfig.ConversationModelConfig', - ) - conversation_process_config: 'HumanAgentAssistantConfig.ConversationProcessConfig' = proto.Field( - proto.MESSAGE, - number=8, - message='HumanAgentAssistantConfig.ConversationProcessConfig', - ) - - class SuggestionConfig(proto.Message): - r"""Detail human agent assistant config. - - Attributes: - feature_configs (MutableSequence[google.cloud.dialogflow_v2beta1.types.HumanAgentAssistantConfig.SuggestionFeatureConfig]): - Configuration of different suggestion - features. One feature can have only one config. - group_suggestion_responses (bool): - If ``group_suggestion_responses`` is false, and there are - multiple ``feature_configs`` in ``event based suggestion`` - or StreamingAnalyzeContent, we will try to deliver - suggestions to customers as soon as we get new suggestion. - Different type of suggestions based on the same context will - be in separate Pub/Sub event or - ``StreamingAnalyzeContentResponse``. - - If ``group_suggestion_responses`` set to true. All the - suggestions to the same participant based on the same - context will be grouped into a single Pub/Sub event or - StreamingAnalyzeContentResponse. - """ - - feature_configs: MutableSequence['HumanAgentAssistantConfig.SuggestionFeatureConfig'] = proto.RepeatedField( - proto.MESSAGE, - number=2, - message='HumanAgentAssistantConfig.SuggestionFeatureConfig', - ) - group_suggestion_responses: bool = proto.Field( - proto.BOOL, - number=3, - ) - - class SuggestionQueryConfig(proto.Message): - r"""Config for suggestion query. - - This message has `oneof`_ fields (mutually exclusive fields). - For each oneof, at most one member field can be set at the same time. - Setting any member of the oneof automatically clears all other - members. - - .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields - - Attributes: - knowledge_base_query_source (google.cloud.dialogflow_v2beta1.types.HumanAgentAssistantConfig.SuggestionQueryConfig.KnowledgeBaseQuerySource): - Query from knowledgebase. It is used by: ARTICLE_SUGGESTION, - FAQ. - - This field is a member of `oneof`_ ``query_source``. - document_query_source (google.cloud.dialogflow_v2beta1.types.HumanAgentAssistantConfig.SuggestionQueryConfig.DocumentQuerySource): - Query from knowledge base document. It is used by: - SMART_REPLY, SMART_COMPOSE. - - This field is a member of `oneof`_ ``query_source``. - dialogflow_query_source (google.cloud.dialogflow_v2beta1.types.HumanAgentAssistantConfig.SuggestionQueryConfig.DialogflowQuerySource): - Query from Dialogflow agent. It is used by - DIALOGFLOW_ASSIST. - - This field is a member of `oneof`_ ``query_source``. - max_results (int): - Maximum number of results to return. - Currently, if unset, defaults to 10. And the max - number is 20. - confidence_threshold (float): - Confidence threshold of query result. - - Agent Assist gives each suggestion a score in the range - [0.0, 1.0], based on the relevance between the suggestion - and the current conversation context. A score of 0.0 has no - relevance, while a score of 1.0 has high relevance. Only - suggestions with a score greater than or equal to the value - of this field are included in the results. - - For a baseline model (the default), the recommended value is - in the range [0.05, 0.1]. - - For a custom model, there is no recommended value. Tune this - value by starting from a very low value and slowly - increasing until you have desired results. - - If this field is not set, it is default to 0.0, which means - that all suggestions are returned. - - Supported features: ARTICLE_SUGGESTION, FAQ, SMART_REPLY, - SMART_COMPOSE. - context_filter_settings (google.cloud.dialogflow_v2beta1.types.HumanAgentAssistantConfig.SuggestionQueryConfig.ContextFilterSettings): - Determines how recent conversation context is - filtered when generating suggestions. If - unspecified, no messages will be dropped. - """ - - class KnowledgeBaseQuerySource(proto.Message): - r"""Knowledge base source settings. - - Supported features: ARTICLE_SUGGESTION, FAQ. - - Attributes: - knowledge_bases (MutableSequence[str]): - Required. Knowledge bases to query. Format: - ``projects//locations//knowledgeBases/``. - Currently, only one knowledge base is supported. - """ - - knowledge_bases: MutableSequence[str] = proto.RepeatedField( - proto.STRING, - number=1, - ) - - class DocumentQuerySource(proto.Message): - r"""Document source settings. - - Supported features: SMART_REPLY, SMART_COMPOSE. - - Attributes: - documents (MutableSequence[str]): - Required. Knowledge documents to query from. Format: - ``projects//locations//knowledgeBases//documents/``. - Currently, only one document is supported. - """ - - documents: MutableSequence[str] = proto.RepeatedField( - proto.STRING, - number=1, - ) - - class DialogflowQuerySource(proto.Message): - r"""Dialogflow source setting. - - Supported feature: DIALOGFLOW_ASSIST. - - Attributes: - agent (str): - Required. The name of a dialogflow virtual agent used for - end user side intent detection and suggestion. Format: - ``projects//locations//agent``. - When multiple agents are allowed in the same Dialogflow - project. - """ - - agent: str = proto.Field( - proto.STRING, - number=1, - ) - - class ContextFilterSettings(proto.Message): - r"""Settings that determine how to filter recent conversation - context when generating suggestions. - - Attributes: - drop_handoff_messages (bool): - If set to true, the last message from virtual - agent (hand off message) and the message before - it (trigger message of hand off) are dropped. - drop_virtual_agent_messages (bool): - If set to true, all messages from virtual - agent are dropped. - drop_ivr_messages (bool): - If set to true, all messages from ivr stage - are dropped. - """ - - drop_handoff_messages: bool = proto.Field( - proto.BOOL, - number=1, - ) - drop_virtual_agent_messages: bool = proto.Field( - proto.BOOL, - number=2, - ) - drop_ivr_messages: bool = proto.Field( - proto.BOOL, - number=3, - ) - - knowledge_base_query_source: 'HumanAgentAssistantConfig.SuggestionQueryConfig.KnowledgeBaseQuerySource' = proto.Field( - proto.MESSAGE, - number=1, - oneof='query_source', - message='HumanAgentAssistantConfig.SuggestionQueryConfig.KnowledgeBaseQuerySource', - ) - document_query_source: 'HumanAgentAssistantConfig.SuggestionQueryConfig.DocumentQuerySource' = proto.Field( - proto.MESSAGE, - number=2, - oneof='query_source', - message='HumanAgentAssistantConfig.SuggestionQueryConfig.DocumentQuerySource', - ) - dialogflow_query_source: 'HumanAgentAssistantConfig.SuggestionQueryConfig.DialogflowQuerySource' = proto.Field( - proto.MESSAGE, - number=3, - oneof='query_source', - message='HumanAgentAssistantConfig.SuggestionQueryConfig.DialogflowQuerySource', - ) - max_results: int = proto.Field( - proto.INT32, - number=4, - ) - confidence_threshold: float = proto.Field( - proto.FLOAT, - number=5, - ) - context_filter_settings: 'HumanAgentAssistantConfig.SuggestionQueryConfig.ContextFilterSettings' = proto.Field( - proto.MESSAGE, - number=7, - message='HumanAgentAssistantConfig.SuggestionQueryConfig.ContextFilterSettings', - ) - - class ConversationModelConfig(proto.Message): - r"""Custom conversation models used in agent assist feature. - - Supported feature: ARTICLE_SUGGESTION, SMART_COMPOSE, SMART_REPLY, - CONVERSATION_SUMMARIZATION. - - Attributes: - model (str): - Conversation model resource name. Format: - ``projects//conversationModels/``. - """ - - model: str = proto.Field( - proto.STRING, - number=1, - ) - - class ConversationProcessConfig(proto.Message): - r"""Config to process conversation. - - Attributes: - recent_sentences_count (int): - Number of recent non-small-talk sentences to - use as context for article and FAQ suggestion - """ - - recent_sentences_count: int = proto.Field( - proto.INT32, - number=2, - ) - - class MessageAnalysisConfig(proto.Message): - r"""Configuration for analyses to run on each conversation - message. - - Attributes: - enable_entity_extraction (bool): - Enable entity extraction in conversation messages on `agent - 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 - stage `__. - If unspecified, defaults to false. Sentiment analysis - inspects user input and identifies the prevailing subjective - opinion, especially to determine a user's attitude as - positive, negative, or neutral: - https://cloud.google.com/natural-language/docs/basics#sentiment_analysis - For - [Participants.StreamingAnalyzeContent][google.cloud.dialogflow.v2beta1.Participants.StreamingAnalyzeContent] - method, result will be in - [StreamingAnalyzeContentResponse.message.SentimentAnalysisResult][google.cloud.dialogflow.v2beta1.StreamingAnalyzeContentResponse.message]. - For - [Participants.AnalyzeContent][google.cloud.dialogflow.v2beta1.Participants.AnalyzeContent] - method, result will be in - [AnalyzeContentResponse.message.SentimentAnalysisResult][google.cloud.dialogflow.v2beta1.AnalyzeContentResponse.message] - For - [Conversations.ListMessages][google.cloud.dialogflow.v2beta1.Conversations.ListMessages] - method, result will be in - [ListMessagesResponse.messages.SentimentAnalysisResult][google.cloud.dialogflow.v2beta1.ListMessagesResponse.messages] - If Pub/Sub notification is configured, result will be in - [ConversationEvent.new_message_payload.SentimentAnalysisResult][google.cloud.dialogflow.v2beta1.ConversationEvent.new_message_payload]. - """ - - enable_entity_extraction: bool = proto.Field( - proto.BOOL, - number=2, - ) - enable_sentiment_analysis: bool = proto.Field( - proto.BOOL, - number=3, - ) - - notification_config: 'NotificationConfig' = proto.Field( - proto.MESSAGE, - number=2, - message='NotificationConfig', - ) - human_agent_suggestion_config: SuggestionConfig = proto.Field( - proto.MESSAGE, - number=3, - message=SuggestionConfig, - ) - end_user_suggestion_config: SuggestionConfig = proto.Field( - proto.MESSAGE, - number=4, - message=SuggestionConfig, - ) - message_analysis_config: MessageAnalysisConfig = proto.Field( - proto.MESSAGE, - number=5, - message=MessageAnalysisConfig, - ) - - -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. - - This message has `oneof`_ fields (mutually exclusive fields). - For each oneof, at most one member field can be set at the same time. - Setting any member of the oneof automatically clears all other - members. - - .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields - - Attributes: - live_person_config (google.cloud.dialogflow_v2beta1.types.HumanAgentHandoffConfig.LivePersonConfig): - Uses LivePerson (https://www.liveperson.com). - - This field is a member of `oneof`_ ``agent_service``. - salesforce_live_agent_config (google.cloud.dialogflow_v2beta1.types.HumanAgentHandoffConfig.SalesforceLiveAgentConfig): - Uses Salesforce Live Agent. - - This field is a member of `oneof`_ ``agent_service``. - """ - - class LivePersonConfig(proto.Message): - r"""Configuration specific to LivePerson - (https://www.liveperson.com). - - Attributes: - account_number (str): - Required. Account number of the LivePerson - account to connect. This is the account number - you input at the login page. - """ - - account_number: str = 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 - Salesforce account. - deployment_id (str): - Required. Live Agent deployment ID. - button_id (str): - Required. Live Agent chat button ID. - endpoint_domain (str): - Required. Domain of the Live Agent endpoint for this agent. - You can find the endpoint URL in the ``Live Agent settings`` - page. For example if URL has the form - https://d.la4-c2-phx.salesforceliveagent.com/..., you should - fill in d.la4-c2-phx.salesforceliveagent.com. - """ - - organization_id: str = proto.Field( - proto.STRING, - number=1, - ) - deployment_id: str = proto.Field( - proto.STRING, - number=2, - ) - button_id: str = proto.Field( - proto.STRING, - number=3, - ) - endpoint_domain: str = proto.Field( - proto.STRING, - number=4, - ) - - live_person_config: LivePersonConfig = proto.Field( - proto.MESSAGE, - number=1, - oneof='agent_service', - message=LivePersonConfig, - ) - salesforce_live_agent_config: SalesforceLiveAgentConfig = proto.Field( - proto.MESSAGE, - number=2, - oneof='agent_service', - message=SalesforceLiveAgentConfig, - ) - - -class NotificationConfig(proto.Message): - r"""Defines notification behavior. - - Attributes: - topic (str): - Name of the Pub/Sub topic to publish conversation events - like - [CONVERSATION_STARTED][google.cloud.dialogflow.v2beta1.ConversationEvent.Type.CONVERSATION_STARTED] - as serialized - [ConversationEvent][google.cloud.dialogflow.v2beta1.ConversationEvent] - protos. - - For telephony integration to receive notification, make sure - either this topic is in the same project as the conversation - or you grant - ``service-@gcp-sa-dialogflow.iam.gserviceaccount.com`` - the ``Dialogflow Service Agent`` role in the topic project. - - For chat integration to receive notification, make sure API - caller has been granted the ``Dialogflow Service Agent`` - role for the topic. - - Format: - ``projects//locations//topics/``. - message_format (google.cloud.dialogflow_v2beta1.types.NotificationConfig.MessageFormat): - Format of message. - """ - class MessageFormat(proto.Enum): - r"""Format of cloud pub/sub message. - - Values: - MESSAGE_FORMAT_UNSPECIFIED (0): - If it is unspecified, PROTO will be used. - PROTO (1): - Pub/Sub message will be serialized proto. - JSON (2): - Pub/Sub message will be json. - """ - MESSAGE_FORMAT_UNSPECIFIED = 0 - PROTO = 1 - JSON = 2 - - topic: str = proto.Field( - proto.STRING, - number=1, - ) - message_format: MessageFormat = 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 - [CONVERSATION_STARTED][google.cloud.dialogflow.v2beta1.ConversationEvent.Type.CONVERSATION_STARTED] - to Stackdriver in the conversation project as JSON format - [ConversationEvent][google.cloud.dialogflow.v2beta1.ConversationEvent] - protos. - """ - - enable_stackdriver_logging: bool = proto.Field( - proto.BOOL, - number=3, - ) - - -class ListConversationProfilesRequest(proto.Message): - r"""The request message for - [ConversationProfiles.ListConversationProfiles][google.cloud.dialogflow.v2beta1.ConversationProfiles.ListConversationProfiles]. - - Attributes: - parent (str): - Required. The project to list all conversation profiles - from. Format: - ``projects//locations/``. - page_size (int): - The maximum number of items to return in a - single page. By default 100 and at most 1000. - page_token (str): - The next_page_token value returned from a previous list - request. - """ - - parent: str = proto.Field( - proto.STRING, - number=1, - ) - page_size: int = proto.Field( - proto.INT32, - number=2, - ) - page_token: str = proto.Field( - proto.STRING, - number=3, - ) - - -class ListConversationProfilesResponse(proto.Message): - r"""The response message for - [ConversationProfiles.ListConversationProfiles][google.cloud.dialogflow.v2beta1.ConversationProfiles.ListConversationProfiles]. - - Attributes: - conversation_profiles (MutableSequence[google.cloud.dialogflow_v2beta1.types.ConversationProfile]): - The list of project conversation profiles. There is 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 - - conversation_profiles: MutableSequence['ConversationProfile'] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message='ConversationProfile', - ) - next_page_token: str = proto.Field( - proto.STRING, - number=2, - ) - - -class GetConversationProfileRequest(proto.Message): - r"""The request message for - [ConversationProfiles.GetConversationProfile][google.cloud.dialogflow.v2beta1.ConversationProfiles.GetConversationProfile]. - - Attributes: - name (str): - Required. The resource name of the conversation profile. - Format: - ``projects//locations//conversationProfiles/``. - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - - -class CreateConversationProfileRequest(proto.Message): - r"""The request message for - [ConversationProfiles.CreateConversationProfile][google.cloud.dialogflow.v2beta1.ConversationProfiles.CreateConversationProfile]. - - Attributes: - parent (str): - Required. The project to create a conversation profile for. - Format: ``projects//locations/``. - conversation_profile (google.cloud.dialogflow_v2beta1.types.ConversationProfile): - Required. The conversation profile to create. - """ - - parent: str = proto.Field( - proto.STRING, - number=1, - ) - conversation_profile: 'ConversationProfile' = proto.Field( - proto.MESSAGE, - number=2, - message='ConversationProfile', - ) - - -class UpdateConversationProfileRequest(proto.Message): - r"""The request message for - [ConversationProfiles.UpdateConversationProfile][google.cloud.dialogflow.v2beta1.ConversationProfiles.UpdateConversationProfile]. - - Attributes: - conversation_profile (google.cloud.dialogflow_v2beta1.types.ConversationProfile): - Required. The conversation profile to update. - update_mask (google.protobuf.field_mask_pb2.FieldMask): - Required. The mask to control which fields to - update. - """ - - conversation_profile: 'ConversationProfile' = proto.Field( - proto.MESSAGE, - number=1, - message='ConversationProfile', - ) - update_mask: field_mask_pb2.FieldMask = proto.Field( - proto.MESSAGE, - number=2, - message=field_mask_pb2.FieldMask, - ) - - -class DeleteConversationProfileRequest(proto.Message): - r"""The request message for - [ConversationProfiles.DeleteConversationProfile][google.cloud.dialogflow.v2beta1.ConversationProfiles.DeleteConversationProfile]. - - This operation fails if the conversation profile is still referenced - from a phone number. - - Attributes: - name (str): - Required. The name of the conversation profile to delete. - Format: - ``projects//locations//conversationProfiles/``. - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - - -class SetSuggestionFeatureConfigRequest(proto.Message): - r"""The request message for - [ConversationProfiles.SetSuggestionFeature][]. - - Attributes: - conversation_profile (str): - Required. The Conversation Profile to add or update the - suggestion feature config. Format: - ``projects//locations//conversationProfiles/``. - participant_role (google.cloud.dialogflow_v2beta1.types.Participant.Role): - Required. The participant role to add or update the - suggestion feature config. Only HUMAN_AGENT or END_USER can - be used. - suggestion_feature_config (google.cloud.dialogflow_v2beta1.types.HumanAgentAssistantConfig.SuggestionFeatureConfig): - Required. The suggestion feature config to - add or update. - """ - - conversation_profile: str = proto.Field( - proto.STRING, - number=1, - ) - participant_role: participant.Participant.Role = proto.Field( - proto.ENUM, - number=2, - enum=participant.Participant.Role, - ) - suggestion_feature_config: 'HumanAgentAssistantConfig.SuggestionFeatureConfig' = proto.Field( - proto.MESSAGE, - number=3, - message='HumanAgentAssistantConfig.SuggestionFeatureConfig', - ) - - -class ClearSuggestionFeatureConfigRequest(proto.Message): - r"""The request message for [ConversationProfiles.ClearFeature][]. - - Attributes: - conversation_profile (str): - Required. The Conversation Profile to add or update the - suggestion feature config. Format: - ``projects//locations//conversationProfiles/``. - participant_role (google.cloud.dialogflow_v2beta1.types.Participant.Role): - Required. The participant role to remove the suggestion - feature config. Only HUMAN_AGENT or END_USER can be used. - suggestion_feature_type (google.cloud.dialogflow_v2beta1.types.SuggestionFeature.Type): - Required. The type of the suggestion feature - to remove. - """ - - conversation_profile: str = proto.Field( - proto.STRING, - number=1, - ) - participant_role: participant.Participant.Role = proto.Field( - proto.ENUM, - number=2, - enum=participant.Participant.Role, - ) - suggestion_feature_type: participant.SuggestionFeature.Type = proto.Field( - proto.ENUM, - number=3, - enum=participant.SuggestionFeature.Type, - ) - - -class SetSuggestionFeatureConfigOperationMetadata(proto.Message): - r"""Metadata for a [ConversationProfile.SetSuggestionFeatureConfig][] - operation. - - Attributes: - conversation_profile (str): - The resource name of the conversation profile. Format: - ``projects//locations//conversationProfiles/`` - participant_role (google.cloud.dialogflow_v2beta1.types.Participant.Role): - Required. The participant role to add or update the - suggestion feature config. Only HUMAN_AGENT or END_USER can - be used. - suggestion_feature_type (google.cloud.dialogflow_v2beta1.types.SuggestionFeature.Type): - Required. The type of the suggestion feature - to add or update. - create_time (google.protobuf.timestamp_pb2.Timestamp): - Timestamp whe the request was created. The - time is measured on server side. - """ - - conversation_profile: str = proto.Field( - proto.STRING, - number=1, - ) - participant_role: participant.Participant.Role = proto.Field( - proto.ENUM, - number=2, - enum=participant.Participant.Role, - ) - suggestion_feature_type: participant.SuggestionFeature.Type = proto.Field( - proto.ENUM, - number=3, - enum=participant.SuggestionFeature.Type, - ) - create_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=4, - message=timestamp_pb2.Timestamp, - ) - - -class ClearSuggestionFeatureConfigOperationMetadata(proto.Message): - r"""Metadata for a [ConversationProfile.ClearSuggestionFeatureConfig][] - operation. - - Attributes: - conversation_profile (str): - The resource name of the conversation profile. Format: - ``projects//locations//conversationProfiles/`` - participant_role (google.cloud.dialogflow_v2beta1.types.Participant.Role): - Required. The participant role to remove the suggestion - feature config. Only HUMAN_AGENT or END_USER can be used. - suggestion_feature_type (google.cloud.dialogflow_v2beta1.types.SuggestionFeature.Type): - Required. The type of the suggestion feature - to remove. - create_time (google.protobuf.timestamp_pb2.Timestamp): - Timestamp whe the request was created. The - time is measured on server side. - """ - - conversation_profile: str = proto.Field( - proto.STRING, - number=1, - ) - participant_role: participant.Participant.Role = proto.Field( - proto.ENUM, - number=2, - enum=participant.Participant.Role, - ) - suggestion_feature_type: participant.SuggestionFeature.Type = proto.Field( - proto.ENUM, - number=3, - enum=participant.SuggestionFeature.Type, - ) - create_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=4, - message=timestamp_pb2.Timestamp, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/types/document.py b/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/types/document.py deleted file mode 100644 index 2fdce9b3a..000000000 --- a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/types/document.py +++ /dev/null @@ -1,666 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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 __future__ import annotations - -from typing import MutableMapping, MutableSequence - -import proto # type: ignore - -from google.cloud.dialogflow_v2beta1.types import gcs -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( - package='google.cloud.dialogflow.v2beta1', - manifest={ - 'Document', - 'GetDocumentRequest', - 'ListDocumentsRequest', - 'ListDocumentsResponse', - 'CreateDocumentRequest', - 'ImportDocumentsRequest', - 'ImportDocumentTemplate', - 'ImportDocumentsResponse', - 'DeleteDocumentRequest', - 'UpdateDocumentRequest', - 'ExportOperationMetadata', - 'KnowledgeOperationMetadata', - 'ReloadDocumentRequest', - }, -) - - -class Document(proto.Message): - r"""A knowledge document to be used by a - [KnowledgeBase][google.cloud.dialogflow.v2beta1.KnowledgeBase]. - - For more information, see the `knowledge base - guide `__. - - Note: The ``projects.agent.knowledgeBases.documents`` resource is - deprecated; only use ``projects.knowledgeBases.documents``. - - This message has `oneof`_ fields (mutually exclusive fields). - For each oneof, at most one member field can be set at the same time. - Setting any member of the oneof automatically clears all other - members. - - .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields - - Attributes: - name (str): - Optional. The document resource name. The name must be empty - when creating a document. Format: - ``projects//locations//knowledgeBases//documents/``. - display_name (str): - Required. The display name of the document. - The name must be 1024 bytes or less; otherwise, - the creation request fails. - mime_type (str): - Required. The MIME type of this document. - knowledge_types (MutableSequence[google.cloud.dialogflow_v2beta1.types.Document.KnowledgeType]): - Required. The knowledge type of document - content. - content_uri (str): - The URI where the file content is located. - - For documents stored in Google Cloud Storage, these URIs - must have the form ``gs:///``. - - NOTE: External URLs must correspond to public webpages, - i.e., they must be indexed by Google Search. In particular, - URLs for showing documents in Google Cloud Storage (i.e. the - URL in your browser) are not supported. Instead use the - ``gs://`` format URI described above. - - This field is a member of `oneof`_ ``source``. - content (str): - The raw content of the document. This field is only - permitted for EXTRACTIVE_QA and FAQ knowledge types. Note: - This field is in the process of being deprecated, please use - raw_content instead. - - This field is a member of `oneof`_ ``source``. - raw_content (bytes): - The raw content of the document. This field is only - permitted for EXTRACTIVE_QA and FAQ knowledge types. - - This field is a member of `oneof`_ ``source``. - enable_auto_reload (bool): - Optional. If true, we try to automatically reload the - document every day (at a time picked by the system). If - false or unspecified, we don't try to automatically reload - the document. - - Currently you can only enable automatic reload for documents - sourced from a public url, see ``source`` field for the - source types. - - Reload status can be tracked in ``latest_reload_status``. If - a reload fails, we will keep the document unchanged. - - If a reload fails with internal errors, the system will try - to reload the document on the next day. If a reload fails - with non-retriable errors (e.g. PERMISSION_DENIED), the - system will not try to reload the document anymore. You need - to manually reload the document successfully by calling - ``ReloadDocument`` and clear the errors. - latest_reload_status (google.cloud.dialogflow_v2beta1.types.Document.ReloadStatus): - Output only. The time and status of the - latest reload. This reload may have been - triggered automatically or manually and may not - have succeeded. - metadata (MutableMapping[str, str]): - Optional. Metadata for the document. The metadata supports - arbitrary key-value pairs. Suggested use cases include - storing a document's title, an external URL distinct from - the document's content_uri, etc. The max size of a ``key`` - or a ``value`` of the metadata is 1024 bytes. - state (google.cloud.dialogflow_v2beta1.types.Document.State): - Output only. The current state of the - document. - """ - class KnowledgeType(proto.Enum): - r"""The knowledge type of document content. - - Values: - KNOWLEDGE_TYPE_UNSPECIFIED (0): - The type is unspecified or arbitrary. - FAQ (1): - The document content contains question and - answer pairs as either HTML or CSV. Typical FAQ - HTML formats are parsed accurately, but unusual - formats may fail to be parsed. - - CSV must have questions in the first column and - answers in the second, with no header. Because - of this explicit format, they are always parsed - accurately. - EXTRACTIVE_QA (2): - Documents for which unstructured text is - extracted and used for question answering. - ARTICLE_SUGGESTION (3): - The entire document content as a whole can be - used for query results. Only for Contact Center - Solutions on Dialogflow. - AGENT_FACING_SMART_REPLY (4): - The document contains agent-facing Smart - Reply entries. - SMART_REPLY (4): - The legacy enum for agent-facing smart reply - feature. - """ - _pb_options = {'allow_alias': True} - KNOWLEDGE_TYPE_UNSPECIFIED = 0 - FAQ = 1 - EXTRACTIVE_QA = 2 - ARTICLE_SUGGESTION = 3 - AGENT_FACING_SMART_REPLY = 4 - SMART_REPLY = 4 - - class State(proto.Enum): - r"""Possible states of the document - - Values: - STATE_UNSPECIFIED (0): - The document state is unspecified. - CREATING (1): - The document creation is in progress. - ACTIVE (2): - The document is active and ready to use. - UPDATING (3): - The document updation is in progress. - RELOADING (4): - The document is reloading. - DELETING (5): - The document deletion is in progress. - """ - STATE_UNSPECIFIED = 0 - CREATING = 1 - ACTIVE = 2 - UPDATING = 3 - RELOADING = 4 - DELETING = 5 - - 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. - This reload may have been triggered - automatically or manually and may not have - succeeded. - status (google.rpc.status_pb2.Status): - Output only. The status of a reload attempt - or the initial load. - """ - - time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=1, - message=timestamp_pb2.Timestamp, - ) - status: status_pb2.Status = proto.Field( - proto.MESSAGE, - number=2, - message=status_pb2.Status, - ) - - name: str = proto.Field( - proto.STRING, - number=1, - ) - display_name: str = proto.Field( - proto.STRING, - number=2, - ) - mime_type: str = proto.Field( - proto.STRING, - number=3, - ) - knowledge_types: MutableSequence[KnowledgeType] = proto.RepeatedField( - proto.ENUM, - number=4, - enum=KnowledgeType, - ) - content_uri: str = proto.Field( - proto.STRING, - number=5, - oneof='source', - ) - content: str = proto.Field( - proto.STRING, - number=6, - oneof='source', - ) - raw_content: bytes = proto.Field( - proto.BYTES, - number=9, - oneof='source', - ) - enable_auto_reload: bool = proto.Field( - proto.BOOL, - number=11, - ) - latest_reload_status: ReloadStatus = proto.Field( - proto.MESSAGE, - number=12, - message=ReloadStatus, - ) - metadata: MutableMapping[str, str] = proto.MapField( - proto.STRING, - proto.STRING, - number=7, - ) - state: State = proto.Field( - proto.ENUM, - number=13, - enum=State, - ) - - -class GetDocumentRequest(proto.Message): - r"""Request message for - [Documents.GetDocument][google.cloud.dialogflow.v2beta1.Documents.GetDocument]. - - Attributes: - name (str): - Required. The name of the document to retrieve. Format - ``projects//locations//knowledgeBases//documents/``. - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - - -class ListDocumentsRequest(proto.Message): - r"""Request message for - [Documents.ListDocuments][google.cloud.dialogflow.v2beta1.Documents.ListDocuments]. - - Attributes: - parent (str): - Required. The knowledge base to list all documents for. - Format: - ``projects//locations//knowledgeBases/``. - page_size (int): - The maximum number of items to return in a - single page. By default 10 and at most 100. - page_token (str): - The next_page_token value returned from a previous list - request. - filter (str): - The filter expression used to filter documents returned by - the list method. The expression has the following syntax: - - [AND ] ... - - The following fields and operators are supported: - - - knowledge_types with has(:) operator - - display_name with has(:) operator - - state with equals(=) operator - - Examples: - - - "knowledge_types:FAQ" matches documents with FAQ - knowledge type. - - "display_name:customer" matches documents whose display - name contains "customer". - - "state=ACTIVE" matches documents with ACTIVE state. - - "knowledge_types:FAQ AND state=ACTIVE" matches all active - FAQ documents. - - For more information about filtering, see `API - Filtering `__. - """ - - parent: str = proto.Field( - proto.STRING, - number=1, - ) - page_size: int = proto.Field( - proto.INT32, - number=2, - ) - page_token: str = proto.Field( - proto.STRING, - number=3, - ) - filter: str = proto.Field( - proto.STRING, - number=4, - ) - - -class ListDocumentsResponse(proto.Message): - r"""Response message for - [Documents.ListDocuments][google.cloud.dialogflow.v2beta1.Documents.ListDocuments]. - - Attributes: - documents (MutableSequence[google.cloud.dialogflow_v2beta1.types.Document]): - The list of documents. - 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 - - documents: MutableSequence['Document'] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message='Document', - ) - next_page_token: str = proto.Field( - proto.STRING, - number=2, - ) - - -class CreateDocumentRequest(proto.Message): - r"""Request message for - [Documents.CreateDocument][google.cloud.dialogflow.v2beta1.Documents.CreateDocument]. - - Attributes: - parent (str): - Required. The knowledge base to create a document for. - Format: - ``projects//locations//knowledgeBases/``. - document (google.cloud.dialogflow_v2beta1.types.Document): - Required. The document to create. - import_gcs_custom_metadata (bool): - Whether to import custom metadata from Google - Cloud Storage. Only valid when the document - source is Google Cloud Storage URI. - """ - - parent: str = proto.Field( - proto.STRING, - number=1, - ) - document: 'Document' = proto.Field( - proto.MESSAGE, - number=2, - message='Document', - ) - import_gcs_custom_metadata: bool = proto.Field( - proto.BOOL, - number=3, - ) - - -class ImportDocumentsRequest(proto.Message): - r"""Request message for - [Documents.ImportDocuments][google.cloud.dialogflow.v2beta1.Documents.ImportDocuments]. - - - .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields - - Attributes: - parent (str): - Required. The knowledge base to import documents into. - Format: - ``projects//locations//knowledgeBases/``. - gcs_source (google.cloud.dialogflow_v2beta1.types.GcsSources): - The Google Cloud Storage location for the documents. The - path can include a wildcard. - - These URIs may have the forms - ``gs:///``. - ``gs:////*.``. - - This field is a member of `oneof`_ ``source``. - document_template (google.cloud.dialogflow_v2beta1.types.ImportDocumentTemplate): - Required. Document template used for - importing all the documents. - import_gcs_custom_metadata (bool): - Whether to import custom metadata from Google - Cloud Storage. Only valid when the document - source is Google Cloud Storage URI. - """ - - parent: str = proto.Field( - proto.STRING, - number=1, - ) - gcs_source: gcs.GcsSources = proto.Field( - proto.MESSAGE, - number=2, - oneof='source', - message=gcs.GcsSources, - ) - document_template: 'ImportDocumentTemplate' = proto.Field( - proto.MESSAGE, - number=3, - message='ImportDocumentTemplate', - ) - import_gcs_custom_metadata: bool = 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. - knowledge_types (MutableSequence[google.cloud.dialogflow_v2beta1.types.Document.KnowledgeType]): - Required. The knowledge type of document - content. - metadata (MutableMapping[str, str]): - Metadata for the document. The metadata supports arbitrary - key-value pairs. Suggested use cases include storing a - document's title, an external URL distinct from the - document's content_uri, etc. The max size of a ``key`` or a - ``value`` of the metadata is 1024 bytes. - """ - - mime_type: str = proto.Field( - proto.STRING, - number=1, - ) - knowledge_types: MutableSequence['Document.KnowledgeType'] = proto.RepeatedField( - proto.ENUM, - number=2, - enum='Document.KnowledgeType', - ) - metadata: MutableMapping[str, str] = proto.MapField( - proto.STRING, - proto.STRING, - number=3, - ) - - -class ImportDocumentsResponse(proto.Message): - r"""Response message for - [Documents.ImportDocuments][google.cloud.dialogflow.v2beta1.Documents.ImportDocuments]. - - Attributes: - warnings (MutableSequence[google.rpc.status_pb2.Status]): - Includes details about skipped documents or - any other warnings. - """ - - warnings: MutableSequence[status_pb2.Status] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message=status_pb2.Status, - ) - - -class DeleteDocumentRequest(proto.Message): - r"""Request message for - [Documents.DeleteDocument][google.cloud.dialogflow.v2beta1.Documents.DeleteDocument]. - - Attributes: - name (str): - Required. The name of the document to delete. Format: - ``projects//locations//knowledgeBases//documents/``. - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - - -class UpdateDocumentRequest(proto.Message): - r"""Request message for - [Documents.UpdateDocument][google.cloud.dialogflow.v2beta1.Documents.UpdateDocument]. - - Attributes: - document (google.cloud.dialogflow_v2beta1.types.Document): - Required. The document to update. - update_mask (google.protobuf.field_mask_pb2.FieldMask): - Optional. Not specified means ``update all``. Currently, - only ``display_name`` can be updated, an InvalidArgument - will be returned for attempting to update other fields. - """ - - document: 'Document' = proto.Field( - proto.MESSAGE, - number=1, - message='Document', - ) - update_mask: field_mask_pb2.FieldMask = proto.Field( - proto.MESSAGE, - number=2, - message=field_mask_pb2.FieldMask, - ) - - -class ExportOperationMetadata(proto.Message): - r"""Metadata related to the Export Data Operations (e.g. - ExportDocument). - - Attributes: - exported_gcs_destination (google.cloud.dialogflow_v2beta1.types.GcsDestination): - Cloud Storage file path of the exported data. - """ - - exported_gcs_destination: gcs.GcsDestination = proto.Field( - proto.MESSAGE, - number=1, - message=gcs.GcsDestination, - ) - - -class KnowledgeOperationMetadata(proto.Message): - r"""Metadata in google::longrunning::Operation for Knowledge - operations. - - - .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields - - Attributes: - state (google.cloud.dialogflow_v2beta1.types.KnowledgeOperationMetadata.State): - Required. Output only. The current state of - this operation. - knowledge_base (str): - The name of the knowledge base interacted - with during the operation. - export_operation_metadata (google.cloud.dialogflow_v2beta1.types.ExportOperationMetadata): - Metadata for the Export Data Operation such - as the destination of export. - - This field is a member of `oneof`_ ``operation_metadata``. - """ - class State(proto.Enum): - r"""States of the operation. - - Values: - STATE_UNSPECIFIED (0): - State unspecified. - PENDING (1): - The operation has been created. - RUNNING (2): - The operation is currently running. - DONE (3): - The operation is done, either cancelled or - completed. - """ - STATE_UNSPECIFIED = 0 - PENDING = 1 - RUNNING = 2 - DONE = 3 - - state: State = proto.Field( - proto.ENUM, - number=1, - enum=State, - ) - knowledge_base: str = proto.Field( - proto.STRING, - number=3, - ) - export_operation_metadata: 'ExportOperationMetadata' = proto.Field( - proto.MESSAGE, - number=4, - oneof='operation_metadata', - message='ExportOperationMetadata', - ) - - -class ReloadDocumentRequest(proto.Message): - r"""Request message for - [Documents.ReloadDocument][google.cloud.dialogflow.v2beta1.Documents.ReloadDocument]. - - - .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields - - Attributes: - name (str): - Required. The name of the document to reload. Format: - ``projects//locations//knowledgeBases//documents/`` - gcs_source (google.cloud.dialogflow_v2beta1.types.GcsSource): - The path for a Cloud Storage source file for - reloading document content. If not provided, the - Document's existing source will be reloaded. - - This field is a member of `oneof`_ ``source``. - import_gcs_custom_metadata (bool): - Whether to import custom metadata from Google - Cloud Storage. Only valid when the document - source is Google Cloud Storage URI. - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - gcs_source: gcs.GcsSource = proto.Field( - proto.MESSAGE, - number=3, - oneof='source', - message=gcs.GcsSource, - ) - import_gcs_custom_metadata: bool = proto.Field( - proto.BOOL, - number=4, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/types/entity_type.py b/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/types/entity_type.py deleted file mode 100644 index 5bfa90602..000000000 --- a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/types/entity_type.py +++ /dev/null @@ -1,626 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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 __future__ import annotations - -from typing import MutableMapping, MutableSequence - -import proto # type: ignore - -from google.protobuf import field_mask_pb2 # type: ignore - - -__protobuf__ = proto.module( - package='google.cloud.dialogflow.v2beta1', - manifest={ - 'EntityType', - 'ListEntityTypesRequest', - 'ListEntityTypesResponse', - 'GetEntityTypeRequest', - 'CreateEntityTypeRequest', - 'UpdateEntityTypeRequest', - 'DeleteEntityTypeRequest', - 'BatchUpdateEntityTypesRequest', - 'BatchUpdateEntityTypesResponse', - 'BatchDeleteEntityTypesRequest', - 'BatchCreateEntitiesRequest', - 'BatchUpdateEntitiesRequest', - 'BatchDeleteEntitiesRequest', - 'EntityTypeBatch', - }, -) - - -class EntityType(proto.Message): - r"""Each intent parameter has a type, called the entity type, which - dictates exactly how data from an end-user expression is extracted. - - Dialogflow provides predefined system entities that can match many - common types of data. For example, there are system entities for - matching dates, times, colors, email addresses, and so on. You can - also create your own custom entities for matching custom data. For - example, you could define a vegetable entity that can match the - types of vegetables available for purchase with a grocery store - agent. - - For more information, see the `Entity - guide `__. - - Attributes: - name (str): - The unique identifier of the entity type. Required for - [EntityTypes.UpdateEntityType][google.cloud.dialogflow.v2beta1.EntityTypes.UpdateEntityType] - and - [EntityTypes.BatchUpdateEntityTypes][google.cloud.dialogflow.v2beta1.EntityTypes.BatchUpdateEntityTypes] - methods. Supported formats: - - - ``projects//agent/entityTypes/`` - - ``projects//locations//agent/entityTypes/`` - display_name (str): - Required. The name of the entity type. - kind (google.cloud.dialogflow_v2beta1.types.EntityType.Kind): - Required. Indicates the kind of entity type. - auto_expansion_mode (google.cloud.dialogflow_v2beta1.types.EntityType.AutoExpansionMode): - Optional. Indicates whether the entity type - can be automatically expanded. - entities (MutableSequence[google.cloud.dialogflow_v2beta1.types.EntityType.Entity]): - Optional. The collection of entity entries - associated with the entity type. - enable_fuzzy_extraction (bool): - Optional. Enables fuzzy entity extraction - during classification. - """ - class Kind(proto.Enum): - r"""Represents kinds of entities. - - Values: - KIND_UNSPECIFIED (0): - Not specified. This value should be never - used. - KIND_MAP (1): - Map entity types allow mapping of a group of - synonyms to a reference value. - KIND_LIST (2): - List entity types contain a set of entries - that do not map to reference values. However, - list entity types can contain references to - other entity types (with or without aliases). - KIND_REGEXP (3): - Regexp entity types allow to specify regular - expressions in entries values. - """ - KIND_UNSPECIFIED = 0 - KIND_MAP = 1 - KIND_LIST = 2 - KIND_REGEXP = 3 - - class AutoExpansionMode(proto.Enum): - r"""Represents different entity type expansion modes. Automated - expansion allows an agent to recognize values that have not been - explicitly listed in the entity (for example, new kinds of - shopping list items). - - Values: - AUTO_EXPANSION_MODE_UNSPECIFIED (0): - Auto expansion disabled for the entity. - AUTO_EXPANSION_MODE_DEFAULT (1): - Allows an agent to recognize values that have - not been explicitly listed in the entity. - """ - AUTO_EXPANSION_MODE_UNSPECIFIED = 0 - AUTO_EXPANSION_MODE_DEFAULT = 1 - - class Entity(proto.Message): - r"""An **entity entry** for an associated entity type. - - Attributes: - value (str): - Required. The primary value associated with this entity - entry. For example, if the entity type is *vegetable*, the - value could be *scallions*. - - For ``KIND_MAP`` entity types: - - - A reference value to be used in place of synonyms. - - For ``KIND_LIST`` entity types: - - - A string that can contain references to other entity - types (with or without aliases). - synonyms (MutableSequence[str]): - Required. A collection of value synonyms. For example, if - the entity type is *vegetable*, and ``value`` is - *scallions*, a synonym could be *green onions*. - - For ``KIND_LIST`` entity types: - - - This collection must contain exactly one synonym equal to - ``value``. - """ - - value: str = proto.Field( - proto.STRING, - number=1, - ) - synonyms: MutableSequence[str] = proto.RepeatedField( - proto.STRING, - number=2, - ) - - name: str = proto.Field( - proto.STRING, - number=1, - ) - display_name: str = proto.Field( - proto.STRING, - number=2, - ) - kind: Kind = proto.Field( - proto.ENUM, - number=3, - enum=Kind, - ) - auto_expansion_mode: AutoExpansionMode = proto.Field( - proto.ENUM, - number=4, - enum=AutoExpansionMode, - ) - entities: MutableSequence[Entity] = proto.RepeatedField( - proto.MESSAGE, - number=6, - message=Entity, - ) - enable_fuzzy_extraction: bool = proto.Field( - proto.BOOL, - number=7, - ) - - -class ListEntityTypesRequest(proto.Message): - r"""The request message for - [EntityTypes.ListEntityTypes][google.cloud.dialogflow.v2beta1.EntityTypes.ListEntityTypes]. - - Attributes: - parent (str): - Required. The agent to list all entity types from. Supported - formats: - - - ``projects//agent`` - - ``projects//locations//agent`` - language_code (str): - Optional. The language used to access language-specific - data. If not specified, the agent's default language is - used. For more information, see `Multilingual intent and - entity - data `__. - 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: str = proto.Field( - proto.STRING, - number=1, - ) - language_code: str = proto.Field( - proto.STRING, - number=2, - ) - page_size: int = proto.Field( - proto.INT32, - number=3, - ) - page_token: str = proto.Field( - proto.STRING, - number=4, - ) - - -class ListEntityTypesResponse(proto.Message): - r"""The response message for - [EntityTypes.ListEntityTypes][google.cloud.dialogflow.v2beta1.EntityTypes.ListEntityTypes]. - - Attributes: - entity_types (MutableSequence[google.cloud.dialogflow_v2beta1.types.EntityType]): - The list of agent entity types. 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 - - entity_types: MutableSequence['EntityType'] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message='EntityType', - ) - next_page_token: str = proto.Field( - proto.STRING, - number=2, - ) - - -class GetEntityTypeRequest(proto.Message): - r"""The request message for - [EntityTypes.GetEntityType][google.cloud.dialogflow.v2beta1.EntityTypes.GetEntityType]. - - Attributes: - name (str): - Required. The name of the entity type. Supported formats: - - - ``projects//agent/entityTypes/`` - - ``projects//locations//agent/entityTypes/`` - language_code (str): - Optional. The language used to access language-specific - data. If not specified, the agent's default language is - used. For more information, see `Multilingual intent and - entity - data `__. - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - language_code: str = proto.Field( - proto.STRING, - number=2, - ) - - -class CreateEntityTypeRequest(proto.Message): - r"""The request message for - [EntityTypes.CreateEntityType][google.cloud.dialogflow.v2beta1.EntityTypes.CreateEntityType]. - - Attributes: - parent (str): - Required. The agent to create a entity type for. Supported - formats: - - - ``projects//agent`` - - ``projects//locations//agent`` - entity_type (google.cloud.dialogflow_v2beta1.types.EntityType): - Required. The entity type to create. - language_code (str): - Optional. The language used to access language-specific - data. If not specified, the agent's default language is - used. For more information, see `Multilingual intent and - entity - data `__. - """ - - parent: str = proto.Field( - proto.STRING, - number=1, - ) - entity_type: 'EntityType' = proto.Field( - proto.MESSAGE, - number=2, - message='EntityType', - ) - language_code: str = proto.Field( - proto.STRING, - number=3, - ) - - -class UpdateEntityTypeRequest(proto.Message): - r"""The request message for - [EntityTypes.UpdateEntityType][google.cloud.dialogflow.v2beta1.EntityTypes.UpdateEntityType]. - - Attributes: - entity_type (google.cloud.dialogflow_v2beta1.types.EntityType): - Required. The entity type to update. - language_code (str): - Optional. The language used to access language-specific - data. If not specified, the agent's default language is - used. For more information, see `Multilingual intent and - entity - data `__. - update_mask (google.protobuf.field_mask_pb2.FieldMask): - Optional. The mask to control which fields - get updated. - """ - - entity_type: 'EntityType' = proto.Field( - proto.MESSAGE, - number=1, - message='EntityType', - ) - language_code: str = proto.Field( - proto.STRING, - number=2, - ) - update_mask: field_mask_pb2.FieldMask = proto.Field( - proto.MESSAGE, - number=3, - message=field_mask_pb2.FieldMask, - ) - - -class DeleteEntityTypeRequest(proto.Message): - r"""The request message for - [EntityTypes.DeleteEntityType][google.cloud.dialogflow.v2beta1.EntityTypes.DeleteEntityType]. - - Attributes: - name (str): - Required. The name of the entity type to delete. Supported - formats: - - - ``projects//agent/entityTypes/`` - - ``projects//locations//agent/entityTypes/`` - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - - -class BatchUpdateEntityTypesRequest(proto.Message): - r"""The request message for - [EntityTypes.BatchUpdateEntityTypes][google.cloud.dialogflow.v2beta1.EntityTypes.BatchUpdateEntityTypes]. - - This message has `oneof`_ fields (mutually exclusive fields). - For each oneof, at most one member field can be set at the same time. - Setting any member of the oneof automatically clears all other - members. - - .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields - - Attributes: - parent (str): - Required. The name of the agent to update or create entity - types in. Supported formats: - - - ``projects//agent`` - - ``projects//locations//agent`` - entity_type_batch_uri (str): - The URI to a Google Cloud Storage file - containing entity types to update or create. The - file format can either be a serialized proto (of - EntityBatch type) or a JSON object. Note: The - URI must start with "gs://". - - This field is a member of `oneof`_ ``entity_type_batch``. - entity_type_batch_inline (google.cloud.dialogflow_v2beta1.types.EntityTypeBatch): - The collection of entity types to update or - create. - - This field is a member of `oneof`_ ``entity_type_batch``. - language_code (str): - Optional. The language used to access language-specific - data. If not specified, the agent's default language is - used. For more information, see `Multilingual intent and - entity - data `__. - update_mask (google.protobuf.field_mask_pb2.FieldMask): - Optional. The mask to control which fields - get updated. - """ - - parent: str = proto.Field( - proto.STRING, - number=1, - ) - entity_type_batch_uri: str = proto.Field( - proto.STRING, - number=2, - oneof='entity_type_batch', - ) - entity_type_batch_inline: 'EntityTypeBatch' = proto.Field( - proto.MESSAGE, - number=3, - oneof='entity_type_batch', - message='EntityTypeBatch', - ) - language_code: str = proto.Field( - proto.STRING, - number=4, - ) - update_mask: field_mask_pb2.FieldMask = proto.Field( - proto.MESSAGE, - number=5, - message=field_mask_pb2.FieldMask, - ) - - -class BatchUpdateEntityTypesResponse(proto.Message): - r"""The response message for - [EntityTypes.BatchUpdateEntityTypes][google.cloud.dialogflow.v2beta1.EntityTypes.BatchUpdateEntityTypes]. - - Attributes: - entity_types (MutableSequence[google.cloud.dialogflow_v2beta1.types.EntityType]): - The collection of updated or created entity - types. - """ - - entity_types: MutableSequence['EntityType'] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message='EntityType', - ) - - -class BatchDeleteEntityTypesRequest(proto.Message): - r"""The request message for - [EntityTypes.BatchDeleteEntityTypes][google.cloud.dialogflow.v2beta1.EntityTypes.BatchDeleteEntityTypes]. - - Attributes: - parent (str): - Required. The name of the agent to delete all entities types - for. Supported formats: - - - ``projects//agent``, - - ``projects//locations//agent``. - entity_type_names (MutableSequence[str]): - Required. The names entity types to delete. All names must - point to the same agent as ``parent``. - """ - - parent: str = proto.Field( - proto.STRING, - number=1, - ) - entity_type_names: MutableSequence[str] = proto.RepeatedField( - proto.STRING, - number=2, - ) - - -class BatchCreateEntitiesRequest(proto.Message): - r"""The request message for - [EntityTypes.BatchCreateEntities][google.cloud.dialogflow.v2beta1.EntityTypes.BatchCreateEntities]. - - Attributes: - parent (str): - Required. The name of the entity type to create entities in. - Supported formats: - - - ``projects//agent/entityTypes/`` - - ``projects//locations//agent/entityTypes/`` - entities (MutableSequence[google.cloud.dialogflow_v2beta1.types.EntityType.Entity]): - Required. The entities to create. - language_code (str): - Optional. The language used to access language-specific - data. If not specified, the agent's default language is - used. For more information, see `Multilingual intent and - entity - data `__. - """ - - parent: str = proto.Field( - proto.STRING, - number=1, - ) - entities: MutableSequence['EntityType.Entity'] = proto.RepeatedField( - proto.MESSAGE, - number=2, - message='EntityType.Entity', - ) - language_code: str = proto.Field( - proto.STRING, - number=3, - ) - - -class BatchUpdateEntitiesRequest(proto.Message): - r"""The request message for - [EntityTypes.BatchUpdateEntities][google.cloud.dialogflow.v2beta1.EntityTypes.BatchUpdateEntities]. - - Attributes: - parent (str): - Required. The name of the entity type to update or create - entities in. Supported formats: - - - ``projects//agent/entityTypes/`` - - ``projects//locations//agent/entityTypes/`` - entities (MutableSequence[google.cloud.dialogflow_v2beta1.types.EntityType.Entity]): - Required. The entities to update or create. - language_code (str): - Optional. The language used to access language-specific - data. If not specified, the agent's default language is - used. For more information, see `Multilingual intent and - entity - data `__. - update_mask (google.protobuf.field_mask_pb2.FieldMask): - Optional. The mask to control which fields - get updated. - """ - - parent: str = proto.Field( - proto.STRING, - number=1, - ) - entities: MutableSequence['EntityType.Entity'] = proto.RepeatedField( - proto.MESSAGE, - number=2, - message='EntityType.Entity', - ) - language_code: str = proto.Field( - proto.STRING, - number=3, - ) - update_mask: field_mask_pb2.FieldMask = proto.Field( - proto.MESSAGE, - number=4, - message=field_mask_pb2.FieldMask, - ) - - -class BatchDeleteEntitiesRequest(proto.Message): - r"""The request message for - [EntityTypes.BatchDeleteEntities][google.cloud.dialogflow.v2beta1.EntityTypes.BatchDeleteEntities]. - - Attributes: - parent (str): - Required. The name of the entity type to delete entries for. - Supported formats: - - - ``projects//agent/entityTypes/`` - - ``projects//locations//agent/entityTypes/`` - entity_values (MutableSequence[str]): - Required. The reference ``values`` of the entities to - delete. Note that these are not fully-qualified names, i.e. - they don't start with ``projects/``. - language_code (str): - Optional. The language used to access language-specific - data. If not specified, the agent's default language is - used. For more information, see `Multilingual intent and - entity - data `__. - """ - - parent: str = proto.Field( - proto.STRING, - number=1, - ) - entity_values: MutableSequence[str] = proto.RepeatedField( - proto.STRING, - number=2, - ) - language_code: str = proto.Field( - proto.STRING, - number=3, - ) - - -class EntityTypeBatch(proto.Message): - r"""This message is a wrapper around a collection of entity - types. - - Attributes: - entity_types (MutableSequence[google.cloud.dialogflow_v2beta1.types.EntityType]): - A collection of entity types. - """ - - entity_types: MutableSequence['EntityType'] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message='EntityType', - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/types/environment.py b/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/types/environment.py deleted file mode 100644 index 96aa62a28..000000000 --- a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/types/environment.py +++ /dev/null @@ -1,474 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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 __future__ import annotations - -from typing import MutableMapping, MutableSequence - -import proto # 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', - 'TextToSpeechSettings', - 'ListEnvironmentsRequest', - 'ListEnvironmentsResponse', - 'GetEnvironmentRequest', - 'CreateEnvironmentRequest', - 'UpdateEnvironmentRequest', - 'DeleteEnvironmentRequest', - 'GetEnvironmentHistoryRequest', - 'EnvironmentHistory', - }, -) - - -class Environment(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 - 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 - characters. If exceeded, the request is - rejected. - agent_version (str): - Optional. The agent version loaded into this environment. - Supported formats: - - - ``projects//agent/versions/`` - - ``projects//locations//agent/versions/`` - state (google.cloud.dialogflow_v2beta1.types.Environment.State): - Output only. The state of this environment. - This field is read-only, i.e., it cannot be set - by create and update methods. - update_time (google.protobuf.timestamp_pb2.Timestamp): - 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): - r"""Represents an environment state. When an environment is pointed to a - new 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. - - Values: - STATE_UNSPECIFIED (0): - Not specified. This value is not used. - STOPPED (1): - Stopped. - LOADING (2): - Loading. - RUNNING (3): - Running. - """ - STATE_UNSPECIFIED = 0 - STOPPED = 1 - LOADING = 2 - RUNNING = 3 - - name: str = proto.Field( - proto.STRING, - number=1, - ) - description: str = proto.Field( - proto.STRING, - number=2, - ) - agent_version: str = proto.Field( - proto.STRING, - number=3, - ) - state: State = proto.Field( - proto.ENUM, - number=4, - enum=State, - ) - update_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=5, - message=timestamp_pb2.Timestamp, - ) - text_to_speech_settings: 'TextToSpeechSettings' = proto.Field( - proto.MESSAGE, - number=7, - message='TextToSpeechSettings', - ) - fulfillment: gcd_fulfillment.Fulfillment = proto.Field( - proto.MESSAGE, - number=8, - message=gcd_fulfillment.Fulfillment, - ) - - -class TextToSpeechSettings(proto.Message): - r"""Instructs the speech synthesizer on how to generate the - output audio content. - - 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 (MutableMapping[str, google.cloud.dialogflow_v2beta1.types.SynthesizeSpeechConfig]): - Optional. Configuration of how speech should - be synthesized, mapping from language - (https://cloud.google.com/dialogflow/docs/reference/language) - to SynthesizeSpeechConfig. - """ - - enable_text_to_speech: bool = proto.Field( - proto.BOOL, - number=1, - ) - output_audio_encoding: audio_config.OutputAudioEncoding = proto.Field( - proto.ENUM, - number=2, - enum=audio_config.OutputAudioEncoding, - ) - sample_rate_hertz: int = proto.Field( - proto.INT32, - number=3, - ) - synthesize_speech_configs: MutableMapping[str, audio_config.SynthesizeSpeechConfig] = proto.MapField( - proto.STRING, - proto.MESSAGE, - number=4, - message=audio_config.SynthesizeSpeechConfig, - ) - - -class ListEnvironmentsRequest(proto.Message): - r"""The request message for - [Environments.ListEnvironments][google.cloud.dialogflow.v2beta1.Environments.ListEnvironments]. - - Attributes: - parent (str): - Required. The agent to list all environments from. Format: - - - ``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: str = proto.Field( - proto.STRING, - number=1, - ) - page_size: int = proto.Field( - proto.INT32, - number=2, - ) - page_token: str = proto.Field( - proto.STRING, - number=3, - ) - - -class ListEnvironmentsResponse(proto.Message): - r"""The response message for - [Environments.ListEnvironments][google.cloud.dialogflow.v2beta1.Environments.ListEnvironments]. - - Attributes: - environments (MutableSequence[google.cloud.dialogflow_v2beta1.types.Environment]): - 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): - 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 - - environments: MutableSequence['Environment'] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message='Environment', - ) - next_page_token: str = 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: str = 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: str = proto.Field( - proto.STRING, - number=1, - ) - environment: 'Environment' = proto.Field( - proto.MESSAGE, - number=2, - message='Environment', - ) - environment_id: str = 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: 'Environment' = proto.Field( - proto.MESSAGE, - number=1, - message='Environment', - ) - update_mask: field_mask_pb2.FieldMask = proto.Field( - proto.MESSAGE, - number=2, - message=field_mask_pb2.FieldMask, - ) - allow_load_to_draft_and_discard_changes: bool = 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: str = 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: str = proto.Field( - proto.STRING, - number=1, - ) - page_size: int = proto.Field( - proto.INT32, - number=2, - ) - page_token: str = 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 (MutableSequence[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: str = proto.Field( - proto.STRING, - number=1, - ) - description: str = proto.Field( - proto.STRING, - number=2, - ) - create_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=3, - message=timestamp_pb2.Timestamp, - ) - - @property - def raw_page(self): - return self - - parent: str = proto.Field( - proto.STRING, - number=1, - ) - entries: MutableSequence[Entry] = proto.RepeatedField( - proto.MESSAGE, - number=2, - message=Entry, - ) - next_page_token: str = proto.Field( - proto.STRING, - number=3, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/types/fulfillment.py b/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/types/fulfillment.py deleted file mode 100644 index 30f3a11a2..000000000 --- a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/types/fulfillment.py +++ /dev/null @@ -1,218 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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 __future__ import annotations - -from typing import MutableMapping, MutableSequence - -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 `__. - - - .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields - - 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. - - This field is a member of `oneof`_ ``fulfillment``. - enabled (bool): - Whether fulfillment is enabled. - features (MutableSequence[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 (MutableMapping[str, str]): - 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: str = proto.Field( - proto.STRING, - number=1, - ) - username: str = proto.Field( - proto.STRING, - number=2, - ) - password: str = proto.Field( - proto.STRING, - number=3, - ) - request_headers: MutableMapping[str, str] = proto.MapField( - proto.STRING, - proto.STRING, - number=4, - ) - is_cloud_function: bool = 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. - - Values: - TYPE_UNSPECIFIED (0): - Feature type not specified. - SMALLTALK (1): - Fulfillment is enabled for SmallTalk. - """ - TYPE_UNSPECIFIED = 0 - SMALLTALK = 1 - - type_: 'Fulfillment.Feature.Type' = proto.Field( - proto.ENUM, - number=1, - enum='Fulfillment.Feature.Type', - ) - - name: str = proto.Field( - proto.STRING, - number=1, - ) - display_name: str = proto.Field( - proto.STRING, - number=2, - ) - generic_web_service: GenericWebService = proto.Field( - proto.MESSAGE, - number=3, - oneof='fulfillment', - message=GenericWebService, - ) - enabled: bool = proto.Field( - proto.BOOL, - number=4, - ) - features: MutableSequence[Feature] = 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: str = 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: 'Fulfillment' = proto.Field( - proto.MESSAGE, - number=1, - message='Fulfillment', - ) - update_mask: field_mask_pb2.FieldMask = proto.Field( - proto.MESSAGE, - number=2, - message=field_mask_pb2.FieldMask, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/types/gcs.py b/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/types/gcs.py deleted file mode 100644 index 44403b226..000000000 --- a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/types/gcs.py +++ /dev/null @@ -1,88 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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 __future__ import annotations - -from typing import MutableMapping, MutableSequence - -import proto # type: ignore - - -__protobuf__ = proto.module( - package='google.cloud.dialogflow.v2beta1', - manifest={ - 'GcsSources', - 'GcsSource', - 'GcsDestination', - }, -) - - -class GcsSources(proto.Message): - r"""Google Cloud Storage locations for the inputs. - - Attributes: - uris (MutableSequence[str]): - Required. Google Cloud Storage URIs for the - inputs. A URI is of the form: - gs://bucket/object-prefix-or-name - Whether a prefix or name is used depends on the - use case. - """ - - uris: MutableSequence[str] = 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 - the inputs. A URI is of the form: - gs://bucket/object-prefix-or-name - Whether a prefix or name is used depends on the - use case. - """ - - uri: str = proto.Field( - proto.STRING, - number=1, - ) - - -class GcsDestination(proto.Message): - r"""Google Cloud Storage location for the output. - - Attributes: - uri (str): - Required. The Google Cloud Storage URIs for - the output. A URI is of the form: - gs://bucket/object-prefix-or-name - Whether a prefix or name is used depends on the - use case. The requesting user must have - "write-permission" to the bucket. - """ - - uri: str = proto.Field( - proto.STRING, - number=1, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/types/human_agent_assistant_event.py b/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/types/human_agent_assistant_event.py deleted file mode 100644 index 6ac40dbaf..000000000 --- a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/types/human_agent_assistant_event.py +++ /dev/null @@ -1,73 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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 __future__ import annotations - -from typing import MutableMapping, MutableSequence - -import proto # type: ignore - -from google.cloud.dialogflow_v2beta1.types import participant as gcd_participant - - -__protobuf__ = proto.module( - package='google.cloud.dialogflow.v2beta1', - manifest={ - 'HumanAgentAssistantEvent', - }, -) - - -class HumanAgentAssistantEvent(proto.Message): - r"""Output only. Represents a notification sent to Pub/Sub - subscribers for agent assistant events in a specific - conversation. - - Attributes: - conversation (str): - The conversation this notification refers to. Format: - ``projects//conversations/``. - participant (str): - The participant that the suggestion is compiled for. And - This field is used to call - [Participants.ListSuggestions][google.cloud.dialogflow.v2beta1.Participants.ListSuggestions] - API. Format: - ``projects//conversations//participants/``. - It will not be set in legacy workflow. - [HumanAgentAssistantConfig.name][google.cloud.dialogflow.v2beta1.HumanAgentAssistantConfig.name] - for more information. - suggestion_results (MutableSequence[google.cloud.dialogflow_v2beta1.types.SuggestionResult]): - The suggestion results payload that this notification refers - to. It will only be set when - [HumanAgentAssistantConfig.SuggestionConfig.group_suggestion_responses][google.cloud.dialogflow.v2beta1.HumanAgentAssistantConfig.SuggestionConfig.group_suggestion_responses] - sets to true. - """ - - conversation: str = proto.Field( - proto.STRING, - number=1, - ) - participant: str = proto.Field( - proto.STRING, - number=3, - ) - suggestion_results: MutableSequence[gcd_participant.SuggestionResult] = proto.RepeatedField( - proto.MESSAGE, - number=5, - message=gcd_participant.SuggestionResult, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/types/intent.py b/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/types/intent.py deleted file mode 100644 index 67503f311..000000000 --- a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/types/intent.py +++ /dev/null @@ -1,2429 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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 __future__ import annotations - -from typing import MutableMapping, MutableSequence - -import proto # type: ignore - -from google.cloud.dialogflow_v2beta1.types import context -from google.protobuf import field_mask_pb2 # type: ignore -from google.protobuf import struct_pb2 # type: ignore - - -__protobuf__ = proto.module( - package='google.cloud.dialogflow.v2beta1', - manifest={ - 'IntentView', - 'Intent', - 'ListIntentsRequest', - 'ListIntentsResponse', - 'GetIntentRequest', - 'CreateIntentRequest', - 'UpdateIntentRequest', - 'DeleteIntentRequest', - 'BatchUpdateIntentsRequest', - 'BatchUpdateIntentsResponse', - 'BatchDeleteIntentsRequest', - 'IntentBatch', - }, -) - - -class IntentView(proto.Enum): - r"""Represents the options for views of an intent. - An intent can be a sizable object. Therefore, we provide a - resource view that does not return training phrases in the - response by default. - - Values: - INTENT_VIEW_UNSPECIFIED (0): - Training phrases field is not populated in - the response. - INTENT_VIEW_FULL (1): - All fields are populated. - """ - INTENT_VIEW_UNSPECIFIED = 0 - INTENT_VIEW_FULL = 1 - - -class Intent(proto.Message): - r"""An intent categorizes an end-user's intention for one conversation - turn. For each agent, you define many intents, where your combined - intents can handle a complete conversation. When an end-user writes - or says something, referred to as an end-user expression or end-user - input, Dialogflow matches the end-user input to the best intent in - your agent. Matching an intent is also known as intent - classification. - - For more information, see the `intent - guide `__. - - Attributes: - name (str): - Optional. The unique identifier of this intent. Required for - [Intents.UpdateIntent][google.cloud.dialogflow.v2beta1.Intents.UpdateIntent] - and - [Intents.BatchUpdateIntents][google.cloud.dialogflow.v2beta1.Intents.BatchUpdateIntents] - methods. Supported formats: - - - ``projects//agent/intents/`` - - ``projects//locations//agent/intents/`` - display_name (str): - Required. The name of this intent. - webhook_state (google.cloud.dialogflow_v2beta1.types.Intent.WebhookState): - Optional. Indicates whether webhooks are - enabled for the intent. - priority (int): - Optional. The priority of this intent. Higher numbers - represent higher priorities. - - - If the supplied value is unspecified or 0, the service - translates the value to 500,000, which corresponds to the - ``Normal`` priority in the console. - - If the supplied value is negative, the intent is ignored - in runtime detect intent requests. - is_fallback (bool): - Optional. Indicates whether this is a - fallback intent. - ml_enabled (bool): - Optional. Indicates whether Machine Learning is enabled for - the intent. Note: If ``ml_enabled`` setting is set to false, - then this intent is not taken into account during inference - in ``ML ONLY`` match mode. Also, auto-markup in the UI is - turned off. DEPRECATED! Please use ``ml_disabled`` field - instead. NOTE: If both ``ml_enabled`` and ``ml_disabled`` - are either not set or false, then the default value is - determined as follows: - - - Before April 15th, 2018 the default is: ml_enabled = - false / ml_disabled = true. - - After April 15th, 2018 the default is: ml_enabled = true - / ml_disabled = false. - ml_disabled (bool): - Optional. Indicates whether Machine Learning is disabled for - the intent. Note: If ``ml_disabled`` setting is set to true, - then this intent is not taken into account during inference - in ``ML ONLY`` match mode. Also, auto-markup in the UI is - turned off. - live_agent_handoff (bool): - Optional. Indicates that a live agent should be brought in - to handle the interaction with the user. In most cases, when - you set this flag to true, you would also want to set - end_interaction to true as well. Default is false. - end_interaction (bool): - Optional. Indicates that this intent ends an - interaction. Some integrations (e.g., Actions on - Google or Dialogflow phone gateway) use this - information to close interaction with an end - user. Default is false. - input_context_names (MutableSequence[str]): - Optional. The list of context names required for this intent - to be triggered. Formats: - - - ``projects//agent/sessions/-/contexts/`` - - ``projects//locations//agent/sessions/-/contexts/`` - events (MutableSequence[str]): - Optional. The collection of event names that - trigger the intent. If the collection of input - contexts is not empty, all of the contexts must - be present in the active user session for an - event to trigger this intent. Event names are - limited to 150 characters. - training_phrases (MutableSequence[google.cloud.dialogflow_v2beta1.types.Intent.TrainingPhrase]): - Optional. The collection of examples that the - agent is trained on. - action (str): - Optional. The name of the action associated - with the intent. Note: The action name must not - contain whitespaces. - output_contexts (MutableSequence[google.cloud.dialogflow_v2beta1.types.Context]): - Optional. The collection of contexts that are activated when - the intent is matched. Context messages in this collection - should not set the parameters field. Setting the - ``lifespan_count`` to 0 will reset the context when the - intent is matched. Format: - ``projects//agent/sessions/-/contexts/``. - reset_contexts (bool): - Optional. Indicates whether to delete all - contexts in the current session when this intent - is matched. - parameters (MutableSequence[google.cloud.dialogflow_v2beta1.types.Intent.Parameter]): - Optional. The collection of parameters - associated with the intent. - messages (MutableSequence[google.cloud.dialogflow_v2beta1.types.Intent.Message]): - Optional. The collection of rich messages corresponding to - the ``Response`` field in the Dialogflow console. - default_response_platforms (MutableSequence[google.cloud.dialogflow_v2beta1.types.Intent.Message.Platform]): - Optional. The list of platforms for which the first - responses will be copied from the messages in - PLATFORM_UNSPECIFIED (i.e. default platform). - root_followup_intent_name (str): - Output only. The unique identifier of the root intent in the - chain of followup intents. It identifies the correct - followup intents chain for this intent. - - Format: ``projects//agent/intents/``. - parent_followup_intent_name (str): - Optional. The unique identifier of the parent intent in the - chain of followup intents. You can set this field when - creating an intent, for example with - [CreateIntent][google.cloud.dialogflow.v2beta1.Intents.CreateIntent] - or - [BatchUpdateIntents][google.cloud.dialogflow.v2beta1.Intents.BatchUpdateIntents], - in order to make this intent a followup intent. - - It identifies the parent followup intent. Format: - ``projects//agent/intents/``. - followup_intent_info (MutableSequence[google.cloud.dialogflow_v2beta1.types.Intent.FollowupIntentInfo]): - Output only. Information about all followup - intents that have this intent as a direct or - indirect parent. We populate this field only in - the output. - """ - class WebhookState(proto.Enum): - r"""Represents the different states that webhooks can be in. - - Values: - WEBHOOK_STATE_UNSPECIFIED (0): - Webhook is disabled in the agent and in the - intent. - WEBHOOK_STATE_ENABLED (1): - Webhook is enabled in the agent and in the - intent. - WEBHOOK_STATE_ENABLED_FOR_SLOT_FILLING (2): - Webhook is enabled in the agent and in the - intent. Also, each slot filling prompt is - forwarded to the webhook. - """ - WEBHOOK_STATE_UNSPECIFIED = 0 - WEBHOOK_STATE_ENABLED = 1 - WEBHOOK_STATE_ENABLED_FOR_SLOT_FILLING = 2 - - class TrainingPhrase(proto.Message): - r"""Represents an example that the agent is trained on. - - Attributes: - name (str): - Output only. The unique identifier of this - training phrase. - type_ (google.cloud.dialogflow_v2beta1.types.Intent.TrainingPhrase.Type): - Required. The type of the training phrase. - parts (MutableSequence[google.cloud.dialogflow_v2beta1.types.Intent.TrainingPhrase.Part]): - Required. The ordered list of training phrase parts. The - parts are concatenated in order to form the training phrase. - - Note: The API does not automatically annotate training - phrases like the Dialogflow Console does. - - Note: Do not forget to include whitespace at part - boundaries, so the training phrase is well formatted when - the parts are concatenated. - - If the training phrase does not need to be annotated with - parameters, you just need a single part with only the - [Part.text][google.cloud.dialogflow.v2beta1.Intent.TrainingPhrase.Part.text] - field set. - - If you want to annotate the training phrase, you must create - multiple parts, where the fields of each part are populated - in one of two ways: - - - ``Part.text`` is set to a part of the phrase that has no - parameters. - - ``Part.text`` is set to a part of the phrase that you - want to annotate, and the ``entity_type``, ``alias``, and - ``user_defined`` fields are all set. - times_added_count (int): - Optional. Indicates how many times this - example was added to the intent. Each time a - developer adds an existing sample by editing an - intent or training, this counter is increased. - """ - class Type(proto.Enum): - r"""Represents different types of training phrases. - - Values: - TYPE_UNSPECIFIED (0): - Not specified. This value should never be - used. - EXAMPLE (1): - Examples do not contain @-prefixed entity - type names, but example parts can be annotated - with entity types. - TEMPLATE (2): - Templates are not annotated with entity - types, but they can contain @-prefixed entity - type names as substrings. Note: Template mode - has been deprecated. Example mode is the only - supported way to create new training phrases. If - you have existing training phrases in template - mode, they will be removed during training and - it can cause a drop in agent performance. - """ - TYPE_UNSPECIFIED = 0 - EXAMPLE = 1 - TEMPLATE = 2 - - class Part(proto.Message): - r"""Represents a part of a training phrase. - - Attributes: - text (str): - Required. The text for this part. - entity_type (str): - Optional. The entity type name prefixed with ``@``. This - field is required for annotated parts of the training - phrase. - alias (str): - Optional. The parameter name for the value - extracted from the annotated part of the - example. This field is required for annotated - parts of the training phrase. - user_defined (bool): - Optional. Indicates whether the text was - manually annotated. This field is set to true - when the Dialogflow Console is used to manually - annotate the part. When creating an annotated - part with the API, you must set this to true. - """ - - text: str = proto.Field( - proto.STRING, - number=1, - ) - entity_type: str = proto.Field( - proto.STRING, - number=2, - ) - alias: str = proto.Field( - proto.STRING, - number=3, - ) - user_defined: bool = proto.Field( - proto.BOOL, - number=4, - ) - - name: str = proto.Field( - proto.STRING, - number=1, - ) - type_: 'Intent.TrainingPhrase.Type' = proto.Field( - proto.ENUM, - number=2, - enum='Intent.TrainingPhrase.Type', - ) - parts: MutableSequence['Intent.TrainingPhrase.Part'] = proto.RepeatedField( - proto.MESSAGE, - number=3, - message='Intent.TrainingPhrase.Part', - ) - times_added_count: int = proto.Field( - proto.INT32, - number=4, - ) - - class Parameter(proto.Message): - r"""Represents intent parameters. - - Attributes: - name (str): - The unique identifier of this parameter. - display_name (str): - Required. The name of the parameter. - value (str): - Optional. The definition of the parameter value. It can be: - - - a constant string, - - a parameter value defined as ``$parameter_name``, - - an original parameter value defined as - ``$parameter_name.original``, - - a parameter value from some context defined as - ``#context_name.parameter_name``. - default_value (str): - Optional. The default value to use when the ``value`` yields - an empty result. Default values can be extracted from - contexts by using the following syntax: - ``#context_name.parameter_name``. - entity_type_display_name (str): - Optional. The name of the entity type, prefixed with ``@``, - that describes values of the parameter. If the parameter is - required, this must be provided. - mandatory (bool): - Optional. Indicates whether the parameter is - required. That is, whether the intent cannot be - completed without collecting the parameter - value. - prompts (MutableSequence[str]): - Optional. The collection of prompts that the - agent can present to the user in order to - collect a value for the parameter. - is_list (bool): - Optional. Indicates whether the parameter - represents a list of values. - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - display_name: str = proto.Field( - proto.STRING, - number=2, - ) - value: str = proto.Field( - proto.STRING, - number=3, - ) - default_value: str = proto.Field( - proto.STRING, - number=4, - ) - entity_type_display_name: str = proto.Field( - proto.STRING, - number=5, - ) - mandatory: bool = proto.Field( - proto.BOOL, - number=6, - ) - prompts: MutableSequence[str] = proto.RepeatedField( - proto.STRING, - number=7, - ) - is_list: bool = proto.Field( - proto.BOOL, - number=8, - ) - - class Message(proto.Message): - r"""Corresponds to the ``Response`` field in the Dialogflow console. - - This message has `oneof`_ fields (mutually exclusive fields). - For each oneof, at most one member field can be set at the same time. - Setting any member of the oneof automatically clears all other - members. - - .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields - - Attributes: - text (google.cloud.dialogflow_v2beta1.types.Intent.Message.Text): - Returns a text response. - - This field is a member of `oneof`_ ``message``. - image (google.cloud.dialogflow_v2beta1.types.Intent.Message.Image): - Displays an image. - - This field is a member of `oneof`_ ``message``. - quick_replies (google.cloud.dialogflow_v2beta1.types.Intent.Message.QuickReplies): - Displays quick replies. - - This field is a member of `oneof`_ ``message``. - card (google.cloud.dialogflow_v2beta1.types.Intent.Message.Card): - Displays a card. - - This field is a member of `oneof`_ ``message``. - payload (google.protobuf.struct_pb2.Struct): - A custom platform-specific response. - - This field is a member of `oneof`_ ``message``. - simple_responses (google.cloud.dialogflow_v2beta1.types.Intent.Message.SimpleResponses): - Returns a voice or text-only response for - Actions on Google. - - This field is a member of `oneof`_ ``message``. - basic_card (google.cloud.dialogflow_v2beta1.types.Intent.Message.BasicCard): - Displays a basic card for Actions on Google. - - This field is a member of `oneof`_ ``message``. - suggestions (google.cloud.dialogflow_v2beta1.types.Intent.Message.Suggestions): - Displays suggestion chips for Actions on - Google. - - This field is a member of `oneof`_ ``message``. - link_out_suggestion (google.cloud.dialogflow_v2beta1.types.Intent.Message.LinkOutSuggestion): - Displays a link out suggestion chip for - Actions on Google. - - This field is a member of `oneof`_ ``message``. - list_select (google.cloud.dialogflow_v2beta1.types.Intent.Message.ListSelect): - Displays a list card for Actions on Google. - - This field is a member of `oneof`_ ``message``. - carousel_select (google.cloud.dialogflow_v2beta1.types.Intent.Message.CarouselSelect): - Displays a carousel card for Actions on - Google. - - This field is a member of `oneof`_ ``message``. - telephony_play_audio (google.cloud.dialogflow_v2beta1.types.Intent.Message.TelephonyPlayAudio): - Plays audio from a file in Telephony Gateway. - - This field is a member of `oneof`_ ``message``. - telephony_synthesize_speech (google.cloud.dialogflow_v2beta1.types.Intent.Message.TelephonySynthesizeSpeech): - Synthesizes speech in Telephony Gateway. - - This field is a member of `oneof`_ ``message``. - telephony_transfer_call (google.cloud.dialogflow_v2beta1.types.Intent.Message.TelephonyTransferCall): - Transfers the call in Telephony Gateway. - - This field is a member of `oneof`_ ``message``. - rbm_text (google.cloud.dialogflow_v2beta1.types.Intent.Message.RbmText): - Rich Business Messaging (RBM) text response. - RBM allows businesses to send enriched and - branded versions of SMS. See - https://jibe.google.com/business-messaging. - - This field is a member of `oneof`_ ``message``. - rbm_standalone_rich_card (google.cloud.dialogflow_v2beta1.types.Intent.Message.RbmStandaloneCard): - Standalone Rich Business Messaging (RBM) rich - card response. - - This field is a member of `oneof`_ ``message``. - rbm_carousel_rich_card (google.cloud.dialogflow_v2beta1.types.Intent.Message.RbmCarouselCard): - Rich Business Messaging (RBM) carousel rich - card response. - - This field is a member of `oneof`_ ``message``. - browse_carousel_card (google.cloud.dialogflow_v2beta1.types.Intent.Message.BrowseCarouselCard): - Browse carousel card for Actions on Google. - - This field is a member of `oneof`_ ``message``. - table_card (google.cloud.dialogflow_v2beta1.types.Intent.Message.TableCard): - Table card for Actions on Google. - - This field is a member of `oneof`_ ``message``. - media_content (google.cloud.dialogflow_v2beta1.types.Intent.Message.MediaContent): - The media content card for Actions on Google. - - This field is a member of `oneof`_ ``message``. - platform (google.cloud.dialogflow_v2beta1.types.Intent.Message.Platform): - Optional. The platform that this message is - intended for. - """ - class Platform(proto.Enum): - r"""Represents different platforms that a rich message can be - intended for. - - Values: - PLATFORM_UNSPECIFIED (0): - Not specified. - FACEBOOK (1): - Facebook. - SLACK (2): - Slack. - TELEGRAM (3): - Telegram. - KIK (4): - Kik. - SKYPE (5): - Skype. - LINE (6): - Line. - VIBER (7): - Viber. - ACTIONS_ON_GOOGLE (8): - Google Assistant See `Dialogflow webhook - format `__ - TELEPHONY (10): - Telephony Gateway. - GOOGLE_HANGOUTS (11): - Google Hangouts. - """ - PLATFORM_UNSPECIFIED = 0 - FACEBOOK = 1 - SLACK = 2 - TELEGRAM = 3 - KIK = 4 - SKYPE = 5 - LINE = 6 - VIBER = 7 - ACTIONS_ON_GOOGLE = 8 - TELEPHONY = 10 - GOOGLE_HANGOUTS = 11 - - class Text(proto.Message): - r"""The text response message. - - Attributes: - text (MutableSequence[str]): - Optional. The collection of the agent's - responses. - """ - - text: MutableSequence[str] = 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. - accessibility_text (str): - A text description of the image to be used for - accessibility, e.g., screen readers. Required if image_uri - is set for CarouselSelect. - """ - - image_uri: str = proto.Field( - proto.STRING, - number=1, - ) - accessibility_text: str = 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 - quick replies. - quick_replies (MutableSequence[str]): - Optional. The collection of quick replies. - """ - - title: str = proto.Field( - proto.STRING, - number=1, - ) - quick_replies: MutableSequence[str] = proto.RepeatedField( - proto.STRING, - number=2, - ) - - class Card(proto.Message): - r"""The card response message. - - Attributes: - title (str): - Optional. The title of the card. - subtitle (str): - Optional. The subtitle of the card. - image_uri (str): - Optional. The public URI to an image file for - the card. - buttons (MutableSequence[google.cloud.dialogflow_v2beta1.types.Intent.Message.Card.Button]): - Optional. The collection of card buttons. - """ - - class Button(proto.Message): - r"""Optional. Contains information about a button. - - Attributes: - text (str): - Optional. The text to show on the button. - postback (str): - Optional. The text to send back to the - Dialogflow API or a URI to open. - """ - - text: str = proto.Field( - proto.STRING, - number=1, - ) - postback: str = proto.Field( - proto.STRING, - number=2, - ) - - title: str = proto.Field( - proto.STRING, - number=1, - ) - subtitle: str = proto.Field( - proto.STRING, - number=2, - ) - image_uri: str = proto.Field( - proto.STRING, - number=3, - ) - buttons: MutableSequence['Intent.Message.Card.Button'] = 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 - text of the speech output. Mutually exclusive with ssml. - ssml (str): - One of text_to_speech or ssml must be provided. Structured - spoken response to the user in the SSML format. Mutually - exclusive with text_to_speech. - display_text (str): - Optional. The text to display. - """ - - text_to_speech: str = proto.Field( - proto.STRING, - number=1, - ) - ssml: str = proto.Field( - proto.STRING, - number=2, - ) - display_text: str = proto.Field( - proto.STRING, - number=3, - ) - - class SimpleResponses(proto.Message): - r"""The collection of simple response candidates. This message in - ``QueryResult.fulfillment_messages`` and - ``WebhookResponse.fulfillment_messages`` should contain only one - ``SimpleResponse``. - - Attributes: - simple_responses (MutableSequence[google.cloud.dialogflow_v2beta1.types.Intent.Message.SimpleResponse]): - Required. The list of simple responses. - """ - - simple_responses: MutableSequence['Intent.Message.SimpleResponse'] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message='Intent.Message.SimpleResponse', - ) - - class BasicCard(proto.Message): - r"""The basic card message. Useful for displaying information. - - Attributes: - title (str): - Optional. The title of the card. - subtitle (str): - Optional. The subtitle of the card. - formatted_text (str): - Required, unless image is present. The body - text of the card. - image (google.cloud.dialogflow_v2beta1.types.Intent.Message.Image): - Optional. The image for the card. - buttons (MutableSequence[google.cloud.dialogflow_v2beta1.types.Intent.Message.BasicCard.Button]): - Optional. The collection of card buttons. - """ - - 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. - open_uri_action (google.cloud.dialogflow_v2beta1.types.Intent.Message.BasicCard.Button.OpenUriAction): - Required. Action to take when a user taps on - the button. - """ - - class OpenUriAction(proto.Message): - r"""Opens the given URI. - - Attributes: - uri (str): - Required. The HTTP or HTTPS scheme URI. - """ - - uri: str = proto.Field( - proto.STRING, - number=1, - ) - - title: str = proto.Field( - proto.STRING, - number=1, - ) - open_uri_action: 'Intent.Message.BasicCard.Button.OpenUriAction' = proto.Field( - proto.MESSAGE, - number=2, - message='Intent.Message.BasicCard.Button.OpenUriAction', - ) - - title: str = proto.Field( - proto.STRING, - number=1, - ) - subtitle: str = proto.Field( - proto.STRING, - number=2, - ) - formatted_text: str = proto.Field( - proto.STRING, - number=3, - ) - image: 'Intent.Message.Image' = proto.Field( - proto.MESSAGE, - number=4, - message='Intent.Message.Image', - ) - buttons: MutableSequence['Intent.Message.BasicCard.Button'] = proto.RepeatedField( - proto.MESSAGE, - number=5, - message='Intent.Message.BasicCard.Button', - ) - - class Suggestion(proto.Message): - r"""The suggestion chip message that the user can tap to quickly - post a reply to the conversation. - - Attributes: - title (str): - Required. The text shown the in the - suggestion chip. - """ - - title: str = proto.Field( - proto.STRING, - number=1, - ) - - class Suggestions(proto.Message): - r"""The collection of suggestions. - - Attributes: - suggestions (MutableSequence[google.cloud.dialogflow_v2beta1.types.Intent.Message.Suggestion]): - Required. The list of suggested replies. - """ - - suggestions: MutableSequence['Intent.Message.Suggestion'] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message='Intent.Message.Suggestion', - ) - - class LinkOutSuggestion(proto.Message): - r"""The suggestion chip message that allows the user to jump out - to the app or website associated with this agent. - - Attributes: - destination_name (str): - Required. The name of the app or site this - chip is linking to. - uri (str): - Required. The URI of the app or site to open - when the user taps the suggestion chip. - """ - - destination_name: str = proto.Field( - proto.STRING, - number=1, - ) - uri: str = 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. - items (MutableSequence[google.cloud.dialogflow_v2beta1.types.Intent.Message.ListSelect.Item]): - Required. List items. - subtitle (str): - Optional. Subtitle of the list. - """ - - 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 - option. - title (str): - Required. The title of the list item. - description (str): - Optional. The main text describing the item. - image (google.cloud.dialogflow_v2beta1.types.Intent.Message.Image): - Optional. The image to display. - """ - - info: 'Intent.Message.SelectItemInfo' = proto.Field( - proto.MESSAGE, - number=1, - message='Intent.Message.SelectItemInfo', - ) - title: str = proto.Field( - proto.STRING, - number=2, - ) - description: str = proto.Field( - proto.STRING, - number=3, - ) - image: 'Intent.Message.Image' = proto.Field( - proto.MESSAGE, - number=4, - message='Intent.Message.Image', - ) - - title: str = proto.Field( - proto.STRING, - number=1, - ) - items: MutableSequence['Intent.Message.ListSelect.Item'] = proto.RepeatedField( - proto.MESSAGE, - number=2, - message='Intent.Message.ListSelect.Item', - ) - subtitle: str = proto.Field( - proto.STRING, - number=3, - ) - - class CarouselSelect(proto.Message): - r"""The card for presenting a carousel of options to select from. - - Attributes: - items (MutableSequence[google.cloud.dialogflow_v2beta1.types.Intent.Message.CarouselSelect.Item]): - Required. Carousel items. - """ - - 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 - item. - title (str): - Required. Title of the carousel item. - description (str): - Optional. The body text of the card. - image (google.cloud.dialogflow_v2beta1.types.Intent.Message.Image): - Optional. The image to display. - """ - - info: 'Intent.Message.SelectItemInfo' = proto.Field( - proto.MESSAGE, - number=1, - message='Intent.Message.SelectItemInfo', - ) - title: str = proto.Field( - proto.STRING, - number=2, - ) - description: str = proto.Field( - proto.STRING, - number=3, - ) - image: 'Intent.Message.Image' = proto.Field( - proto.MESSAGE, - number=4, - message='Intent.Message.Image', - ) - - items: MutableSequence['Intent.Message.CarouselSelect.Item'] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message='Intent.Message.CarouselSelect.Item', - ) - - class SelectItemInfo(proto.Message): - r"""Additional info about the select item for when it is - triggered in a dialog. - - Attributes: - key (str): - Required. A unique key that will be sent back - to the agent if this response is given. - synonyms (MutableSequence[str]): - Optional. A list of synonyms that can also be - used to trigger this item in dialog. - """ - - key: str = proto.Field( - proto.STRING, - number=1, - ) - synonyms: MutableSequence[str] = 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 - the audio to play, e.g., "gs://bucket/object". The object - must contain a single channel (mono) of linear PCM audio (2 - bytes / sample) at 8kHz. - - This object must be readable by the - ``service-@gcp-sa-dialogflow.iam.gserviceaccount.com`` - service account where is the number of the Telephony Gateway - project (usually the same as the Dialogflow agent project). - If the Google Cloud Storage bucket is in the Telephony - Gateway project, this permission is added by default when - enabling the Dialogflow V2 API. - - For audio from other sources, consider using the - ``TelephonySynthesizeSpeech`` message with SSML. - """ - - audio_uri: str = proto.Field( - proto.STRING, - number=1, - ) - - class TelephonySynthesizeSpeech(proto.Message): - r"""Synthesizes speech and plays back the synthesized audio to the - caller in Telephony Gateway. - - Telephony Gateway takes the synthesizer settings from - ``DetectIntentResponse.output_audio_config`` which can either be set - at request-level or can come from the agent-level synthesizer - config. - - This message has `oneof`_ fields (mutually exclusive fields). - For each oneof, at most one member field can be set at the same time. - Setting any member of the oneof automatically clears all other - members. - - .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields - - Attributes: - text (str): - The raw text to be synthesized. - - This field is a member of `oneof`_ ``source``. - ssml (str): - The SSML to be synthesized. For more information, see - `SSML `__. - - This field is a member of `oneof`_ ``source``. - """ - - text: str = proto.Field( - proto.STRING, - number=1, - oneof='source', - ) - ssml: str = 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 - format `__. - - We currently only allow transferring to US numbers - (+1xxxyyyzzzz). - """ - - phone_number: str = 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 - user. - rbm_suggestion (MutableSequence[google.cloud.dialogflow_v2beta1.types.Intent.Message.RbmSuggestion]): - Optional. One or more suggestions to show to - the user. - """ - - text: str = proto.Field( - proto.STRING, - number=1, - ) - rbm_suggestion: MutableSequence['Intent.Message.RbmSuggestion'] = proto.RepeatedField( - proto.MESSAGE, - number=2, - message='Intent.Message.RbmSuggestion', - ) - - class RbmCarouselCard(proto.Message): - r"""Carousel Rich Business Messaging (RBM) rich card. - - Rich cards allow you to respond to users with more vivid content, - e.g. with media and suggestions. - - If you want to show a single card with more control over the layout, - please use - [RbmStandaloneCard][google.cloud.dialogflow.v2beta1.Intent.Message.RbmStandaloneCard] - instead. - - Attributes: - card_width (google.cloud.dialogflow_v2beta1.types.Intent.Message.RbmCarouselCard.CardWidth): - Required. The width of the cards in the - carousel. - card_contents (MutableSequence[google.cloud.dialogflow_v2beta1.types.Intent.Message.RbmCardContent]): - Required. The cards in the carousel. A - carousel must have at least 2 cards and at most - 10. - """ - class CardWidth(proto.Enum): - r"""The width of the cards in the carousel. - - Values: - CARD_WIDTH_UNSPECIFIED (0): - Not specified. - SMALL (1): - 120 DP. Note that tall media cannot be used. - MEDIUM (2): - 232 DP. - """ - CARD_WIDTH_UNSPECIFIED = 0 - SMALL = 1 - MEDIUM = 2 - - card_width: 'Intent.Message.RbmCarouselCard.CardWidth' = proto.Field( - proto.ENUM, - number=1, - enum='Intent.Message.RbmCarouselCard.CardWidth', - ) - card_contents: MutableSequence['Intent.Message.RbmCardContent'] = proto.RepeatedField( - proto.MESSAGE, - number=2, - message='Intent.Message.RbmCardContent', - ) - - class RbmStandaloneCard(proto.Message): - r"""Standalone Rich Business Messaging (RBM) rich card. - - Rich cards allow you to respond to users with more vivid content, - e.g. with media and suggestions. - - You can group multiple rich cards into one using - [RbmCarouselCard][google.cloud.dialogflow.v2beta1.Intent.Message.RbmCarouselCard] - but carousel cards will give you less control over the card layout. - - Attributes: - card_orientation (google.cloud.dialogflow_v2beta1.types.Intent.Message.RbmStandaloneCard.CardOrientation): - Required. Orientation of the card. - thumbnail_image_alignment (google.cloud.dialogflow_v2beta1.types.Intent.Message.RbmStandaloneCard.ThumbnailImageAlignment): - Required if orientation is horizontal. - Image preview alignment for standalone cards - with horizontal layout. - card_content (google.cloud.dialogflow_v2beta1.types.Intent.Message.RbmCardContent): - Required. Card content. - """ - class CardOrientation(proto.Enum): - r"""Orientation of the card. - - Values: - CARD_ORIENTATION_UNSPECIFIED (0): - Not specified. - HORIZONTAL (1): - Horizontal layout. - VERTICAL (2): - Vertical layout. - """ - CARD_ORIENTATION_UNSPECIFIED = 0 - HORIZONTAL = 1 - VERTICAL = 2 - - class ThumbnailImageAlignment(proto.Enum): - r"""Thumbnail preview alignment for standalone cards with - horizontal layout. - - Values: - THUMBNAIL_IMAGE_ALIGNMENT_UNSPECIFIED (0): - Not specified. - LEFT (1): - Thumbnail preview is left-aligned. - RIGHT (2): - Thumbnail preview is right-aligned. - """ - THUMBNAIL_IMAGE_ALIGNMENT_UNSPECIFIED = 0 - LEFT = 1 - RIGHT = 2 - - card_orientation: 'Intent.Message.RbmStandaloneCard.CardOrientation' = proto.Field( - proto.ENUM, - number=1, - enum='Intent.Message.RbmStandaloneCard.CardOrientation', - ) - thumbnail_image_alignment: 'Intent.Message.RbmStandaloneCard.ThumbnailImageAlignment' = proto.Field( - proto.ENUM, - number=2, - enum='Intent.Message.RbmStandaloneCard.ThumbnailImageAlignment', - ) - card_content: 'Intent.Message.RbmCardContent' = 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 - bytes). - At least one of the title, description or media - must be set. - description (str): - Optional. Description of the card (at most - 2000 bytes). - At least one of the title, description or media - must be set. - media (google.cloud.dialogflow_v2beta1.types.Intent.Message.RbmCardContent.RbmMedia): - Optional. However at least one of the title, - description or media must be set. Media (image, - GIF or a video) to include in the card. - suggestions (MutableSequence[google.cloud.dialogflow_v2beta1.types.Intent.Message.RbmSuggestion]): - Optional. List of suggestions to include in - the card. - """ - - class RbmMedia(proto.Message): - r"""Rich Business Messaging (RBM) Media displayed in Cards The following - media-types are currently supported: - - Image Types - - - image/jpeg - - image/jpg' - - image/gif - - image/png - - Video Types - - - video/h263 - - video/m4v - - video/mp4 - - video/mpeg - - video/mpeg4 - - video/webm - - Attributes: - file_uri (str): - Required. Publicly reachable URI of the file. - The RBM platform determines the MIME type of the - file from the content-type field in the HTTP - headers when the platform fetches the file. The - content-type field must be present and accurate - in the HTTP response from the URL. - thumbnail_uri (str): - Optional. Publicly reachable URI of the - thumbnail.If you don't provide a thumbnail URI, - the RBM platform displays a blank placeholder - thumbnail until the user's device downloads the - file. Depending on the user's setting, the file - may not download automatically and may require - the user to tap a download button. - height (google.cloud.dialogflow_v2beta1.types.Intent.Message.RbmCardContent.RbmMedia.Height): - Required for cards with vertical orientation. - The height of the media within a rich card with - a vertical layout. For a standalone card with - horizontal layout, height is not customizable, - and this field is ignored. - """ - class Height(proto.Enum): - r"""Media height - - Values: - HEIGHT_UNSPECIFIED (0): - Not specified. - SHORT (1): - 112 DP. - MEDIUM (2): - 168 DP. - TALL (3): - 264 DP. Not available for rich card carousels - when the card width is set to small. - """ - HEIGHT_UNSPECIFIED = 0 - SHORT = 1 - MEDIUM = 2 - TALL = 3 - - file_uri: str = proto.Field( - proto.STRING, - number=1, - ) - thumbnail_uri: str = proto.Field( - proto.STRING, - number=2, - ) - height: 'Intent.Message.RbmCardContent.RbmMedia.Height' = proto.Field( - proto.ENUM, - number=3, - enum='Intent.Message.RbmCardContent.RbmMedia.Height', - ) - - title: str = proto.Field( - proto.STRING, - number=1, - ) - description: str = proto.Field( - proto.STRING, - number=2, - ) - media: 'Intent.Message.RbmCardContent.RbmMedia' = proto.Field( - proto.MESSAGE, - number=3, - message='Intent.Message.RbmCardContent.RbmMedia', - ) - suggestions: MutableSequence['Intent.Message.RbmSuggestion'] = proto.RepeatedField( - proto.MESSAGE, - number=4, - message='Intent.Message.RbmSuggestion', - ) - - class RbmSuggestion(proto.Message): - r"""Rich Business Messaging (RBM) suggestion. Suggestions allow - user to easily select/click a predefined response or perform an - action (like opening a web uri). - - This message has `oneof`_ fields (mutually exclusive fields). - For each oneof, at most one member field can be set at the same time. - Setting any member of the oneof automatically clears all other - members. - - .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields - - Attributes: - reply (google.cloud.dialogflow_v2beta1.types.Intent.Message.RbmSuggestedReply): - Predefined replies for user to select instead - of typing - - This field is a member of `oneof`_ ``suggestion``. - action (google.cloud.dialogflow_v2beta1.types.Intent.Message.RbmSuggestedAction): - Predefined client side actions that user can - choose - - This field is a member of `oneof`_ ``suggestion``. - """ - - reply: 'Intent.Message.RbmSuggestedReply' = proto.Field( - proto.MESSAGE, - number=1, - oneof='suggestion', - message='Intent.Message.RbmSuggestedReply', - ) - action: 'Intent.Message.RbmSuggestedAction' = proto.Field( - proto.MESSAGE, - number=2, - oneof='suggestion', - message='Intent.Message.RbmSuggestedAction', - ) - - class RbmSuggestedReply(proto.Message): - r"""Rich Business Messaging (RBM) suggested reply that the user - can click instead of typing in their own response. - - Attributes: - text (str): - Suggested reply text. - postback_data (str): - Opaque payload that the Dialogflow receives - in a user event when the user taps the suggested - reply. This data will be also forwarded to - webhook to allow performing custom business - logic. - """ - - text: str = proto.Field( - proto.STRING, - number=1, - ) - postback_data: str = proto.Field( - proto.STRING, - number=2, - ) - - class RbmSuggestedAction(proto.Message): - r"""Rich Business Messaging (RBM) suggested client-side action - that the user can choose from the card. - - This message has `oneof`_ fields (mutually exclusive fields). - For each oneof, at most one member field can be set at the same time. - Setting any member of the oneof automatically clears all other - members. - - .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields - - Attributes: - text (str): - Text to display alongside the action. - postback_data (str): - Opaque payload that the Dialogflow receives - in a user event when the user taps the suggested - action. This data will be also forwarded to - webhook to allow performing custom business - logic. - dial (google.cloud.dialogflow_v2beta1.types.Intent.Message.RbmSuggestedAction.RbmSuggestedActionDial): - Suggested client side action: Dial a phone - number - - This field is a member of `oneof`_ ``action``. - open_url (google.cloud.dialogflow_v2beta1.types.Intent.Message.RbmSuggestedAction.RbmSuggestedActionOpenUri): - Suggested client side action: Open a URI on - device - - This field is a member of `oneof`_ ``action``. - share_location (google.cloud.dialogflow_v2beta1.types.Intent.Message.RbmSuggestedAction.RbmSuggestedActionShareLocation): - Suggested client side action: Share user - location - - This field is a member of `oneof`_ ``action``. - """ - - class RbmSuggestedActionDial(proto.Message): - r"""Opens the user's default dialer app with the specified phone - number but does not dial automatically. - - Attributes: - phone_number (str): - Required. The phone number to fill in the default dialer - app. This field should be in - `E.164 `__ format. An - example of a correctly formatted phone number: +15556767888. - """ - - phone_number: str = proto.Field( - proto.STRING, - number=1, - ) - - class RbmSuggestedActionOpenUri(proto.Message): - r"""Opens the user's default web browser app to the specified uri - If the user has an app installed that is - registered as the default handler for the URL, then this app - will be opened instead, and its icon will be used in the - suggested action UI. - - Attributes: - uri (str): - Required. The uri to open on the user device - """ - - uri: str = 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: str = proto.Field( - proto.STRING, - number=1, - ) - postback_data: str = proto.Field( - proto.STRING, - number=2, - ) - dial: 'Intent.Message.RbmSuggestedAction.RbmSuggestedActionDial' = proto.Field( - proto.MESSAGE, - number=3, - oneof='action', - message='Intent.Message.RbmSuggestedAction.RbmSuggestedActionDial', - ) - open_url: 'Intent.Message.RbmSuggestedAction.RbmSuggestedActionOpenUri' = proto.Field( - proto.MESSAGE, - number=4, - oneof='action', - message='Intent.Message.RbmSuggestedAction.RbmSuggestedActionOpenUri', - ) - share_location: 'Intent.Message.RbmSuggestedAction.RbmSuggestedActionShareLocation' = proto.Field( - proto.MESSAGE, - number=5, - oneof='action', - message='Intent.Message.RbmSuggestedAction.RbmSuggestedActionShareLocation', - ) - - 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 - (ie "audio"). - media_objects (MutableSequence[google.cloud.dialogflow_v2beta1.types.Intent.Message.MediaContent.ResponseMediaObject]): - Required. List of media objects. - """ - class ResponseMediaType(proto.Enum): - r"""Format of response media type. - - Values: - RESPONSE_MEDIA_TYPE_UNSPECIFIED (0): - Unspecified. - AUDIO (1): - Response media type is audio. - """ - RESPONSE_MEDIA_TYPE_UNSPECIFIED = 0 - AUDIO = 1 - - class ResponseMediaObject(proto.Message): - r"""Response media object for media content card. - - This message has `oneof`_ fields (mutually exclusive fields). - For each oneof, at most one member field can be set at the same time. - Setting any member of the oneof automatically clears all other - members. - - .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields - - Attributes: - name (str): - Required. Name of media card. - description (str): - Optional. Description of media card. - large_image (google.cloud.dialogflow_v2beta1.types.Intent.Message.Image): - Optional. Image to display above media - content. - - This field is a member of `oneof`_ ``image``. - icon (google.cloud.dialogflow_v2beta1.types.Intent.Message.Image): - Optional. Icon to display above media - content. - - This field is a member of `oneof`_ ``image``. - content_url (str): - Required. Url where the media is stored. - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - description: str = proto.Field( - proto.STRING, - number=2, - ) - large_image: 'Intent.Message.Image' = proto.Field( - proto.MESSAGE, - number=3, - oneof='image', - message='Intent.Message.Image', - ) - icon: 'Intent.Message.Image' = proto.Field( - proto.MESSAGE, - number=4, - oneof='image', - message='Intent.Message.Image', - ) - content_url: str = proto.Field( - proto.STRING, - number=5, - ) - - media_type: 'Intent.Message.MediaContent.ResponseMediaType' = proto.Field( - proto.ENUM, - number=1, - enum='Intent.Message.MediaContent.ResponseMediaType', - ) - media_objects: MutableSequence['Intent.Message.MediaContent.ResponseMediaObject'] = proto.RepeatedField( - proto.MESSAGE, - number=2, - message='Intent.Message.MediaContent.ResponseMediaObject', - ) - - class BrowseCarouselCard(proto.Message): - r"""Browse Carousel Card for Actions on Google. - https://developers.google.com/actions/assistant/responses#browsing_carousel - - Attributes: - items (MutableSequence[google.cloud.dialogflow_v2beta1.types.Intent.Message.BrowseCarouselCard.BrowseCarouselCardItem]): - Required. List of items in the Browse - Carousel Card. Minimum of two items, maximum of - ten. - image_display_options (google.cloud.dialogflow_v2beta1.types.Intent.Message.BrowseCarouselCard.ImageDisplayOptions): - Optional. Settings for displaying the image. Applies to - every image in - [items][google.cloud.dialogflow.v2beta1.Intent.Message.BrowseCarouselCard.items]. - """ - class ImageDisplayOptions(proto.Enum): - r"""Image display options for Actions on Google. This should be - used for when the image's aspect ratio does not match the image - container's aspect ratio. - - Values: - IMAGE_DISPLAY_OPTIONS_UNSPECIFIED (0): - Fill the gaps between the image and the image - container with gray bars. - GRAY (1): - Fill the gaps between the image and the image - container with gray bars. - WHITE (2): - Fill the gaps between the image and the image - container with white bars. - CROPPED (3): - Image is scaled such that the image width and - height match or exceed the container dimensions. - This may crop the top and bottom of the image if - the scaled image height is greater than the - container height, or crop the left and right of - the image if the scaled image width is greater - than the container width. This is similar to - "Zoom Mode" on a widescreen TV when playing a - 4:3 video. - BLURRED_BACKGROUND (4): - Pad the gaps between image and image frame - with a blurred copy of the same image. - """ - IMAGE_DISPLAY_OPTIONS_UNSPECIFIED = 0 - GRAY = 1 - WHITE = 2 - CROPPED = 3 - BLURRED_BACKGROUND = 4 - - 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. - title (str): - Required. Title of the carousel item. Maximum - of two lines of text. - description (str): - Optional. Description of the carousel item. - Maximum of four lines of text. - image (google.cloud.dialogflow_v2beta1.types.Intent.Message.Image): - Optional. Hero image for the carousel item. - footer (str): - Optional. Text that appears at the bottom of - the Browse Carousel Card. Maximum of one line of - text. - """ - - class OpenUrlAction(proto.Message): - r"""Actions on Google action to open a given url. - - Attributes: - url (str): - Required. URL - url_type_hint (google.cloud.dialogflow_v2beta1.types.Intent.Message.BrowseCarouselCard.BrowseCarouselCardItem.OpenUrlAction.UrlTypeHint): - Optional. Specifies the type of viewer that - is used when opening the URL. Defaults to - opening via web browser. - """ - class UrlTypeHint(proto.Enum): - r"""Type of the URI. - - Values: - URL_TYPE_HINT_UNSPECIFIED (0): - Unspecified - AMP_ACTION (1): - Url would be an amp action - AMP_CONTENT (2): - URL that points directly to AMP content, or - to a canonical URL which refers to AMP content - via . - """ - URL_TYPE_HINT_UNSPECIFIED = 0 - AMP_ACTION = 1 - AMP_CONTENT = 2 - - url: str = proto.Field( - proto.STRING, - number=1, - ) - url_type_hint: 'Intent.Message.BrowseCarouselCard.BrowseCarouselCardItem.OpenUrlAction.UrlTypeHint' = proto.Field( - proto.ENUM, - number=3, - enum='Intent.Message.BrowseCarouselCard.BrowseCarouselCardItem.OpenUrlAction.UrlTypeHint', - ) - - open_uri_action: 'Intent.Message.BrowseCarouselCard.BrowseCarouselCardItem.OpenUrlAction' = proto.Field( - proto.MESSAGE, - number=1, - message='Intent.Message.BrowseCarouselCard.BrowseCarouselCardItem.OpenUrlAction', - ) - title: str = proto.Field( - proto.STRING, - number=2, - ) - description: str = proto.Field( - proto.STRING, - number=3, - ) - image: 'Intent.Message.Image' = proto.Field( - proto.MESSAGE, - number=4, - message='Intent.Message.Image', - ) - footer: str = proto.Field( - proto.STRING, - number=5, - ) - - items: MutableSequence['Intent.Message.BrowseCarouselCard.BrowseCarouselCardItem'] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message='Intent.Message.BrowseCarouselCard.BrowseCarouselCardItem', - ) - image_display_options: 'Intent.Message.BrowseCarouselCard.ImageDisplayOptions' = proto.Field( - proto.ENUM, - number=2, - enum='Intent.Message.BrowseCarouselCard.ImageDisplayOptions', - ) - - class TableCard(proto.Message): - r"""Table card for Actions on Google. - - Attributes: - title (str): - Required. Title of the card. - subtitle (str): - Optional. Subtitle to the title. - image (google.cloud.dialogflow_v2beta1.types.Intent.Message.Image): - Optional. Image which should be displayed on - the card. - column_properties (MutableSequence[google.cloud.dialogflow_v2beta1.types.Intent.Message.ColumnProperties]): - Optional. Display properties for the columns - in this table. - rows (MutableSequence[google.cloud.dialogflow_v2beta1.types.Intent.Message.TableCardRow]): - Optional. Rows in this table of data. - buttons (MutableSequence[google.cloud.dialogflow_v2beta1.types.Intent.Message.BasicCard.Button]): - Optional. List of buttons for the card. - """ - - title: str = proto.Field( - proto.STRING, - number=1, - ) - subtitle: str = proto.Field( - proto.STRING, - number=2, - ) - image: 'Intent.Message.Image' = proto.Field( - proto.MESSAGE, - number=3, - message='Intent.Message.Image', - ) - column_properties: MutableSequence['Intent.Message.ColumnProperties'] = proto.RepeatedField( - proto.MESSAGE, - number=4, - message='Intent.Message.ColumnProperties', - ) - rows: MutableSequence['Intent.Message.TableCardRow'] = proto.RepeatedField( - proto.MESSAGE, - number=5, - message='Intent.Message.TableCardRow', - ) - buttons: MutableSequence['Intent.Message.BasicCard.Button'] = proto.RepeatedField( - proto.MESSAGE, - number=6, - message='Intent.Message.BasicCard.Button', - ) - - class ColumnProperties(proto.Message): - r"""Column properties for - [TableCard][google.cloud.dialogflow.v2beta1.Intent.Message.TableCard]. - - Attributes: - header (str): - Required. Column heading. - horizontal_alignment (google.cloud.dialogflow_v2beta1.types.Intent.Message.ColumnProperties.HorizontalAlignment): - Optional. Defines text alignment for all - cells in this column. - """ - class HorizontalAlignment(proto.Enum): - r"""Text alignments within a cell. - - Values: - HORIZONTAL_ALIGNMENT_UNSPECIFIED (0): - Text is aligned to the leading edge of the - column. - LEADING (1): - Text is aligned to the leading edge of the - column. - CENTER (2): - Text is centered in the column. - TRAILING (3): - Text is aligned to the trailing edge of the - column. - """ - HORIZONTAL_ALIGNMENT_UNSPECIFIED = 0 - LEADING = 1 - CENTER = 2 - TRAILING = 3 - - header: str = proto.Field( - proto.STRING, - number=1, - ) - horizontal_alignment: 'Intent.Message.ColumnProperties.HorizontalAlignment' = proto.Field( - proto.ENUM, - number=2, - enum='Intent.Message.ColumnProperties.HorizontalAlignment', - ) - - class TableCardRow(proto.Message): - r"""Row of - [TableCard][google.cloud.dialogflow.v2beta1.Intent.Message.TableCard]. - - Attributes: - cells (MutableSequence[google.cloud.dialogflow_v2beta1.types.Intent.Message.TableCardCell]): - Optional. List of cells that make up this - row. - divider_after (bool): - Optional. Whether to add a visual divider - after this row. - """ - - cells: MutableSequence['Intent.Message.TableCardCell'] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message='Intent.Message.TableCardCell', - ) - divider_after: bool = proto.Field( - proto.BOOL, - number=2, - ) - - class TableCardCell(proto.Message): - r"""Cell of - [TableCardRow][google.cloud.dialogflow.v2beta1.Intent.Message.TableCardRow]. - - Attributes: - text (str): - Required. Text in this cell. - """ - - text: str = proto.Field( - proto.STRING, - number=1, - ) - - text: 'Intent.Message.Text' = proto.Field( - proto.MESSAGE, - number=1, - oneof='message', - message='Intent.Message.Text', - ) - image: 'Intent.Message.Image' = proto.Field( - proto.MESSAGE, - number=2, - oneof='message', - message='Intent.Message.Image', - ) - quick_replies: 'Intent.Message.QuickReplies' = proto.Field( - proto.MESSAGE, - number=3, - oneof='message', - message='Intent.Message.QuickReplies', - ) - card: 'Intent.Message.Card' = proto.Field( - proto.MESSAGE, - number=4, - oneof='message', - message='Intent.Message.Card', - ) - payload: struct_pb2.Struct = proto.Field( - proto.MESSAGE, - number=5, - oneof='message', - message=struct_pb2.Struct, - ) - simple_responses: 'Intent.Message.SimpleResponses' = proto.Field( - proto.MESSAGE, - number=7, - oneof='message', - message='Intent.Message.SimpleResponses', - ) - basic_card: 'Intent.Message.BasicCard' = proto.Field( - proto.MESSAGE, - number=8, - oneof='message', - message='Intent.Message.BasicCard', - ) - suggestions: 'Intent.Message.Suggestions' = proto.Field( - proto.MESSAGE, - number=9, - oneof='message', - message='Intent.Message.Suggestions', - ) - link_out_suggestion: 'Intent.Message.LinkOutSuggestion' = proto.Field( - proto.MESSAGE, - number=10, - oneof='message', - message='Intent.Message.LinkOutSuggestion', - ) - list_select: 'Intent.Message.ListSelect' = proto.Field( - proto.MESSAGE, - number=11, - oneof='message', - message='Intent.Message.ListSelect', - ) - carousel_select: 'Intent.Message.CarouselSelect' = proto.Field( - proto.MESSAGE, - number=12, - oneof='message', - message='Intent.Message.CarouselSelect', - ) - telephony_play_audio: 'Intent.Message.TelephonyPlayAudio' = proto.Field( - proto.MESSAGE, - number=13, - oneof='message', - message='Intent.Message.TelephonyPlayAudio', - ) - telephony_synthesize_speech: 'Intent.Message.TelephonySynthesizeSpeech' = proto.Field( - proto.MESSAGE, - number=14, - oneof='message', - message='Intent.Message.TelephonySynthesizeSpeech', - ) - telephony_transfer_call: 'Intent.Message.TelephonyTransferCall' = proto.Field( - proto.MESSAGE, - number=15, - oneof='message', - message='Intent.Message.TelephonyTransferCall', - ) - rbm_text: 'Intent.Message.RbmText' = proto.Field( - proto.MESSAGE, - number=18, - oneof='message', - message='Intent.Message.RbmText', - ) - rbm_standalone_rich_card: 'Intent.Message.RbmStandaloneCard' = proto.Field( - proto.MESSAGE, - number=19, - oneof='message', - message='Intent.Message.RbmStandaloneCard', - ) - rbm_carousel_rich_card: 'Intent.Message.RbmCarouselCard' = proto.Field( - proto.MESSAGE, - number=20, - oneof='message', - message='Intent.Message.RbmCarouselCard', - ) - browse_carousel_card: 'Intent.Message.BrowseCarouselCard' = proto.Field( - proto.MESSAGE, - number=22, - oneof='message', - message='Intent.Message.BrowseCarouselCard', - ) - table_card: 'Intent.Message.TableCard' = proto.Field( - proto.MESSAGE, - number=23, - oneof='message', - message='Intent.Message.TableCard', - ) - media_content: 'Intent.Message.MediaContent' = proto.Field( - proto.MESSAGE, - number=24, - oneof='message', - message='Intent.Message.MediaContent', - ) - platform: 'Intent.Message.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: - ``projects//agent/intents/``. - parent_followup_intent_name (str): - The unique identifier of the followup intent's parent. - Format: ``projects//agent/intents/``. - """ - - followup_intent_name: str = proto.Field( - proto.STRING, - number=1, - ) - parent_followup_intent_name: str = proto.Field( - proto.STRING, - number=2, - ) - - name: str = proto.Field( - proto.STRING, - number=1, - ) - display_name: str = proto.Field( - proto.STRING, - number=2, - ) - webhook_state: WebhookState = proto.Field( - proto.ENUM, - number=6, - enum=WebhookState, - ) - priority: int = proto.Field( - proto.INT32, - number=3, - ) - is_fallback: bool = proto.Field( - proto.BOOL, - number=4, - ) - ml_enabled: bool = proto.Field( - proto.BOOL, - number=5, - ) - ml_disabled: bool = proto.Field( - proto.BOOL, - number=19, - ) - live_agent_handoff: bool = proto.Field( - proto.BOOL, - number=20, - ) - end_interaction: bool = proto.Field( - proto.BOOL, - number=21, - ) - input_context_names: MutableSequence[str] = proto.RepeatedField( - proto.STRING, - number=7, - ) - events: MutableSequence[str] = proto.RepeatedField( - proto.STRING, - number=8, - ) - training_phrases: MutableSequence[TrainingPhrase] = proto.RepeatedField( - proto.MESSAGE, - number=9, - message=TrainingPhrase, - ) - action: str = proto.Field( - proto.STRING, - number=10, - ) - output_contexts: MutableSequence[context.Context] = proto.RepeatedField( - proto.MESSAGE, - number=11, - message=context.Context, - ) - reset_contexts: bool = proto.Field( - proto.BOOL, - number=12, - ) - parameters: MutableSequence[Parameter] = proto.RepeatedField( - proto.MESSAGE, - number=13, - message=Parameter, - ) - messages: MutableSequence[Message] = proto.RepeatedField( - proto.MESSAGE, - number=14, - message=Message, - ) - default_response_platforms: MutableSequence[Message.Platform] = proto.RepeatedField( - proto.ENUM, - number=15, - enum=Message.Platform, - ) - root_followup_intent_name: str = proto.Field( - proto.STRING, - number=16, - ) - parent_followup_intent_name: str = proto.Field( - proto.STRING, - number=17, - ) - followup_intent_info: MutableSequence[FollowupIntentInfo] = proto.RepeatedField( - proto.MESSAGE, - number=18, - message=FollowupIntentInfo, - ) - - -class ListIntentsRequest(proto.Message): - r"""The request message for - [Intents.ListIntents][google.cloud.dialogflow.v2beta1.Intents.ListIntents]. - - Attributes: - parent (str): - Required. The agent to list all intents from. Format: - ``projects//agent`` or - ``projects//locations//agent``. - - Alternatively, you can specify the environment to list - intents for. Format: - ``projects//agent/environments/`` - or - ``projects//locations//agent/environments/``. - Note: training phrases of the intents will not be returned - for non-draft environment. - language_code (str): - Optional. The language used to access language-specific - data. If not specified, the agent's default language is - used. For more information, see `Multilingual intent and - entity - data `__. - intent_view (google.cloud.dialogflow_v2beta1.types.IntentView): - Optional. The resource view to apply to the - returned intent. - 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: str = proto.Field( - proto.STRING, - number=1, - ) - language_code: str = proto.Field( - proto.STRING, - number=2, - ) - intent_view: 'IntentView' = proto.Field( - proto.ENUM, - number=3, - enum='IntentView', - ) - page_size: int = proto.Field( - proto.INT32, - number=4, - ) - page_token: str = proto.Field( - proto.STRING, - number=5, - ) - - -class ListIntentsResponse(proto.Message): - r"""The response message for - [Intents.ListIntents][google.cloud.dialogflow.v2beta1.Intents.ListIntents]. - - Attributes: - intents (MutableSequence[google.cloud.dialogflow_v2beta1.types.Intent]): - The list of agent intents. 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 - - intents: MutableSequence['Intent'] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message='Intent', - ) - next_page_token: str = proto.Field( - proto.STRING, - number=2, - ) - - -class GetIntentRequest(proto.Message): - r"""The request message for - [Intents.GetIntent][google.cloud.dialogflow.v2beta1.Intents.GetIntent]. - - Attributes: - name (str): - Required. The name of the intent. Supported formats: - - - ``projects//agent/intents/`` - - ``projects//locations//agent/intents/`` - language_code (str): - Optional. The language used to access language-specific - data. If not specified, the agent's default language is - used. For more information, see `Multilingual intent and - entity - data `__. - intent_view (google.cloud.dialogflow_v2beta1.types.IntentView): - Optional. The resource view to apply to the - returned intent. - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - language_code: str = proto.Field( - proto.STRING, - number=2, - ) - intent_view: 'IntentView' = proto.Field( - proto.ENUM, - number=3, - enum='IntentView', - ) - - -class CreateIntentRequest(proto.Message): - r"""The request message for - [Intents.CreateIntent][google.cloud.dialogflow.v2beta1.Intents.CreateIntent]. - - Attributes: - parent (str): - Required. The agent to create a intent for. Supported - formats: - - - ``projects//agent`` - - ``projects//locations//agent`` - intent (google.cloud.dialogflow_v2beta1.types.Intent): - Required. The intent to create. - language_code (str): - Optional. The language used to access language-specific - data. If not specified, the agent's default language is - used. For more information, see `Multilingual intent and - entity - data `__. - intent_view (google.cloud.dialogflow_v2beta1.types.IntentView): - Optional. The resource view to apply to the - returned intent. - """ - - parent: str = proto.Field( - proto.STRING, - number=1, - ) - intent: 'Intent' = proto.Field( - proto.MESSAGE, - number=2, - message='Intent', - ) - language_code: str = proto.Field( - proto.STRING, - number=3, - ) - intent_view: 'IntentView' = proto.Field( - proto.ENUM, - number=4, - enum='IntentView', - ) - - -class UpdateIntentRequest(proto.Message): - r"""The request message for - [Intents.UpdateIntent][google.cloud.dialogflow.v2beta1.Intents.UpdateIntent]. - - Attributes: - intent (google.cloud.dialogflow_v2beta1.types.Intent): - Required. The intent to update. - language_code (str): - Optional. The language used to access language-specific - data. If not specified, the agent's default language is - used. For more information, see `Multilingual intent and - entity - data `__. - update_mask (google.protobuf.field_mask_pb2.FieldMask): - Optional. The mask to control which fields - get updated. - intent_view (google.cloud.dialogflow_v2beta1.types.IntentView): - Optional. The resource view to apply to the - returned intent. - """ - - intent: 'Intent' = proto.Field( - proto.MESSAGE, - number=1, - message='Intent', - ) - language_code: str = proto.Field( - proto.STRING, - number=2, - ) - update_mask: field_mask_pb2.FieldMask = proto.Field( - proto.MESSAGE, - number=3, - message=field_mask_pb2.FieldMask, - ) - intent_view: 'IntentView' = proto.Field( - proto.ENUM, - number=4, - enum='IntentView', - ) - - -class DeleteIntentRequest(proto.Message): - r"""The request message for - [Intents.DeleteIntent][google.cloud.dialogflow.v2beta1.Intents.DeleteIntent]. - - Attributes: - name (str): - Required. The name of the intent to delete. If this intent - has direct or indirect followup intents, we also delete - them. - - Supported formats: - - - ``projects//agent/intents/`` - - ``projects//locations//agent/intents/`` - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - - -class BatchUpdateIntentsRequest(proto.Message): - r"""The request message for - [Intents.BatchUpdateIntents][google.cloud.dialogflow.v2beta1.Intents.BatchUpdateIntents]. - - This message has `oneof`_ fields (mutually exclusive fields). - For each oneof, at most one member field can be set at the same time. - Setting any member of the oneof automatically clears all other - members. - - .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields - - Attributes: - parent (str): - Required. The name of the agent to update or create intents - in. Supported formats: - - - ``projects//agent`` - - ``projects//locations//agent`` - intent_batch_uri (str): - The URI to a Google Cloud Storage file - containing intents to update or create. The file - format can either be a serialized proto (of - IntentBatch type) or JSON object. Note: The URI - must start with "gs://". - - This field is a member of `oneof`_ ``intent_batch``. - intent_batch_inline (google.cloud.dialogflow_v2beta1.types.IntentBatch): - The collection of intents to update or - create. - - This field is a member of `oneof`_ ``intent_batch``. - language_code (str): - Optional. The language used to access language-specific - data. If not specified, the agent's default language is - used. For more information, see `Multilingual intent and - entity - data `__. - update_mask (google.protobuf.field_mask_pb2.FieldMask): - Optional. The mask to control which fields - get updated. - intent_view (google.cloud.dialogflow_v2beta1.types.IntentView): - Optional. The resource view to apply to the - returned intent. - """ - - parent: str = proto.Field( - proto.STRING, - number=1, - ) - intent_batch_uri: str = proto.Field( - proto.STRING, - number=2, - oneof='intent_batch', - ) - intent_batch_inline: 'IntentBatch' = proto.Field( - proto.MESSAGE, - number=3, - oneof='intent_batch', - message='IntentBatch', - ) - language_code: str = proto.Field( - proto.STRING, - number=4, - ) - update_mask: field_mask_pb2.FieldMask = proto.Field( - proto.MESSAGE, - number=5, - message=field_mask_pb2.FieldMask, - ) - intent_view: 'IntentView' = proto.Field( - proto.ENUM, - number=6, - enum='IntentView', - ) - - -class BatchUpdateIntentsResponse(proto.Message): - r"""The response message for - [Intents.BatchUpdateIntents][google.cloud.dialogflow.v2beta1.Intents.BatchUpdateIntents]. - - Attributes: - intents (MutableSequence[google.cloud.dialogflow_v2beta1.types.Intent]): - The collection of updated or created intents. - """ - - intents: MutableSequence['Intent'] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message='Intent', - ) - - -class BatchDeleteIntentsRequest(proto.Message): - r"""The request message for - [Intents.BatchDeleteIntents][google.cloud.dialogflow.v2beta1.Intents.BatchDeleteIntents]. - - Attributes: - parent (str): - Required. The name of the agent to delete all entities types - for. Supported formats: - - - ``projects//agent`` - - ``projects//locations//agent`` - intents (MutableSequence[google.cloud.dialogflow_v2beta1.types.Intent]): - Required. The collection of intents to delete. Only intent - ``name`` must be filled in. - """ - - parent: str = proto.Field( - proto.STRING, - number=1, - ) - intents: MutableSequence['Intent'] = 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 (MutableSequence[google.cloud.dialogflow_v2beta1.types.Intent]): - A collection of intents. - """ - - intents: MutableSequence['Intent'] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message='Intent', - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/types/knowledge_base.py b/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/types/knowledge_base.py deleted file mode 100644 index 8cfc17220..000000000 --- a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/types/knowledge_base.py +++ /dev/null @@ -1,261 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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 __future__ import annotations - -from typing import MutableMapping, MutableSequence - -import proto # type: ignore - -from google.protobuf import field_mask_pb2 # type: ignore - - -__protobuf__ = proto.module( - package='google.cloud.dialogflow.v2beta1', - manifest={ - 'KnowledgeBase', - 'ListKnowledgeBasesRequest', - 'ListKnowledgeBasesResponse', - 'GetKnowledgeBaseRequest', - 'CreateKnowledgeBaseRequest', - 'DeleteKnowledgeBaseRequest', - 'UpdateKnowledgeBaseRequest', - }, -) - - -class KnowledgeBase(proto.Message): - r"""A knowledge base represents a collection of knowledge documents that - you provide to Dialogflow. Your knowledge documents contain - information that may be useful during conversations with end-users. - Some Dialogflow features use knowledge bases when looking for a - response to an end-user input. - - For more information, see the `knowledge base - guide `__. - - Note: The ``projects.agent.knowledgeBases`` resource is deprecated; - only use ``projects.knowledgeBases``. - - Attributes: - name (str): - The knowledge base resource name. The name must be empty - when creating a knowledge base. Format: - ``projects//locations//knowledgeBases/``. - display_name (str): - Required. The display name of the knowledge - base. The name must be 1024 bytes or less; - otherwise, the creation request fails. - language_code (str): - Language which represents the KnowledgeBase. - When the KnowledgeBase is created/updated, this - is populated for all non en-us languages. If not - populated, the default language en-us applies. - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - display_name: str = proto.Field( - proto.STRING, - number=2, - ) - language_code: str = proto.Field( - proto.STRING, - number=4, - ) - - -class ListKnowledgeBasesRequest(proto.Message): - r"""Request message for - [KnowledgeBases.ListKnowledgeBases][google.cloud.dialogflow.v2beta1.KnowledgeBases.ListKnowledgeBases]. - - Attributes: - parent (str): - Required. The project to list of knowledge bases for. - Format: ``projects//locations/``. - page_size (int): - The maximum number of items to return in a - single page. By default 10 and at most 100. - page_token (str): - The next_page_token value returned from a previous list - request. - filter (str): - The filter expression used to filter knowledge bases - returned by the list method. The expression has the - following syntax: - - [AND ] ... - - The following fields and operators are supported: - - - display_name with has(:) operator - - language_code with equals(=) operator - - Examples: - - - 'language_code=en-us' matches knowledge bases with en-us - language code. - - 'display_name:articles' matches knowledge bases whose - display name contains "articles". - - 'display_name:"Best Articles"' matches knowledge bases - whose display name contains "Best Articles". - - 'language_code=en-gb AND display_name=articles' matches - all knowledge bases whose display name contains - "articles" and whose language code is "en-gb". - - Note: An empty filter string (i.e. "") is a no-op and will - result in no filtering. - - For more information about filtering, see `API - Filtering `__. - """ - - parent: str = proto.Field( - proto.STRING, - number=1, - ) - page_size: int = proto.Field( - proto.INT32, - number=2, - ) - page_token: str = proto.Field( - proto.STRING, - number=3, - ) - filter: str = proto.Field( - proto.STRING, - number=4, - ) - - -class ListKnowledgeBasesResponse(proto.Message): - r"""Response message for - [KnowledgeBases.ListKnowledgeBases][google.cloud.dialogflow.v2beta1.KnowledgeBases.ListKnowledgeBases]. - - Attributes: - knowledge_bases (MutableSequence[google.cloud.dialogflow_v2beta1.types.KnowledgeBase]): - The list of knowledge bases. - 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 - - knowledge_bases: MutableSequence['KnowledgeBase'] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message='KnowledgeBase', - ) - next_page_token: str = proto.Field( - proto.STRING, - number=2, - ) - - -class GetKnowledgeBaseRequest(proto.Message): - r"""Request message for - [KnowledgeBases.GetKnowledgeBase][google.cloud.dialogflow.v2beta1.KnowledgeBases.GetKnowledgeBase]. - - Attributes: - name (str): - Required. The name of the knowledge base to retrieve. Format - ``projects//locations//knowledgeBases/``. - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - - -class CreateKnowledgeBaseRequest(proto.Message): - r"""Request message for - [KnowledgeBases.CreateKnowledgeBase][google.cloud.dialogflow.v2beta1.KnowledgeBases.CreateKnowledgeBase]. - - Attributes: - parent (str): - Required. The project to create a knowledge base for. - Format: ``projects//locations/``. - knowledge_base (google.cloud.dialogflow_v2beta1.types.KnowledgeBase): - Required. The knowledge base to create. - """ - - parent: str = proto.Field( - proto.STRING, - number=1, - ) - knowledge_base: 'KnowledgeBase' = proto.Field( - proto.MESSAGE, - number=2, - message='KnowledgeBase', - ) - - -class DeleteKnowledgeBaseRequest(proto.Message): - r"""Request message for - [KnowledgeBases.DeleteKnowledgeBase][google.cloud.dialogflow.v2beta1.KnowledgeBases.DeleteKnowledgeBase]. - - Attributes: - name (str): - Required. The name of the knowledge base to delete. Format: - ``projects//locations//knowledgeBases/``. - force (bool): - Optional. Force deletes the knowledge base. - When set to true, any documents in the knowledge - base are also deleted. - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - force: bool = proto.Field( - proto.BOOL, - number=2, - ) - - -class UpdateKnowledgeBaseRequest(proto.Message): - r"""Request message for - [KnowledgeBases.UpdateKnowledgeBase][google.cloud.dialogflow.v2beta1.KnowledgeBases.UpdateKnowledgeBase]. - - Attributes: - knowledge_base (google.cloud.dialogflow_v2beta1.types.KnowledgeBase): - Required. The knowledge base to update. - update_mask (google.protobuf.field_mask_pb2.FieldMask): - Optional. Not specified means ``update all``. Currently, - only ``display_name`` can be updated, an InvalidArgument - will be returned for attempting to update other fields. - """ - - knowledge_base: 'KnowledgeBase' = proto.Field( - proto.MESSAGE, - number=1, - message='KnowledgeBase', - ) - update_mask: field_mask_pb2.FieldMask = proto.Field( - proto.MESSAGE, - number=2, - message=field_mask_pb2.FieldMask, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/types/participant.py b/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/types/participant.py deleted file mode 100644 index b5c2cc2fe..000000000 --- a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/types/participant.py +++ /dev/null @@ -1,2241 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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 __future__ import annotations - -from typing import MutableMapping, MutableSequence - -import proto # type: ignore - -from google.cloud.dialogflow_v2beta1.types import audio_config as gcd_audio_config -from google.cloud.dialogflow_v2beta1.types import session -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( - package='google.cloud.dialogflow.v2beta1', - manifest={ - 'Participant', - 'Message', - 'CreateParticipantRequest', - 'GetParticipantRequest', - 'ListParticipantsRequest', - 'ListParticipantsResponse', - 'UpdateParticipantRequest', - 'AudioInput', - 'OutputAudio', - 'AutomatedAgentReply', - 'SuggestionFeature', - 'AssistQueryParameters', - 'AnalyzeContentRequest', - 'DtmfParameters', - 'AnalyzeContentResponse', - 'InputTextConfig', - 'StreamingAnalyzeContentRequest', - 'StreamingAnalyzeContentResponse', - 'AnnotatedMessagePart', - 'MessageAnnotation', - 'ArticleAnswer', - 'FaqAnswer', - 'SmartReplyAnswer', - 'SuggestionResult', - 'SuggestArticlesRequest', - 'SuggestArticlesResponse', - 'SuggestFaqAnswersRequest', - 'SuggestFaqAnswersResponse', - 'SuggestSmartRepliesRequest', - 'SuggestSmartRepliesResponse', - 'Suggestion', - 'ListSuggestionsRequest', - 'ListSuggestionsResponse', - 'CompileSuggestionRequest', - 'CompileSuggestionResponse', - 'ResponseMessage', - }, -) - - -class Participant(proto.Message): - r"""Represents a conversation participant (human agent, virtual - agent, end-user). - - Attributes: - name (str): - Optional. The unique identifier of this participant. Format: - ``projects//locations//conversations//participants/``. - role (google.cloud.dialogflow_v2beta1.types.Participant.Role): - Immutable. The role this participant plays in - the conversation. This field must be set during - participant creation and is then immutable. - obfuscated_external_user_id (str): - Optional. Obfuscated user id that should be associated with - the created participant. - - You can specify a user id as follows: - - 1. If you set this field in - [CreateParticipantRequest][google.cloud.dialogflow.v2beta1.CreateParticipantRequest.participant] - or - [UpdateParticipantRequest][google.cloud.dialogflow.v2beta1.UpdateParticipantRequest.participant], - Dialogflow adds the obfuscated user id with the - participant. - - 2. If you set this field in - [AnalyzeContent][google.cloud.dialogflow.v2beta1.AnalyzeContentRequest.obfuscated_external_user_id] - or - [StreamingAnalyzeContent][google.cloud.dialogflow.v2beta1.StreamingAnalyzeContentRequest.obfuscated_external_user_id], - Dialogflow will update - [Participant.obfuscated_external_user_id][google.cloud.dialogflow.v2beta1.Participant.obfuscated_external_user_id]. - - Dialogflow uses this user id for following purposes: - - 1) Billing and measurement. If user with the same - obfuscated_external_user_id is created in a later - conversation, dialogflow will know it's the same user. 2) - Agent assist suggestion personalization. For example, - Dialogflow can use it to provide personalized smart reply - suggestions for this user. - - Note: - - - Please never pass raw user ids to Dialogflow. Always - obfuscate your user id first. - - Dialogflow only accepts a UTF-8 encoded string, e.g., a - hex digest of a hash function like SHA-512. - - The length of the user id must be <= 256 characters. - documents_metadata_filters (MutableMapping[str, str]): - Optional. Key-value filters on the metadata of documents - returned by article suggestion. If specified, article - suggestion only returns suggested documents that match all - filters in their - [Document.metadata][google.cloud.dialogflow.v2beta1.Document.metadata]. - Multiple values for a metadata key should be concatenated by - comma. For example, filters to match all documents that have - 'US' or 'CA' in their market metadata values and 'agent' in - their user metadata values will be - - :: - - documents_metadata_filters { - key: "market" - value: "US,CA" - } - documents_metadata_filters { - key: "user" - value: "agent" - } - """ - class Role(proto.Enum): - r"""Enumeration of the roles a participant can play in a - conversation. - - Values: - ROLE_UNSPECIFIED (0): - Participant role not set. - HUMAN_AGENT (1): - Participant is a human agent. - AUTOMATED_AGENT (2): - Participant is an automated agent, such as a - Dialogflow agent. - END_USER (3): - Participant is an end user that has called or - chatted with Dialogflow services. - """ - ROLE_UNSPECIFIED = 0 - HUMAN_AGENT = 1 - AUTOMATED_AGENT = 2 - END_USER = 3 - - name: str = proto.Field( - proto.STRING, - number=1, - ) - role: Role = proto.Field( - proto.ENUM, - number=2, - enum=Role, - ) - obfuscated_external_user_id: str = proto.Field( - proto.STRING, - number=7, - ) - documents_metadata_filters: MutableMapping[str, str] = proto.MapField( - proto.STRING, - proto.STRING, - number=8, - ) - - -class Message(proto.Message): - r"""Represents a message posted into a conversation. - - Attributes: - name (str): - Optional. The unique identifier of the message. Format: - ``projects//locations//conversations//messages/``. - content (str): - Required. The message content. - language_code (str): - Optional. The message language. This should be a - `BCP-47 `__ - language tag. Example: "en-US". - participant (str): - Output only. The participant that sends this - message. - participant_role (google.cloud.dialogflow_v2beta1.types.Participant.Role): - Output only. The role of the participant. - create_time (google.protobuf.timestamp_pb2.Timestamp): - Output only. The time when the message was - created in Contact Center AI. - send_time (google.protobuf.timestamp_pb2.Timestamp): - Optional. The time when the message was sent. - message_annotation (google.cloud.dialogflow_v2beta1.types.MessageAnnotation): - Output only. The annotation for the message. - sentiment_analysis (google.cloud.dialogflow_v2beta1.types.SentimentAnalysisResult): - Output only. The sentiment analysis result - for the message. - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - content: str = proto.Field( - proto.STRING, - number=2, - ) - language_code: str = proto.Field( - proto.STRING, - number=3, - ) - participant: str = proto.Field( - proto.STRING, - number=4, - ) - participant_role: 'Participant.Role' = proto.Field( - proto.ENUM, - number=5, - enum='Participant.Role', - ) - create_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=6, - message=timestamp_pb2.Timestamp, - ) - send_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=9, - message=timestamp_pb2.Timestamp, - ) - message_annotation: 'MessageAnnotation' = proto.Field( - proto.MESSAGE, - number=7, - message='MessageAnnotation', - ) - sentiment_analysis: session.SentimentAnalysisResult = proto.Field( - proto.MESSAGE, - number=8, - message=session.SentimentAnalysisResult, - ) - - -class CreateParticipantRequest(proto.Message): - r"""The request message for - [Participants.CreateParticipant][google.cloud.dialogflow.v2beta1.Participants.CreateParticipant]. - - Attributes: - parent (str): - Required. Resource identifier of the conversation adding the - participant. Format: - ``projects//locations//conversations/``. - participant (google.cloud.dialogflow_v2beta1.types.Participant): - Required. The participant to create. - """ - - parent: str = proto.Field( - proto.STRING, - number=1, - ) - participant: 'Participant' = proto.Field( - proto.MESSAGE, - number=2, - message='Participant', - ) - - -class GetParticipantRequest(proto.Message): - r"""The request message for - [Participants.GetParticipant][google.cloud.dialogflow.v2beta1.Participants.GetParticipant]. - - Attributes: - name (str): - Required. The name of the participant. Format: - ``projects//locations//conversations//participants/``. - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - - -class ListParticipantsRequest(proto.Message): - r"""The request message for - [Participants.ListParticipants][google.cloud.dialogflow.v2beta1.Participants.ListParticipants]. - - Attributes: - parent (str): - Required. The conversation to list all participants from. - Format: - ``projects//locations//conversations/``. - 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: str = proto.Field( - proto.STRING, - number=1, - ) - page_size: int = proto.Field( - proto.INT32, - number=2, - ) - page_token: str = proto.Field( - proto.STRING, - number=3, - ) - - -class ListParticipantsResponse(proto.Message): - r"""The response message for - [Participants.ListParticipants][google.cloud.dialogflow.v2beta1.Participants.ListParticipants]. - - Attributes: - participants (MutableSequence[google.cloud.dialogflow_v2beta1.types.Participant]): - The list of participants. There is 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 - - participants: MutableSequence['Participant'] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message='Participant', - ) - next_page_token: str = proto.Field( - proto.STRING, - number=2, - ) - - -class UpdateParticipantRequest(proto.Message): - r"""The request message for - [Participants.UpdateParticipant][google.cloud.dialogflow.v2beta1.Participants.UpdateParticipant]. - - Attributes: - participant (google.cloud.dialogflow_v2beta1.types.Participant): - Required. The participant to update. - update_mask (google.protobuf.field_mask_pb2.FieldMask): - Required. The mask to specify which fields to - update. - """ - - participant: 'Participant' = proto.Field( - proto.MESSAGE, - number=1, - message='Participant', - ) - update_mask: field_mask_pb2.FieldMask = proto.Field( - proto.MESSAGE, - number=2, - message=field_mask_pb2.FieldMask, - ) - - -class AudioInput(proto.Message): - r"""Represents the natural language speech audio to be processed. - - Attributes: - config (google.cloud.dialogflow_v2beta1.types.InputAudioConfig): - Required. Instructs the speech recognizer how - to process the speech audio. - audio (bytes): - Required. The natural language speech audio - to be processed. A single request can contain up - to 1 minute of speech audio data. The - transcribed text cannot contain more than 256 - bytes for virtual agent interactions. - """ - - config: gcd_audio_config.InputAudioConfig = proto.Field( - proto.MESSAGE, - number=1, - message=gcd_audio_config.InputAudioConfig, - ) - audio: bytes = proto.Field( - proto.BYTES, - number=2, - ) - - -class OutputAudio(proto.Message): - r"""Represents the natural language speech audio to be played to - the end user. - - Attributes: - config (google.cloud.dialogflow_v2beta1.types.OutputAudioConfig): - Required. Instructs the speech synthesizer - how to generate the speech audio. - audio (bytes): - Required. The natural language speech audio. - """ - - config: gcd_audio_config.OutputAudioConfig = proto.Field( - proto.MESSAGE, - number=1, - message=gcd_audio_config.OutputAudioConfig, - ) - audio: bytes = proto.Field( - proto.BYTES, - number=2, - ) - - -class AutomatedAgentReply(proto.Message): - r"""Represents a response from an automated agent. - - This message has `oneof`_ fields (mutually exclusive fields). - For each oneof, at most one member field can be set at the same time. - Setting any member of the oneof automatically clears all other - members. - - .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields - - Attributes: - detect_intent_response (google.cloud.dialogflow_v2beta1.types.DetectIntentResponse): - Response of the Dialogflow - [Sessions.DetectIntent][google.cloud.dialogflow.v2beta1.Sessions.DetectIntent] - call. - - This field is a member of `oneof`_ ``response``. - response_messages (MutableSequence[google.cloud.dialogflow_v2beta1.types.ResponseMessage]): - Response messages from the automated agent. - intent (str): - Name of the intent if an intent is matched for the query. - For a V2 query, the value format is - ``projects//locations/ /agent/intents/``. - For a V3 query, the value format is - ``projects//locations/ /agents//intents/``. - - This field is a member of `oneof`_ ``match``. - event (str): - Event name if an event is triggered for the - query. - - This field is a member of `oneof`_ ``match``. - match_confidence (float): - The confidence of the match. Values range - from 0.0 (completely uncertain) to 1.0 - (completely certain). This value is for - informational purpose only and is only used to - help match the best intent within the - classification threshold. This value may change - for the same end-user expression at any time due - to a model retraining or change in - implementation. - parameters (google.protobuf.struct_pb2.Struct): - The collection of current parameters at the - time of this response. - cx_session_parameters (google.protobuf.struct_pb2.Struct): - The collection of current Dialogflow CX agent session - parameters at the time of this response. Deprecated: Use - ``parameters`` instead. - automated_agent_reply_type (google.cloud.dialogflow_v2beta1.types.AutomatedAgentReply.AutomatedAgentReplyType): - AutomatedAgentReply type. - allow_cancellation (bool): - Indicates whether the partial automated agent - reply is interruptible when a later reply - message arrives. e.g. if the agent specified - some music as partial response, it can be - cancelled. - cx_current_page (str): - The unique identifier of the current Dialogflow CX - conversation page. Format: - ``projects//locations//agents//flows//pages/``. - """ - class AutomatedAgentReplyType(proto.Enum): - r"""Represents different automated agent reply types. - - Values: - AUTOMATED_AGENT_REPLY_TYPE_UNSPECIFIED (0): - Not specified. This should never happen. - PARTIAL (1): - Partial reply. e.g. Aggregated responses in a - ``Fulfillment`` that enables ``return_partial_response`` can - be returned as partial reply. WARNING: partial reply is not - eligible for barge-in. - FINAL (2): - Final reply. - """ - AUTOMATED_AGENT_REPLY_TYPE_UNSPECIFIED = 0 - PARTIAL = 1 - FINAL = 2 - - detect_intent_response: session.DetectIntentResponse = proto.Field( - proto.MESSAGE, - number=1, - oneof='response', - message=session.DetectIntentResponse, - ) - response_messages: MutableSequence['ResponseMessage'] = proto.RepeatedField( - proto.MESSAGE, - number=3, - message='ResponseMessage', - ) - intent: str = proto.Field( - proto.STRING, - number=4, - oneof='match', - ) - event: str = proto.Field( - proto.STRING, - number=5, - oneof='match', - ) - match_confidence: float = proto.Field( - proto.FLOAT, - number=9, - ) - parameters: struct_pb2.Struct = proto.Field( - proto.MESSAGE, - number=10, - message=struct_pb2.Struct, - ) - cx_session_parameters: struct_pb2.Struct = proto.Field( - proto.MESSAGE, - number=6, - message=struct_pb2.Struct, - ) - automated_agent_reply_type: AutomatedAgentReplyType = proto.Field( - proto.ENUM, - number=7, - enum=AutomatedAgentReplyType, - ) - allow_cancellation: bool = proto.Field( - proto.BOOL, - number=8, - ) - cx_current_page: str = proto.Field( - proto.STRING, - number=11, - ) - - -class SuggestionFeature(proto.Message): - r"""The type of Human Agent Assistant API suggestion to perform, and the - maximum number of results to return for that type. Multiple - ``Feature`` objects can be specified in the ``features`` list. - - Attributes: - type_ (google.cloud.dialogflow_v2beta1.types.SuggestionFeature.Type): - Type of Human Agent Assistant API feature to - request. - """ - class Type(proto.Enum): - r"""Defines the type of Human Agent Assistant feature. - - Values: - TYPE_UNSPECIFIED (0): - Unspecified feature type. - ARTICLE_SUGGESTION (1): - Run article suggestion model for chat. - FAQ (2): - Run FAQ model. - SMART_REPLY (3): - Run smart reply model for chat. - CONVERSATION_SUMMARIZATION (8): - Run conversation summarization model for - chat. - """ - TYPE_UNSPECIFIED = 0 - ARTICLE_SUGGESTION = 1 - FAQ = 2 - SMART_REPLY = 3 - CONVERSATION_SUMMARIZATION = 8 - - type_: Type = proto.Field( - proto.ENUM, - number=1, - enum=Type, - ) - - -class AssistQueryParameters(proto.Message): - r"""Represents the parameters of human assist query. - - Attributes: - documents_metadata_filters (MutableMapping[str, str]): - Key-value filters on the metadata of documents returned by - article suggestion. If specified, article suggestion only - returns suggested documents that match all filters in their - [Document.metadata][google.cloud.dialogflow.v2beta1.Document.metadata]. - Multiple values for a metadata key should be concatenated by - comma. For example, filters to match all documents that have - 'US' or 'CA' in their market metadata values and 'agent' in - their user metadata values will be - - :: - - documents_metadata_filters { - key: "market" - value: "US,CA" - } - documents_metadata_filters { - key: "user" - value: "agent" - } - """ - - documents_metadata_filters: MutableMapping[str, str] = proto.MapField( - proto.STRING, - proto.STRING, - number=1, - ) - - -class AnalyzeContentRequest(proto.Message): - r"""The request message for - [Participants.AnalyzeContent][google.cloud.dialogflow.v2beta1.Participants.AnalyzeContent]. - - This message has `oneof`_ fields (mutually exclusive fields). - For each oneof, at most one member field can be set at the same time. - Setting any member of the oneof automatically clears all other - members. - - .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields - - Attributes: - participant (str): - Required. The name of the participant this text comes from. - Format: - ``projects//locations//conversations//participants/``. - text_input (google.cloud.dialogflow_v2beta1.types.TextInput): - The natural language text to be processed. - - This field is a member of `oneof`_ ``input``. - audio_input (google.cloud.dialogflow_v2beta1.types.AudioInput): - The natural language speech audio to be - processed. - - This field is a member of `oneof`_ ``input``. - event_input (google.cloud.dialogflow_v2beta1.types.EventInput): - An input event to send to Dialogflow. - - This field is a member of `oneof`_ ``input``. - reply_audio_config (google.cloud.dialogflow_v2beta1.types.OutputAudioConfig): - Speech synthesis configuration. - The speech synthesis settings for a virtual - agent that may be configured for the associated - conversation profile are not used when calling - AnalyzeContent. If this configuration is not - supplied, speech synthesis is disabled. - query_params (google.cloud.dialogflow_v2beta1.types.QueryParameters): - Parameters for a Dialogflow virtual-agent - query. - assist_query_params (google.cloud.dialogflow_v2beta1.types.AssistQueryParameters): - Parameters for a human assist query. - cx_parameters (google.protobuf.struct_pb2.Struct): - Additional parameters to be put into - Dialogflow CX session parameters. To remove a - parameter from the session, clients should - explicitly set the parameter value to null. - - Note: this field should only be used if you are - connecting to a Dialogflow CX agent. - cx_current_page (str): - The unique identifier of the CX page to override the - ``current_page`` in the session. Format: - ``projects//locations//agents//flows//pages/``. - - If ``cx_current_page`` is specified, the previous state of - the session will be ignored by Dialogflow CX, including the - [previous page][QueryResult.current_page] and the [previous - session parameters][QueryResult.parameters]. In most cases, - ``cx_current_page`` and ``cx_parameters`` should be - configured together to direct a session to a specific state. - - Note: this field should only be used if you are connecting - to a Dialogflow CX agent. - message_send_time (google.protobuf.timestamp_pb2.Timestamp): - Optional. The send time of the message from - end user or human agent's perspective. It is - used for identifying the same message under one - participant. - - Given two messages under the same participant: - - If send time are different regardless of - whether the content of the messages are exactly - the same, the conversation will regard them as - two distinct messages sent by the participant. - - If send time is the same regardless of whether - the content of the messages are exactly the - same, the conversation will regard them as same - message, and ignore the message received later. - If the value is not provided, a new request will - always be regarded as a new message without any - de-duplication. - request_id (str): - A unique identifier for this request. Restricted to 36 ASCII - characters. A random UUID is recommended. This request is - only idempotent if a ``request_id`` is provided. - """ - - participant: str = proto.Field( - proto.STRING, - number=1, - ) - text_input: session.TextInput = proto.Field( - proto.MESSAGE, - number=6, - oneof='input', - message=session.TextInput, - ) - audio_input: 'AudioInput' = proto.Field( - proto.MESSAGE, - number=7, - oneof='input', - message='AudioInput', - ) - event_input: session.EventInput = proto.Field( - proto.MESSAGE, - number=8, - oneof='input', - message=session.EventInput, - ) - reply_audio_config: gcd_audio_config.OutputAudioConfig = proto.Field( - proto.MESSAGE, - number=5, - message=gcd_audio_config.OutputAudioConfig, - ) - query_params: session.QueryParameters = proto.Field( - proto.MESSAGE, - number=9, - message=session.QueryParameters, - ) - assist_query_params: 'AssistQueryParameters' = proto.Field( - proto.MESSAGE, - number=14, - message='AssistQueryParameters', - ) - cx_parameters: struct_pb2.Struct = proto.Field( - proto.MESSAGE, - number=18, - message=struct_pb2.Struct, - ) - cx_current_page: str = proto.Field( - proto.STRING, - number=20, - ) - message_send_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=10, - message=timestamp_pb2.Timestamp, - ) - request_id: str = proto.Field( - proto.STRING, - number=11, - ) - - -class DtmfParameters(proto.Message): - r"""The message in the response that indicates the parameters of - DTMF. - - Attributes: - accepts_dtmf_input (bool): - Indicates whether DTMF input can be handled - in the next request. - """ - - accepts_dtmf_input: bool = proto.Field( - proto.BOOL, - number=1, - ) - - -class AnalyzeContentResponse(proto.Message): - r"""The response message for - [Participants.AnalyzeContent][google.cloud.dialogflow.v2beta1.Participants.AnalyzeContent]. - - Attributes: - reply_text (str): - Output only. The output text content. - This field is set if the automated agent - responded with text to show to the user. - reply_audio (google.cloud.dialogflow_v2beta1.types.OutputAudio): - Optional. The audio data bytes encoded as specified in the - request. This field is set if: - - - ``reply_audio_config`` was specified in the request, or - - The automated agent responded with audio to play to the - user. In such case, ``reply_audio.config`` contains - settings used to synthesize the speech. - - In some scenarios, multiple output audio fields may be - present in the response structure. In these cases, only the - top-most-level audio output has content. - automated_agent_reply (google.cloud.dialogflow_v2beta1.types.AutomatedAgentReply): - Optional. Only set if a Dialogflow automated agent has - responded. Note that: - [AutomatedAgentReply.detect_intent_response.output_audio][] - and - [AutomatedAgentReply.detect_intent_response.output_audio_config][] - are always empty, use - [reply_audio][google.cloud.dialogflow.v2beta1.AnalyzeContentResponse.reply_audio] - instead. - message (google.cloud.dialogflow_v2beta1.types.Message): - Output only. Message analyzed by CCAI. - human_agent_suggestion_results (MutableSequence[google.cloud.dialogflow_v2beta1.types.SuggestionResult]): - The suggestions for most recent human agent. The order is - the same as - [HumanAgentAssistantConfig.SuggestionConfig.feature_configs][google.cloud.dialogflow.v2beta1.HumanAgentAssistantConfig.SuggestionConfig.feature_configs] - of - [HumanAgentAssistantConfig.human_agent_suggestion_config][google.cloud.dialogflow.v2beta1.HumanAgentAssistantConfig.human_agent_suggestion_config]. - - Note that any failure of Agent Assist features will not lead - to the overall failure of an AnalyzeContent API call. - Instead, the features will fail silently with the error - field set in the corresponding SuggestionResult. - end_user_suggestion_results (MutableSequence[google.cloud.dialogflow_v2beta1.types.SuggestionResult]): - The suggestions for end user. The order is the same as - [HumanAgentAssistantConfig.SuggestionConfig.feature_configs][google.cloud.dialogflow.v2beta1.HumanAgentAssistantConfig.SuggestionConfig.feature_configs] - of - [HumanAgentAssistantConfig.end_user_suggestion_config][google.cloud.dialogflow.v2beta1.HumanAgentAssistantConfig.end_user_suggestion_config]. - - Same as human_agent_suggestion_results, any failure of Agent - Assist features will not lead to the overall failure of an - AnalyzeContent API call. Instead, the features will fail - silently with the error field set in the corresponding - SuggestionResult. - dtmf_parameters (google.cloud.dialogflow_v2beta1.types.DtmfParameters): - Indicates the parameters of DTMF. - """ - - reply_text: str = proto.Field( - proto.STRING, - number=1, - ) - reply_audio: 'OutputAudio' = proto.Field( - proto.MESSAGE, - number=2, - message='OutputAudio', - ) - automated_agent_reply: 'AutomatedAgentReply' = proto.Field( - proto.MESSAGE, - number=3, - message='AutomatedAgentReply', - ) - message: 'Message' = proto.Field( - proto.MESSAGE, - number=5, - message='Message', - ) - human_agent_suggestion_results: MutableSequence['SuggestionResult'] = proto.RepeatedField( - proto.MESSAGE, - number=6, - message='SuggestionResult', - ) - end_user_suggestion_results: MutableSequence['SuggestionResult'] = proto.RepeatedField( - proto.MESSAGE, - number=7, - message='SuggestionResult', - ) - dtmf_parameters: 'DtmfParameters' = proto.Field( - proto.MESSAGE, - number=9, - message='DtmfParameters', - ) - - -class InputTextConfig(proto.Message): - r"""Defines the language used in the input text. - - Attributes: - language_code (str): - Required. The language of this conversational query. See - `Language - Support `__ - for a list of the currently supported language codes. - """ - - language_code: str = proto.Field( - proto.STRING, - number=1, - ) - - -class StreamingAnalyzeContentRequest(proto.Message): - r"""The top-level message sent by the client to the - [Participants.StreamingAnalyzeContent][google.cloud.dialogflow.v2beta1.Participants.StreamingAnalyzeContent] - method. - - Multiple request messages should be sent in order: - - 1. The first message must contain - [participant][google.cloud.dialogflow.v2beta1.StreamingAnalyzeContentRequest.participant], - [config][google.cloud.dialogflow.v2beta1.StreamingAnalyzeContentRequest.config] - and optionally - [query_params][google.cloud.dialogflow.v2beta1.StreamingAnalyzeContentRequest.query_params]. - If you want to receive an audio response, it should also contain - [reply_audio_config][google.cloud.dialogflow.v2beta1.StreamingAnalyzeContentRequest.reply_audio_config]. - The message must not contain - [input][google.cloud.dialogflow.v2beta1.StreamingAnalyzeContentRequest.input]. - - 2. If - [config][google.cloud.dialogflow.v2beta1.StreamingAnalyzeContentRequest.config] - in the first message was set to - [audio_config][google.cloud.dialogflow.v2beta1.StreamingAnalyzeContentRequest.audio_config], - all subsequent messages must contain - [input_audio][google.cloud.dialogflow.v2beta1.StreamingAnalyzeContentRequest.input_audio] - to continue with Speech recognition. If you decide to rather - analyze text input after you already started Speech recognition, - please send a message with - [StreamingAnalyzeContentRequest.input_text][google.cloud.dialogflow.v2beta1.StreamingAnalyzeContentRequest.input_text]. - - However, note that: - - - Dialogflow will bill you for the audio so far. - - Dialogflow discards all Speech recognition results in favor of - the text input. - - 3. If - [StreamingAnalyzeContentRequest.config][google.cloud.dialogflow.v2beta1.StreamingAnalyzeContentRequest.config] - in the first message was set to - [StreamingAnalyzeContentRequest.text_config][google.cloud.dialogflow.v2beta1.StreamingAnalyzeContentRequest.text_config], - then the second message must contain only - [input_text][google.cloud.dialogflow.v2beta1.StreamingAnalyzeContentRequest.input_text]. - Moreover, you must not send more than two messages. - - After you sent all input, you must half-close or abort the request - stream. - - This message has `oneof`_ fields (mutually exclusive fields). - For each oneof, at most one member field can be set at the same time. - Setting any member of the oneof automatically clears all other - members. - - .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields - - Attributes: - participant (str): - Required. The name of the participant this text comes from. - Format: - ``projects//locations//conversations//participants/``. - audio_config (google.cloud.dialogflow_v2beta1.types.InputAudioConfig): - Instructs the speech recognizer how to - process the speech audio. - - This field is a member of `oneof`_ ``config``. - text_config (google.cloud.dialogflow_v2beta1.types.InputTextConfig): - The natural language text to be processed. - - This field is a member of `oneof`_ ``config``. - reply_audio_config (google.cloud.dialogflow_v2beta1.types.OutputAudioConfig): - Speech synthesis configuration. - The speech synthesis settings for a virtual - agent that may be configured for the associated - conversation profile are not used when calling - StreamingAnalyzeContent. If this configuration - is not supplied, speech synthesis is disabled. - input_audio (bytes): - The input audio content to be recognized. Must be sent if - ``audio_config`` is set in the first message. The complete - audio over all streaming messages must not exceed 1 minute. - - This field is a member of `oneof`_ ``input``. - input_text (str): - The UTF-8 encoded natural language text to be processed. - Must be sent if ``text_config`` is set in the first message. - Text length must not exceed 256 bytes for virtual agent - interactions. The ``input_text`` field can be only sent - once. - - This field is a member of `oneof`_ ``input``. - input_dtmf (google.cloud.dialogflow_v2beta1.types.TelephonyDtmfEvents): - The DTMF digits used to invoke intent and - fill in parameter value. - This input is ignored if the previous response - indicated that DTMF input is not accepted. - - This field is a member of `oneof`_ ``input``. - query_params (google.cloud.dialogflow_v2beta1.types.QueryParameters): - Parameters for a Dialogflow virtual-agent - query. - assist_query_params (google.cloud.dialogflow_v2beta1.types.AssistQueryParameters): - Parameters for a human assist query. - cx_parameters (google.protobuf.struct_pb2.Struct): - Additional parameters to be put into - Dialogflow CX session parameters. To remove a - parameter from the session, clients should - explicitly set the parameter value to null. - - Note: this field should only be used if you are - connecting to a Dialogflow CX agent. - cx_current_page (str): - The unique identifier of the CX page to override the - ``current_page`` in the session. Format: - ``projects//locations//agents//flows//pages/``. - - If ``cx_current_page`` is specified, the previous state of - the session will be ignored by Dialogflow CX, including the - [previous page][QueryResult.current_page] and the [previous - session parameters][QueryResult.parameters]. In most cases, - ``cx_current_page`` and ``cx_parameters`` should be - configured together to direct a session to a specific state. - - Note: this field should only be used if you are connecting - to a Dialogflow CX agent. - enable_partial_automated_agent_reply (bool): - Enable partial virtual agent responses. If this flag is not - enabled, response stream still contains only one final - response even if some ``Fulfillment``\ s in Dialogflow - virtual agent have been configured to return partial - responses. - """ - - participant: str = proto.Field( - proto.STRING, - number=1, - ) - audio_config: gcd_audio_config.InputAudioConfig = proto.Field( - proto.MESSAGE, - number=2, - oneof='config', - message=gcd_audio_config.InputAudioConfig, - ) - text_config: 'InputTextConfig' = proto.Field( - proto.MESSAGE, - number=3, - oneof='config', - message='InputTextConfig', - ) - reply_audio_config: gcd_audio_config.OutputAudioConfig = proto.Field( - proto.MESSAGE, - number=4, - message=gcd_audio_config.OutputAudioConfig, - ) - input_audio: bytes = proto.Field( - proto.BYTES, - number=5, - oneof='input', - ) - input_text: str = proto.Field( - proto.STRING, - number=6, - oneof='input', - ) - input_dtmf: gcd_audio_config.TelephonyDtmfEvents = proto.Field( - proto.MESSAGE, - number=9, - oneof='input', - message=gcd_audio_config.TelephonyDtmfEvents, - ) - query_params: session.QueryParameters = proto.Field( - proto.MESSAGE, - number=7, - message=session.QueryParameters, - ) - assist_query_params: 'AssistQueryParameters' = proto.Field( - proto.MESSAGE, - number=8, - message='AssistQueryParameters', - ) - cx_parameters: struct_pb2.Struct = proto.Field( - proto.MESSAGE, - number=13, - message=struct_pb2.Struct, - ) - cx_current_page: str = proto.Field( - proto.STRING, - number=15, - ) - enable_partial_automated_agent_reply: bool = proto.Field( - proto.BOOL, - number=12, - ) - - -class StreamingAnalyzeContentResponse(proto.Message): - r"""The top-level message returned from the ``StreamingAnalyzeContent`` - method. - - Multiple response messages can be returned in order: - - 1. If the input was set to streaming audio, the first one or more - messages contain ``recognition_result``. Each - ``recognition_result`` represents a more complete transcript of - what the user said. The last ``recognition_result`` has - ``is_final`` set to ``true``. - - 2. In virtual agent stage: if - ``enable_partial_automated_agent_reply`` is true, the following N - (currently 1 <= N <= 4) messages contain - ``automated_agent_reply`` and optionally ``reply_audio`` returned - by the virtual agent. The first (N-1) - ``automated_agent_reply``\ s will have - ``automated_agent_reply_type`` set to ``PARTIAL``. The last - ``automated_agent_reply`` has ``automated_agent_reply_type`` set - to ``FINAL``. If ``enable_partial_automated_agent_reply`` is not - enabled, response stream only contains the final reply. - - In human assist stage: the following N (N >= 1) messages contain - ``human_agent_suggestion_results``, - ``end_user_suggestion_results`` or ``message``. - - Attributes: - recognition_result (google.cloud.dialogflow_v2beta1.types.StreamingRecognitionResult): - The result of speech recognition. - reply_text (str): - Optional. The output text content. - This field is set if an automated agent - responded with a text for the user. - reply_audio (google.cloud.dialogflow_v2beta1.types.OutputAudio): - Optional. The audio data bytes encoded as specified in the - request. This field is set if: - - - The ``reply_audio_config`` field is specified in the - request. - - The automated agent, which this output comes from, - responded with audio. In such case, the - ``reply_audio.config`` field contains settings used to - synthesize the speech. - - In some scenarios, multiple output audio fields may be - present in the response structure. In these cases, only the - top-most-level audio output has content. - automated_agent_reply (google.cloud.dialogflow_v2beta1.types.AutomatedAgentReply): - Optional. Only set if a Dialogflow automated agent has - responded. Note that: - [AutomatedAgentReply.detect_intent_response.output_audio][] - and - [AutomatedAgentReply.detect_intent_response.output_audio_config][] - are always empty, use - [reply_audio][google.cloud.dialogflow.v2beta1.StreamingAnalyzeContentResponse.reply_audio] - instead. - message (google.cloud.dialogflow_v2beta1.types.Message): - Output only. Message analyzed by CCAI. - human_agent_suggestion_results (MutableSequence[google.cloud.dialogflow_v2beta1.types.SuggestionResult]): - The suggestions for most recent human agent. The order is - the same as - [HumanAgentAssistantConfig.SuggestionConfig.feature_configs][google.cloud.dialogflow.v2beta1.HumanAgentAssistantConfig.SuggestionConfig.feature_configs] - of - [HumanAgentAssistantConfig.human_agent_suggestion_config][google.cloud.dialogflow.v2beta1.HumanAgentAssistantConfig.human_agent_suggestion_config]. - end_user_suggestion_results (MutableSequence[google.cloud.dialogflow_v2beta1.types.SuggestionResult]): - The suggestions for end user. The order is the same as - [HumanAgentAssistantConfig.SuggestionConfig.feature_configs][google.cloud.dialogflow.v2beta1.HumanAgentAssistantConfig.SuggestionConfig.feature_configs] - of - [HumanAgentAssistantConfig.end_user_suggestion_config][google.cloud.dialogflow.v2beta1.HumanAgentAssistantConfig.end_user_suggestion_config]. - dtmf_parameters (google.cloud.dialogflow_v2beta1.types.DtmfParameters): - Indicates the parameters of DTMF. - """ - - recognition_result: session.StreamingRecognitionResult = proto.Field( - proto.MESSAGE, - number=1, - message=session.StreamingRecognitionResult, - ) - reply_text: str = proto.Field( - proto.STRING, - number=2, - ) - reply_audio: 'OutputAudio' = proto.Field( - proto.MESSAGE, - number=3, - message='OutputAudio', - ) - automated_agent_reply: 'AutomatedAgentReply' = proto.Field( - proto.MESSAGE, - number=4, - message='AutomatedAgentReply', - ) - message: 'Message' = proto.Field( - proto.MESSAGE, - number=6, - message='Message', - ) - human_agent_suggestion_results: MutableSequence['SuggestionResult'] = proto.RepeatedField( - proto.MESSAGE, - number=7, - message='SuggestionResult', - ) - end_user_suggestion_results: MutableSequence['SuggestionResult'] = proto.RepeatedField( - proto.MESSAGE, - number=8, - message='SuggestionResult', - ) - dtmf_parameters: 'DtmfParameters' = proto.Field( - proto.MESSAGE, - number=10, - message='DtmfParameters', - ) - - -class AnnotatedMessagePart(proto.Message): - r"""Represents a part of a message possibly annotated with an - entity. The part can be an entity or purely a part of the - message between two entities or message start/end. - - Attributes: - text (str): - Required. A part of a message possibly - annotated with an entity. - entity_type (str): - Optional. The `Dialogflow system entity - type `__ - of this message part. If this is empty, Dialogflow could not - annotate the phrase part with a system entity. - formatted_value (google.protobuf.struct_pb2.Value): - Optional. The `Dialogflow system entity formatted - value `__ - of this message part. For example for a system entity of - type ``@sys.unit-currency``, this may contain: - - .. raw:: html - -
-                {
-                  "amount": 5,
-                  "currency": "USD"
-                }
-                
- """ - - text: str = proto.Field( - proto.STRING, - number=1, - ) - entity_type: str = proto.Field( - proto.STRING, - number=2, - ) - formatted_value: struct_pb2.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 (MutableSequence[google.cloud.dialogflow_v2beta1.types.AnnotatedMessagePart]): - Optional. The collection of annotated message parts ordered - by their position in the message. You can recover the - annotated message by concatenating - [AnnotatedMessagePart.text]. - contain_entities (bool): - Required. Indicates whether the text message - contains entities. - """ - - parts: MutableSequence['AnnotatedMessagePart'] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message='AnnotatedMessagePart', - ) - contain_entities: bool = proto.Field( - proto.BOOL, - number=2, - ) - - -class ArticleAnswer(proto.Message): - r"""Represents article answer. - - Attributes: - title (str): - The article title. - uri (str): - The article URI. - snippets (MutableSequence[str]): - Output only. Article snippets. - metadata (MutableMapping[str, str]): - A map that contains metadata about the answer - and the document from which it originates. - answer_record (str): - The name of answer record, in the format of - "projects//locations//answerRecords/". - """ - - title: str = proto.Field( - proto.STRING, - number=1, - ) - uri: str = proto.Field( - proto.STRING, - number=2, - ) - snippets: MutableSequence[str] = proto.RepeatedField( - proto.STRING, - number=3, - ) - metadata: MutableMapping[str, str] = proto.MapField( - proto.STRING, - proto.STRING, - number=5, - ) - answer_record: str = 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 - document. - confidence (float): - The system's confidence score that this - Knowledge answer is a good match for this - conversational query, range from 0.0 (completely - uncertain) to 1.0 (completely certain). - question (str): - The corresponding FAQ question. - source (str): - Indicates which Knowledge Document this answer was extracted - from. Format: - ``projects//locations//agent/knowledgeBases//documents/``. - metadata (MutableMapping[str, str]): - A map that contains metadata about the answer - and the document from which it originates. - answer_record (str): - The name of answer record, in the format of - "projects//locations//answerRecords/". - """ - - answer: str = proto.Field( - proto.STRING, - number=1, - ) - confidence: float = proto.Field( - proto.FLOAT, - number=2, - ) - question: str = proto.Field( - proto.STRING, - number=3, - ) - source: str = proto.Field( - proto.STRING, - number=4, - ) - metadata: MutableMapping[str, str] = proto.MapField( - proto.STRING, - proto.STRING, - number=5, - ) - answer_record: str = proto.Field( - proto.STRING, - number=6, - ) - - -class SmartReplyAnswer(proto.Message): - r"""Represents a smart reply answer. - - Attributes: - reply (str): - The content of the reply. - confidence (float): - Smart reply confidence. - The system's confidence score that this reply is - a good match for this conversation, as a value - from 0.0 (completely uncertain) to 1.0 - (completely certain). - answer_record (str): - The name of answer record, in the format of - "projects//locations//answerRecords/". - """ - - reply: str = proto.Field( - proto.STRING, - number=1, - ) - confidence: float = proto.Field( - proto.FLOAT, - number=2, - ) - answer_record: str = proto.Field( - proto.STRING, - number=3, - ) - - -class SuggestionResult(proto.Message): - r"""One response of different type of suggestion response which is used - in the response of - [Participants.AnalyzeContent][google.cloud.dialogflow.v2beta1.Participants.AnalyzeContent] - and - [Participants.AnalyzeContent][google.cloud.dialogflow.v2beta1.Participants.AnalyzeContent], - as well as - [HumanAgentAssistantEvent][google.cloud.dialogflow.v2beta1.HumanAgentAssistantEvent]. - - This message has `oneof`_ fields (mutually exclusive fields). - For each oneof, at most one member field can be set at the same time. - Setting any member of the oneof automatically clears all other - members. - - .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields - - Attributes: - error (google.rpc.status_pb2.Status): - Error status if the request failed. - - This field is a member of `oneof`_ ``suggestion_response``. - suggest_articles_response (google.cloud.dialogflow_v2beta1.types.SuggestArticlesResponse): - SuggestArticlesResponse if request is for - ARTICLE_SUGGESTION. - - This field is a member of `oneof`_ ``suggestion_response``. - suggest_faq_answers_response (google.cloud.dialogflow_v2beta1.types.SuggestFaqAnswersResponse): - SuggestFaqAnswersResponse if request is for FAQ_ANSWER. - - This field is a member of `oneof`_ ``suggestion_response``. - suggest_smart_replies_response (google.cloud.dialogflow_v2beta1.types.SuggestSmartRepliesResponse): - SuggestSmartRepliesResponse if request is for SMART_REPLY. - - This field is a member of `oneof`_ ``suggestion_response``. - """ - - error: status_pb2.Status = proto.Field( - proto.MESSAGE, - number=1, - oneof='suggestion_response', - message=status_pb2.Status, - ) - suggest_articles_response: 'SuggestArticlesResponse' = proto.Field( - proto.MESSAGE, - number=2, - oneof='suggestion_response', - message='SuggestArticlesResponse', - ) - suggest_faq_answers_response: 'SuggestFaqAnswersResponse' = proto.Field( - proto.MESSAGE, - number=3, - oneof='suggestion_response', - message='SuggestFaqAnswersResponse', - ) - suggest_smart_replies_response: 'SuggestSmartRepliesResponse' = proto.Field( - proto.MESSAGE, - number=4, - oneof='suggestion_response', - message='SuggestSmartRepliesResponse', - ) - - -class SuggestArticlesRequest(proto.Message): - r"""The request message for - [Participants.SuggestArticles][google.cloud.dialogflow.v2beta1.Participants.SuggestArticles]. - - Attributes: - parent (str): - Required. The name of the participant to fetch suggestion - for. Format: - ``projects//locations//conversations//participants/``. - latest_message (str): - Optional. The name of the latest conversation message to - compile suggestion for. If empty, it will be the latest - message of the conversation. - - Format: - ``projects//locations//conversations//messages/``. - context_size (int): - Optional. Max number of messages prior to and including - [latest_message][google.cloud.dialogflow.v2beta1.SuggestArticlesRequest.latest_message] - to use as context when compiling the suggestion. By default - 20 and at most 50. - assist_query_params (google.cloud.dialogflow_v2beta1.types.AssistQueryParameters): - Optional. Parameters for a human assist - query. - """ - - parent: str = proto.Field( - proto.STRING, - number=1, - ) - latest_message: str = proto.Field( - proto.STRING, - number=2, - ) - context_size: int = proto.Field( - proto.INT32, - number=3, - ) - assist_query_params: 'AssistQueryParameters' = proto.Field( - proto.MESSAGE, - number=4, - message='AssistQueryParameters', - ) - - -class SuggestArticlesResponse(proto.Message): - r"""The response message for - [Participants.SuggestArticles][google.cloud.dialogflow.v2beta1.Participants.SuggestArticles]. - - Attributes: - article_answers (MutableSequence[google.cloud.dialogflow_v2beta1.types.ArticleAnswer]): - Output only. Articles ordered by score in - descending order. - latest_message (str): - The name of the latest conversation message used to compile - suggestion for. - - Format: - ``projects//locations//conversations//messages/``. - context_size (int): - Number of messages prior to and including - [latest_message][google.cloud.dialogflow.v2beta1.SuggestArticlesResponse.latest_message] - to compile the suggestion. It may be smaller than the - [SuggestArticlesResponse.context_size][google.cloud.dialogflow.v2beta1.SuggestArticlesResponse.context_size] - field in the request if there aren't that many messages in - the conversation. - """ - - article_answers: MutableSequence['ArticleAnswer'] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message='ArticleAnswer', - ) - latest_message: str = proto.Field( - proto.STRING, - number=2, - ) - context_size: int = proto.Field( - proto.INT32, - number=3, - ) - - -class SuggestFaqAnswersRequest(proto.Message): - r"""The request message for - [Participants.SuggestFaqAnswers][google.cloud.dialogflow.v2beta1.Participants.SuggestFaqAnswers]. - - Attributes: - parent (str): - Required. The name of the participant to fetch suggestion - for. Format: - ``projects//locations//conversations//participants/``. - latest_message (str): - Optional. The name of the latest conversation message to - compile suggestion for. If empty, it will be the latest - message of the conversation. - - Format: - ``projects//locations//conversations//messages/``. - context_size (int): - Optional. Max number of messages prior to and including - [latest_message] to use as context when compiling the - suggestion. By default 20 and at most 50. - assist_query_params (google.cloud.dialogflow_v2beta1.types.AssistQueryParameters): - Optional. Parameters for a human assist - query. - """ - - parent: str = proto.Field( - proto.STRING, - number=1, - ) - latest_message: str = proto.Field( - proto.STRING, - number=2, - ) - context_size: int = proto.Field( - proto.INT32, - number=3, - ) - assist_query_params: 'AssistQueryParameters' = proto.Field( - proto.MESSAGE, - number=4, - message='AssistQueryParameters', - ) - - -class SuggestFaqAnswersResponse(proto.Message): - r"""The request message for - [Participants.SuggestFaqAnswers][google.cloud.dialogflow.v2beta1.Participants.SuggestFaqAnswers]. - - Attributes: - faq_answers (MutableSequence[google.cloud.dialogflow_v2beta1.types.FaqAnswer]): - Output only. Answers extracted from FAQ - documents. - latest_message (str): - The name of the latest conversation message used to compile - suggestion for. - - Format: - ``projects//locations//conversations//messages/``. - context_size (int): - Number of messages prior to and including - [latest_message][google.cloud.dialogflow.v2beta1.SuggestFaqAnswersResponse.latest_message] - to compile the suggestion. It may be smaller than the - [SuggestFaqAnswersRequest.context_size][google.cloud.dialogflow.v2beta1.SuggestFaqAnswersRequest.context_size] - field in the request if there aren't that many messages in - the conversation. - """ - - faq_answers: MutableSequence['FaqAnswer'] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message='FaqAnswer', - ) - latest_message: str = proto.Field( - proto.STRING, - number=2, - ) - context_size: int = proto.Field( - proto.INT32, - number=3, - ) - - -class SuggestSmartRepliesRequest(proto.Message): - r"""The request message for - [Participants.SuggestSmartReplies][google.cloud.dialogflow.v2beta1.Participants.SuggestSmartReplies]. - - Attributes: - parent (str): - Required. The name of the participant to fetch suggestion - for. Format: - ``projects//locations//conversations//participants/``. - current_text_input (google.cloud.dialogflow_v2beta1.types.TextInput): - The current natural language text segment to - compile suggestion for. This provides a way for - user to get follow up smart reply suggestion - after a smart reply selection, without sending a - text message. - latest_message (str): - The name of the latest conversation message to compile - suggestion for. If empty, it will be the latest message of - the conversation. - - Format: - ``projects//locations//conversations//messages/``. - context_size (int): - Optional. Max number of messages prior to and including - [latest_message] to use as context when compiling the - suggestion. By default 20 and at most 50. - """ - - parent: str = proto.Field( - proto.STRING, - number=1, - ) - current_text_input: session.TextInput = proto.Field( - proto.MESSAGE, - number=4, - message=session.TextInput, - ) - latest_message: str = proto.Field( - proto.STRING, - number=2, - ) - context_size: int = proto.Field( - proto.INT32, - number=3, - ) - - -class SuggestSmartRepliesResponse(proto.Message): - r"""The response message for - [Participants.SuggestSmartReplies][google.cloud.dialogflow.v2beta1.Participants.SuggestSmartReplies]. - - Attributes: - smart_reply_answers (MutableSequence[google.cloud.dialogflow_v2beta1.types.SmartReplyAnswer]): - Output only. Multiple reply options provided - by smart reply service. The order is based on - the rank of the model prediction. The maximum - number of the returned replies is set in - SmartReplyConfig. - latest_message (str): - The name of the latest conversation message used to compile - suggestion for. - - Format: - ``projects//locations//conversations//messages/``. - context_size (int): - Number of messages prior to and including - [latest_message][google.cloud.dialogflow.v2beta1.SuggestSmartRepliesResponse.latest_message] - to compile the suggestion. It may be smaller than the - [SuggestSmartRepliesRequest.context_size][google.cloud.dialogflow.v2beta1.SuggestSmartRepliesRequest.context_size] - field in the request if there aren't that many messages in - the conversation. - """ - - smart_reply_answers: MutableSequence['SmartReplyAnswer'] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message='SmartReplyAnswer', - ) - latest_message: str = proto.Field( - proto.STRING, - number=2, - ) - context_size: int = 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: - ``projects//locations//conversations//participants/*/suggestions/``. - articles (MutableSequence[google.cloud.dialogflow_v2beta1.types.Suggestion.Article]): - Output only. Articles ordered by score in - descending order. - faq_answers (MutableSequence[google.cloud.dialogflow_v2beta1.types.Suggestion.FaqAnswer]): - Output only. Answers extracted from FAQ - documents. - create_time (google.protobuf.timestamp_pb2.Timestamp): - Output only. The time the suggestion was - created. - latest_message (str): - Output only. Latest message used as context to compile this - suggestion. - - Format: - ``projects//locations//conversations//messages/``. - """ - - class Article(proto.Message): - r"""Represents suggested article. - - Attributes: - title (str): - Output only. The article title. - uri (str): - Output only. The article URI. - snippets (MutableSequence[str]): - Output only. Article snippets. - metadata (MutableMapping[str, str]): - Output only. A map that contains metadata - about the answer and the document from which it - originates. - answer_record (str): - Output only. The name of answer record, in - the format of "projects//locations//answerRecords/". - """ - - title: str = proto.Field( - proto.STRING, - number=1, - ) - uri: str = proto.Field( - proto.STRING, - number=2, - ) - snippets: MutableSequence[str] = proto.RepeatedField( - proto.STRING, - number=3, - ) - metadata: MutableMapping[str, str] = proto.MapField( - proto.STRING, - proto.STRING, - number=5, - ) - answer_record: str = proto.Field( - proto.STRING, - number=6, - ) - - class FaqAnswer(proto.Message): - r"""Represents suggested answer from "frequently asked - questions". - - Attributes: - answer (str): - Output only. The piece of text from the ``source`` knowledge - base document. - confidence (float): - The system's confidence score that this - Knowledge answer is a good match for this - conversational query, range from 0.0 (completely - uncertain) to 1.0 (completely certain). - question (str): - Output only. The corresponding FAQ question. - source (str): - Output only. Indicates which Knowledge Document this answer - was extracted from. Format: - ``projects//locations//agent/knowledgeBases//documents/``. - metadata (MutableMapping[str, str]): - Output only. A map that contains metadata - about the answer and the document from which it - originates. - answer_record (str): - Output only. The name of answer record, in - the format of "projects//locations//answerRecords/". - """ - - answer: str = proto.Field( - proto.STRING, - number=1, - ) - confidence: float = proto.Field( - proto.FLOAT, - number=2, - ) - question: str = proto.Field( - proto.STRING, - number=3, - ) - source: str = proto.Field( - proto.STRING, - number=4, - ) - metadata: MutableMapping[str, str] = proto.MapField( - proto.STRING, - proto.STRING, - number=5, - ) - answer_record: str = proto.Field( - proto.STRING, - number=6, - ) - - name: str = proto.Field( - proto.STRING, - number=1, - ) - articles: MutableSequence[Article] = proto.RepeatedField( - proto.MESSAGE, - number=2, - message=Article, - ) - faq_answers: MutableSequence[FaqAnswer] = proto.RepeatedField( - proto.MESSAGE, - number=4, - message=FaqAnswer, - ) - create_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=5, - message=timestamp_pb2.Timestamp, - ) - latest_message: str = proto.Field( - proto.STRING, - number=7, - ) - - -class ListSuggestionsRequest(proto.Message): - r"""The request message for - [Participants.ListSuggestions][google.cloud.dialogflow.v2beta1.Participants.ListSuggestions]. - - Attributes: - parent (str): - Required. The name of the participant to fetch suggestions - for. Format: - ``projects//locations//conversations//participants/``. - page_size (int): - Optional. The maximum number of items to - return in a single page. The default value is - 100; the maximum value is 1000. - page_token (str): - Optional. The next_page_token value returned from a previous - list request. - filter (str): - Optional. Filter on suggestions fields. Currently predicates - on ``create_time`` and ``create_time_epoch_microseconds`` - are supported. ``create_time`` only support milliseconds - accuracy. E.g., - ``create_time_epoch_microseconds > 1551790877964485`` or - ``create_time > "2017-01-15T01:30:15.01Z"`` - - For more information about filtering, see `API - Filtering `__. - """ - - parent: str = proto.Field( - proto.STRING, - number=1, - ) - page_size: int = proto.Field( - proto.INT32, - number=2, - ) - page_token: str = proto.Field( - proto.STRING, - number=3, - ) - filter: str = proto.Field( - proto.STRING, - number=4, - ) - - -class ListSuggestionsResponse(proto.Message): - r"""The response message for - [Participants.ListSuggestions][google.cloud.dialogflow.v2beta1.Participants.ListSuggestions]. - - Attributes: - suggestions (MutableSequence[google.cloud.dialogflow_v2beta1.types.Suggestion]): - Required. The list of suggestions. There will be a maximum - number of items returned based on the page_size field in the - request. ``suggestions`` is sorted by ``create_time`` in - descending order. - next_page_token (str): - Optional. 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 - - suggestions: MutableSequence['Suggestion'] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message='Suggestion', - ) - next_page_token: str = proto.Field( - proto.STRING, - number=2, - ) - - -class CompileSuggestionRequest(proto.Message): - r"""The request message for - [Participants.CompileSuggestion][google.cloud.dialogflow.v2beta1.Participants.CompileSuggestion]. - - Attributes: - parent (str): - Required. The name of the participant to fetch suggestion - for. Format: - ``projects//locations//conversations//participants/``. - latest_message (str): - Optional. The name of the latest conversation message to - compile suggestion for. If empty, it will be the latest - message of the conversation. - - Format: - ``projects//locations//conversations//messages/``. - context_size (int): - Optional. Max number of messages prior to and including - [latest_message] to use as context when compiling the - suggestion. If zero or less than zero, 20 is used. - """ - - parent: str = proto.Field( - proto.STRING, - number=1, - ) - latest_message: str = proto.Field( - proto.STRING, - number=2, - ) - context_size: int = proto.Field( - proto.INT32, - number=3, - ) - - -class CompileSuggestionResponse(proto.Message): - r"""The response message for - [Participants.CompileSuggestion][google.cloud.dialogflow.v2beta1.Participants.CompileSuggestion]. - - Attributes: - suggestion (google.cloud.dialogflow_v2beta1.types.Suggestion): - The compiled suggestion. - latest_message (str): - The name of the latest conversation message used to compile - suggestion for. - - Format: - ``projects//locations//conversations//messages/``. - context_size (int): - Number of messages prior to and including - [latest_message][google.cloud.dialogflow.v2beta1.CompileSuggestionResponse.latest_message] - to compile the suggestion. It may be smaller than the - [CompileSuggestionRequest.context_size][google.cloud.dialogflow.v2beta1.CompileSuggestionRequest.context_size] - field in the request if there aren't that many messages in - the conversation. - """ - - suggestion: 'Suggestion' = proto.Field( - proto.MESSAGE, - number=1, - message='Suggestion', - ) - latest_message: str = proto.Field( - proto.STRING, - number=2, - ) - context_size: int = proto.Field( - proto.INT32, - number=3, - ) - - -class ResponseMessage(proto.Message): - r"""Response messages from an automated agent. - - This message has `oneof`_ fields (mutually exclusive fields). - For each oneof, at most one member field can be set at the same time. - Setting any member of the oneof automatically clears all other - members. - - .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields - - Attributes: - text (google.cloud.dialogflow_v2beta1.types.ResponseMessage.Text): - Returns a text response. - - This field is a member of `oneof`_ ``message``. - payload (google.protobuf.struct_pb2.Struct): - Returns a response containing a custom, - platform-specific payload. - - This field is a member of `oneof`_ ``message``. - live_agent_handoff (google.cloud.dialogflow_v2beta1.types.ResponseMessage.LiveAgentHandoff): - Hands off conversation to a live agent. - - This field is a member of `oneof`_ ``message``. - end_interaction (google.cloud.dialogflow_v2beta1.types.ResponseMessage.EndInteraction): - A signal that indicates the interaction with - the Dialogflow agent has ended. - - This field is a member of `oneof`_ ``message``. - mixed_audio (google.cloud.dialogflow_v2beta1.types.ResponseMessage.MixedAudio): - An audio response message composed of both - the synthesized Dialogflow agent responses and - the audios hosted in places known to the client. - - This field is a member of `oneof`_ ``message``. - telephony_transfer_call (google.cloud.dialogflow_v2beta1.types.ResponseMessage.TelephonyTransferCall): - A signal that the client should transfer the - phone call connected to this agent to a - third-party endpoint. - - This field is a member of `oneof`_ ``message``. - """ - - class Text(proto.Message): - r"""The text response message. - - Attributes: - text (MutableSequence[str]): - A collection of text responses. - """ - - text: MutableSequence[str] = proto.RepeatedField( - proto.STRING, - number=1, - ) - - class LiveAgentHandoff(proto.Message): - r"""Indicates that the conversation should be handed off to a human - agent. - - Dialogflow only uses this to determine which conversations were - handed off to a human agent for measurement purposes. What else to - do with this signal is up to you and your handoff procedures. - - You may set this, for example: - - - In the entry fulfillment of a CX Page if entering the page - indicates something went extremely wrong in the conversation. - - In a webhook response when you determine that the customer issue - can only be handled by a human. - - Attributes: - metadata (google.protobuf.struct_pb2.Struct): - Custom metadata for your handoff procedure. - Dialogflow doesn't impose any structure on this. - """ - - metadata: struct_pb2.Struct = proto.Field( - proto.MESSAGE, - number=1, - message=struct_pb2.Struct, - ) - - class EndInteraction(proto.Message): - r"""Indicates that interaction with the Dialogflow agent has - ended. - - """ - - class MixedAudio(proto.Message): - r"""Represents an audio message that is composed of both segments - synthesized from the Dialogflow agent prompts and ones hosted - externally at the specified URIs. - - Attributes: - segments (MutableSequence[google.cloud.dialogflow_v2beta1.types.ResponseMessage.MixedAudio.Segment]): - Segments this audio response is composed of. - """ - - class Segment(proto.Message): - r"""Represents one segment of audio. - - This message has `oneof`_ fields (mutually exclusive fields). - For each oneof, at most one member field can be set at the same time. - Setting any member of the oneof automatically clears all other - members. - - .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields - - Attributes: - audio (bytes): - Raw audio synthesized from the Dialogflow - agent's response using the output config - specified in the request. - - This field is a member of `oneof`_ ``content``. - uri (str): - Client-specific URI that points to an audio - clip accessible to the client. - - This field is a member of `oneof`_ ``content``. - allow_playback_interruption (bool): - Whether the playback of this segment can be - interrupted by the end user's speech and the - client should then start the next Dialogflow - request. - """ - - audio: bytes = proto.Field( - proto.BYTES, - number=1, - oneof='content', - ) - uri: str = proto.Field( - proto.STRING, - number=2, - oneof='content', - ) - allow_playback_interruption: bool = proto.Field( - proto.BOOL, - number=3, - ) - - segments: MutableSequence['ResponseMessage.MixedAudio.Segment'] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message='ResponseMessage.MixedAudio.Segment', - ) - - class TelephonyTransferCall(proto.Message): - r"""Represents the signal that telles the client to transfer the - phone call connected to the agent to a third-party endpoint. - - This message has `oneof`_ fields (mutually exclusive fields). - For each oneof, at most one member field can be set at the same time. - Setting any member of the oneof automatically clears all other - members. - - .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields - - Attributes: - phone_number (str): - Transfer the call to a phone number in `E.164 - format `__. - - This field is a member of `oneof`_ ``endpoint``. - sip_uri (str): - Transfer the call to a SIP endpoint. - - This field is a member of `oneof`_ ``endpoint``. - """ - - phone_number: str = proto.Field( - proto.STRING, - number=1, - oneof='endpoint', - ) - sip_uri: str = proto.Field( - proto.STRING, - number=2, - oneof='endpoint', - ) - - text: Text = proto.Field( - proto.MESSAGE, - number=1, - oneof='message', - message=Text, - ) - payload: struct_pb2.Struct = proto.Field( - proto.MESSAGE, - number=2, - oneof='message', - message=struct_pb2.Struct, - ) - live_agent_handoff: LiveAgentHandoff = proto.Field( - proto.MESSAGE, - number=3, - oneof='message', - message=LiveAgentHandoff, - ) - end_interaction: EndInteraction = proto.Field( - proto.MESSAGE, - number=4, - oneof='message', - message=EndInteraction, - ) - mixed_audio: MixedAudio = proto.Field( - proto.MESSAGE, - number=5, - oneof='message', - message=MixedAudio, - ) - telephony_transfer_call: TelephonyTransferCall = proto.Field( - proto.MESSAGE, - number=6, - oneof='message', - message=TelephonyTransferCall, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/types/session.py b/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/types/session.py deleted file mode 100644 index d985984c2..000000000 --- a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/types/session.py +++ /dev/null @@ -1,1251 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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 __future__ import annotations - -from typing import MutableMapping, MutableSequence - -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 # 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( - package='google.cloud.dialogflow.v2beta1', - manifest={ - 'DetectIntentRequest', - 'DetectIntentResponse', - 'QueryParameters', - 'QueryInput', - 'QueryResult', - 'KnowledgeAnswers', - 'StreamingDetectIntentRequest', - 'StreamingDetectIntentResponse', - 'StreamingRecognitionResult', - 'TextInput', - 'EventInput', - 'SentimentAnalysisRequestConfig', - 'SentimentAnalysisResult', - 'Sentiment', - }, -) - - -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. - Supported formats: - - - \`projects//agent/sessions/, - - ``projects//locations//agent/sessions/``, - - ``projects//agent/environments//users//sessions/``, - - ``projects//locations//agent/environments//users//sessions/``, - - If ``Location ID`` is not specified we assume default 'us' - location. If ``Environment ID`` is not specified, we assume - default 'draft' environment (``Environment ID`` might be - referred to as environment name at some places). If - ``User ID`` is not specified, we are using "-". It's up to - the API caller to choose an appropriate ``Session ID`` and - ``User Id``. They can be a random number or some type of - user and session identifiers (preferably hashed). The length - of the ``Session ID`` and ``User ID`` must not exceed 36 - characters. For more information, see the `API interactions - guide `__. - - Note: Always use agent versions for production traffic. See - `Versions and - environments `__. - query_params (google.cloud.dialogflow_v2beta1.types.QueryParameters): - The parameters of this query. - query_input (google.cloud.dialogflow_v2beta1.types.QueryInput): - Required. The input specification. It can be - set to: - 1. an audio config - which instructs the speech recognizer how to - process the speech audio, - 2. a conversational query in the form of text, - or - 3. an event that specifies which intent to - trigger. - output_audio_config (google.cloud.dialogflow_v2beta1.types.OutputAudioConfig): - Instructs the speech synthesizer how to - generate the output audio. If this field is not - set and agent-level speech synthesizer is not - configured, no output audio is generated. - output_audio_config_mask (google.protobuf.field_mask_pb2.FieldMask): - Mask for - [output_audio_config][google.cloud.dialogflow.v2beta1.DetectIntentRequest.output_audio_config] - indicating which settings in this request-level config - should override speech synthesizer settings defined at - agent-level. - - If unspecified or empty, - [output_audio_config][google.cloud.dialogflow.v2beta1.DetectIntentRequest.output_audio_config] - replaces the agent-level config in its entirety. - input_audio (bytes): - The natural language speech audio to be processed. This - field should be populated iff ``query_input`` is set to an - input audio config. A single request can contain up to 1 - minute of speech audio data. - """ - - session: str = proto.Field( - proto.STRING, - number=1, - ) - query_params: 'QueryParameters' = proto.Field( - proto.MESSAGE, - number=2, - message='QueryParameters', - ) - query_input: 'QueryInput' = proto.Field( - proto.MESSAGE, - number=3, - message='QueryInput', - ) - output_audio_config: gcd_audio_config.OutputAudioConfig = proto.Field( - proto.MESSAGE, - number=4, - message=gcd_audio_config.OutputAudioConfig, - ) - output_audio_config_mask: field_mask_pb2.FieldMask = proto.Field( - proto.MESSAGE, - number=7, - message=field_mask_pb2.FieldMask, - ) - input_audio: bytes = 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 - be used to locate a response in the training - example set or for reporting issues. - query_result (google.cloud.dialogflow_v2beta1.types.QueryResult): - The selected results of the conversational query or event - processing. See ``alternative_query_results`` for additional - potential results. - alternative_query_results (MutableSequence[google.cloud.dialogflow_v2beta1.types.QueryResult]): - If Knowledge Connectors are enabled, there could be more - than one result returned for a given query or event, and - this field will contain all results except for the top one, - which is captured in query_result. The alternative results - are ordered by decreasing - ``QueryResult.intent_detection_confidence``. If Knowledge - Connectors are disabled, this field will be empty until - multiple responses for regular intents are supported, at - which point those additional results will be surfaced here. - webhook_status (google.rpc.status_pb2.Status): - Specifies the status of the webhook request. - output_audio (bytes): - The audio data bytes encoded as specified in the request. - Note: The output audio is generated based on the values of - default platform text responses found in the - ``query_result.fulfillment_messages`` field. If multiple - default text responses exist, they will be concatenated when - generating audio. If no default platform text responses - exist, the generated audio content will be empty. - - In some scenarios, multiple output audio fields may be - present in the response structure. In these cases, only the - top-most-level audio output has content. - output_audio_config (google.cloud.dialogflow_v2beta1.types.OutputAudioConfig): - The config used by the speech synthesizer to - generate the output audio. - """ - - response_id: str = proto.Field( - proto.STRING, - number=1, - ) - query_result: 'QueryResult' = proto.Field( - proto.MESSAGE, - number=2, - message='QueryResult', - ) - alternative_query_results: MutableSequence['QueryResult'] = proto.RepeatedField( - proto.MESSAGE, - number=5, - message='QueryResult', - ) - webhook_status: status_pb2.Status = proto.Field( - proto.MESSAGE, - number=3, - message=status_pb2.Status, - ) - output_audio: bytes = proto.Field( - proto.BYTES, - number=4, - ) - output_audio_config: gcd_audio_config.OutputAudioConfig = proto.Field( - proto.MESSAGE, - number=6, - message=gcd_audio_config.OutputAudioConfig, - ) - - -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 - zone database `__, e.g., - America/New_York, Europe/Paris. If not provided, the time - zone specified in agent settings is used. - geo_location (google.type.latlng_pb2.LatLng): - The geo location of this conversational - query. - contexts (MutableSequence[google.cloud.dialogflow_v2beta1.types.Context]): - The collection of contexts to be activated - before this query is executed. - reset_contexts (bool): - Specifies whether to delete all contexts in - the current session before the new ones are - activated. - session_entity_types (MutableSequence[google.cloud.dialogflow_v2beta1.types.SessionEntityType]): - Additional session entity types to replace or - extend developer entity types with. The entity - synonyms apply to all languages and persist for - the session of this query. - payload (google.protobuf.struct_pb2.Struct): - This field can be used to pass custom data to your webhook. - Arbitrary JSON objects are supported. If supplied, the value - is used to populate the - ``WebhookRequest.original_detect_intent_request.payload`` - field sent to your webhook. - knowledge_base_names (MutableSequence[str]): - KnowledgeBases to get alternative results from. If not set, - the KnowledgeBases enabled in the agent (through UI) will be - used. Format: - ``projects//knowledgeBases/``. - sentiment_analysis_request_config (google.cloud.dialogflow_v2beta1.types.SentimentAnalysisRequestConfig): - Configures the type of sentiment analysis to - perform. If not provided, sentiment analysis is - not performed. Note: Sentiment Analysis is only - currently available for Essentials Edition - agents. - sub_agents (MutableSequence[google.cloud.dialogflow_v2beta1.types.SubAgent]): - For mega agent query, directly specify which - sub agents to query. If any specified sub agent - is not linked to the mega agent, an error will - be returned. If empty, Dialogflow will decide - which sub agents to query. If specified for a - non-mega-agent query, will be silently ignored. - webhook_headers (MutableMapping[str, str]): - This field can be used to pass HTTP headers - for a webhook call. These headers will be sent - to webhook along with the headers that have been - configured through Dialogflow web console. The - headers defined within this field will overwrite - the headers configured through Dialogflow - console if there is a conflict. Header names are - case-insensitive. Google's specified headers are - not allowed. Including: "Host", - "Content-Length", "Connection", "From", - "User-Agent", "Accept-Encoding", - "If-Modified-Since", "If-None-Match", - "X-Forwarded-For", etc. - """ - - time_zone: str = proto.Field( - proto.STRING, - number=1, - ) - geo_location: latlng_pb2.LatLng = proto.Field( - proto.MESSAGE, - number=2, - message=latlng_pb2.LatLng, - ) - contexts: MutableSequence[context.Context] = proto.RepeatedField( - proto.MESSAGE, - number=3, - message=context.Context, - ) - reset_contexts: bool = proto.Field( - proto.BOOL, - number=4, - ) - session_entity_types: MutableSequence[session_entity_type.SessionEntityType] = proto.RepeatedField( - proto.MESSAGE, - number=5, - message=session_entity_type.SessionEntityType, - ) - payload: struct_pb2.Struct = proto.Field( - proto.MESSAGE, - number=6, - message=struct_pb2.Struct, - ) - knowledge_base_names: MutableSequence[str] = proto.RepeatedField( - proto.STRING, - number=12, - ) - sentiment_analysis_request_config: 'SentimentAnalysisRequestConfig' = proto.Field( - proto.MESSAGE, - number=10, - message='SentimentAnalysisRequestConfig', - ) - sub_agents: MutableSequence[agent.SubAgent] = proto.RepeatedField( - proto.MESSAGE, - number=13, - message=agent.SubAgent, - ) - webhook_headers: MutableMapping[str, str] = proto.MapField( - proto.STRING, - proto.STRING, - number=14, - ) - - -class QueryInput(proto.Message): - r"""Represents the query input. It can contain either: - 1. An audio config which - instructs the speech recognizer how to process the speech - audio. - 2. A conversational query in the form of text. - - 3. An event that specifies which intent to trigger. - - This message has `oneof`_ fields (mutually exclusive fields). - For each oneof, at most one member field can be set at the same time. - Setting any member of the oneof automatically clears all other - members. - - .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields - - Attributes: - audio_config (google.cloud.dialogflow_v2beta1.types.InputAudioConfig): - Instructs the speech recognizer how to - process the speech audio. - - This field is a member of `oneof`_ ``input``. - text (google.cloud.dialogflow_v2beta1.types.TextInput): - The natural language text to be processed. - - This field is a member of `oneof`_ ``input``. - event (google.cloud.dialogflow_v2beta1.types.EventInput): - The event to be processed. - - This field is a member of `oneof`_ ``input``. - dtmf (google.cloud.dialogflow_v2beta1.types.TelephonyDtmfEvents): - The DTMF digits used to invoke intent and - fill in parameter value. - - This field is a member of `oneof`_ ``input``. - """ - - audio_config: gcd_audio_config.InputAudioConfig = proto.Field( - proto.MESSAGE, - number=1, - oneof='input', - message=gcd_audio_config.InputAudioConfig, - ) - text: 'TextInput' = proto.Field( - proto.MESSAGE, - number=2, - oneof='input', - message='TextInput', - ) - event: 'EventInput' = proto.Field( - proto.MESSAGE, - number=3, - oneof='input', - message='EventInput', - ) - dtmf: gcd_audio_config.TelephonyDtmfEvents = proto.Field( - proto.MESSAGE, - number=4, - oneof='input', - message=gcd_audio_config.TelephonyDtmfEvents, - ) - - -class QueryResult(proto.Message): - r"""Represents the result of conversational query or event - processing. - - Attributes: - query_text (str): - The original conversational query text: - - - If natural language text was provided as input, - ``query_text`` contains a copy of the input. - - If natural language speech audio was provided as input, - ``query_text`` contains the speech recognition result. If - speech recognizer produced multiple alternatives, a - particular one is picked. - - If automatic spell correction is enabled, ``query_text`` - will contain the corrected user input. - language_code (str): - The language that was triggered during intent detection. See - `Language - Support `__ - for a list of the currently supported language codes. - speech_recognition_confidence (float): - The Speech recognition confidence between 0.0 - and 1.0. A higher number indicates an estimated - greater likelihood that the recognized words are - correct. The default of 0.0 is a sentinel value - indicating that confidence was not set. - - This field is not guaranteed to be accurate or - set. In particular this field isn't set for - StreamingDetectIntent since the streaming - endpoint has separate confidence estimates per - portion of the audio in - StreamingRecognitionResult. - action (str): - The action name from the matched intent. - parameters (google.protobuf.struct_pb2.Struct): - The collection of extracted parameters. - Depending on your protocol or client library - language, this is a map, associative array, - symbol table, dictionary, or JSON object - composed of a collection of (MapKey, MapValue) - pairs: - - MapKey type: string - - MapKey value: parameter name - - MapValue type: - - If parameter's entity type is a - composite entity: map - Else: depending on - parameter value type, could be one of string, - number, boolean, null, list or map - - MapValue value: - - If parameter's entity type is a - composite entity: map from composite - entity property names to property values - - Else: parameter value - all_required_params_present (bool): - This field is set to: - - - ``false`` if the matched intent has required parameters - and not all of the required parameter values have been - collected. - - ``true`` if all required parameter values have been - collected, or if the matched intent doesn't contain any - required parameters. - cancels_slot_filling (bool): - Indicates whether the conversational query triggers a - cancellation for slot filling. For more information, see the - `cancel slot filling - documentation `__. - fulfillment_text (str): - The text to be pronounced to the user or shown on the - screen. Note: This is a legacy field, - ``fulfillment_messages`` should be preferred. - fulfillment_messages (MutableSequence[google.cloud.dialogflow_v2beta1.types.Intent.Message]): - The collection of rich messages to present to - the user. - webhook_source (str): - If the query was fulfilled by a webhook call, this field is - set to the value of the ``source`` field returned in the - webhook response. - webhook_payload (google.protobuf.struct_pb2.Struct): - If the query was fulfilled by a webhook call, this field is - set to the value of the ``payload`` field returned in the - webhook response. - output_contexts (MutableSequence[google.cloud.dialogflow_v2beta1.types.Context]): - The collection of output contexts. If applicable, - ``output_contexts.parameters`` contains entries with name - ``.original`` containing the original - parameter values before the query. - intent (google.cloud.dialogflow_v2beta1.types.Intent): - The intent that matched the conversational query. Some, not - all fields are filled in this message, including but not - limited to: ``name``, ``display_name``, ``end_interaction`` - and ``is_fallback``. - intent_detection_confidence (float): - The intent detection confidence. Values range from 0.0 - (completely uncertain) to 1.0 (completely certain). This - value is for informational purpose only and is only used to - help match the best intent within the classification - threshold. This value may change for the same end-user - expression at any time due to a model retraining or change - in implementation. If there are - ``multiple knowledge_answers`` messages, this value is set - to the greatest ``knowledgeAnswers.match_confidence`` value - in the list. - diagnostic_info (google.protobuf.struct_pb2.Struct): - Free-form diagnostic information for the - associated detect intent request. The fields of - this data can change without notice, so you - should not write code that depends on its - structure. - The data may contain: - - - webhook call latency - - webhook errors - sentiment_analysis_result (google.cloud.dialogflow_v2beta1.types.SentimentAnalysisResult): - The sentiment analysis result, which depends on the - ``sentiment_analysis_request_config`` specified in the - request. - knowledge_answers (google.cloud.dialogflow_v2beta1.types.KnowledgeAnswers): - The result from Knowledge Connector (if any), ordered by - decreasing ``KnowledgeAnswers.match_confidence``. - """ - - query_text: str = proto.Field( - proto.STRING, - number=1, - ) - language_code: str = proto.Field( - proto.STRING, - number=15, - ) - speech_recognition_confidence: float = proto.Field( - proto.FLOAT, - number=2, - ) - action: str = proto.Field( - proto.STRING, - number=3, - ) - parameters: struct_pb2.Struct = proto.Field( - proto.MESSAGE, - number=4, - message=struct_pb2.Struct, - ) - all_required_params_present: bool = proto.Field( - proto.BOOL, - number=5, - ) - cancels_slot_filling: bool = proto.Field( - proto.BOOL, - number=21, - ) - fulfillment_text: str = proto.Field( - proto.STRING, - number=6, - ) - fulfillment_messages: MutableSequence[gcd_intent.Intent.Message] = proto.RepeatedField( - proto.MESSAGE, - number=7, - message=gcd_intent.Intent.Message, - ) - webhook_source: str = proto.Field( - proto.STRING, - number=8, - ) - webhook_payload: struct_pb2.Struct = proto.Field( - proto.MESSAGE, - number=9, - message=struct_pb2.Struct, - ) - output_contexts: MutableSequence[context.Context] = proto.RepeatedField( - proto.MESSAGE, - number=10, - message=context.Context, - ) - intent: gcd_intent.Intent = proto.Field( - proto.MESSAGE, - number=11, - message=gcd_intent.Intent, - ) - intent_detection_confidence: float = proto.Field( - proto.FLOAT, - number=12, - ) - diagnostic_info: struct_pb2.Struct = proto.Field( - proto.MESSAGE, - number=14, - message=struct_pb2.Struct, - ) - sentiment_analysis_result: 'SentimentAnalysisResult' = proto.Field( - proto.MESSAGE, - number=17, - message='SentimentAnalysisResult', - ) - knowledge_answers: 'KnowledgeAnswers' = proto.Field( - proto.MESSAGE, - number=18, - message='KnowledgeAnswers', - ) - - -class KnowledgeAnswers(proto.Message): - r"""Represents the result of querying a Knowledge base. - - Attributes: - answers (MutableSequence[google.cloud.dialogflow_v2beta1.types.KnowledgeAnswers.Answer]): - A list of answers from Knowledge Connector. - """ - - class Answer(proto.Message): - r"""An answer from Knowledge Connector. - - Attributes: - source (str): - Indicates which Knowledge Document this answer was extracted - from. Format: - ``projects//knowledgeBases//documents/``. - faq_question (str): - The corresponding FAQ question if the answer - was extracted from a FAQ Document, empty - otherwise. - answer (str): - The piece of text from the ``source`` knowledge base - document that answers this conversational query. - match_confidence_level (google.cloud.dialogflow_v2beta1.types.KnowledgeAnswers.Answer.MatchConfidenceLevel): - The system's confidence level that this knowledge answer is - a good match for this conversational query. NOTE: The - confidence level for a given ```` pair may - change without notice, as it depends on models that are - constantly being improved. However, it will change less - frequently than the confidence score below, and should be - preferred for referencing the quality of an answer. - match_confidence (float): - The system's confidence score that this Knowledge answer is - a good match for this conversational query. The range is - from 0.0 (completely uncertain) to 1.0 (completely certain). - Note: The confidence score is likely to vary somewhat - (possibly even for identical requests), as the underlying - model is under constant improvement. It may be deprecated in - the future. We recommend using ``match_confidence_level`` - which should be generally more stable. - """ - class MatchConfidenceLevel(proto.Enum): - r"""Represents the system's confidence that this knowledge answer - is a good match for this conversational query. - - Values: - MATCH_CONFIDENCE_LEVEL_UNSPECIFIED (0): - Not specified. - LOW (1): - Indicates that the confidence is low. - MEDIUM (2): - Indicates our confidence is medium. - HIGH (3): - Indicates our confidence is high. - """ - MATCH_CONFIDENCE_LEVEL_UNSPECIFIED = 0 - LOW = 1 - MEDIUM = 2 - HIGH = 3 - - source: str = proto.Field( - proto.STRING, - number=1, - ) - faq_question: str = proto.Field( - proto.STRING, - number=2, - ) - answer: str = proto.Field( - proto.STRING, - number=3, - ) - match_confidence_level: 'KnowledgeAnswers.Answer.MatchConfidenceLevel' = proto.Field( - proto.ENUM, - number=4, - enum='KnowledgeAnswers.Answer.MatchConfidenceLevel', - ) - match_confidence: float = proto.Field( - proto.FLOAT, - number=5, - ) - - answers: MutableSequence[Answer] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message=Answer, - ) - - -class StreamingDetectIntentRequest(proto.Message): - r"""The top-level message sent by the client to the - [Sessions.StreamingDetectIntent][google.cloud.dialogflow.v2beta1.Sessions.StreamingDetectIntent] - method. - - Multiple request messages should be sent in order: - - 1. The first message must contain - [session][google.cloud.dialogflow.v2beta1.StreamingDetectIntentRequest.session], - [query_input][google.cloud.dialogflow.v2beta1.StreamingDetectIntentRequest.query_input] - plus optionally - [query_params][google.cloud.dialogflow.v2beta1.StreamingDetectIntentRequest.query_params]. - If the client wants to receive an audio response, it should also - contain - [output_audio_config][google.cloud.dialogflow.v2beta1.StreamingDetectIntentRequest.output_audio_config]. - The message must not contain - [input_audio][google.cloud.dialogflow.v2beta1.StreamingDetectIntentRequest.input_audio]. - - 2. If - [query_input][google.cloud.dialogflow.v2beta1.StreamingDetectIntentRequest.query_input] - was set to - [query_input.audio_config][google.cloud.dialogflow.v2beta1.InputAudioConfig], - all subsequent messages must contain - [input_audio][google.cloud.dialogflow.v2beta1.StreamingDetectIntentRequest.input_audio] - to continue with Speech recognition. If you decide to rather - detect an intent from text input after you already started Speech - recognition, please send a message with - [query_input.text][google.cloud.dialogflow.v2beta1.QueryInput.text]. - - However, note that: - - - Dialogflow will bill you for the audio duration so far. - - Dialogflow discards all Speech recognition results in favor of - the input text. - - Dialogflow will use the language code from the first message. - - After you sent all input, you must half-close or abort the request - stream. - - Attributes: - session (str): - Required. The name of the session the query is sent to. - Supported formats: - - - \`projects//agent/sessions/, - - ``projects//locations//agent/sessions/``, - - ``projects//agent/environments//users//sessions/``, - - ``projects//locations//agent/environments//users//sessions/``, - - If ``Location ID`` is not specified we assume default 'us' - location. If ``Environment ID`` is not specified, we assume - default 'draft' environment. If ``User ID`` is not - specified, we are using "-". It's up to the API caller to - choose an appropriate ``Session ID`` and ``User Id``. They - can be a random number or some type of user and session - identifiers (preferably hashed). The length of the - ``Session ID`` and ``User ID`` must not exceed 36 - characters. - - For more information, see the `API interactions - guide `__. - - Note: Always use agent versions for production traffic. See - `Versions and - environments `__. - query_params (google.cloud.dialogflow_v2beta1.types.QueryParameters): - The parameters of this query. - query_input (google.cloud.dialogflow_v2beta1.types.QueryInput): - Required. The input specification. It can be - set to: - 1. an audio config which instructs the speech - recognizer how to process the speech audio, - - 2. a conversational query in the form of text, - or - 3. an event that specifies which intent to - trigger. - single_utterance (bool): - DEPRECATED. Please use - [InputAudioConfig.single_utterance][google.cloud.dialogflow.v2beta1.InputAudioConfig.single_utterance] - instead. If ``false`` (default), recognition does not cease - until the client closes the stream. If ``true``, the - recognizer will detect a single spoken utterance in input - audio. Recognition ceases when it detects the audio's voice - has stopped or paused. In this case, once a detected intent - is received, the client should close the stream and start a - new request with a new stream as needed. This setting is - ignored when ``query_input`` is a piece of text or an event. - output_audio_config (google.cloud.dialogflow_v2beta1.types.OutputAudioConfig): - Instructs the speech synthesizer how to - generate the output audio. If this field is not - set and agent-level speech synthesizer is not - configured, no output audio is generated. - output_audio_config_mask (google.protobuf.field_mask_pb2.FieldMask): - Mask for - [output_audio_config][google.cloud.dialogflow.v2beta1.StreamingDetectIntentRequest.output_audio_config] - indicating which settings in this request-level config - should override speech synthesizer settings defined at - agent-level. - - If unspecified or empty, - [output_audio_config][google.cloud.dialogflow.v2beta1.StreamingDetectIntentRequest.output_audio_config] - replaces the agent-level config in its entirety. - input_audio (bytes): - The input audio content to be recognized. Must be sent if - ``query_input`` was set to a streaming input audio config. - The complete audio over all streaming messages must not - exceed 1 minute. - """ - - session: str = proto.Field( - proto.STRING, - number=1, - ) - query_params: 'QueryParameters' = proto.Field( - proto.MESSAGE, - number=2, - message='QueryParameters', - ) - query_input: 'QueryInput' = proto.Field( - proto.MESSAGE, - number=3, - message='QueryInput', - ) - single_utterance: bool = proto.Field( - proto.BOOL, - number=4, - ) - output_audio_config: gcd_audio_config.OutputAudioConfig = proto.Field( - proto.MESSAGE, - number=5, - message=gcd_audio_config.OutputAudioConfig, - ) - output_audio_config_mask: field_mask_pb2.FieldMask = proto.Field( - proto.MESSAGE, - number=7, - message=field_mask_pb2.FieldMask, - ) - input_audio: bytes = proto.Field( - proto.BYTES, - number=6, - ) - - -class StreamingDetectIntentResponse(proto.Message): - r"""The top-level message returned from the ``StreamingDetectIntent`` - method. - - Multiple response messages can be returned in order: - - 1. If the ``StreamingDetectIntentRequest.input_audio`` field was - set, the ``recognition_result`` field is populated for one or - more messages. See the - [StreamingRecognitionResult][google.cloud.dialogflow.v2beta1.StreamingRecognitionResult] - message for details about the result message sequence. - - 2. The next message contains ``response_id``, ``query_result``, - ``alternative_query_results`` and optionally ``webhook_status`` - if a WebHook was called. - - 3. If ``output_audio_config`` was specified in the request or - agent-level speech synthesizer is configured, all subsequent - messages contain ``output_audio`` and ``output_audio_config``. - - Attributes: - response_id (str): - The unique identifier of the response. It can - be used to locate a response in the training - example set or for reporting issues. - recognition_result (google.cloud.dialogflow_v2beta1.types.StreamingRecognitionResult): - The result of speech recognition. - query_result (google.cloud.dialogflow_v2beta1.types.QueryResult): - The selected results of the conversational query or event - processing. See ``alternative_query_results`` for additional - potential results. - alternative_query_results (MutableSequence[google.cloud.dialogflow_v2beta1.types.QueryResult]): - If Knowledge Connectors are enabled, there could be more - than one result returned for a given query or event, and - this field will contain all results except for the top one, - which is captured in query_result. The alternative results - are ordered by decreasing - ``QueryResult.intent_detection_confidence``. If Knowledge - Connectors are disabled, this field will be empty until - multiple responses for regular intents are supported, at - which point those additional results will be surfaced here. - webhook_status (google.rpc.status_pb2.Status): - Specifies the status of the webhook request. - output_audio (bytes): - The audio data bytes encoded as specified in the request. - Note: The output audio is generated based on the values of - default platform text responses found in the - ``query_result.fulfillment_messages`` field. If multiple - default text responses exist, they will be concatenated when - generating audio. If no default platform text responses - exist, the generated audio content will be empty. - - In some scenarios, multiple output audio fields may be - present in the response structure. In these cases, only the - top-most-level audio output has content. - output_audio_config (google.cloud.dialogflow_v2beta1.types.OutputAudioConfig): - The config used by the speech synthesizer to - generate the output audio. - """ - - response_id: str = proto.Field( - proto.STRING, - number=1, - ) - recognition_result: 'StreamingRecognitionResult' = proto.Field( - proto.MESSAGE, - number=2, - message='StreamingRecognitionResult', - ) - query_result: 'QueryResult' = proto.Field( - proto.MESSAGE, - number=3, - message='QueryResult', - ) - alternative_query_results: MutableSequence['QueryResult'] = proto.RepeatedField( - proto.MESSAGE, - number=7, - message='QueryResult', - ) - webhook_status: status_pb2.Status = proto.Field( - proto.MESSAGE, - number=4, - message=status_pb2.Status, - ) - output_audio: bytes = proto.Field( - proto.BYTES, - number=5, - ) - output_audio_config: gcd_audio_config.OutputAudioConfig = proto.Field( - proto.MESSAGE, - number=6, - message=gcd_audio_config.OutputAudioConfig, - ) - - -class StreamingRecognitionResult(proto.Message): - r"""Contains a speech recognition result corresponding to a portion of - the audio that is currently being processed or an indication that - this is the end of the single requested utterance. - - While end-user audio is being processed, Dialogflow sends a series - of results. Each result may contain a ``transcript`` value. A - transcript represents a portion of the utterance. While the - recognizer is processing audio, transcript values may be interim - values or finalized values. Once a transcript is finalized, the - ``is_final`` value is set to true and processing continues for the - next transcript. - - If - ``StreamingDetectIntentRequest.query_input.audio_config.single_utterance`` - was true, and the recognizer has completed processing audio, the - ``message_type`` value is set to \`END_OF_SINGLE_UTTERANCE and the - following (last) result contains the last finalized transcript. - - The complete end-user utterance is determined by concatenating the - finalized transcript values received for the series of results. - - In the following example, single utterance is enabled. In the case - where single utterance is not enabled, result 7 would not occur. - - :: - - Num | transcript | message_type | is_final - --- | ----------------------- | ----------------------- | -------- - 1 | "tube" | TRANSCRIPT | false - 2 | "to be a" | TRANSCRIPT | false - 3 | "to be" | TRANSCRIPT | false - 4 | "to be or not to be" | TRANSCRIPT | true - 5 | "that's" | TRANSCRIPT | false - 6 | "that is | TRANSCRIPT | false - 7 | unset | END_OF_SINGLE_UTTERANCE | unset - 8 | " that is the question" | TRANSCRIPT | true - - Concatenating the finalized transcripts with ``is_final`` set to - true, the complete utterance becomes "to be or not to be that is the - question". - - Attributes: - message_type (google.cloud.dialogflow_v2beta1.types.StreamingRecognitionResult.MessageType): - Type of the result message. - transcript (str): - Transcript text representing the words that the user spoke. - Populated if and only if ``message_type`` = ``TRANSCRIPT``. - is_final (bool): - If ``false``, the ``StreamingRecognitionResult`` represents - an interim result that may change. If ``true``, the - recognizer will not return any further hypotheses about this - piece of the audio. May only be populated for - ``message_type`` = ``TRANSCRIPT``. - confidence (float): - The Speech confidence between 0.0 and 1.0 for the current - portion of audio. A higher number indicates an estimated - greater likelihood that the recognized words are correct. - The default of 0.0 is a sentinel value indicating that - confidence was not set. - - This field is typically only provided if ``is_final`` is - true and you should not rely on it being accurate or even - set. - stability (float): - An estimate of the likelihood that the speech recognizer - will not change its guess about this interim recognition - result: - - - If the value is unspecified or 0.0, Dialogflow didn't - compute the stability. In particular, Dialogflow will - only provide stability for ``TRANSCRIPT`` results with - ``is_final = false``. - - Otherwise, the value is in (0.0, 1.0] where 0.0 means - completely unstable and 1.0 means completely stable. - speech_word_info (MutableSequence[google.cloud.dialogflow_v2beta1.types.SpeechWordInfo]): - Word-specific information for the words recognized by Speech - in - [transcript][google.cloud.dialogflow.v2beta1.StreamingRecognitionResult.transcript]. - Populated if and only if ``message_type`` = ``TRANSCRIPT`` - and [InputAudioConfig.enable_word_info] is set. - speech_end_offset (google.protobuf.duration_pb2.Duration): - Time offset of the end of this Speech recognition result - relative to the beginning of the audio. Only populated for - ``message_type`` = ``TRANSCRIPT``. - language_code (str): - Detected language code for the transcript. - dtmf_digits (google.cloud.dialogflow_v2beta1.types.TelephonyDtmfEvents): - DTMF digits. Populated if and only if ``message_type`` = - ``DTMF_DIGITS``. - """ - class MessageType(proto.Enum): - r"""Type of the response message. - - Values: - MESSAGE_TYPE_UNSPECIFIED (0): - Not specified. Should never be used. - TRANSCRIPT (1): - Message contains a (possibly partial) - transcript. - DTMF_DIGITS (3): - Message contains DTMF digits. When the client - gets the message, it should stop sending - additional data, half-close the gRPC connection, - and wait for any additional results until the - server closes the gRPC. connection. - END_OF_SINGLE_UTTERANCE (2): - Event indicates that the server has detected the end of the - user's speech utterance and expects no additional speech. - Therefore, the server will not process additional audio - (although it may subsequently return additional results). - The client should stop sending additional audio data, - half-close the gRPC connection, and wait for any additional - results until the server closes the gRPC connection. This - message is only sent if ``single_utterance`` was set to - ``true``, and is not used otherwise. - PARTIAL_DTMF_DIGITS (4): - Message contains DTMF digits. Before a message with - DTMF_DIGITS is sent, a message with PARTIAL_DTMF_DIGITS may - be sent with DTMF digits collected up to the time of - sending, which represents an intermediate result. - """ - MESSAGE_TYPE_UNSPECIFIED = 0 - TRANSCRIPT = 1 - DTMF_DIGITS = 3 - END_OF_SINGLE_UTTERANCE = 2 - PARTIAL_DTMF_DIGITS = 4 - - message_type: MessageType = proto.Field( - proto.ENUM, - number=1, - enum=MessageType, - ) - transcript: str = proto.Field( - proto.STRING, - number=2, - ) - is_final: bool = proto.Field( - proto.BOOL, - number=3, - ) - confidence: float = proto.Field( - proto.FLOAT, - number=4, - ) - stability: float = proto.Field( - proto.FLOAT, - number=6, - ) - speech_word_info: MutableSequence[gcd_audio_config.SpeechWordInfo] = proto.RepeatedField( - proto.MESSAGE, - number=7, - message=gcd_audio_config.SpeechWordInfo, - ) - speech_end_offset: duration_pb2.Duration = proto.Field( - proto.MESSAGE, - number=8, - message=duration_pb2.Duration, - ) - language_code: str = proto.Field( - proto.STRING, - number=10, - ) - dtmf_digits: gcd_audio_config.TelephonyDtmfEvents = proto.Field( - proto.MESSAGE, - number=5, - message=gcd_audio_config.TelephonyDtmfEvents, - ) - - -class TextInput(proto.Message): - r"""Represents the natural language text to be processed. - - Attributes: - text (str): - Required. The UTF-8 encoded natural language - text to be processed. Text length must not - exceed 256 characters for virtual agent - interactions. - language_code (str): - Required. The language of this conversational query. See - `Language - Support `__ - for a list of the currently supported language codes. Note - that queries in the same session do not necessarily need to - specify the same language. - """ - - text: str = proto.Field( - proto.STRING, - number=1, - ) - language_code: str = proto.Field( - proto.STRING, - number=2, - ) - - -class EventInput(proto.Message): - r"""Events allow for matching intents by event name instead of the - natural language input. For instance, input - ```` - can trigger a personalized welcome response. The parameter ``name`` - may be used by the agent in the response: - ``"Hello #welcome_event.name! What can I do for you today?"``. - - Attributes: - name (str): - Required. The unique identifier of the event. - parameters (google.protobuf.struct_pb2.Struct): - The collection of parameters associated with - the event. - Depending on your protocol or client library - language, this is a map, associative array, - symbol table, dictionary, or JSON object - composed of a collection of (MapKey, MapValue) - pairs: - - MapKey type: string - - MapKey value: parameter name - - MapValue type: - - If parameter's entity type is a - composite entity: map - Else: depending on - parameter value type, could be one of string, - number, boolean, null, list or map - - MapValue value: - - If parameter's entity type is a - composite entity: map from composite - entity property names to property values - - Else: parameter value - language_code (str): - Required. The language of this query. See `Language - Support `__ - for a list of the currently supported language codes. Note - that queries in the same session do not necessarily need to - specify the same language. - - This field is ignored when used in the context of a - [WebhookResponse.followup_event_input][google.cloud.dialogflow.v2beta1.WebhookResponse.followup_event_input] - field, because the language was already defined in the - originating detect intent request. - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - parameters: struct_pb2.Struct = proto.Field( - proto.MESSAGE, - number=2, - message=struct_pb2.Struct, - ) - language_code: str = 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 - ``query_text``. If not provided, sentiment analysis is not - performed on ``query_text``. - """ - - analyze_query_text_sentiment: bool = proto.Field( - proto.BOOL, - number=1, - ) - - -class SentimentAnalysisResult(proto.Message): - r"""The result of sentiment analysis. Sentiment analysis inspects user - input and identifies the prevailing subjective opinion, especially - to determine a user's attitude as positive, negative, or neutral. - For [Participants.DetectIntent][], it needs to be configured in - [DetectIntentRequest.query_params][google.cloud.dialogflow.v2beta1.DetectIntentRequest.query_params]. - For [Participants.StreamingDetectIntent][], it needs to be - configured in - [StreamingDetectIntentRequest.query_params][google.cloud.dialogflow.v2beta1.StreamingDetectIntentRequest.query_params]. - And for - [Participants.AnalyzeContent][google.cloud.dialogflow.v2beta1.Participants.AnalyzeContent] - and - [Participants.StreamingAnalyzeContent][google.cloud.dialogflow.v2beta1.Participants.StreamingAnalyzeContent], - it needs to be configured in - [ConversationProfile.human_agent_assistant_config][google.cloud.dialogflow.v2beta1.ConversationProfile.human_agent_assistant_config] - - Attributes: - query_text_sentiment (google.cloud.dialogflow_v2beta1.types.Sentiment): - The sentiment analysis result for ``query_text``. - """ - - query_text_sentiment: 'Sentiment' = proto.Field( - proto.MESSAGE, - number=1, - message='Sentiment', - ) - - -class Sentiment(proto.Message): - r"""The sentiment, such as positive/negative feeling or association, for - a unit of analysis, such as the query text. See: - https://cloud.google.com/natural-language/docs/basics#interpreting_sentiment_analysis_values - for how to interpret the result. - - Attributes: - score (float): - Sentiment score between -1.0 (negative - sentiment) and 1.0 (positive sentiment). - magnitude (float): - A non-negative number in the [0, +inf) range, which - represents the absolute magnitude of sentiment, regardless - of score (positive or negative). - """ - - score: float = proto.Field( - proto.FLOAT, - number=1, - ) - magnitude: float = proto.Field( - proto.FLOAT, - number=2, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/types/session_entity_type.py b/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/types/session_entity_type.py deleted file mode 100644 index 0960aeaf9..000000000 --- a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/types/session_entity_type.py +++ /dev/null @@ -1,300 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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 __future__ import annotations - -from typing import MutableMapping, MutableSequence - -import proto # type: ignore - -from google.cloud.dialogflow_v2beta1.types import entity_type -from google.protobuf import field_mask_pb2 # type: ignore - - -__protobuf__ = proto.module( - package='google.cloud.dialogflow.v2beta1', - manifest={ - 'SessionEntityType', - 'ListSessionEntityTypesRequest', - 'ListSessionEntityTypesResponse', - 'GetSessionEntityTypeRequest', - 'CreateSessionEntityTypeRequest', - 'UpdateSessionEntityTypeRequest', - 'DeleteSessionEntityTypeRequest', - }, -) - - -class SessionEntityType(proto.Message): - r"""A session represents a conversation between a Dialogflow agent and - an end-user. You can create special entities, called session - entities, during a session. Session entities can extend or replace - custom entity types and only exist during the session that they were - created for. All session data, including session entities, is stored - by Dialogflow for 20 minutes. - - For more information, see the `session entity - guide `__. - - Attributes: - name (str): - Required. The unique identifier of this session entity type. - Supported formats: - - - ``projects//agent/sessions//entityTypes/`` - - ``projects//locations//agent/sessions//entityTypes/`` - - ``projects//agent/environments//users//sessions//entityTypes/`` - - ``projects//locations//agent/environments/ /users//sessions//entityTypes/`` - - If ``Location ID`` is not specified we assume default 'us' - location. If ``Environment ID`` is not specified, we assume - default 'draft' environment. If ``User ID`` is not - specified, we assume default '-' user. - ```` must be the display name of - an existing entity type in the same agent that will be - overridden or supplemented. - entity_override_mode (google.cloud.dialogflow_v2beta1.types.SessionEntityType.EntityOverrideMode): - Required. Indicates whether the additional - data should override or supplement the custom - entity type definition. - entities (MutableSequence[google.cloud.dialogflow_v2beta1.types.EntityType.Entity]): - Required. The collection of entities - associated with this session entity type. - """ - class EntityOverrideMode(proto.Enum): - r"""The types of modifications for a session entity type. - - Values: - ENTITY_OVERRIDE_MODE_UNSPECIFIED (0): - Not specified. This value should be never - used. - ENTITY_OVERRIDE_MODE_OVERRIDE (1): - The collection of session entities overrides - the collection of entities in the corresponding - custom entity type. - ENTITY_OVERRIDE_MODE_SUPPLEMENT (2): - The collection of session entities extends the collection of - entities in the corresponding custom entity type. - - Note: Even in this override mode calls to - ``ListSessionEntityTypes``, ``GetSessionEntityType``, - ``CreateSessionEntityType`` and ``UpdateSessionEntityType`` - only return the additional entities added in this session - entity type. If you want to get the supplemented list, - please call - [EntityTypes.GetEntityType][google.cloud.dialogflow.v2beta1.EntityTypes.GetEntityType] - on the custom entity type and merge. - """ - ENTITY_OVERRIDE_MODE_UNSPECIFIED = 0 - ENTITY_OVERRIDE_MODE_OVERRIDE = 1 - ENTITY_OVERRIDE_MODE_SUPPLEMENT = 2 - - name: str = proto.Field( - proto.STRING, - number=1, - ) - entity_override_mode: EntityOverrideMode = proto.Field( - proto.ENUM, - number=2, - enum=EntityOverrideMode, - ) - entities: MutableSequence[entity_type.EntityType.Entity] = proto.RepeatedField( - proto.MESSAGE, - number=3, - message=entity_type.EntityType.Entity, - ) - - -class ListSessionEntityTypesRequest(proto.Message): - r"""The request message for - [SessionEntityTypes.ListSessionEntityTypes][google.cloud.dialogflow.v2beta1.SessionEntityTypes.ListSessionEntityTypes]. - - Attributes: - parent (str): - Required. The session to list all session entity types from. - Supported formats: - - - \`projects//agent/sessions/, - - ``projects//locations//agent/sessions/``, - - ``projects//agent/environments//users//sessions/``, - - ``projects//locations//agent/environments//users//sessions/``, - - If ``Location ID`` is not specified we assume default 'us' - location. If ``Environment ID`` is not specified, we assume - default 'draft' environment. If ``User ID`` is not - specified, we assume default '-' user. - 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: str = proto.Field( - proto.STRING, - number=1, - ) - page_size: int = proto.Field( - proto.INT32, - number=2, - ) - page_token: str = proto.Field( - proto.STRING, - number=3, - ) - - -class ListSessionEntityTypesResponse(proto.Message): - r"""The response message for - [SessionEntityTypes.ListSessionEntityTypes][google.cloud.dialogflow.v2beta1.SessionEntityTypes.ListSessionEntityTypes]. - - Attributes: - session_entity_types (MutableSequence[google.cloud.dialogflow_v2beta1.types.SessionEntityType]): - The list of session entity types. 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 - - session_entity_types: MutableSequence['SessionEntityType'] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message='SessionEntityType', - ) - next_page_token: str = proto.Field( - proto.STRING, - number=2, - ) - - -class GetSessionEntityTypeRequest(proto.Message): - r"""The request message for - [SessionEntityTypes.GetSessionEntityType][google.cloud.dialogflow.v2beta1.SessionEntityTypes.GetSessionEntityType]. - - Attributes: - name (str): - Required. The name of the session entity type. Supported - formats: - - - ``projects//agent/sessions//entityTypes/`` - - ``projects//locations//agent/sessions//entityTypes/`` - - ``projects//agent/environments//users//sessions//entityTypes/`` - - ``projects//locations//agent/environments/ /users//sessions//entityTypes/`` - - If ``Location ID`` is not specified we assume default 'us' - location. If ``Environment ID`` is not specified, we assume - default 'draft' environment. If ``User ID`` is not - specified, we assume default '-' user. - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - - -class CreateSessionEntityTypeRequest(proto.Message): - r"""The request message for - [SessionEntityTypes.CreateSessionEntityType][google.cloud.dialogflow.v2beta1.SessionEntityTypes.CreateSessionEntityType]. - - Attributes: - parent (str): - Required. The session to create a session entity type for. - Supported formats: - - - \`projects//agent/sessions/, - - ``projects//locations//agent/sessions/``, - - ``projects//agent/environments//users//sessions/``, - - ``projects//locations//agent/environments//users//sessions/``, - - If ``Location ID`` is not specified we assume default 'us' - location. If ``Environment ID`` is not specified, we assume - default 'draft' environment. If ``User ID`` is not - specified, we assume default '-' user. - session_entity_type (google.cloud.dialogflow_v2beta1.types.SessionEntityType): - Required. The session entity type to create. - """ - - parent: str = proto.Field( - proto.STRING, - number=1, - ) - session_entity_type: 'SessionEntityType' = proto.Field( - proto.MESSAGE, - number=2, - message='SessionEntityType', - ) - - -class UpdateSessionEntityTypeRequest(proto.Message): - r"""The request message for - [SessionEntityTypes.UpdateSessionEntityType][google.cloud.dialogflow.v2beta1.SessionEntityTypes.UpdateSessionEntityType]. - - Attributes: - session_entity_type (google.cloud.dialogflow_v2beta1.types.SessionEntityType): - Required. The session entity type to update. - update_mask (google.protobuf.field_mask_pb2.FieldMask): - Optional. The mask to control which fields - get updated. - """ - - session_entity_type: 'SessionEntityType' = proto.Field( - proto.MESSAGE, - number=1, - message='SessionEntityType', - ) - update_mask: field_mask_pb2.FieldMask = proto.Field( - proto.MESSAGE, - number=2, - message=field_mask_pb2.FieldMask, - ) - - -class DeleteSessionEntityTypeRequest(proto.Message): - r"""The request message for - [SessionEntityTypes.DeleteSessionEntityType][google.cloud.dialogflow.v2beta1.SessionEntityTypes.DeleteSessionEntityType]. - - Attributes: - name (str): - Required. The name of the entity type to delete. Supported - formats: - - - ``projects//agent/sessions//entityTypes/`` - - ``projects//locations//agent/sessions//entityTypes/`` - - ``projects//agent/environments//users//sessions//entityTypes/`` - - ``projects//locations//agent/environments/ /users//sessions//entityTypes/`` - - If ``Location ID`` is not specified we assume default 'us' - location. If ``Environment ID`` is not specified, we assume - default 'draft' environment. If ``User ID`` is not - specified, we assume default '-' user. - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/types/validation_result.py b/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/types/validation_result.py deleted file mode 100644 index 9ee226de1..000000000 --- a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/types/validation_result.py +++ /dev/null @@ -1,114 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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 __future__ import annotations - -from typing import MutableMapping, MutableSequence - -import proto # type: ignore - - -__protobuf__ = proto.module( - package='google.cloud.dialogflow.v2beta1', - manifest={ - 'ValidationError', - 'ValidationResult', - }, -) - - -class ValidationError(proto.Message): - r"""Represents a single validation error. - - Attributes: - severity (google.cloud.dialogflow_v2beta1.types.ValidationError.Severity): - The severity of the error. - entries (MutableSequence[str]): - The names of the entries that the error is - associated with. Format: - - - "projects//agent", if the error is - associated with the entire agent. - - "projects//agent/intents/", if the error is associated with certain - intents. - - "projects//agent/intents//trainingPhrases/", if - the error is associated with certain intent - training phrases. - "projects//agent/intents//parameters/", if the error is - associated with certain intent parameters. - - "projects//agent/entities/", if the error is associated with certain - entities. - error_message (str): - The detailed error message. - """ - class Severity(proto.Enum): - r"""Represents a level of severity. - - Values: - SEVERITY_UNSPECIFIED (0): - Not specified. This value should never be - used. - INFO (1): - The agent doesn't follow Dialogflow best - practices. - WARNING (2): - The agent may not behave as expected. - ERROR (3): - The agent may experience partial failures. - CRITICAL (4): - The agent may completely fail. - """ - SEVERITY_UNSPECIFIED = 0 - INFO = 1 - WARNING = 2 - ERROR = 3 - CRITICAL = 4 - - severity: Severity = proto.Field( - proto.ENUM, - number=1, - enum=Severity, - ) - entries: MutableSequence[str] = proto.RepeatedField( - proto.STRING, - number=3, - ) - error_message: str = proto.Field( - proto.STRING, - number=4, - ) - - -class ValidationResult(proto.Message): - r"""Represents the output of agent validation. - - Attributes: - validation_errors (MutableSequence[google.cloud.dialogflow_v2beta1.types.ValidationError]): - Contains all validation errors. - """ - - validation_errors: MutableSequence['ValidationError'] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message='ValidationError', - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/types/version.py b/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/types/version.py deleted file mode 100644 index b98b7c3a5..000000000 --- a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/types/version.py +++ /dev/null @@ -1,281 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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 __future__ import annotations - -from typing import MutableMapping, MutableSequence - -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. - - Values: - VERSION_STATUS_UNSPECIFIED (0): - Not specified. This value is not used. - IN_PROGRESS (1): - Version is not ready to serve (e.g. training - is in progress). - READY (2): - Version is ready to serve. - FAILED (3): - Version training failed. - """ - VERSION_STATUS_UNSPECIFIED = 0 - IN_PROGRESS = 1 - READY = 2 - FAILED = 3 - - name: str = proto.Field( - proto.STRING, - number=1, - ) - description: str = proto.Field( - proto.STRING, - number=2, - ) - version_number: int = proto.Field( - proto.INT32, - number=3, - ) - create_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=4, - message=timestamp_pb2.Timestamp, - ) - status: VersionStatus = 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: str = proto.Field( - proto.STRING, - number=1, - ) - page_size: int = proto.Field( - proto.INT32, - number=2, - ) - page_token: str = 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 (MutableSequence[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: MutableSequence['Version'] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message='Version', - ) - next_page_token: str = 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: str = 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: str = proto.Field( - proto.STRING, - number=1, - ) - version: '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: 'Version' = proto.Field( - proto.MESSAGE, - number=1, - message='Version', - ) - update_mask: field_mask_pb2.FieldMask = 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: str = proto.Field( - proto.STRING, - number=1, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/types/webhook.py b/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/types/webhook.py deleted file mode 100644 index db02fdaa9..000000000 --- a/owl-bot-staging/v2beta1/google/cloud/dialogflow_v2beta1/types/webhook.py +++ /dev/null @@ -1,265 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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 __future__ import annotations - -from typing import MutableMapping, MutableSequence - -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 # type: ignore - - -__protobuf__ = proto.module( - package='google.cloud.dialogflow.v2beta1', - manifest={ - 'WebhookRequest', - 'WebhookResponse', - 'OriginalDetectIntentRequest', - }, -) - - -class WebhookRequest(proto.Message): - r"""The request message for a webhook call. - - Attributes: - session (str): - The unique identifier of detectIntent request session. Can - be used to identify end-user inside webhook implementation. - Supported formats: - - - \`projects//agent/sessions/, - - ``projects//locations//agent/sessions/``, - - ``projects//agent/environments//users//sessions/``, - - ``projects//locations//agent/environments//users//sessions/``, - response_id (str): - The unique identifier of the response. Contains the same - value as ``[Streaming]DetectIntentResponse.response_id``. - query_result (google.cloud.dialogflow_v2beta1.types.QueryResult): - The result of the conversational query or event processing. - Contains the same value as - ``[Streaming]DetectIntentResponse.query_result``. - alternative_query_results (MutableSequence[google.cloud.dialogflow_v2beta1.types.QueryResult]): - Alternative query results from - KnowledgeService. - original_detect_intent_request (google.cloud.dialogflow_v2beta1.types.OriginalDetectIntentRequest): - Optional. The contents of the original request that was - passed to ``[Streaming]DetectIntent`` call. - """ - - session: str = proto.Field( - proto.STRING, - number=4, - ) - response_id: str = proto.Field( - proto.STRING, - number=1, - ) - query_result: gcd_session.QueryResult = proto.Field( - proto.MESSAGE, - number=2, - message=gcd_session.QueryResult, - ) - alternative_query_results: MutableSequence[gcd_session.QueryResult] = proto.RepeatedField( - proto.MESSAGE, - number=5, - message=gcd_session.QueryResult, - ) - original_detect_intent_request: 'OriginalDetectIntentRequest' = proto.Field( - proto.MESSAGE, - number=3, - message='OriginalDetectIntentRequest', - ) - - -class WebhookResponse(proto.Message): - r"""The response message for a webhook call. - - This response is validated by the Dialogflow server. If validation - fails, an error will be returned in the - [QueryResult.diagnostic_info][google.cloud.dialogflow.v2beta1.QueryResult.diagnostic_info] - field. Setting JSON fields to an empty value with the wrong type is - a common error. To avoid this error: - - - Use ``""`` for empty strings - - Use ``{}`` or ``null`` for empty objects - - Use ``[]`` or ``null`` for empty arrays - - For more information, see the `Protocol Buffers Language - Guide `__. - - Attributes: - fulfillment_text (str): - Optional. The text response message intended for the - end-user. It is recommended to use - ``fulfillment_messages.text.text[0]`` instead. When - provided, Dialogflow uses this field to populate - [QueryResult.fulfillment_text][google.cloud.dialogflow.v2beta1.QueryResult.fulfillment_text] - sent to the integration or API caller. - fulfillment_messages (MutableSequence[google.cloud.dialogflow_v2beta1.types.Intent.Message]): - Optional. The rich response messages intended for the - end-user. When provided, Dialogflow uses this field to - populate - [QueryResult.fulfillment_messages][google.cloud.dialogflow.v2beta1.QueryResult.fulfillment_messages] - sent to the integration or API caller. - source (str): - Optional. A custom field used to identify the webhook - source. Arbitrary strings are supported. When provided, - Dialogflow uses this field to populate - [QueryResult.webhook_source][google.cloud.dialogflow.v2beta1.QueryResult.webhook_source] - sent to the integration or API caller. - payload (google.protobuf.struct_pb2.Struct): - Optional. This field can be used to pass custom data from - your webhook to the integration or API caller. Arbitrary - JSON objects are supported. When provided, Dialogflow uses - this field to populate - [QueryResult.webhook_payload][google.cloud.dialogflow.v2beta1.QueryResult.webhook_payload] - sent to the integration or API caller. This field is also - used by the `Google Assistant - integration `__ - for rich response messages. See the format definition at - `Google Assistant Dialogflow webhook - format `__ - output_contexts (MutableSequence[google.cloud.dialogflow_v2beta1.types.Context]): - Optional. The collection of output contexts that will - overwrite currently active contexts for the session and - reset their lifespans. When provided, Dialogflow uses this - field to populate - [QueryResult.output_contexts][google.cloud.dialogflow.v2beta1.QueryResult.output_contexts] - sent to the integration or API caller. - followup_event_input (google.cloud.dialogflow_v2beta1.types.EventInput): - Optional. Invokes the supplied events. When this field is - set, Dialogflow ignores the ``fulfillment_text``, - ``fulfillment_messages``, and ``payload`` fields. - live_agent_handoff (bool): - Indicates that a live agent should be brought in to handle - the interaction with the user. In most cases, when you set - this flag to true, you would also want to set - end_interaction to true as well. Default is false. - end_interaction (bool): - Optional. Indicates that this intent ends an - interaction. Some integrations (e.g., Actions on - Google or Dialogflow phone gateway) use this - information to close interaction with an end - user. Default is false. - session_entity_types (MutableSequence[google.cloud.dialogflow_v2beta1.types.SessionEntityType]): - Optional. Additional session entity types to replace or - extend developer entity types with. The entity synonyms - apply to all languages and persist for the session. Setting - this data from a webhook overwrites the session entity types - that have been set using ``detectIntent``, - ``streamingDetectIntent`` or - [SessionEntityType][google.cloud.dialogflow.v2beta1.SessionEntityType] - management methods. - """ - - fulfillment_text: str = proto.Field( - proto.STRING, - number=1, - ) - fulfillment_messages: MutableSequence[intent.Intent.Message] = proto.RepeatedField( - proto.MESSAGE, - number=2, - message=intent.Intent.Message, - ) - source: str = proto.Field( - proto.STRING, - number=3, - ) - payload: struct_pb2.Struct = proto.Field( - proto.MESSAGE, - number=4, - message=struct_pb2.Struct, - ) - output_contexts: MutableSequence[context.Context] = proto.RepeatedField( - proto.MESSAGE, - number=5, - message=context.Context, - ) - followup_event_input: gcd_session.EventInput = proto.Field( - proto.MESSAGE, - number=6, - message=gcd_session.EventInput, - ) - live_agent_handoff: bool = proto.Field( - proto.BOOL, - number=7, - ) - end_interaction: bool = proto.Field( - proto.BOOL, - number=8, - ) - session_entity_types: MutableSequence[session_entity_type.SessionEntityType] = proto.RepeatedField( - proto.MESSAGE, - number=10, - message=session_entity_type.SessionEntityType, - ) - - -class OriginalDetectIntentRequest(proto.Message): - r"""Represents the contents of the original request that was passed to - the ``[Streaming]DetectIntent`` call. - - Attributes: - source (str): - The source of this request, e.g., ``google``, ``facebook``, - ``slack``. It is set by Dialogflow-owned servers. - version (str): - Optional. The version of the protocol used - for this request. This field is AoG-specific. - payload (google.protobuf.struct_pb2.Struct): - Optional. This field is set to the value of the - ``QueryParameters.payload`` field passed in the request. - Some integrations that query a Dialogflow agent may provide - additional information in the payload. - - In particular, for the Dialogflow Phone Gateway integration, - this field has the form: - - .. raw:: html - -
{
-                 "telephony": {
-                   "caller_id": "+18558363987"
-                 }
-                }
- - Note: The caller ID field (``caller_id``) will be redacted - for Trial Edition agents and populated with the caller ID in - `E.164 format `__ for - Essentials Edition agents. - """ - - source: str = proto.Field( - proto.STRING, - number=1, - ) - version: str = proto.Field( - proto.STRING, - number=2, - ) - payload: struct_pb2.Struct = proto.Field( - proto.MESSAGE, - number=3, - message=struct_pb2.Struct, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v2beta1/mypy.ini b/owl-bot-staging/v2beta1/mypy.ini deleted file mode 100644 index 574c5aed3..000000000 --- a/owl-bot-staging/v2beta1/mypy.ini +++ /dev/null @@ -1,3 +0,0 @@ -[mypy] -python_version = 3.7 -namespace_packages = True diff --git a/owl-bot-staging/v2beta1/noxfile.py b/owl-bot-staging/v2beta1/noxfile.py deleted file mode 100644 index 066bc55f8..000000000 --- a/owl-bot-staging/v2beta1/noxfile.py +++ /dev/null @@ -1,184 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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 pathlib -import shutil -import subprocess -import sys - - -import nox # type: ignore - -ALL_PYTHON = [ - "3.7", - "3.8", - "3.9", - "3.10", - "3.11", -] - -CURRENT_DIRECTORY = pathlib.Path(__file__).parent.absolute() - -LOWER_BOUND_CONSTRAINTS_FILE = CURRENT_DIRECTORY / "constraints.txt" -PACKAGE_NAME = subprocess.check_output([sys.executable, "setup.py", "--name"], encoding="utf-8") - -BLACK_VERSION = "black==22.3.0" -BLACK_PATHS = ["docs", "google", "tests", "samples", "noxfile.py", "setup.py"] -DEFAULT_PYTHON_VERSION = "3.11" - -nox.sessions = [ - "unit", - "cover", - "mypy", - "check_lower_bounds" - # exclude update_lower_bounds from default - "docs", - "blacken", - "lint", - "lint_setup_py", -] - -@nox.session(python=ALL_PYTHON) -def unit(session): - """Run the unit test suite.""" - - session.install('coverage', 'pytest', 'pytest-cov', 'pytest-asyncio', 'asyncmock; python_version < "3.8"') - session.install('-e', '.') - - session.run( - 'py.test', - '--quiet', - '--cov=google/cloud/dialogflow_v2beta1/', - '--cov=tests/', - '--cov-config=.coveragerc', - '--cov-report=term', - '--cov-report=html', - os.path.join('tests', 'unit', ''.join(session.posargs)) - ) - - -@nox.session(python=DEFAULT_PYTHON_VERSION) -def cover(session): - """Run the final coverage report. - This outputs the coverage report aggregating coverage from the unit - test runs (not system test runs), and then erases coverage data. - """ - session.install("coverage", "pytest-cov") - session.run("coverage", "report", "--show-missing", "--fail-under=100") - - session.run("coverage", "erase") - - -@nox.session(python=ALL_PYTHON) -def mypy(session): - """Run the type checker.""" - session.install( - 'mypy', - 'types-requests', - 'types-protobuf' - ) - session.install('.') - session.run( - 'mypy', - '--explicit-package-bases', - 'google', - ) - - -@nox.session -def update_lower_bounds(session): - """Update lower bounds in constraints.txt to match setup.py""" - session.install('google-cloud-testutils') - session.install('.') - - session.run( - 'lower-bound-checker', - 'update', - '--package-name', - PACKAGE_NAME, - '--constraints-file', - str(LOWER_BOUND_CONSTRAINTS_FILE), - ) - - -@nox.session -def check_lower_bounds(session): - """Check lower bounds in setup.py are reflected in constraints file""" - session.install('google-cloud-testutils') - session.install('.') - - session.run( - 'lower-bound-checker', - 'check', - '--package-name', - PACKAGE_NAME, - '--constraints-file', - str(LOWER_BOUND_CONSTRAINTS_FILE), - ) - -@nox.session(python=DEFAULT_PYTHON_VERSION) -def docs(session): - """Build the docs for this library.""" - - session.install("-e", ".") - session.install("sphinx==4.0.1", "alabaster", "recommonmark") - - shutil.rmtree(os.path.join("docs", "_build"), ignore_errors=True) - session.run( - "sphinx-build", - "-W", # warnings as errors - "-T", # show full traceback on exception - "-N", # no colors - "-b", - "html", - "-d", - os.path.join("docs", "_build", "doctrees", ""), - os.path.join("docs", ""), - os.path.join("docs", "_build", "html", ""), - ) - - -@nox.session(python=DEFAULT_PYTHON_VERSION) -def lint(session): - """Run linters. - - Returns a failure if the linters find linting errors or sufficiently - serious code quality issues. - """ - session.install("flake8", BLACK_VERSION) - session.run( - "black", - "--check", - *BLACK_PATHS, - ) - session.run("flake8", "google", "tests", "samples") - - -@nox.session(python=DEFAULT_PYTHON_VERSION) -def blacken(session): - """Run black. Format code to uniform standard.""" - session.install(BLACK_VERSION) - session.run( - "black", - *BLACK_PATHS, - ) - - -@nox.session(python=DEFAULT_PYTHON_VERSION) -def lint_setup_py(session): - """Verify that setup.py is valid (including RST check).""" - session.install("docutils", "pygments") - session.run("python", "setup.py", "check", "--restructuredtext", "--strict") diff --git a/owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_agents_delete_agent_async.py b/owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_agents_delete_agent_async.py deleted file mode 100644 index b2d04e607..000000000 --- a/owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_agents_delete_agent_async.py +++ /dev/null @@ -1,50 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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. -# -# Generated code. DO NOT EDIT! -# -# Snippet for DeleteAgent -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-dialogflow - - -# [START dialogflow_v2beta1_generated_Agents_DeleteAgent_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import dialogflow_v2beta1 - - -async def sample_delete_agent(): - # Create a client - client = dialogflow_v2beta1.AgentsAsyncClient() - - # Initialize request argument(s) - request = dialogflow_v2beta1.DeleteAgentRequest( - parent="parent_value", - ) - - # Make the request - await client.delete_agent(request=request) - - -# [END dialogflow_v2beta1_generated_Agents_DeleteAgent_async] diff --git a/owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_agents_delete_agent_sync.py b/owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_agents_delete_agent_sync.py deleted file mode 100644 index 5a75b2ed1..000000000 --- a/owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_agents_delete_agent_sync.py +++ /dev/null @@ -1,50 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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. -# -# Generated code. DO NOT EDIT! -# -# Snippet for DeleteAgent -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-dialogflow - - -# [START dialogflow_v2beta1_generated_Agents_DeleteAgent_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import dialogflow_v2beta1 - - -def sample_delete_agent(): - # Create a client - client = dialogflow_v2beta1.AgentsClient() - - # Initialize request argument(s) - request = dialogflow_v2beta1.DeleteAgentRequest( - parent="parent_value", - ) - - # Make the request - client.delete_agent(request=request) - - -# [END dialogflow_v2beta1_generated_Agents_DeleteAgent_sync] diff --git a/owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_agents_export_agent_async.py b/owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_agents_export_agent_async.py deleted file mode 100644 index 95c9b230b..000000000 --- a/owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_agents_export_agent_async.py +++ /dev/null @@ -1,56 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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. -# -# Generated code. DO NOT EDIT! -# -# Snippet for ExportAgent -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-dialogflow - - -# [START dialogflow_v2beta1_generated_Agents_ExportAgent_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import dialogflow_v2beta1 - - -async def sample_export_agent(): - # Create a client - client = dialogflow_v2beta1.AgentsAsyncClient() - - # Initialize request argument(s) - request = dialogflow_v2beta1.ExportAgentRequest( - parent="parent_value", - ) - - # Make the request - operation = client.export_agent(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - -# [END dialogflow_v2beta1_generated_Agents_ExportAgent_async] diff --git a/owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_agents_export_agent_sync.py b/owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_agents_export_agent_sync.py deleted file mode 100644 index 4372bccb7..000000000 --- a/owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_agents_export_agent_sync.py +++ /dev/null @@ -1,56 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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. -# -# Generated code. DO NOT EDIT! -# -# Snippet for ExportAgent -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-dialogflow - - -# [START dialogflow_v2beta1_generated_Agents_ExportAgent_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import dialogflow_v2beta1 - - -def sample_export_agent(): - # Create a client - client = dialogflow_v2beta1.AgentsClient() - - # Initialize request argument(s) - request = dialogflow_v2beta1.ExportAgentRequest( - parent="parent_value", - ) - - # Make the request - operation = client.export_agent(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - -# [END dialogflow_v2beta1_generated_Agents_ExportAgent_sync] diff --git a/owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_agents_get_agent_async.py b/owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_agents_get_agent_async.py deleted file mode 100644 index 98f8b66f9..000000000 --- a/owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_agents_get_agent_async.py +++ /dev/null @@ -1,52 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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. -# -# Generated code. DO NOT EDIT! -# -# Snippet for GetAgent -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-dialogflow - - -# [START dialogflow_v2beta1_generated_Agents_GetAgent_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import dialogflow_v2beta1 - - -async def sample_get_agent(): - # Create a client - client = dialogflow_v2beta1.AgentsAsyncClient() - - # Initialize request argument(s) - request = dialogflow_v2beta1.GetAgentRequest( - parent="parent_value", - ) - - # Make the request - response = await client.get_agent(request=request) - - # Handle the response - print(response) - -# [END dialogflow_v2beta1_generated_Agents_GetAgent_async] diff --git a/owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_agents_get_agent_sync.py b/owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_agents_get_agent_sync.py deleted file mode 100644 index 086b9045d..000000000 --- a/owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_agents_get_agent_sync.py +++ /dev/null @@ -1,52 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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. -# -# Generated code. DO NOT EDIT! -# -# Snippet for GetAgent -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-dialogflow - - -# [START dialogflow_v2beta1_generated_Agents_GetAgent_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import dialogflow_v2beta1 - - -def sample_get_agent(): - # Create a client - client = dialogflow_v2beta1.AgentsClient() - - # Initialize request argument(s) - request = dialogflow_v2beta1.GetAgentRequest( - parent="parent_value", - ) - - # Make the request - response = client.get_agent(request=request) - - # Handle the response - print(response) - -# [END dialogflow_v2beta1_generated_Agents_GetAgent_sync] diff --git a/owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_agents_get_validation_result_async.py b/owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_agents_get_validation_result_async.py deleted file mode 100644 index 53a617332..000000000 --- a/owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_agents_get_validation_result_async.py +++ /dev/null @@ -1,52 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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. -# -# Generated code. DO NOT EDIT! -# -# Snippet for GetValidationResult -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-dialogflow - - -# [START dialogflow_v2beta1_generated_Agents_GetValidationResult_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import dialogflow_v2beta1 - - -async def sample_get_validation_result(): - # Create a client - client = dialogflow_v2beta1.AgentsAsyncClient() - - # Initialize request argument(s) - request = dialogflow_v2beta1.GetValidationResultRequest( - parent="parent_value", - ) - - # Make the request - response = await client.get_validation_result(request=request) - - # Handle the response - print(response) - -# [END dialogflow_v2beta1_generated_Agents_GetValidationResult_async] diff --git a/owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_agents_get_validation_result_sync.py b/owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_agents_get_validation_result_sync.py deleted file mode 100644 index d68bd3c96..000000000 --- a/owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_agents_get_validation_result_sync.py +++ /dev/null @@ -1,52 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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. -# -# Generated code. DO NOT EDIT! -# -# Snippet for GetValidationResult -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-dialogflow - - -# [START dialogflow_v2beta1_generated_Agents_GetValidationResult_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import dialogflow_v2beta1 - - -def sample_get_validation_result(): - # Create a client - client = dialogflow_v2beta1.AgentsClient() - - # Initialize request argument(s) - request = dialogflow_v2beta1.GetValidationResultRequest( - parent="parent_value", - ) - - # Make the request - response = client.get_validation_result(request=request) - - # Handle the response - print(response) - -# [END dialogflow_v2beta1_generated_Agents_GetValidationResult_sync] diff --git a/owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_agents_import_agent_async.py b/owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_agents_import_agent_async.py deleted file mode 100644 index a03ae5b9c..000000000 --- a/owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_agents_import_agent_async.py +++ /dev/null @@ -1,57 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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. -# -# Generated code. DO NOT EDIT! -# -# Snippet for ImportAgent -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-dialogflow - - -# [START dialogflow_v2beta1_generated_Agents_ImportAgent_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import dialogflow_v2beta1 - - -async def sample_import_agent(): - # Create a client - client = dialogflow_v2beta1.AgentsAsyncClient() - - # Initialize request argument(s) - request = dialogflow_v2beta1.ImportAgentRequest( - agent_uri="agent_uri_value", - parent="parent_value", - ) - - # Make the request - operation = client.import_agent(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - -# [END dialogflow_v2beta1_generated_Agents_ImportAgent_async] diff --git a/owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_agents_import_agent_sync.py b/owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_agents_import_agent_sync.py deleted file mode 100644 index aeae76029..000000000 --- a/owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_agents_import_agent_sync.py +++ /dev/null @@ -1,57 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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. -# -# Generated code. DO NOT EDIT! -# -# Snippet for ImportAgent -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-dialogflow - - -# [START dialogflow_v2beta1_generated_Agents_ImportAgent_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import dialogflow_v2beta1 - - -def sample_import_agent(): - # Create a client - client = dialogflow_v2beta1.AgentsClient() - - # Initialize request argument(s) - request = dialogflow_v2beta1.ImportAgentRequest( - agent_uri="agent_uri_value", - parent="parent_value", - ) - - # Make the request - operation = client.import_agent(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - -# [END dialogflow_v2beta1_generated_Agents_ImportAgent_sync] diff --git a/owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_agents_restore_agent_async.py b/owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_agents_restore_agent_async.py deleted file mode 100644 index 52ded9196..000000000 --- a/owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_agents_restore_agent_async.py +++ /dev/null @@ -1,57 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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. -# -# Generated code. DO NOT EDIT! -# -# Snippet for RestoreAgent -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-dialogflow - - -# [START dialogflow_v2beta1_generated_Agents_RestoreAgent_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import dialogflow_v2beta1 - - -async def sample_restore_agent(): - # Create a client - client = dialogflow_v2beta1.AgentsAsyncClient() - - # Initialize request argument(s) - request = dialogflow_v2beta1.RestoreAgentRequest( - agent_uri="agent_uri_value", - parent="parent_value", - ) - - # Make the request - operation = client.restore_agent(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - -# [END dialogflow_v2beta1_generated_Agents_RestoreAgent_async] diff --git a/owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_agents_restore_agent_sync.py b/owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_agents_restore_agent_sync.py deleted file mode 100644 index 5a67e6d72..000000000 --- a/owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_agents_restore_agent_sync.py +++ /dev/null @@ -1,57 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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. -# -# Generated code. DO NOT EDIT! -# -# Snippet for RestoreAgent -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-dialogflow - - -# [START dialogflow_v2beta1_generated_Agents_RestoreAgent_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import dialogflow_v2beta1 - - -def sample_restore_agent(): - # Create a client - client = dialogflow_v2beta1.AgentsClient() - - # Initialize request argument(s) - request = dialogflow_v2beta1.RestoreAgentRequest( - agent_uri="agent_uri_value", - parent="parent_value", - ) - - # Make the request - operation = client.restore_agent(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - -# [END dialogflow_v2beta1_generated_Agents_RestoreAgent_sync] diff --git a/owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_agents_search_agents_async.py b/owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_agents_search_agents_async.py deleted file mode 100644 index 933056697..000000000 --- a/owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_agents_search_agents_async.py +++ /dev/null @@ -1,53 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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. -# -# Generated code. DO NOT EDIT! -# -# Snippet for SearchAgents -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-dialogflow - - -# [START dialogflow_v2beta1_generated_Agents_SearchAgents_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import dialogflow_v2beta1 - - -async def sample_search_agents(): - # Create a client - client = dialogflow_v2beta1.AgentsAsyncClient() - - # Initialize request argument(s) - request = dialogflow_v2beta1.SearchAgentsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.search_agents(request=request) - - # Handle the response - async for response in page_result: - print(response) - -# [END dialogflow_v2beta1_generated_Agents_SearchAgents_async] diff --git a/owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_agents_search_agents_sync.py b/owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_agents_search_agents_sync.py deleted file mode 100644 index 5a0121893..000000000 --- a/owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_agents_search_agents_sync.py +++ /dev/null @@ -1,53 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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. -# -# Generated code. DO NOT EDIT! -# -# Snippet for SearchAgents -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-dialogflow - - -# [START dialogflow_v2beta1_generated_Agents_SearchAgents_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import dialogflow_v2beta1 - - -def sample_search_agents(): - # Create a client - client = dialogflow_v2beta1.AgentsClient() - - # Initialize request argument(s) - request = dialogflow_v2beta1.SearchAgentsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.search_agents(request=request) - - # Handle the response - for response in page_result: - print(response) - -# [END dialogflow_v2beta1_generated_Agents_SearchAgents_sync] diff --git a/owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_agents_set_agent_async.py b/owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_agents_set_agent_async.py deleted file mode 100644 index 2f071d167..000000000 --- a/owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_agents_set_agent_async.py +++ /dev/null @@ -1,55 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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. -# -# Generated code. DO NOT EDIT! -# -# Snippet for SetAgent -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-dialogflow - - -# [START dialogflow_v2beta1_generated_Agents_SetAgent_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import dialogflow_v2beta1 - - -async def sample_set_agent(): - # Create a client - client = dialogflow_v2beta1.AgentsAsyncClient() - - # Initialize request argument(s) - agent = dialogflow_v2beta1.Agent() - agent.parent = "parent_value" - - request = dialogflow_v2beta1.SetAgentRequest( - agent=agent, - ) - - # Make the request - response = await client.set_agent(request=request) - - # Handle the response - print(response) - -# [END dialogflow_v2beta1_generated_Agents_SetAgent_async] diff --git a/owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_agents_set_agent_sync.py b/owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_agents_set_agent_sync.py deleted file mode 100644 index 63f15e0f8..000000000 --- a/owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_agents_set_agent_sync.py +++ /dev/null @@ -1,55 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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. -# -# Generated code. DO NOT EDIT! -# -# Snippet for SetAgent -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-dialogflow - - -# [START dialogflow_v2beta1_generated_Agents_SetAgent_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import dialogflow_v2beta1 - - -def sample_set_agent(): - # Create a client - client = dialogflow_v2beta1.AgentsClient() - - # Initialize request argument(s) - agent = dialogflow_v2beta1.Agent() - agent.parent = "parent_value" - - request = dialogflow_v2beta1.SetAgentRequest( - agent=agent, - ) - - # Make the request - response = client.set_agent(request=request) - - # Handle the response - print(response) - -# [END dialogflow_v2beta1_generated_Agents_SetAgent_sync] diff --git a/owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_agents_train_agent_async.py b/owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_agents_train_agent_async.py deleted file mode 100644 index d13ff1e3d..000000000 --- a/owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_agents_train_agent_async.py +++ /dev/null @@ -1,56 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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. -# -# Generated code. DO NOT EDIT! -# -# Snippet for TrainAgent -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-dialogflow - - -# [START dialogflow_v2beta1_generated_Agents_TrainAgent_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import dialogflow_v2beta1 - - -async def sample_train_agent(): - # Create a client - client = dialogflow_v2beta1.AgentsAsyncClient() - - # Initialize request argument(s) - request = dialogflow_v2beta1.TrainAgentRequest( - parent="parent_value", - ) - - # Make the request - operation = client.train_agent(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - -# [END dialogflow_v2beta1_generated_Agents_TrainAgent_async] diff --git a/owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_agents_train_agent_sync.py b/owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_agents_train_agent_sync.py deleted file mode 100644 index 7836388a7..000000000 --- a/owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_agents_train_agent_sync.py +++ /dev/null @@ -1,56 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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. -# -# Generated code. DO NOT EDIT! -# -# Snippet for TrainAgent -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-dialogflow - - -# [START dialogflow_v2beta1_generated_Agents_TrainAgent_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import dialogflow_v2beta1 - - -def sample_train_agent(): - # Create a client - client = dialogflow_v2beta1.AgentsClient() - - # Initialize request argument(s) - request = dialogflow_v2beta1.TrainAgentRequest( - parent="parent_value", - ) - - # Make the request - operation = client.train_agent(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - -# [END dialogflow_v2beta1_generated_Agents_TrainAgent_sync] diff --git a/owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_answer_records_get_answer_record_async.py b/owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_answer_records_get_answer_record_async.py deleted file mode 100644 index 80607292c..000000000 --- a/owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_answer_records_get_answer_record_async.py +++ /dev/null @@ -1,51 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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. -# -# Generated code. DO NOT EDIT! -# -# Snippet for GetAnswerRecord -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-dialogflow - - -# [START dialogflow_v2beta1_generated_AnswerRecords_GetAnswerRecord_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import dialogflow_v2beta1 - - -async def sample_get_answer_record(): - # Create a client - client = dialogflow_v2beta1.AnswerRecordsAsyncClient() - - # Initialize request argument(s) - request = dialogflow_v2beta1.GetAnswerRecordRequest( - ) - - # Make the request - response = await client.get_answer_record(request=request) - - # Handle the response - print(response) - -# [END dialogflow_v2beta1_generated_AnswerRecords_GetAnswerRecord_async] diff --git a/owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_answer_records_get_answer_record_sync.py b/owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_answer_records_get_answer_record_sync.py deleted file mode 100644 index 83c0db0b6..000000000 --- a/owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_answer_records_get_answer_record_sync.py +++ /dev/null @@ -1,51 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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. -# -# Generated code. DO NOT EDIT! -# -# Snippet for GetAnswerRecord -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-dialogflow - - -# [START dialogflow_v2beta1_generated_AnswerRecords_GetAnswerRecord_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import dialogflow_v2beta1 - - -def sample_get_answer_record(): - # Create a client - client = dialogflow_v2beta1.AnswerRecordsClient() - - # Initialize request argument(s) - request = dialogflow_v2beta1.GetAnswerRecordRequest( - ) - - # Make the request - response = client.get_answer_record(request=request) - - # Handle the response - print(response) - -# [END dialogflow_v2beta1_generated_AnswerRecords_GetAnswerRecord_sync] diff --git a/owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_answer_records_list_answer_records_async.py b/owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_answer_records_list_answer_records_async.py deleted file mode 100644 index 577de8ea2..000000000 --- a/owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_answer_records_list_answer_records_async.py +++ /dev/null @@ -1,52 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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. -# -# Generated code. DO NOT EDIT! -# -# Snippet for ListAnswerRecords -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-dialogflow - - -# [START dialogflow_v2beta1_generated_AnswerRecords_ListAnswerRecords_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import dialogflow_v2beta1 - - -async def sample_list_answer_records(): - # Create a client - client = dialogflow_v2beta1.AnswerRecordsAsyncClient() - - # Initialize request argument(s) - request = dialogflow_v2beta1.ListAnswerRecordsRequest( - ) - - # Make the request - page_result = client.list_answer_records(request=request) - - # Handle the response - async for response in page_result: - print(response) - -# [END dialogflow_v2beta1_generated_AnswerRecords_ListAnswerRecords_async] diff --git a/owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_answer_records_list_answer_records_sync.py b/owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_answer_records_list_answer_records_sync.py deleted file mode 100644 index f4d61bdf6..000000000 --- a/owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_answer_records_list_answer_records_sync.py +++ /dev/null @@ -1,52 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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. -# -# Generated code. DO NOT EDIT! -# -# Snippet for ListAnswerRecords -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-dialogflow - - -# [START dialogflow_v2beta1_generated_AnswerRecords_ListAnswerRecords_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import dialogflow_v2beta1 - - -def sample_list_answer_records(): - # Create a client - client = dialogflow_v2beta1.AnswerRecordsClient() - - # Initialize request argument(s) - request = dialogflow_v2beta1.ListAnswerRecordsRequest( - ) - - # Make the request - page_result = client.list_answer_records(request=request) - - # Handle the response - for response in page_result: - print(response) - -# [END dialogflow_v2beta1_generated_AnswerRecords_ListAnswerRecords_sync] diff --git a/owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_answer_records_update_answer_record_async.py b/owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_answer_records_update_answer_record_async.py deleted file mode 100644 index 34708a7a5..000000000 --- a/owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_answer_records_update_answer_record_async.py +++ /dev/null @@ -1,51 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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. -# -# Generated code. DO NOT EDIT! -# -# Snippet for UpdateAnswerRecord -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-dialogflow - - -# [START dialogflow_v2beta1_generated_AnswerRecords_UpdateAnswerRecord_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import dialogflow_v2beta1 - - -async def sample_update_answer_record(): - # Create a client - client = dialogflow_v2beta1.AnswerRecordsAsyncClient() - - # Initialize request argument(s) - request = dialogflow_v2beta1.UpdateAnswerRecordRequest( - ) - - # Make the request - response = await client.update_answer_record(request=request) - - # Handle the response - print(response) - -# [END dialogflow_v2beta1_generated_AnswerRecords_UpdateAnswerRecord_async] diff --git a/owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_answer_records_update_answer_record_sync.py b/owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_answer_records_update_answer_record_sync.py deleted file mode 100644 index c0115a1fd..000000000 --- a/owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_answer_records_update_answer_record_sync.py +++ /dev/null @@ -1,51 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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. -# -# Generated code. DO NOT EDIT! -# -# Snippet for UpdateAnswerRecord -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-dialogflow - - -# [START dialogflow_v2beta1_generated_AnswerRecords_UpdateAnswerRecord_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import dialogflow_v2beta1 - - -def sample_update_answer_record(): - # Create a client - client = dialogflow_v2beta1.AnswerRecordsClient() - - # Initialize request argument(s) - request = dialogflow_v2beta1.UpdateAnswerRecordRequest( - ) - - # Make the request - response = client.update_answer_record(request=request) - - # Handle the response - print(response) - -# [END dialogflow_v2beta1_generated_AnswerRecords_UpdateAnswerRecord_sync] diff --git a/owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_contexts_create_context_async.py b/owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_contexts_create_context_async.py deleted file mode 100644 index c92782192..000000000 --- a/owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_contexts_create_context_async.py +++ /dev/null @@ -1,52 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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. -# -# Generated code. DO NOT EDIT! -# -# Snippet for CreateContext -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-dialogflow - - -# [START dialogflow_v2beta1_generated_Contexts_CreateContext_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import dialogflow_v2beta1 - - -async def sample_create_context(): - # Create a client - client = dialogflow_v2beta1.ContextsAsyncClient() - - # Initialize request argument(s) - request = dialogflow_v2beta1.CreateContextRequest( - parent="parent_value", - ) - - # Make the request - response = await client.create_context(request=request) - - # Handle the response - print(response) - -# [END dialogflow_v2beta1_generated_Contexts_CreateContext_async] diff --git a/owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_contexts_create_context_sync.py b/owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_contexts_create_context_sync.py deleted file mode 100644 index 49db7f6e5..000000000 --- a/owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_contexts_create_context_sync.py +++ /dev/null @@ -1,52 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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. -# -# Generated code. DO NOT EDIT! -# -# Snippet for CreateContext -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-dialogflow - - -# [START dialogflow_v2beta1_generated_Contexts_CreateContext_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import dialogflow_v2beta1 - - -def sample_create_context(): - # Create a client - client = dialogflow_v2beta1.ContextsClient() - - # Initialize request argument(s) - request = dialogflow_v2beta1.CreateContextRequest( - parent="parent_value", - ) - - # Make the request - response = client.create_context(request=request) - - # Handle the response - print(response) - -# [END dialogflow_v2beta1_generated_Contexts_CreateContext_sync] diff --git a/owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_contexts_delete_all_contexts_async.py b/owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_contexts_delete_all_contexts_async.py deleted file mode 100644 index 9f2f93ceb..000000000 --- a/owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_contexts_delete_all_contexts_async.py +++ /dev/null @@ -1,50 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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. -# -# Generated code. DO NOT EDIT! -# -# Snippet for DeleteAllContexts -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-dialogflow - - -# [START dialogflow_v2beta1_generated_Contexts_DeleteAllContexts_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import dialogflow_v2beta1 - - -async def sample_delete_all_contexts(): - # Create a client - client = dialogflow_v2beta1.ContextsAsyncClient() - - # Initialize request argument(s) - request = dialogflow_v2beta1.DeleteAllContextsRequest( - parent="parent_value", - ) - - # Make the request - await client.delete_all_contexts(request=request) - - -# [END dialogflow_v2beta1_generated_Contexts_DeleteAllContexts_async] diff --git a/owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_contexts_delete_all_contexts_sync.py b/owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_contexts_delete_all_contexts_sync.py deleted file mode 100644 index 81b881dc9..000000000 --- a/owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_contexts_delete_all_contexts_sync.py +++ /dev/null @@ -1,50 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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. -# -# Generated code. DO NOT EDIT! -# -# Snippet for DeleteAllContexts -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-dialogflow - - -# [START dialogflow_v2beta1_generated_Contexts_DeleteAllContexts_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import dialogflow_v2beta1 - - -def sample_delete_all_contexts(): - # Create a client - client = dialogflow_v2beta1.ContextsClient() - - # Initialize request argument(s) - request = dialogflow_v2beta1.DeleteAllContextsRequest( - parent="parent_value", - ) - - # Make the request - client.delete_all_contexts(request=request) - - -# [END dialogflow_v2beta1_generated_Contexts_DeleteAllContexts_sync] diff --git a/owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_contexts_delete_context_async.py b/owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_contexts_delete_context_async.py deleted file mode 100644 index 5985a0c87..000000000 --- a/owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_contexts_delete_context_async.py +++ /dev/null @@ -1,50 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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. -# -# Generated code. DO NOT EDIT! -# -# Snippet for DeleteContext -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-dialogflow - - -# [START dialogflow_v2beta1_generated_Contexts_DeleteContext_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import dialogflow_v2beta1 - - -async def sample_delete_context(): - # Create a client - client = dialogflow_v2beta1.ContextsAsyncClient() - - # Initialize request argument(s) - request = dialogflow_v2beta1.DeleteContextRequest( - name="name_value", - ) - - # Make the request - await client.delete_context(request=request) - - -# [END dialogflow_v2beta1_generated_Contexts_DeleteContext_async] diff --git a/owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_contexts_delete_context_sync.py b/owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_contexts_delete_context_sync.py deleted file mode 100644 index caad5e72b..000000000 --- a/owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_contexts_delete_context_sync.py +++ /dev/null @@ -1,50 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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. -# -# Generated code. DO NOT EDIT! -# -# Snippet for DeleteContext -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-dialogflow - - -# [START dialogflow_v2beta1_generated_Contexts_DeleteContext_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import dialogflow_v2beta1 - - -def sample_delete_context(): - # Create a client - client = dialogflow_v2beta1.ContextsClient() - - # Initialize request argument(s) - request = dialogflow_v2beta1.DeleteContextRequest( - name="name_value", - ) - - # Make the request - client.delete_context(request=request) - - -# [END dialogflow_v2beta1_generated_Contexts_DeleteContext_sync] diff --git a/owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_contexts_get_context_async.py b/owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_contexts_get_context_async.py deleted file mode 100644 index cb58d4a45..000000000 --- a/owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_contexts_get_context_async.py +++ /dev/null @@ -1,52 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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. -# -# Generated code. DO NOT EDIT! -# -# Snippet for GetContext -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-dialogflow - - -# [START dialogflow_v2beta1_generated_Contexts_GetContext_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import dialogflow_v2beta1 - - -async def sample_get_context(): - # Create a client - client = dialogflow_v2beta1.ContextsAsyncClient() - - # Initialize request argument(s) - request = dialogflow_v2beta1.GetContextRequest( - name="name_value", - ) - - # Make the request - response = await client.get_context(request=request) - - # Handle the response - print(response) - -# [END dialogflow_v2beta1_generated_Contexts_GetContext_async] diff --git a/owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_contexts_get_context_sync.py b/owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_contexts_get_context_sync.py deleted file mode 100644 index 435e07d54..000000000 --- a/owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_contexts_get_context_sync.py +++ /dev/null @@ -1,52 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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. -# -# Generated code. DO NOT EDIT! -# -# Snippet for GetContext -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-dialogflow - - -# [START dialogflow_v2beta1_generated_Contexts_GetContext_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import dialogflow_v2beta1 - - -def sample_get_context(): - # Create a client - client = dialogflow_v2beta1.ContextsClient() - - # Initialize request argument(s) - request = dialogflow_v2beta1.GetContextRequest( - name="name_value", - ) - - # Make the request - response = client.get_context(request=request) - - # Handle the response - print(response) - -# [END dialogflow_v2beta1_generated_Contexts_GetContext_sync] diff --git a/owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_contexts_list_contexts_async.py b/owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_contexts_list_contexts_async.py deleted file mode 100644 index ba63cab1f..000000000 --- a/owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_contexts_list_contexts_async.py +++ /dev/null @@ -1,53 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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. -# -# Generated code. DO NOT EDIT! -# -# Snippet for ListContexts -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-dialogflow - - -# [START dialogflow_v2beta1_generated_Contexts_ListContexts_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import dialogflow_v2beta1 - - -async def sample_list_contexts(): - # Create a client - client = dialogflow_v2beta1.ContextsAsyncClient() - - # Initialize request argument(s) - request = dialogflow_v2beta1.ListContextsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_contexts(request=request) - - # Handle the response - async for response in page_result: - print(response) - -# [END dialogflow_v2beta1_generated_Contexts_ListContexts_async] diff --git a/owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_contexts_list_contexts_sync.py b/owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_contexts_list_contexts_sync.py deleted file mode 100644 index 9ec11d05d..000000000 --- a/owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_contexts_list_contexts_sync.py +++ /dev/null @@ -1,53 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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. -# -# Generated code. DO NOT EDIT! -# -# Snippet for ListContexts -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-dialogflow - - -# [START dialogflow_v2beta1_generated_Contexts_ListContexts_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import dialogflow_v2beta1 - - -def sample_list_contexts(): - # Create a client - client = dialogflow_v2beta1.ContextsClient() - - # Initialize request argument(s) - request = dialogflow_v2beta1.ListContextsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_contexts(request=request) - - # Handle the response - for response in page_result: - print(response) - -# [END dialogflow_v2beta1_generated_Contexts_ListContexts_sync] diff --git a/owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_contexts_update_context_async.py b/owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_contexts_update_context_async.py deleted file mode 100644 index 5f4e25166..000000000 --- a/owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_contexts_update_context_async.py +++ /dev/null @@ -1,51 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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. -# -# Generated code. DO NOT EDIT! -# -# Snippet for UpdateContext -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-dialogflow - - -# [START dialogflow_v2beta1_generated_Contexts_UpdateContext_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import dialogflow_v2beta1 - - -async def sample_update_context(): - # Create a client - client = dialogflow_v2beta1.ContextsAsyncClient() - - # Initialize request argument(s) - request = dialogflow_v2beta1.UpdateContextRequest( - ) - - # Make the request - response = await client.update_context(request=request) - - # Handle the response - print(response) - -# [END dialogflow_v2beta1_generated_Contexts_UpdateContext_async] diff --git a/owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_contexts_update_context_sync.py b/owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_contexts_update_context_sync.py deleted file mode 100644 index 0d91e60ad..000000000 --- a/owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_contexts_update_context_sync.py +++ /dev/null @@ -1,51 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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. -# -# Generated code. DO NOT EDIT! -# -# Snippet for UpdateContext -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-dialogflow - - -# [START dialogflow_v2beta1_generated_Contexts_UpdateContext_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import dialogflow_v2beta1 - - -def sample_update_context(): - # Create a client - client = dialogflow_v2beta1.ContextsClient() - - # Initialize request argument(s) - request = dialogflow_v2beta1.UpdateContextRequest( - ) - - # Make the request - response = client.update_context(request=request) - - # Handle the response - print(response) - -# [END dialogflow_v2beta1_generated_Contexts_UpdateContext_sync] diff --git a/owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_conversation_profiles_clear_suggestion_feature_config_async.py b/owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_conversation_profiles_clear_suggestion_feature_config_async.py deleted file mode 100644 index 67470e5f8..000000000 --- a/owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_conversation_profiles_clear_suggestion_feature_config_async.py +++ /dev/null @@ -1,58 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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. -# -# Generated code. DO NOT EDIT! -# -# Snippet for ClearSuggestionFeatureConfig -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-dialogflow - - -# [START dialogflow_v2beta1_generated_ConversationProfiles_ClearSuggestionFeatureConfig_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import dialogflow_v2beta1 - - -async def sample_clear_suggestion_feature_config(): - # Create a client - client = dialogflow_v2beta1.ConversationProfilesAsyncClient() - - # Initialize request argument(s) - request = dialogflow_v2beta1.ClearSuggestionFeatureConfigRequest( - conversation_profile="conversation_profile_value", - participant_role="END_USER", - suggestion_feature_type="CONVERSATION_SUMMARIZATION", - ) - - # Make the request - operation = client.clear_suggestion_feature_config(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - -# [END dialogflow_v2beta1_generated_ConversationProfiles_ClearSuggestionFeatureConfig_async] diff --git a/owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_conversation_profiles_clear_suggestion_feature_config_sync.py b/owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_conversation_profiles_clear_suggestion_feature_config_sync.py deleted file mode 100644 index d6205dbe3..000000000 --- a/owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_conversation_profiles_clear_suggestion_feature_config_sync.py +++ /dev/null @@ -1,58 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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. -# -# Generated code. DO NOT EDIT! -# -# Snippet for ClearSuggestionFeatureConfig -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-dialogflow - - -# [START dialogflow_v2beta1_generated_ConversationProfiles_ClearSuggestionFeatureConfig_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import dialogflow_v2beta1 - - -def sample_clear_suggestion_feature_config(): - # Create a client - client = dialogflow_v2beta1.ConversationProfilesClient() - - # Initialize request argument(s) - request = dialogflow_v2beta1.ClearSuggestionFeatureConfigRequest( - conversation_profile="conversation_profile_value", - participant_role="END_USER", - suggestion_feature_type="CONVERSATION_SUMMARIZATION", - ) - - # Make the request - operation = client.clear_suggestion_feature_config(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - -# [END dialogflow_v2beta1_generated_ConversationProfiles_ClearSuggestionFeatureConfig_sync] diff --git a/owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_conversation_profiles_create_conversation_profile_async.py b/owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_conversation_profiles_create_conversation_profile_async.py deleted file mode 100644 index 7f16aaa58..000000000 --- a/owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_conversation_profiles_create_conversation_profile_async.py +++ /dev/null @@ -1,56 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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. -# -# Generated code. DO NOT EDIT! -# -# Snippet for CreateConversationProfile -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-dialogflow - - -# [START dialogflow_v2beta1_generated_ConversationProfiles_CreateConversationProfile_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import dialogflow_v2beta1 - - -async def sample_create_conversation_profile(): - # Create a client - client = dialogflow_v2beta1.ConversationProfilesAsyncClient() - - # Initialize request argument(s) - conversation_profile = dialogflow_v2beta1.ConversationProfile() - conversation_profile.display_name = "display_name_value" - - request = dialogflow_v2beta1.CreateConversationProfileRequest( - parent="parent_value", - conversation_profile=conversation_profile, - ) - - # Make the request - response = await client.create_conversation_profile(request=request) - - # Handle the response - print(response) - -# [END dialogflow_v2beta1_generated_ConversationProfiles_CreateConversationProfile_async] diff --git a/owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_conversation_profiles_create_conversation_profile_sync.py b/owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_conversation_profiles_create_conversation_profile_sync.py deleted file mode 100644 index 102dae48f..000000000 --- a/owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_conversation_profiles_create_conversation_profile_sync.py +++ /dev/null @@ -1,56 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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. -# -# Generated code. DO NOT EDIT! -# -# Snippet for CreateConversationProfile -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-dialogflow - - -# [START dialogflow_v2beta1_generated_ConversationProfiles_CreateConversationProfile_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import dialogflow_v2beta1 - - -def sample_create_conversation_profile(): - # Create a client - client = dialogflow_v2beta1.ConversationProfilesClient() - - # Initialize request argument(s) - conversation_profile = dialogflow_v2beta1.ConversationProfile() - conversation_profile.display_name = "display_name_value" - - request = dialogflow_v2beta1.CreateConversationProfileRequest( - parent="parent_value", - conversation_profile=conversation_profile, - ) - - # Make the request - response = client.create_conversation_profile(request=request) - - # Handle the response - print(response) - -# [END dialogflow_v2beta1_generated_ConversationProfiles_CreateConversationProfile_sync] diff --git a/owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_conversation_profiles_delete_conversation_profile_async.py b/owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_conversation_profiles_delete_conversation_profile_async.py deleted file mode 100644 index 81f8382a9..000000000 --- a/owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_conversation_profiles_delete_conversation_profile_async.py +++ /dev/null @@ -1,50 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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. -# -# Generated code. DO NOT EDIT! -# -# Snippet for DeleteConversationProfile -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-dialogflow - - -# [START dialogflow_v2beta1_generated_ConversationProfiles_DeleteConversationProfile_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import dialogflow_v2beta1 - - -async def sample_delete_conversation_profile(): - # Create a client - client = dialogflow_v2beta1.ConversationProfilesAsyncClient() - - # Initialize request argument(s) - request = dialogflow_v2beta1.DeleteConversationProfileRequest( - name="name_value", - ) - - # Make the request - await client.delete_conversation_profile(request=request) - - -# [END dialogflow_v2beta1_generated_ConversationProfiles_DeleteConversationProfile_async] diff --git a/owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_conversation_profiles_delete_conversation_profile_sync.py b/owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_conversation_profiles_delete_conversation_profile_sync.py deleted file mode 100644 index 63bd24085..000000000 --- a/owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_conversation_profiles_delete_conversation_profile_sync.py +++ /dev/null @@ -1,50 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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. -# -# Generated code. DO NOT EDIT! -# -# Snippet for DeleteConversationProfile -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-dialogflow - - -# [START dialogflow_v2beta1_generated_ConversationProfiles_DeleteConversationProfile_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import dialogflow_v2beta1 - - -def sample_delete_conversation_profile(): - # Create a client - client = dialogflow_v2beta1.ConversationProfilesClient() - - # Initialize request argument(s) - request = dialogflow_v2beta1.DeleteConversationProfileRequest( - name="name_value", - ) - - # Make the request - client.delete_conversation_profile(request=request) - - -# [END dialogflow_v2beta1_generated_ConversationProfiles_DeleteConversationProfile_sync] diff --git a/owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_conversation_profiles_get_conversation_profile_async.py b/owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_conversation_profiles_get_conversation_profile_async.py deleted file mode 100644 index 4d6af0a85..000000000 --- a/owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_conversation_profiles_get_conversation_profile_async.py +++ /dev/null @@ -1,52 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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. -# -# Generated code. DO NOT EDIT! -# -# Snippet for GetConversationProfile -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-dialogflow - - -# [START dialogflow_v2beta1_generated_ConversationProfiles_GetConversationProfile_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import dialogflow_v2beta1 - - -async def sample_get_conversation_profile(): - # Create a client - client = dialogflow_v2beta1.ConversationProfilesAsyncClient() - - # Initialize request argument(s) - request = dialogflow_v2beta1.GetConversationProfileRequest( - name="name_value", - ) - - # Make the request - response = await client.get_conversation_profile(request=request) - - # Handle the response - print(response) - -# [END dialogflow_v2beta1_generated_ConversationProfiles_GetConversationProfile_async] diff --git a/owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_conversation_profiles_get_conversation_profile_sync.py b/owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_conversation_profiles_get_conversation_profile_sync.py deleted file mode 100644 index 13aa8a856..000000000 --- a/owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_conversation_profiles_get_conversation_profile_sync.py +++ /dev/null @@ -1,52 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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. -# -# Generated code. DO NOT EDIT! -# -# Snippet for GetConversationProfile -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-dialogflow - - -# [START dialogflow_v2beta1_generated_ConversationProfiles_GetConversationProfile_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import dialogflow_v2beta1 - - -def sample_get_conversation_profile(): - # Create a client - client = dialogflow_v2beta1.ConversationProfilesClient() - - # Initialize request argument(s) - request = dialogflow_v2beta1.GetConversationProfileRequest( - name="name_value", - ) - - # Make the request - response = client.get_conversation_profile(request=request) - - # Handle the response - print(response) - -# [END dialogflow_v2beta1_generated_ConversationProfiles_GetConversationProfile_sync] diff --git a/owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_conversation_profiles_list_conversation_profiles_async.py b/owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_conversation_profiles_list_conversation_profiles_async.py deleted file mode 100644 index a234fd72b..000000000 --- a/owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_conversation_profiles_list_conversation_profiles_async.py +++ /dev/null @@ -1,53 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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. -# -# Generated code. DO NOT EDIT! -# -# Snippet for ListConversationProfiles -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-dialogflow - - -# [START dialogflow_v2beta1_generated_ConversationProfiles_ListConversationProfiles_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import dialogflow_v2beta1 - - -async def sample_list_conversation_profiles(): - # Create a client - client = dialogflow_v2beta1.ConversationProfilesAsyncClient() - - # Initialize request argument(s) - request = dialogflow_v2beta1.ListConversationProfilesRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_conversation_profiles(request=request) - - # Handle the response - async for response in page_result: - print(response) - -# [END dialogflow_v2beta1_generated_ConversationProfiles_ListConversationProfiles_async] diff --git a/owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_conversation_profiles_list_conversation_profiles_sync.py b/owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_conversation_profiles_list_conversation_profiles_sync.py deleted file mode 100644 index 73b698cd8..000000000 --- a/owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_conversation_profiles_list_conversation_profiles_sync.py +++ /dev/null @@ -1,53 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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. -# -# Generated code. DO NOT EDIT! -# -# Snippet for ListConversationProfiles -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-dialogflow - - -# [START dialogflow_v2beta1_generated_ConversationProfiles_ListConversationProfiles_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import dialogflow_v2beta1 - - -def sample_list_conversation_profiles(): - # Create a client - client = dialogflow_v2beta1.ConversationProfilesClient() - - # Initialize request argument(s) - request = dialogflow_v2beta1.ListConversationProfilesRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_conversation_profiles(request=request) - - # Handle the response - for response in page_result: - print(response) - -# [END dialogflow_v2beta1_generated_ConversationProfiles_ListConversationProfiles_sync] diff --git a/owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_conversation_profiles_set_suggestion_feature_config_async.py b/owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_conversation_profiles_set_suggestion_feature_config_async.py deleted file mode 100644 index c2b409996..000000000 --- a/owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_conversation_profiles_set_suggestion_feature_config_async.py +++ /dev/null @@ -1,57 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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. -# -# Generated code. DO NOT EDIT! -# -# Snippet for SetSuggestionFeatureConfig -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-dialogflow - - -# [START dialogflow_v2beta1_generated_ConversationProfiles_SetSuggestionFeatureConfig_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import dialogflow_v2beta1 - - -async def sample_set_suggestion_feature_config(): - # Create a client - client = dialogflow_v2beta1.ConversationProfilesAsyncClient() - - # Initialize request argument(s) - request = dialogflow_v2beta1.SetSuggestionFeatureConfigRequest( - conversation_profile="conversation_profile_value", - participant_role="END_USER", - ) - - # Make the request - operation = client.set_suggestion_feature_config(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - -# [END dialogflow_v2beta1_generated_ConversationProfiles_SetSuggestionFeatureConfig_async] diff --git a/owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_conversation_profiles_set_suggestion_feature_config_sync.py b/owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_conversation_profiles_set_suggestion_feature_config_sync.py deleted file mode 100644 index 7fa4d9a53..000000000 --- a/owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_conversation_profiles_set_suggestion_feature_config_sync.py +++ /dev/null @@ -1,57 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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. -# -# Generated code. DO NOT EDIT! -# -# Snippet for SetSuggestionFeatureConfig -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-dialogflow - - -# [START dialogflow_v2beta1_generated_ConversationProfiles_SetSuggestionFeatureConfig_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import dialogflow_v2beta1 - - -def sample_set_suggestion_feature_config(): - # Create a client - client = dialogflow_v2beta1.ConversationProfilesClient() - - # Initialize request argument(s) - request = dialogflow_v2beta1.SetSuggestionFeatureConfigRequest( - conversation_profile="conversation_profile_value", - participant_role="END_USER", - ) - - # Make the request - operation = client.set_suggestion_feature_config(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - -# [END dialogflow_v2beta1_generated_ConversationProfiles_SetSuggestionFeatureConfig_sync] diff --git a/owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_conversation_profiles_update_conversation_profile_async.py b/owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_conversation_profiles_update_conversation_profile_async.py deleted file mode 100644 index b74816dfb..000000000 --- a/owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_conversation_profiles_update_conversation_profile_async.py +++ /dev/null @@ -1,55 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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. -# -# Generated code. DO NOT EDIT! -# -# Snippet for UpdateConversationProfile -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-dialogflow - - -# [START dialogflow_v2beta1_generated_ConversationProfiles_UpdateConversationProfile_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import dialogflow_v2beta1 - - -async def sample_update_conversation_profile(): - # Create a client - client = dialogflow_v2beta1.ConversationProfilesAsyncClient() - - # Initialize request argument(s) - conversation_profile = dialogflow_v2beta1.ConversationProfile() - conversation_profile.display_name = "display_name_value" - - request = dialogflow_v2beta1.UpdateConversationProfileRequest( - conversation_profile=conversation_profile, - ) - - # Make the request - response = await client.update_conversation_profile(request=request) - - # Handle the response - print(response) - -# [END dialogflow_v2beta1_generated_ConversationProfiles_UpdateConversationProfile_async] diff --git a/owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_conversation_profiles_update_conversation_profile_sync.py b/owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_conversation_profiles_update_conversation_profile_sync.py deleted file mode 100644 index a1d7e253a..000000000 --- a/owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_conversation_profiles_update_conversation_profile_sync.py +++ /dev/null @@ -1,55 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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. -# -# Generated code. DO NOT EDIT! -# -# Snippet for UpdateConversationProfile -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-dialogflow - - -# [START dialogflow_v2beta1_generated_ConversationProfiles_UpdateConversationProfile_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import dialogflow_v2beta1 - - -def sample_update_conversation_profile(): - # Create a client - client = dialogflow_v2beta1.ConversationProfilesClient() - - # Initialize request argument(s) - conversation_profile = dialogflow_v2beta1.ConversationProfile() - conversation_profile.display_name = "display_name_value" - - request = dialogflow_v2beta1.UpdateConversationProfileRequest( - conversation_profile=conversation_profile, - ) - - # Make the request - response = client.update_conversation_profile(request=request) - - # Handle the response - print(response) - -# [END dialogflow_v2beta1_generated_ConversationProfiles_UpdateConversationProfile_sync] diff --git a/owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_conversations_batch_create_messages_async.py b/owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_conversations_batch_create_messages_async.py deleted file mode 100644 index be0687060..000000000 --- a/owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_conversations_batch_create_messages_async.py +++ /dev/null @@ -1,57 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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. -# -# Generated code. DO NOT EDIT! -# -# Snippet for BatchCreateMessages -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-dialogflow - - -# [START dialogflow_v2beta1_generated_Conversations_BatchCreateMessages_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import dialogflow_v2beta1 - - -async def sample_batch_create_messages(): - # Create a client - client = dialogflow_v2beta1.ConversationsAsyncClient() - - # Initialize request argument(s) - requests = dialogflow_v2beta1.CreateMessageRequest() - requests.parent = "parent_value" - requests.message.content = "content_value" - - request = dialogflow_v2beta1.BatchCreateMessagesRequest( - parent="parent_value", - requests=requests, - ) - - # Make the request - response = await client.batch_create_messages(request=request) - - # Handle the response - print(response) - -# [END dialogflow_v2beta1_generated_Conversations_BatchCreateMessages_async] diff --git a/owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_conversations_batch_create_messages_sync.py b/owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_conversations_batch_create_messages_sync.py deleted file mode 100644 index a39c23634..000000000 --- a/owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_conversations_batch_create_messages_sync.py +++ /dev/null @@ -1,57 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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. -# -# Generated code. DO NOT EDIT! -# -# Snippet for BatchCreateMessages -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-dialogflow - - -# [START dialogflow_v2beta1_generated_Conversations_BatchCreateMessages_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import dialogflow_v2beta1 - - -def sample_batch_create_messages(): - # Create a client - client = dialogflow_v2beta1.ConversationsClient() - - # Initialize request argument(s) - requests = dialogflow_v2beta1.CreateMessageRequest() - requests.parent = "parent_value" - requests.message.content = "content_value" - - request = dialogflow_v2beta1.BatchCreateMessagesRequest( - parent="parent_value", - requests=requests, - ) - - # Make the request - response = client.batch_create_messages(request=request) - - # Handle the response - print(response) - -# [END dialogflow_v2beta1_generated_Conversations_BatchCreateMessages_sync] diff --git a/owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_conversations_complete_conversation_async.py b/owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_conversations_complete_conversation_async.py deleted file mode 100644 index 3c76f4422..000000000 --- a/owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_conversations_complete_conversation_async.py +++ /dev/null @@ -1,52 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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. -# -# Generated code. DO NOT EDIT! -# -# Snippet for CompleteConversation -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-dialogflow - - -# [START dialogflow_v2beta1_generated_Conversations_CompleteConversation_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import dialogflow_v2beta1 - - -async def sample_complete_conversation(): - # Create a client - client = dialogflow_v2beta1.ConversationsAsyncClient() - - # Initialize request argument(s) - request = dialogflow_v2beta1.CompleteConversationRequest( - name="name_value", - ) - - # Make the request - response = await client.complete_conversation(request=request) - - # Handle the response - print(response) - -# [END dialogflow_v2beta1_generated_Conversations_CompleteConversation_async] diff --git a/owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_conversations_complete_conversation_sync.py b/owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_conversations_complete_conversation_sync.py deleted file mode 100644 index b40526020..000000000 --- a/owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_conversations_complete_conversation_sync.py +++ /dev/null @@ -1,52 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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. -# -# Generated code. DO NOT EDIT! -# -# Snippet for CompleteConversation -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-dialogflow - - -# [START dialogflow_v2beta1_generated_Conversations_CompleteConversation_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import dialogflow_v2beta1 - - -def sample_complete_conversation(): - # Create a client - client = dialogflow_v2beta1.ConversationsClient() - - # Initialize request argument(s) - request = dialogflow_v2beta1.CompleteConversationRequest( - name="name_value", - ) - - # Make the request - response = client.complete_conversation(request=request) - - # Handle the response - print(response) - -# [END dialogflow_v2beta1_generated_Conversations_CompleteConversation_sync] diff --git a/owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_conversations_create_conversation_async.py b/owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_conversations_create_conversation_async.py deleted file mode 100644 index 323f2fc0e..000000000 --- a/owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_conversations_create_conversation_async.py +++ /dev/null @@ -1,56 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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. -# -# Generated code. DO NOT EDIT! -# -# Snippet for CreateConversation -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-dialogflow - - -# [START dialogflow_v2beta1_generated_Conversations_CreateConversation_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import dialogflow_v2beta1 - - -async def sample_create_conversation(): - # Create a client - client = dialogflow_v2beta1.ConversationsAsyncClient() - - # Initialize request argument(s) - conversation = dialogflow_v2beta1.Conversation() - conversation.conversation_profile = "conversation_profile_value" - - request = dialogflow_v2beta1.CreateConversationRequest( - parent="parent_value", - conversation=conversation, - ) - - # Make the request - response = await client.create_conversation(request=request) - - # Handle the response - print(response) - -# [END dialogflow_v2beta1_generated_Conversations_CreateConversation_async] diff --git a/owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_conversations_create_conversation_sync.py b/owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_conversations_create_conversation_sync.py deleted file mode 100644 index 69559e93d..000000000 --- a/owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_conversations_create_conversation_sync.py +++ /dev/null @@ -1,56 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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. -# -# Generated code. DO NOT EDIT! -# -# Snippet for CreateConversation -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-dialogflow - - -# [START dialogflow_v2beta1_generated_Conversations_CreateConversation_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import dialogflow_v2beta1 - - -def sample_create_conversation(): - # Create a client - client = dialogflow_v2beta1.ConversationsClient() - - # Initialize request argument(s) - conversation = dialogflow_v2beta1.Conversation() - conversation.conversation_profile = "conversation_profile_value" - - request = dialogflow_v2beta1.CreateConversationRequest( - parent="parent_value", - conversation=conversation, - ) - - # Make the request - response = client.create_conversation(request=request) - - # Handle the response - print(response) - -# [END dialogflow_v2beta1_generated_Conversations_CreateConversation_sync] diff --git a/owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_conversations_get_conversation_async.py b/owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_conversations_get_conversation_async.py deleted file mode 100644 index b392d223e..000000000 --- a/owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_conversations_get_conversation_async.py +++ /dev/null @@ -1,52 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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. -# -# Generated code. DO NOT EDIT! -# -# Snippet for GetConversation -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-dialogflow - - -# [START dialogflow_v2beta1_generated_Conversations_GetConversation_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import dialogflow_v2beta1 - - -async def sample_get_conversation(): - # Create a client - client = dialogflow_v2beta1.ConversationsAsyncClient() - - # Initialize request argument(s) - request = dialogflow_v2beta1.GetConversationRequest( - name="name_value", - ) - - # Make the request - response = await client.get_conversation(request=request) - - # Handle the response - print(response) - -# [END dialogflow_v2beta1_generated_Conversations_GetConversation_async] diff --git a/owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_conversations_get_conversation_sync.py b/owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_conversations_get_conversation_sync.py deleted file mode 100644 index d9922d651..000000000 --- a/owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_conversations_get_conversation_sync.py +++ /dev/null @@ -1,52 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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. -# -# Generated code. DO NOT EDIT! -# -# Snippet for GetConversation -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-dialogflow - - -# [START dialogflow_v2beta1_generated_Conversations_GetConversation_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import dialogflow_v2beta1 - - -def sample_get_conversation(): - # Create a client - client = dialogflow_v2beta1.ConversationsClient() - - # Initialize request argument(s) - request = dialogflow_v2beta1.GetConversationRequest( - name="name_value", - ) - - # Make the request - response = client.get_conversation(request=request) - - # Handle the response - print(response) - -# [END dialogflow_v2beta1_generated_Conversations_GetConversation_sync] diff --git a/owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_conversations_list_conversations_async.py b/owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_conversations_list_conversations_async.py deleted file mode 100644 index bf87c04d4..000000000 --- a/owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_conversations_list_conversations_async.py +++ /dev/null @@ -1,53 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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. -# -# Generated code. DO NOT EDIT! -# -# Snippet for ListConversations -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-dialogflow - - -# [START dialogflow_v2beta1_generated_Conversations_ListConversations_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import dialogflow_v2beta1 - - -async def sample_list_conversations(): - # Create a client - client = dialogflow_v2beta1.ConversationsAsyncClient() - - # Initialize request argument(s) - request = dialogflow_v2beta1.ListConversationsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_conversations(request=request) - - # Handle the response - async for response in page_result: - print(response) - -# [END dialogflow_v2beta1_generated_Conversations_ListConversations_async] diff --git a/owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_conversations_list_conversations_sync.py b/owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_conversations_list_conversations_sync.py deleted file mode 100644 index 42f6fb25e..000000000 --- a/owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_conversations_list_conversations_sync.py +++ /dev/null @@ -1,53 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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. -# -# Generated code. DO NOT EDIT! -# -# Snippet for ListConversations -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-dialogflow - - -# [START dialogflow_v2beta1_generated_Conversations_ListConversations_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import dialogflow_v2beta1 - - -def sample_list_conversations(): - # Create a client - client = dialogflow_v2beta1.ConversationsClient() - - # Initialize request argument(s) - request = dialogflow_v2beta1.ListConversationsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_conversations(request=request) - - # Handle the response - for response in page_result: - print(response) - -# [END dialogflow_v2beta1_generated_Conversations_ListConversations_sync] diff --git a/owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_conversations_list_messages_async.py b/owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_conversations_list_messages_async.py deleted file mode 100644 index dab4570d3..000000000 --- a/owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_conversations_list_messages_async.py +++ /dev/null @@ -1,53 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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. -# -# Generated code. DO NOT EDIT! -# -# Snippet for ListMessages -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-dialogflow - - -# [START dialogflow_v2beta1_generated_Conversations_ListMessages_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import dialogflow_v2beta1 - - -async def sample_list_messages(): - # Create a client - client = dialogflow_v2beta1.ConversationsAsyncClient() - - # Initialize request argument(s) - request = dialogflow_v2beta1.ListMessagesRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_messages(request=request) - - # Handle the response - async for response in page_result: - print(response) - -# [END dialogflow_v2beta1_generated_Conversations_ListMessages_async] diff --git a/owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_conversations_list_messages_sync.py b/owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_conversations_list_messages_sync.py deleted file mode 100644 index b0fbd629a..000000000 --- a/owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_conversations_list_messages_sync.py +++ /dev/null @@ -1,53 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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. -# -# Generated code. DO NOT EDIT! -# -# Snippet for ListMessages -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-dialogflow - - -# [START dialogflow_v2beta1_generated_Conversations_ListMessages_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import dialogflow_v2beta1 - - -def sample_list_messages(): - # Create a client - client = dialogflow_v2beta1.ConversationsClient() - - # Initialize request argument(s) - request = dialogflow_v2beta1.ListMessagesRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_messages(request=request) - - # Handle the response - for response in page_result: - print(response) - -# [END dialogflow_v2beta1_generated_Conversations_ListMessages_sync] diff --git a/owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_conversations_suggest_conversation_summary_async.py b/owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_conversations_suggest_conversation_summary_async.py deleted file mode 100644 index 6b6a1e67e..000000000 --- a/owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_conversations_suggest_conversation_summary_async.py +++ /dev/null @@ -1,52 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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. -# -# Generated code. DO NOT EDIT! -# -# Snippet for SuggestConversationSummary -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-dialogflow - - -# [START dialogflow_v2beta1_generated_Conversations_SuggestConversationSummary_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import dialogflow_v2beta1 - - -async def sample_suggest_conversation_summary(): - # Create a client - client = dialogflow_v2beta1.ConversationsAsyncClient() - - # Initialize request argument(s) - request = dialogflow_v2beta1.SuggestConversationSummaryRequest( - conversation="conversation_value", - ) - - # Make the request - response = await client.suggest_conversation_summary(request=request) - - # Handle the response - print(response) - -# [END dialogflow_v2beta1_generated_Conversations_SuggestConversationSummary_async] diff --git a/owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_conversations_suggest_conversation_summary_sync.py b/owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_conversations_suggest_conversation_summary_sync.py deleted file mode 100644 index dde6224f8..000000000 --- a/owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_conversations_suggest_conversation_summary_sync.py +++ /dev/null @@ -1,52 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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. -# -# Generated code. DO NOT EDIT! -# -# Snippet for SuggestConversationSummary -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-dialogflow - - -# [START dialogflow_v2beta1_generated_Conversations_SuggestConversationSummary_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import dialogflow_v2beta1 - - -def sample_suggest_conversation_summary(): - # Create a client - client = dialogflow_v2beta1.ConversationsClient() - - # Initialize request argument(s) - request = dialogflow_v2beta1.SuggestConversationSummaryRequest( - conversation="conversation_value", - ) - - # Make the request - response = client.suggest_conversation_summary(request=request) - - # Handle the response - print(response) - -# [END dialogflow_v2beta1_generated_Conversations_SuggestConversationSummary_sync] diff --git a/owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_documents_create_document_async.py b/owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_documents_create_document_async.py deleted file mode 100644 index c6ba8fd65..000000000 --- a/owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_documents_create_document_async.py +++ /dev/null @@ -1,63 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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. -# -# Generated code. DO NOT EDIT! -# -# Snippet for CreateDocument -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-dialogflow - - -# [START dialogflow_v2beta1_generated_Documents_CreateDocument_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import dialogflow_v2beta1 - - -async def sample_create_document(): - # Create a client - client = dialogflow_v2beta1.DocumentsAsyncClient() - - # Initialize request argument(s) - document = dialogflow_v2beta1.Document() - document.content_uri = "content_uri_value" - document.display_name = "display_name_value" - document.mime_type = "mime_type_value" - document.knowledge_types = ['SMART_REPLY'] - - request = dialogflow_v2beta1.CreateDocumentRequest( - parent="parent_value", - document=document, - ) - - # Make the request - operation = client.create_document(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - -# [END dialogflow_v2beta1_generated_Documents_CreateDocument_async] diff --git a/owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_documents_create_document_sync.py b/owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_documents_create_document_sync.py deleted file mode 100644 index 8e077c689..000000000 --- a/owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_documents_create_document_sync.py +++ /dev/null @@ -1,63 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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. -# -# Generated code. DO NOT EDIT! -# -# Snippet for CreateDocument -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-dialogflow - - -# [START dialogflow_v2beta1_generated_Documents_CreateDocument_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import dialogflow_v2beta1 - - -def sample_create_document(): - # Create a client - client = dialogflow_v2beta1.DocumentsClient() - - # Initialize request argument(s) - document = dialogflow_v2beta1.Document() - document.content_uri = "content_uri_value" - document.display_name = "display_name_value" - document.mime_type = "mime_type_value" - document.knowledge_types = ['SMART_REPLY'] - - request = dialogflow_v2beta1.CreateDocumentRequest( - parent="parent_value", - document=document, - ) - - # Make the request - operation = client.create_document(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - -# [END dialogflow_v2beta1_generated_Documents_CreateDocument_sync] diff --git a/owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_documents_delete_document_async.py b/owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_documents_delete_document_async.py deleted file mode 100644 index 6750255f9..000000000 --- a/owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_documents_delete_document_async.py +++ /dev/null @@ -1,56 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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. -# -# Generated code. DO NOT EDIT! -# -# Snippet for DeleteDocument -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-dialogflow - - -# [START dialogflow_v2beta1_generated_Documents_DeleteDocument_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import dialogflow_v2beta1 - - -async def sample_delete_document(): - # Create a client - client = dialogflow_v2beta1.DocumentsAsyncClient() - - # Initialize request argument(s) - request = dialogflow_v2beta1.DeleteDocumentRequest( - name="name_value", - ) - - # Make the request - operation = client.delete_document(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - -# [END dialogflow_v2beta1_generated_Documents_DeleteDocument_async] diff --git a/owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_documents_delete_document_sync.py b/owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_documents_delete_document_sync.py deleted file mode 100644 index 55afbe47e..000000000 --- a/owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_documents_delete_document_sync.py +++ /dev/null @@ -1,56 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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. -# -# Generated code. DO NOT EDIT! -# -# Snippet for DeleteDocument -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-dialogflow - - -# [START dialogflow_v2beta1_generated_Documents_DeleteDocument_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import dialogflow_v2beta1 - - -def sample_delete_document(): - # Create a client - client = dialogflow_v2beta1.DocumentsClient() - - # Initialize request argument(s) - request = dialogflow_v2beta1.DeleteDocumentRequest( - name="name_value", - ) - - # Make the request - operation = client.delete_document(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - -# [END dialogflow_v2beta1_generated_Documents_DeleteDocument_sync] diff --git a/owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_documents_get_document_async.py b/owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_documents_get_document_async.py deleted file mode 100644 index bf700d78b..000000000 --- a/owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_documents_get_document_async.py +++ /dev/null @@ -1,52 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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. -# -# Generated code. DO NOT EDIT! -# -# Snippet for GetDocument -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-dialogflow - - -# [START dialogflow_v2beta1_generated_Documents_GetDocument_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import dialogflow_v2beta1 - - -async def sample_get_document(): - # Create a client - client = dialogflow_v2beta1.DocumentsAsyncClient() - - # Initialize request argument(s) - request = dialogflow_v2beta1.GetDocumentRequest( - name="name_value", - ) - - # Make the request - response = await client.get_document(request=request) - - # Handle the response - print(response) - -# [END dialogflow_v2beta1_generated_Documents_GetDocument_async] diff --git a/owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_documents_get_document_sync.py b/owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_documents_get_document_sync.py deleted file mode 100644 index 90ea9a730..000000000 --- a/owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_documents_get_document_sync.py +++ /dev/null @@ -1,52 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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. -# -# Generated code. DO NOT EDIT! -# -# Snippet for GetDocument -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-dialogflow - - -# [START dialogflow_v2beta1_generated_Documents_GetDocument_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import dialogflow_v2beta1 - - -def sample_get_document(): - # Create a client - client = dialogflow_v2beta1.DocumentsClient() - - # Initialize request argument(s) - request = dialogflow_v2beta1.GetDocumentRequest( - name="name_value", - ) - - # Make the request - response = client.get_document(request=request) - - # Handle the response - print(response) - -# [END dialogflow_v2beta1_generated_Documents_GetDocument_sync] diff --git a/owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_documents_import_documents_async.py b/owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_documents_import_documents_async.py deleted file mode 100644 index 575b557e3..000000000 --- a/owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_documents_import_documents_async.py +++ /dev/null @@ -1,65 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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. -# -# Generated code. DO NOT EDIT! -# -# Snippet for ImportDocuments -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-dialogflow - - -# [START dialogflow_v2beta1_generated_Documents_ImportDocuments_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import dialogflow_v2beta1 - - -async def sample_import_documents(): - # Create a client - client = dialogflow_v2beta1.DocumentsAsyncClient() - - # Initialize request argument(s) - gcs_source = dialogflow_v2beta1.GcsSources() - gcs_source.uris = ['uris_value1', 'uris_value2'] - - document_template = dialogflow_v2beta1.ImportDocumentTemplate() - document_template.mime_type = "mime_type_value" - document_template.knowledge_types = ['SMART_REPLY'] - - request = dialogflow_v2beta1.ImportDocumentsRequest( - gcs_source=gcs_source, - parent="parent_value", - document_template=document_template, - ) - - # Make the request - operation = client.import_documents(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - -# [END dialogflow_v2beta1_generated_Documents_ImportDocuments_async] diff --git a/owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_documents_import_documents_sync.py b/owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_documents_import_documents_sync.py deleted file mode 100644 index 251290740..000000000 --- a/owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_documents_import_documents_sync.py +++ /dev/null @@ -1,65 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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. -# -# Generated code. DO NOT EDIT! -# -# Snippet for ImportDocuments -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-dialogflow - - -# [START dialogflow_v2beta1_generated_Documents_ImportDocuments_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import dialogflow_v2beta1 - - -def sample_import_documents(): - # Create a client - client = dialogflow_v2beta1.DocumentsClient() - - # Initialize request argument(s) - gcs_source = dialogflow_v2beta1.GcsSources() - gcs_source.uris = ['uris_value1', 'uris_value2'] - - document_template = dialogflow_v2beta1.ImportDocumentTemplate() - document_template.mime_type = "mime_type_value" - document_template.knowledge_types = ['SMART_REPLY'] - - request = dialogflow_v2beta1.ImportDocumentsRequest( - gcs_source=gcs_source, - parent="parent_value", - document_template=document_template, - ) - - # Make the request - operation = client.import_documents(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - -# [END dialogflow_v2beta1_generated_Documents_ImportDocuments_sync] diff --git a/owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_documents_list_documents_async.py b/owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_documents_list_documents_async.py deleted file mode 100644 index a41ca8897..000000000 --- a/owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_documents_list_documents_async.py +++ /dev/null @@ -1,53 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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. -# -# Generated code. DO NOT EDIT! -# -# Snippet for ListDocuments -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-dialogflow - - -# [START dialogflow_v2beta1_generated_Documents_ListDocuments_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import dialogflow_v2beta1 - - -async def sample_list_documents(): - # Create a client - client = dialogflow_v2beta1.DocumentsAsyncClient() - - # Initialize request argument(s) - request = dialogflow_v2beta1.ListDocumentsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_documents(request=request) - - # Handle the response - async for response in page_result: - print(response) - -# [END dialogflow_v2beta1_generated_Documents_ListDocuments_async] diff --git a/owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_documents_list_documents_sync.py b/owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_documents_list_documents_sync.py deleted file mode 100644 index bb47ca037..000000000 --- a/owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_documents_list_documents_sync.py +++ /dev/null @@ -1,53 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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. -# -# Generated code. DO NOT EDIT! -# -# Snippet for ListDocuments -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-dialogflow - - -# [START dialogflow_v2beta1_generated_Documents_ListDocuments_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import dialogflow_v2beta1 - - -def sample_list_documents(): - # Create a client - client = dialogflow_v2beta1.DocumentsClient() - - # Initialize request argument(s) - request = dialogflow_v2beta1.ListDocumentsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_documents(request=request) - - # Handle the response - for response in page_result: - print(response) - -# [END dialogflow_v2beta1_generated_Documents_ListDocuments_sync] diff --git a/owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_documents_reload_document_async.py b/owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_documents_reload_document_async.py deleted file mode 100644 index dacc6a158..000000000 --- a/owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_documents_reload_document_async.py +++ /dev/null @@ -1,56 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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. -# -# Generated code. DO NOT EDIT! -# -# Snippet for ReloadDocument -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-dialogflow - - -# [START dialogflow_v2beta1_generated_Documents_ReloadDocument_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import dialogflow_v2beta1 - - -async def sample_reload_document(): - # Create a client - client = dialogflow_v2beta1.DocumentsAsyncClient() - - # Initialize request argument(s) - request = dialogflow_v2beta1.ReloadDocumentRequest( - name="name_value", - ) - - # Make the request - operation = client.reload_document(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - -# [END dialogflow_v2beta1_generated_Documents_ReloadDocument_async] diff --git a/owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_documents_reload_document_sync.py b/owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_documents_reload_document_sync.py deleted file mode 100644 index a8d6671bd..000000000 --- a/owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_documents_reload_document_sync.py +++ /dev/null @@ -1,56 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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. -# -# Generated code. DO NOT EDIT! -# -# Snippet for ReloadDocument -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-dialogflow - - -# [START dialogflow_v2beta1_generated_Documents_ReloadDocument_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import dialogflow_v2beta1 - - -def sample_reload_document(): - # Create a client - client = dialogflow_v2beta1.DocumentsClient() - - # Initialize request argument(s) - request = dialogflow_v2beta1.ReloadDocumentRequest( - name="name_value", - ) - - # Make the request - operation = client.reload_document(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - -# [END dialogflow_v2beta1_generated_Documents_ReloadDocument_sync] diff --git a/owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_documents_update_document_async.py b/owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_documents_update_document_async.py deleted file mode 100644 index ca77546e7..000000000 --- a/owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_documents_update_document_async.py +++ /dev/null @@ -1,62 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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. -# -# Generated code. DO NOT EDIT! -# -# Snippet for UpdateDocument -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-dialogflow - - -# [START dialogflow_v2beta1_generated_Documents_UpdateDocument_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import dialogflow_v2beta1 - - -async def sample_update_document(): - # Create a client - client = dialogflow_v2beta1.DocumentsAsyncClient() - - # Initialize request argument(s) - document = dialogflow_v2beta1.Document() - document.content_uri = "content_uri_value" - document.display_name = "display_name_value" - document.mime_type = "mime_type_value" - document.knowledge_types = ['SMART_REPLY'] - - request = dialogflow_v2beta1.UpdateDocumentRequest( - document=document, - ) - - # Make the request - operation = client.update_document(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - -# [END dialogflow_v2beta1_generated_Documents_UpdateDocument_async] diff --git a/owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_documents_update_document_sync.py b/owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_documents_update_document_sync.py deleted file mode 100644 index 7fdb062ee..000000000 --- a/owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_documents_update_document_sync.py +++ /dev/null @@ -1,62 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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. -# -# Generated code. DO NOT EDIT! -# -# Snippet for UpdateDocument -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-dialogflow - - -# [START dialogflow_v2beta1_generated_Documents_UpdateDocument_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import dialogflow_v2beta1 - - -def sample_update_document(): - # Create a client - client = dialogflow_v2beta1.DocumentsClient() - - # Initialize request argument(s) - document = dialogflow_v2beta1.Document() - document.content_uri = "content_uri_value" - document.display_name = "display_name_value" - document.mime_type = "mime_type_value" - document.knowledge_types = ['SMART_REPLY'] - - request = dialogflow_v2beta1.UpdateDocumentRequest( - document=document, - ) - - # Make the request - operation = client.update_document(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - -# [END dialogflow_v2beta1_generated_Documents_UpdateDocument_sync] diff --git a/owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_entity_types_batch_create_entities_async.py b/owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_entity_types_batch_create_entities_async.py deleted file mode 100644 index b11a65f46..000000000 --- a/owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_entity_types_batch_create_entities_async.py +++ /dev/null @@ -1,60 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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. -# -# Generated code. DO NOT EDIT! -# -# Snippet for BatchCreateEntities -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-dialogflow - - -# [START dialogflow_v2beta1_generated_EntityTypes_BatchCreateEntities_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import dialogflow_v2beta1 - - -async def sample_batch_create_entities(): - # Create a client - client = dialogflow_v2beta1.EntityTypesAsyncClient() - - # Initialize request argument(s) - entities = dialogflow_v2beta1.Entity() - entities.value = "value_value" - - request = dialogflow_v2beta1.BatchCreateEntitiesRequest( - parent="parent_value", - entities=entities, - ) - - # Make the request - operation = client.batch_create_entities(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - -# [END dialogflow_v2beta1_generated_EntityTypes_BatchCreateEntities_async] diff --git a/owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_entity_types_batch_create_entities_sync.py b/owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_entity_types_batch_create_entities_sync.py deleted file mode 100644 index e9397cd98..000000000 --- a/owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_entity_types_batch_create_entities_sync.py +++ /dev/null @@ -1,60 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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. -# -# Generated code. DO NOT EDIT! -# -# Snippet for BatchCreateEntities -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-dialogflow - - -# [START dialogflow_v2beta1_generated_EntityTypes_BatchCreateEntities_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import dialogflow_v2beta1 - - -def sample_batch_create_entities(): - # Create a client - client = dialogflow_v2beta1.EntityTypesClient() - - # Initialize request argument(s) - entities = dialogflow_v2beta1.Entity() - entities.value = "value_value" - - request = dialogflow_v2beta1.BatchCreateEntitiesRequest( - parent="parent_value", - entities=entities, - ) - - # Make the request - operation = client.batch_create_entities(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - -# [END dialogflow_v2beta1_generated_EntityTypes_BatchCreateEntities_sync] diff --git a/owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_entity_types_batch_delete_entities_async.py b/owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_entity_types_batch_delete_entities_async.py deleted file mode 100644 index 68b803554..000000000 --- a/owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_entity_types_batch_delete_entities_async.py +++ /dev/null @@ -1,57 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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. -# -# Generated code. DO NOT EDIT! -# -# Snippet for BatchDeleteEntities -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-dialogflow - - -# [START dialogflow_v2beta1_generated_EntityTypes_BatchDeleteEntities_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import dialogflow_v2beta1 - - -async def sample_batch_delete_entities(): - # Create a client - client = dialogflow_v2beta1.EntityTypesAsyncClient() - - # Initialize request argument(s) - request = dialogflow_v2beta1.BatchDeleteEntitiesRequest( - parent="parent_value", - entity_values=['entity_values_value1', 'entity_values_value2'], - ) - - # Make the request - operation = client.batch_delete_entities(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - -# [END dialogflow_v2beta1_generated_EntityTypes_BatchDeleteEntities_async] diff --git a/owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_entity_types_batch_delete_entities_sync.py b/owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_entity_types_batch_delete_entities_sync.py deleted file mode 100644 index 45cabc538..000000000 --- a/owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_entity_types_batch_delete_entities_sync.py +++ /dev/null @@ -1,57 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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. -# -# Generated code. DO NOT EDIT! -# -# Snippet for BatchDeleteEntities -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-dialogflow - - -# [START dialogflow_v2beta1_generated_EntityTypes_BatchDeleteEntities_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import dialogflow_v2beta1 - - -def sample_batch_delete_entities(): - # Create a client - client = dialogflow_v2beta1.EntityTypesClient() - - # Initialize request argument(s) - request = dialogflow_v2beta1.BatchDeleteEntitiesRequest( - parent="parent_value", - entity_values=['entity_values_value1', 'entity_values_value2'], - ) - - # Make the request - operation = client.batch_delete_entities(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - -# [END dialogflow_v2beta1_generated_EntityTypes_BatchDeleteEntities_sync] diff --git a/owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_entity_types_batch_delete_entity_types_async.py b/owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_entity_types_batch_delete_entity_types_async.py deleted file mode 100644 index e30b48a85..000000000 --- a/owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_entity_types_batch_delete_entity_types_async.py +++ /dev/null @@ -1,57 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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. -# -# Generated code. DO NOT EDIT! -# -# Snippet for BatchDeleteEntityTypes -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-dialogflow - - -# [START dialogflow_v2beta1_generated_EntityTypes_BatchDeleteEntityTypes_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import dialogflow_v2beta1 - - -async def sample_batch_delete_entity_types(): - # Create a client - client = dialogflow_v2beta1.EntityTypesAsyncClient() - - # Initialize request argument(s) - request = dialogflow_v2beta1.BatchDeleteEntityTypesRequest( - parent="parent_value", - entity_type_names=['entity_type_names_value1', 'entity_type_names_value2'], - ) - - # Make the request - operation = client.batch_delete_entity_types(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - -# [END dialogflow_v2beta1_generated_EntityTypes_BatchDeleteEntityTypes_async] diff --git a/owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_entity_types_batch_delete_entity_types_sync.py b/owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_entity_types_batch_delete_entity_types_sync.py deleted file mode 100644 index 9c37b9871..000000000 --- a/owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_entity_types_batch_delete_entity_types_sync.py +++ /dev/null @@ -1,57 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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. -# -# Generated code. DO NOT EDIT! -# -# Snippet for BatchDeleteEntityTypes -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-dialogflow - - -# [START dialogflow_v2beta1_generated_EntityTypes_BatchDeleteEntityTypes_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import dialogflow_v2beta1 - - -def sample_batch_delete_entity_types(): - # Create a client - client = dialogflow_v2beta1.EntityTypesClient() - - # Initialize request argument(s) - request = dialogflow_v2beta1.BatchDeleteEntityTypesRequest( - parent="parent_value", - entity_type_names=['entity_type_names_value1', 'entity_type_names_value2'], - ) - - # Make the request - operation = client.batch_delete_entity_types(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - -# [END dialogflow_v2beta1_generated_EntityTypes_BatchDeleteEntityTypes_sync] diff --git a/owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_entity_types_batch_update_entities_async.py b/owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_entity_types_batch_update_entities_async.py deleted file mode 100644 index 7808aa6c7..000000000 --- a/owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_entity_types_batch_update_entities_async.py +++ /dev/null @@ -1,60 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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. -# -# Generated code. DO NOT EDIT! -# -# Snippet for BatchUpdateEntities -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-dialogflow - - -# [START dialogflow_v2beta1_generated_EntityTypes_BatchUpdateEntities_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import dialogflow_v2beta1 - - -async def sample_batch_update_entities(): - # Create a client - client = dialogflow_v2beta1.EntityTypesAsyncClient() - - # Initialize request argument(s) - entities = dialogflow_v2beta1.Entity() - entities.value = "value_value" - - request = dialogflow_v2beta1.BatchUpdateEntitiesRequest( - parent="parent_value", - entities=entities, - ) - - # Make the request - operation = client.batch_update_entities(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - -# [END dialogflow_v2beta1_generated_EntityTypes_BatchUpdateEntities_async] diff --git a/owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_entity_types_batch_update_entities_sync.py b/owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_entity_types_batch_update_entities_sync.py deleted file mode 100644 index f1c926e06..000000000 --- a/owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_entity_types_batch_update_entities_sync.py +++ /dev/null @@ -1,60 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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. -# -# Generated code. DO NOT EDIT! -# -# Snippet for BatchUpdateEntities -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-dialogflow - - -# [START dialogflow_v2beta1_generated_EntityTypes_BatchUpdateEntities_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import dialogflow_v2beta1 - - -def sample_batch_update_entities(): - # Create a client - client = dialogflow_v2beta1.EntityTypesClient() - - # Initialize request argument(s) - entities = dialogflow_v2beta1.Entity() - entities.value = "value_value" - - request = dialogflow_v2beta1.BatchUpdateEntitiesRequest( - parent="parent_value", - entities=entities, - ) - - # Make the request - operation = client.batch_update_entities(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - -# [END dialogflow_v2beta1_generated_EntityTypes_BatchUpdateEntities_sync] diff --git a/owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_entity_types_batch_update_entity_types_async.py b/owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_entity_types_batch_update_entity_types_async.py deleted file mode 100644 index ee73480a0..000000000 --- a/owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_entity_types_batch_update_entity_types_async.py +++ /dev/null @@ -1,57 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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. -# -# Generated code. DO NOT EDIT! -# -# Snippet for BatchUpdateEntityTypes -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-dialogflow - - -# [START dialogflow_v2beta1_generated_EntityTypes_BatchUpdateEntityTypes_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import dialogflow_v2beta1 - - -async def sample_batch_update_entity_types(): - # Create a client - client = dialogflow_v2beta1.EntityTypesAsyncClient() - - # Initialize request argument(s) - request = dialogflow_v2beta1.BatchUpdateEntityTypesRequest( - entity_type_batch_uri="entity_type_batch_uri_value", - parent="parent_value", - ) - - # Make the request - operation = client.batch_update_entity_types(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - -# [END dialogflow_v2beta1_generated_EntityTypes_BatchUpdateEntityTypes_async] diff --git a/owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_entity_types_batch_update_entity_types_sync.py b/owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_entity_types_batch_update_entity_types_sync.py deleted file mode 100644 index dbfe896f2..000000000 --- a/owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_entity_types_batch_update_entity_types_sync.py +++ /dev/null @@ -1,57 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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. -# -# Generated code. DO NOT EDIT! -# -# Snippet for BatchUpdateEntityTypes -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-dialogflow - - -# [START dialogflow_v2beta1_generated_EntityTypes_BatchUpdateEntityTypes_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import dialogflow_v2beta1 - - -def sample_batch_update_entity_types(): - # Create a client - client = dialogflow_v2beta1.EntityTypesClient() - - # Initialize request argument(s) - request = dialogflow_v2beta1.BatchUpdateEntityTypesRequest( - entity_type_batch_uri="entity_type_batch_uri_value", - parent="parent_value", - ) - - # Make the request - operation = client.batch_update_entity_types(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - -# [END dialogflow_v2beta1_generated_EntityTypes_BatchUpdateEntityTypes_sync] diff --git a/owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_entity_types_create_entity_type_async.py b/owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_entity_types_create_entity_type_async.py deleted file mode 100644 index 22202444f..000000000 --- a/owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_entity_types_create_entity_type_async.py +++ /dev/null @@ -1,57 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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. -# -# Generated code. DO NOT EDIT! -# -# Snippet for CreateEntityType -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-dialogflow - - -# [START dialogflow_v2beta1_generated_EntityTypes_CreateEntityType_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import dialogflow_v2beta1 - - -async def sample_create_entity_type(): - # Create a client - client = dialogflow_v2beta1.EntityTypesAsyncClient() - - # Initialize request argument(s) - entity_type = dialogflow_v2beta1.EntityType() - entity_type.display_name = "display_name_value" - entity_type.kind = "KIND_REGEXP" - - request = dialogflow_v2beta1.CreateEntityTypeRequest( - parent="parent_value", - entity_type=entity_type, - ) - - # Make the request - response = await client.create_entity_type(request=request) - - # Handle the response - print(response) - -# [END dialogflow_v2beta1_generated_EntityTypes_CreateEntityType_async] diff --git a/owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_entity_types_create_entity_type_sync.py b/owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_entity_types_create_entity_type_sync.py deleted file mode 100644 index ccf471c38..000000000 --- a/owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_entity_types_create_entity_type_sync.py +++ /dev/null @@ -1,57 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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. -# -# Generated code. DO NOT EDIT! -# -# Snippet for CreateEntityType -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-dialogflow - - -# [START dialogflow_v2beta1_generated_EntityTypes_CreateEntityType_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import dialogflow_v2beta1 - - -def sample_create_entity_type(): - # Create a client - client = dialogflow_v2beta1.EntityTypesClient() - - # Initialize request argument(s) - entity_type = dialogflow_v2beta1.EntityType() - entity_type.display_name = "display_name_value" - entity_type.kind = "KIND_REGEXP" - - request = dialogflow_v2beta1.CreateEntityTypeRequest( - parent="parent_value", - entity_type=entity_type, - ) - - # Make the request - response = client.create_entity_type(request=request) - - # Handle the response - print(response) - -# [END dialogflow_v2beta1_generated_EntityTypes_CreateEntityType_sync] diff --git a/owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_entity_types_delete_entity_type_async.py b/owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_entity_types_delete_entity_type_async.py deleted file mode 100644 index 329c1662a..000000000 --- a/owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_entity_types_delete_entity_type_async.py +++ /dev/null @@ -1,50 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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. -# -# Generated code. DO NOT EDIT! -# -# Snippet for DeleteEntityType -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-dialogflow - - -# [START dialogflow_v2beta1_generated_EntityTypes_DeleteEntityType_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import dialogflow_v2beta1 - - -async def sample_delete_entity_type(): - # Create a client - client = dialogflow_v2beta1.EntityTypesAsyncClient() - - # Initialize request argument(s) - request = dialogflow_v2beta1.DeleteEntityTypeRequest( - name="name_value", - ) - - # Make the request - await client.delete_entity_type(request=request) - - -# [END dialogflow_v2beta1_generated_EntityTypes_DeleteEntityType_async] diff --git a/owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_entity_types_delete_entity_type_sync.py b/owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_entity_types_delete_entity_type_sync.py deleted file mode 100644 index 8f231f91b..000000000 --- a/owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_entity_types_delete_entity_type_sync.py +++ /dev/null @@ -1,50 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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. -# -# Generated code. DO NOT EDIT! -# -# Snippet for DeleteEntityType -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-dialogflow - - -# [START dialogflow_v2beta1_generated_EntityTypes_DeleteEntityType_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import dialogflow_v2beta1 - - -def sample_delete_entity_type(): - # Create a client - client = dialogflow_v2beta1.EntityTypesClient() - - # Initialize request argument(s) - request = dialogflow_v2beta1.DeleteEntityTypeRequest( - name="name_value", - ) - - # Make the request - client.delete_entity_type(request=request) - - -# [END dialogflow_v2beta1_generated_EntityTypes_DeleteEntityType_sync] diff --git a/owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_entity_types_get_entity_type_async.py b/owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_entity_types_get_entity_type_async.py deleted file mode 100644 index a29247231..000000000 --- a/owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_entity_types_get_entity_type_async.py +++ /dev/null @@ -1,52 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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. -# -# Generated code. DO NOT EDIT! -# -# Snippet for GetEntityType -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-dialogflow - - -# [START dialogflow_v2beta1_generated_EntityTypes_GetEntityType_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import dialogflow_v2beta1 - - -async def sample_get_entity_type(): - # Create a client - client = dialogflow_v2beta1.EntityTypesAsyncClient() - - # Initialize request argument(s) - request = dialogflow_v2beta1.GetEntityTypeRequest( - name="name_value", - ) - - # Make the request - response = await client.get_entity_type(request=request) - - # Handle the response - print(response) - -# [END dialogflow_v2beta1_generated_EntityTypes_GetEntityType_async] diff --git a/owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_entity_types_get_entity_type_sync.py b/owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_entity_types_get_entity_type_sync.py deleted file mode 100644 index 54a7c59db..000000000 --- a/owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_entity_types_get_entity_type_sync.py +++ /dev/null @@ -1,52 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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. -# -# Generated code. DO NOT EDIT! -# -# Snippet for GetEntityType -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-dialogflow - - -# [START dialogflow_v2beta1_generated_EntityTypes_GetEntityType_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import dialogflow_v2beta1 - - -def sample_get_entity_type(): - # Create a client - client = dialogflow_v2beta1.EntityTypesClient() - - # Initialize request argument(s) - request = dialogflow_v2beta1.GetEntityTypeRequest( - name="name_value", - ) - - # Make the request - response = client.get_entity_type(request=request) - - # Handle the response - print(response) - -# [END dialogflow_v2beta1_generated_EntityTypes_GetEntityType_sync] diff --git a/owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_entity_types_list_entity_types_async.py b/owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_entity_types_list_entity_types_async.py deleted file mode 100644 index 50d579906..000000000 --- a/owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_entity_types_list_entity_types_async.py +++ /dev/null @@ -1,53 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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. -# -# Generated code. DO NOT EDIT! -# -# Snippet for ListEntityTypes -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-dialogflow - - -# [START dialogflow_v2beta1_generated_EntityTypes_ListEntityTypes_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import dialogflow_v2beta1 - - -async def sample_list_entity_types(): - # Create a client - client = dialogflow_v2beta1.EntityTypesAsyncClient() - - # Initialize request argument(s) - request = dialogflow_v2beta1.ListEntityTypesRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_entity_types(request=request) - - # Handle the response - async for response in page_result: - print(response) - -# [END dialogflow_v2beta1_generated_EntityTypes_ListEntityTypes_async] diff --git a/owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_entity_types_list_entity_types_sync.py b/owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_entity_types_list_entity_types_sync.py deleted file mode 100644 index ded48be09..000000000 --- a/owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_entity_types_list_entity_types_sync.py +++ /dev/null @@ -1,53 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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. -# -# Generated code. DO NOT EDIT! -# -# Snippet for ListEntityTypes -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-dialogflow - - -# [START dialogflow_v2beta1_generated_EntityTypes_ListEntityTypes_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import dialogflow_v2beta1 - - -def sample_list_entity_types(): - # Create a client - client = dialogflow_v2beta1.EntityTypesClient() - - # Initialize request argument(s) - request = dialogflow_v2beta1.ListEntityTypesRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_entity_types(request=request) - - # Handle the response - for response in page_result: - print(response) - -# [END dialogflow_v2beta1_generated_EntityTypes_ListEntityTypes_sync] diff --git a/owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_entity_types_update_entity_type_async.py b/owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_entity_types_update_entity_type_async.py deleted file mode 100644 index 815f651b3..000000000 --- a/owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_entity_types_update_entity_type_async.py +++ /dev/null @@ -1,56 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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. -# -# Generated code. DO NOT EDIT! -# -# Snippet for UpdateEntityType -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-dialogflow - - -# [START dialogflow_v2beta1_generated_EntityTypes_UpdateEntityType_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import dialogflow_v2beta1 - - -async def sample_update_entity_type(): - # Create a client - client = dialogflow_v2beta1.EntityTypesAsyncClient() - - # Initialize request argument(s) - entity_type = dialogflow_v2beta1.EntityType() - entity_type.display_name = "display_name_value" - entity_type.kind = "KIND_REGEXP" - - request = dialogflow_v2beta1.UpdateEntityTypeRequest( - entity_type=entity_type, - ) - - # Make the request - response = await client.update_entity_type(request=request) - - # Handle the response - print(response) - -# [END dialogflow_v2beta1_generated_EntityTypes_UpdateEntityType_async] diff --git a/owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_entity_types_update_entity_type_sync.py b/owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_entity_types_update_entity_type_sync.py deleted file mode 100644 index f8bd58e3d..000000000 --- a/owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_entity_types_update_entity_type_sync.py +++ /dev/null @@ -1,56 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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. -# -# Generated code. DO NOT EDIT! -# -# Snippet for UpdateEntityType -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-dialogflow - - -# [START dialogflow_v2beta1_generated_EntityTypes_UpdateEntityType_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import dialogflow_v2beta1 - - -def sample_update_entity_type(): - # Create a client - client = dialogflow_v2beta1.EntityTypesClient() - - # Initialize request argument(s) - entity_type = dialogflow_v2beta1.EntityType() - entity_type.display_name = "display_name_value" - entity_type.kind = "KIND_REGEXP" - - request = dialogflow_v2beta1.UpdateEntityTypeRequest( - entity_type=entity_type, - ) - - # Make the request - response = client.update_entity_type(request=request) - - # Handle the response - print(response) - -# [END dialogflow_v2beta1_generated_EntityTypes_UpdateEntityType_sync] diff --git a/owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_environments_create_environment_async.py b/owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_environments_create_environment_async.py deleted file mode 100644 index 13b690615..000000000 --- a/owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_environments_create_environment_async.py +++ /dev/null @@ -1,53 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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. -# -# Generated code. DO NOT EDIT! -# -# Snippet for CreateEnvironment -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-dialogflow - - -# [START dialogflow_v2beta1_generated_Environments_CreateEnvironment_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import dialogflow_v2beta1 - - -async def sample_create_environment(): - # Create a client - client = dialogflow_v2beta1.EnvironmentsAsyncClient() - - # Initialize request argument(s) - request = dialogflow_v2beta1.CreateEnvironmentRequest( - parent="parent_value", - environment_id="environment_id_value", - ) - - # Make the request - response = await client.create_environment(request=request) - - # Handle the response - print(response) - -# [END dialogflow_v2beta1_generated_Environments_CreateEnvironment_async] diff --git a/owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_environments_create_environment_sync.py b/owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_environments_create_environment_sync.py deleted file mode 100644 index 003c4ab04..000000000 --- a/owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_environments_create_environment_sync.py +++ /dev/null @@ -1,53 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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. -# -# Generated code. DO NOT EDIT! -# -# Snippet for CreateEnvironment -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-dialogflow - - -# [START dialogflow_v2beta1_generated_Environments_CreateEnvironment_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import dialogflow_v2beta1 - - -def sample_create_environment(): - # Create a client - client = dialogflow_v2beta1.EnvironmentsClient() - - # Initialize request argument(s) - request = dialogflow_v2beta1.CreateEnvironmentRequest( - parent="parent_value", - environment_id="environment_id_value", - ) - - # Make the request - response = client.create_environment(request=request) - - # Handle the response - print(response) - -# [END dialogflow_v2beta1_generated_Environments_CreateEnvironment_sync] diff --git a/owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_environments_delete_environment_async.py b/owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_environments_delete_environment_async.py deleted file mode 100644 index 920e1ee42..000000000 --- a/owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_environments_delete_environment_async.py +++ /dev/null @@ -1,50 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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. -# -# Generated code. DO NOT EDIT! -# -# Snippet for DeleteEnvironment -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-dialogflow - - -# [START dialogflow_v2beta1_generated_Environments_DeleteEnvironment_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import dialogflow_v2beta1 - - -async def sample_delete_environment(): - # Create a client - client = dialogflow_v2beta1.EnvironmentsAsyncClient() - - # Initialize request argument(s) - request = dialogflow_v2beta1.DeleteEnvironmentRequest( - name="name_value", - ) - - # Make the request - await client.delete_environment(request=request) - - -# [END dialogflow_v2beta1_generated_Environments_DeleteEnvironment_async] diff --git a/owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_environments_delete_environment_sync.py b/owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_environments_delete_environment_sync.py deleted file mode 100644 index 9338f1be7..000000000 --- a/owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_environments_delete_environment_sync.py +++ /dev/null @@ -1,50 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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. -# -# Generated code. DO NOT EDIT! -# -# Snippet for DeleteEnvironment -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-dialogflow - - -# [START dialogflow_v2beta1_generated_Environments_DeleteEnvironment_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import dialogflow_v2beta1 - - -def sample_delete_environment(): - # Create a client - client = dialogflow_v2beta1.EnvironmentsClient() - - # Initialize request argument(s) - request = dialogflow_v2beta1.DeleteEnvironmentRequest( - name="name_value", - ) - - # Make the request - client.delete_environment(request=request) - - -# [END dialogflow_v2beta1_generated_Environments_DeleteEnvironment_sync] diff --git a/owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_environments_get_environment_async.py b/owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_environments_get_environment_async.py deleted file mode 100644 index 0ba2ded37..000000000 --- a/owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_environments_get_environment_async.py +++ /dev/null @@ -1,52 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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. -# -# Generated code. DO NOT EDIT! -# -# Snippet for GetEnvironment -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-dialogflow - - -# [START dialogflow_v2beta1_generated_Environments_GetEnvironment_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import dialogflow_v2beta1 - - -async def sample_get_environment(): - # Create a client - client = dialogflow_v2beta1.EnvironmentsAsyncClient() - - # Initialize request argument(s) - request = dialogflow_v2beta1.GetEnvironmentRequest( - name="name_value", - ) - - # Make the request - response = await client.get_environment(request=request) - - # Handle the response - print(response) - -# [END dialogflow_v2beta1_generated_Environments_GetEnvironment_async] diff --git a/owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_environments_get_environment_history_async.py b/owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_environments_get_environment_history_async.py deleted file mode 100644 index 70766f530..000000000 --- a/owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_environments_get_environment_history_async.py +++ /dev/null @@ -1,53 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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. -# -# Generated code. DO NOT EDIT! -# -# Snippet for GetEnvironmentHistory -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-dialogflow - - -# [START dialogflow_v2beta1_generated_Environments_GetEnvironmentHistory_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import dialogflow_v2beta1 - - -async def sample_get_environment_history(): - # Create a client - client = dialogflow_v2beta1.EnvironmentsAsyncClient() - - # Initialize request argument(s) - request = dialogflow_v2beta1.GetEnvironmentHistoryRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.get_environment_history(request=request) - - # Handle the response - async for response in page_result: - print(response) - -# [END dialogflow_v2beta1_generated_Environments_GetEnvironmentHistory_async] diff --git a/owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_environments_get_environment_history_sync.py b/owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_environments_get_environment_history_sync.py deleted file mode 100644 index 6ee763839..000000000 --- a/owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_environments_get_environment_history_sync.py +++ /dev/null @@ -1,53 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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. -# -# Generated code. DO NOT EDIT! -# -# Snippet for GetEnvironmentHistory -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-dialogflow - - -# [START dialogflow_v2beta1_generated_Environments_GetEnvironmentHistory_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import dialogflow_v2beta1 - - -def sample_get_environment_history(): - # Create a client - client = dialogflow_v2beta1.EnvironmentsClient() - - # Initialize request argument(s) - request = dialogflow_v2beta1.GetEnvironmentHistoryRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.get_environment_history(request=request) - - # Handle the response - for response in page_result: - print(response) - -# [END dialogflow_v2beta1_generated_Environments_GetEnvironmentHistory_sync] diff --git a/owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_environments_get_environment_sync.py b/owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_environments_get_environment_sync.py deleted file mode 100644 index 41e882eba..000000000 --- a/owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_environments_get_environment_sync.py +++ /dev/null @@ -1,52 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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. -# -# Generated code. DO NOT EDIT! -# -# Snippet for GetEnvironment -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-dialogflow - - -# [START dialogflow_v2beta1_generated_Environments_GetEnvironment_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import dialogflow_v2beta1 - - -def sample_get_environment(): - # Create a client - client = dialogflow_v2beta1.EnvironmentsClient() - - # Initialize request argument(s) - request = dialogflow_v2beta1.GetEnvironmentRequest( - name="name_value", - ) - - # Make the request - response = client.get_environment(request=request) - - # Handle the response - print(response) - -# [END dialogflow_v2beta1_generated_Environments_GetEnvironment_sync] diff --git a/owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_environments_list_environments_async.py b/owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_environments_list_environments_async.py deleted file mode 100644 index 899495064..000000000 --- a/owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_environments_list_environments_async.py +++ /dev/null @@ -1,53 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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. -# -# Generated code. DO NOT EDIT! -# -# Snippet for ListEnvironments -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-dialogflow - - -# [START dialogflow_v2beta1_generated_Environments_ListEnvironments_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import dialogflow_v2beta1 - - -async def sample_list_environments(): - # Create a client - client = dialogflow_v2beta1.EnvironmentsAsyncClient() - - # Initialize request argument(s) - request = dialogflow_v2beta1.ListEnvironmentsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_environments(request=request) - - # Handle the response - async for response in page_result: - print(response) - -# [END dialogflow_v2beta1_generated_Environments_ListEnvironments_async] diff --git a/owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_environments_list_environments_sync.py b/owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_environments_list_environments_sync.py deleted file mode 100644 index 4838fb428..000000000 --- a/owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_environments_list_environments_sync.py +++ /dev/null @@ -1,53 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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. -# -# Generated code. DO NOT EDIT! -# -# Snippet for ListEnvironments -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-dialogflow - - -# [START dialogflow_v2beta1_generated_Environments_ListEnvironments_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import dialogflow_v2beta1 - - -def sample_list_environments(): - # Create a client - client = dialogflow_v2beta1.EnvironmentsClient() - - # Initialize request argument(s) - request = dialogflow_v2beta1.ListEnvironmentsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_environments(request=request) - - # Handle the response - for response in page_result: - print(response) - -# [END dialogflow_v2beta1_generated_Environments_ListEnvironments_sync] diff --git a/owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_environments_update_environment_async.py b/owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_environments_update_environment_async.py deleted file mode 100644 index 0c1cd38c2..000000000 --- a/owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_environments_update_environment_async.py +++ /dev/null @@ -1,51 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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. -# -# Generated code. DO NOT EDIT! -# -# Snippet for UpdateEnvironment -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-dialogflow - - -# [START dialogflow_v2beta1_generated_Environments_UpdateEnvironment_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import dialogflow_v2beta1 - - -async def sample_update_environment(): - # Create a client - client = dialogflow_v2beta1.EnvironmentsAsyncClient() - - # Initialize request argument(s) - request = dialogflow_v2beta1.UpdateEnvironmentRequest( - ) - - # Make the request - response = await client.update_environment(request=request) - - # Handle the response - print(response) - -# [END dialogflow_v2beta1_generated_Environments_UpdateEnvironment_async] diff --git a/owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_environments_update_environment_sync.py b/owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_environments_update_environment_sync.py deleted file mode 100644 index fe0c1826b..000000000 --- a/owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_environments_update_environment_sync.py +++ /dev/null @@ -1,51 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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. -# -# Generated code. DO NOT EDIT! -# -# Snippet for UpdateEnvironment -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-dialogflow - - -# [START dialogflow_v2beta1_generated_Environments_UpdateEnvironment_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import dialogflow_v2beta1 - - -def sample_update_environment(): - # Create a client - client = dialogflow_v2beta1.EnvironmentsClient() - - # Initialize request argument(s) - request = dialogflow_v2beta1.UpdateEnvironmentRequest( - ) - - # Make the request - response = client.update_environment(request=request) - - # Handle the response - print(response) - -# [END dialogflow_v2beta1_generated_Environments_UpdateEnvironment_sync] diff --git a/owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_fulfillments_get_fulfillment_async.py b/owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_fulfillments_get_fulfillment_async.py deleted file mode 100644 index 07038c178..000000000 --- a/owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_fulfillments_get_fulfillment_async.py +++ /dev/null @@ -1,52 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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. -# -# Generated code. DO NOT EDIT! -# -# Snippet for GetFulfillment -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-dialogflow - - -# [START dialogflow_v2beta1_generated_Fulfillments_GetFulfillment_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import dialogflow_v2beta1 - - -async def sample_get_fulfillment(): - # Create a client - client = dialogflow_v2beta1.FulfillmentsAsyncClient() - - # Initialize request argument(s) - request = dialogflow_v2beta1.GetFulfillmentRequest( - name="name_value", - ) - - # Make the request - response = await client.get_fulfillment(request=request) - - # Handle the response - print(response) - -# [END dialogflow_v2beta1_generated_Fulfillments_GetFulfillment_async] diff --git a/owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_fulfillments_get_fulfillment_sync.py b/owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_fulfillments_get_fulfillment_sync.py deleted file mode 100644 index ad4600a10..000000000 --- a/owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_fulfillments_get_fulfillment_sync.py +++ /dev/null @@ -1,52 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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. -# -# Generated code. DO NOT EDIT! -# -# Snippet for GetFulfillment -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-dialogflow - - -# [START dialogflow_v2beta1_generated_Fulfillments_GetFulfillment_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import dialogflow_v2beta1 - - -def sample_get_fulfillment(): - # Create a client - client = dialogflow_v2beta1.FulfillmentsClient() - - # Initialize request argument(s) - request = dialogflow_v2beta1.GetFulfillmentRequest( - name="name_value", - ) - - # Make the request - response = client.get_fulfillment(request=request) - - # Handle the response - print(response) - -# [END dialogflow_v2beta1_generated_Fulfillments_GetFulfillment_sync] diff --git a/owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_fulfillments_update_fulfillment_async.py b/owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_fulfillments_update_fulfillment_async.py deleted file mode 100644 index 5d30ef5d6..000000000 --- a/owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_fulfillments_update_fulfillment_async.py +++ /dev/null @@ -1,56 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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. -# -# Generated code. DO NOT EDIT! -# -# Snippet for UpdateFulfillment -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-dialogflow - - -# [START dialogflow_v2beta1_generated_Fulfillments_UpdateFulfillment_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import dialogflow_v2beta1 - - -async def sample_update_fulfillment(): - # Create a client - client = dialogflow_v2beta1.FulfillmentsAsyncClient() - - # Initialize request argument(s) - fulfillment = dialogflow_v2beta1.Fulfillment() - fulfillment.generic_web_service.uri = "uri_value" - fulfillment.name = "name_value" - - request = dialogflow_v2beta1.UpdateFulfillmentRequest( - fulfillment=fulfillment, - ) - - # Make the request - response = await client.update_fulfillment(request=request) - - # Handle the response - print(response) - -# [END dialogflow_v2beta1_generated_Fulfillments_UpdateFulfillment_async] diff --git a/owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_fulfillments_update_fulfillment_sync.py b/owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_fulfillments_update_fulfillment_sync.py deleted file mode 100644 index 004b4ec89..000000000 --- a/owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_fulfillments_update_fulfillment_sync.py +++ /dev/null @@ -1,56 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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. -# -# Generated code. DO NOT EDIT! -# -# Snippet for UpdateFulfillment -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-dialogflow - - -# [START dialogflow_v2beta1_generated_Fulfillments_UpdateFulfillment_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import dialogflow_v2beta1 - - -def sample_update_fulfillment(): - # Create a client - client = dialogflow_v2beta1.FulfillmentsClient() - - # Initialize request argument(s) - fulfillment = dialogflow_v2beta1.Fulfillment() - fulfillment.generic_web_service.uri = "uri_value" - fulfillment.name = "name_value" - - request = dialogflow_v2beta1.UpdateFulfillmentRequest( - fulfillment=fulfillment, - ) - - # Make the request - response = client.update_fulfillment(request=request) - - # Handle the response - print(response) - -# [END dialogflow_v2beta1_generated_Fulfillments_UpdateFulfillment_sync] diff --git a/owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_intents_batch_delete_intents_async.py b/owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_intents_batch_delete_intents_async.py deleted file mode 100644 index 25a8ca392..000000000 --- a/owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_intents_batch_delete_intents_async.py +++ /dev/null @@ -1,60 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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. -# -# Generated code. DO NOT EDIT! -# -# Snippet for BatchDeleteIntents -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-dialogflow - - -# [START dialogflow_v2beta1_generated_Intents_BatchDeleteIntents_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import dialogflow_v2beta1 - - -async def sample_batch_delete_intents(): - # Create a client - client = dialogflow_v2beta1.IntentsAsyncClient() - - # Initialize request argument(s) - intents = dialogflow_v2beta1.Intent() - intents.display_name = "display_name_value" - - request = dialogflow_v2beta1.BatchDeleteIntentsRequest( - parent="parent_value", - intents=intents, - ) - - # Make the request - operation = client.batch_delete_intents(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - -# [END dialogflow_v2beta1_generated_Intents_BatchDeleteIntents_async] diff --git a/owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_intents_batch_delete_intents_sync.py b/owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_intents_batch_delete_intents_sync.py deleted file mode 100644 index abb5f57c3..000000000 --- a/owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_intents_batch_delete_intents_sync.py +++ /dev/null @@ -1,60 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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. -# -# Generated code. DO NOT EDIT! -# -# Snippet for BatchDeleteIntents -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-dialogflow - - -# [START dialogflow_v2beta1_generated_Intents_BatchDeleteIntents_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import dialogflow_v2beta1 - - -def sample_batch_delete_intents(): - # Create a client - client = dialogflow_v2beta1.IntentsClient() - - # Initialize request argument(s) - intents = dialogflow_v2beta1.Intent() - intents.display_name = "display_name_value" - - request = dialogflow_v2beta1.BatchDeleteIntentsRequest( - parent="parent_value", - intents=intents, - ) - - # Make the request - operation = client.batch_delete_intents(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - -# [END dialogflow_v2beta1_generated_Intents_BatchDeleteIntents_sync] diff --git a/owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_intents_batch_update_intents_async.py b/owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_intents_batch_update_intents_async.py deleted file mode 100644 index 57ad65073..000000000 --- a/owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_intents_batch_update_intents_async.py +++ /dev/null @@ -1,57 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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. -# -# Generated code. DO NOT EDIT! -# -# Snippet for BatchUpdateIntents -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-dialogflow - - -# [START dialogflow_v2beta1_generated_Intents_BatchUpdateIntents_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import dialogflow_v2beta1 - - -async def sample_batch_update_intents(): - # Create a client - client = dialogflow_v2beta1.IntentsAsyncClient() - - # Initialize request argument(s) - request = dialogflow_v2beta1.BatchUpdateIntentsRequest( - intent_batch_uri="intent_batch_uri_value", - parent="parent_value", - ) - - # Make the request - operation = client.batch_update_intents(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - -# [END dialogflow_v2beta1_generated_Intents_BatchUpdateIntents_async] diff --git a/owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_intents_batch_update_intents_sync.py b/owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_intents_batch_update_intents_sync.py deleted file mode 100644 index 43fbf84c9..000000000 --- a/owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_intents_batch_update_intents_sync.py +++ /dev/null @@ -1,57 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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. -# -# Generated code. DO NOT EDIT! -# -# Snippet for BatchUpdateIntents -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-dialogflow - - -# [START dialogflow_v2beta1_generated_Intents_BatchUpdateIntents_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import dialogflow_v2beta1 - - -def sample_batch_update_intents(): - # Create a client - client = dialogflow_v2beta1.IntentsClient() - - # Initialize request argument(s) - request = dialogflow_v2beta1.BatchUpdateIntentsRequest( - intent_batch_uri="intent_batch_uri_value", - parent="parent_value", - ) - - # Make the request - operation = client.batch_update_intents(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - -# [END dialogflow_v2beta1_generated_Intents_BatchUpdateIntents_sync] diff --git a/owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_intents_create_intent_async.py b/owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_intents_create_intent_async.py deleted file mode 100644 index d74b52d0c..000000000 --- a/owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_intents_create_intent_async.py +++ /dev/null @@ -1,56 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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. -# -# Generated code. DO NOT EDIT! -# -# Snippet for CreateIntent -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-dialogflow - - -# [START dialogflow_v2beta1_generated_Intents_CreateIntent_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import dialogflow_v2beta1 - - -async def sample_create_intent(): - # Create a client - client = dialogflow_v2beta1.IntentsAsyncClient() - - # Initialize request argument(s) - intent = dialogflow_v2beta1.Intent() - intent.display_name = "display_name_value" - - request = dialogflow_v2beta1.CreateIntentRequest( - parent="parent_value", - intent=intent, - ) - - # Make the request - response = await client.create_intent(request=request) - - # Handle the response - print(response) - -# [END dialogflow_v2beta1_generated_Intents_CreateIntent_async] diff --git a/owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_intents_create_intent_sync.py b/owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_intents_create_intent_sync.py deleted file mode 100644 index 7d993ff57..000000000 --- a/owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_intents_create_intent_sync.py +++ /dev/null @@ -1,56 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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. -# -# Generated code. DO NOT EDIT! -# -# Snippet for CreateIntent -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-dialogflow - - -# [START dialogflow_v2beta1_generated_Intents_CreateIntent_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import dialogflow_v2beta1 - - -def sample_create_intent(): - # Create a client - client = dialogflow_v2beta1.IntentsClient() - - # Initialize request argument(s) - intent = dialogflow_v2beta1.Intent() - intent.display_name = "display_name_value" - - request = dialogflow_v2beta1.CreateIntentRequest( - parent="parent_value", - intent=intent, - ) - - # Make the request - response = client.create_intent(request=request) - - # Handle the response - print(response) - -# [END dialogflow_v2beta1_generated_Intents_CreateIntent_sync] diff --git a/owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_intents_delete_intent_async.py b/owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_intents_delete_intent_async.py deleted file mode 100644 index f65604f40..000000000 --- a/owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_intents_delete_intent_async.py +++ /dev/null @@ -1,50 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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. -# -# Generated code. DO NOT EDIT! -# -# Snippet for DeleteIntent -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-dialogflow - - -# [START dialogflow_v2beta1_generated_Intents_DeleteIntent_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import dialogflow_v2beta1 - - -async def sample_delete_intent(): - # Create a client - client = dialogflow_v2beta1.IntentsAsyncClient() - - # Initialize request argument(s) - request = dialogflow_v2beta1.DeleteIntentRequest( - name="name_value", - ) - - # Make the request - await client.delete_intent(request=request) - - -# [END dialogflow_v2beta1_generated_Intents_DeleteIntent_async] diff --git a/owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_intents_delete_intent_sync.py b/owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_intents_delete_intent_sync.py deleted file mode 100644 index e5146882d..000000000 --- a/owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_intents_delete_intent_sync.py +++ /dev/null @@ -1,50 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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. -# -# Generated code. DO NOT EDIT! -# -# Snippet for DeleteIntent -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-dialogflow - - -# [START dialogflow_v2beta1_generated_Intents_DeleteIntent_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import dialogflow_v2beta1 - - -def sample_delete_intent(): - # Create a client - client = dialogflow_v2beta1.IntentsClient() - - # Initialize request argument(s) - request = dialogflow_v2beta1.DeleteIntentRequest( - name="name_value", - ) - - # Make the request - client.delete_intent(request=request) - - -# [END dialogflow_v2beta1_generated_Intents_DeleteIntent_sync] diff --git a/owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_intents_get_intent_async.py b/owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_intents_get_intent_async.py deleted file mode 100644 index fe3a97c84..000000000 --- a/owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_intents_get_intent_async.py +++ /dev/null @@ -1,52 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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. -# -# Generated code. DO NOT EDIT! -# -# Snippet for GetIntent -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-dialogflow - - -# [START dialogflow_v2beta1_generated_Intents_GetIntent_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import dialogflow_v2beta1 - - -async def sample_get_intent(): - # Create a client - client = dialogflow_v2beta1.IntentsAsyncClient() - - # Initialize request argument(s) - request = dialogflow_v2beta1.GetIntentRequest( - name="name_value", - ) - - # Make the request - response = await client.get_intent(request=request) - - # Handle the response - print(response) - -# [END dialogflow_v2beta1_generated_Intents_GetIntent_async] diff --git a/owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_intents_get_intent_sync.py b/owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_intents_get_intent_sync.py deleted file mode 100644 index 40c298821..000000000 --- a/owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_intents_get_intent_sync.py +++ /dev/null @@ -1,52 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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. -# -# Generated code. DO NOT EDIT! -# -# Snippet for GetIntent -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-dialogflow - - -# [START dialogflow_v2beta1_generated_Intents_GetIntent_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import dialogflow_v2beta1 - - -def sample_get_intent(): - # Create a client - client = dialogflow_v2beta1.IntentsClient() - - # Initialize request argument(s) - request = dialogflow_v2beta1.GetIntentRequest( - name="name_value", - ) - - # Make the request - response = client.get_intent(request=request) - - # Handle the response - print(response) - -# [END dialogflow_v2beta1_generated_Intents_GetIntent_sync] diff --git a/owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_intents_list_intents_async.py b/owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_intents_list_intents_async.py deleted file mode 100644 index c3ce006f9..000000000 --- a/owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_intents_list_intents_async.py +++ /dev/null @@ -1,53 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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. -# -# Generated code. DO NOT EDIT! -# -# Snippet for ListIntents -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-dialogflow - - -# [START dialogflow_v2beta1_generated_Intents_ListIntents_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import dialogflow_v2beta1 - - -async def sample_list_intents(): - # Create a client - client = dialogflow_v2beta1.IntentsAsyncClient() - - # Initialize request argument(s) - request = dialogflow_v2beta1.ListIntentsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_intents(request=request) - - # Handle the response - async for response in page_result: - print(response) - -# [END dialogflow_v2beta1_generated_Intents_ListIntents_async] diff --git a/owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_intents_list_intents_sync.py b/owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_intents_list_intents_sync.py deleted file mode 100644 index 722b5e2c8..000000000 --- a/owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_intents_list_intents_sync.py +++ /dev/null @@ -1,53 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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. -# -# Generated code. DO NOT EDIT! -# -# Snippet for ListIntents -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-dialogflow - - -# [START dialogflow_v2beta1_generated_Intents_ListIntents_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import dialogflow_v2beta1 - - -def sample_list_intents(): - # Create a client - client = dialogflow_v2beta1.IntentsClient() - - # Initialize request argument(s) - request = dialogflow_v2beta1.ListIntentsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_intents(request=request) - - # Handle the response - for response in page_result: - print(response) - -# [END dialogflow_v2beta1_generated_Intents_ListIntents_sync] diff --git a/owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_intents_update_intent_async.py b/owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_intents_update_intent_async.py deleted file mode 100644 index fc57e3190..000000000 --- a/owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_intents_update_intent_async.py +++ /dev/null @@ -1,55 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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. -# -# Generated code. DO NOT EDIT! -# -# Snippet for UpdateIntent -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-dialogflow - - -# [START dialogflow_v2beta1_generated_Intents_UpdateIntent_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import dialogflow_v2beta1 - - -async def sample_update_intent(): - # Create a client - client = dialogflow_v2beta1.IntentsAsyncClient() - - # Initialize request argument(s) - intent = dialogflow_v2beta1.Intent() - intent.display_name = "display_name_value" - - request = dialogflow_v2beta1.UpdateIntentRequest( - intent=intent, - ) - - # Make the request - response = await client.update_intent(request=request) - - # Handle the response - print(response) - -# [END dialogflow_v2beta1_generated_Intents_UpdateIntent_async] diff --git a/owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_intents_update_intent_sync.py b/owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_intents_update_intent_sync.py deleted file mode 100644 index 9c187c1ae..000000000 --- a/owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_intents_update_intent_sync.py +++ /dev/null @@ -1,55 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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. -# -# Generated code. DO NOT EDIT! -# -# Snippet for UpdateIntent -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-dialogflow - - -# [START dialogflow_v2beta1_generated_Intents_UpdateIntent_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import dialogflow_v2beta1 - - -def sample_update_intent(): - # Create a client - client = dialogflow_v2beta1.IntentsClient() - - # Initialize request argument(s) - intent = dialogflow_v2beta1.Intent() - intent.display_name = "display_name_value" - - request = dialogflow_v2beta1.UpdateIntentRequest( - intent=intent, - ) - - # Make the request - response = client.update_intent(request=request) - - # Handle the response - print(response) - -# [END dialogflow_v2beta1_generated_Intents_UpdateIntent_sync] diff --git a/owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_knowledge_bases_create_knowledge_base_async.py b/owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_knowledge_bases_create_knowledge_base_async.py deleted file mode 100644 index ad2945009..000000000 --- a/owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_knowledge_bases_create_knowledge_base_async.py +++ /dev/null @@ -1,56 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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. -# -# Generated code. DO NOT EDIT! -# -# Snippet for CreateKnowledgeBase -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-dialogflow - - -# [START dialogflow_v2beta1_generated_KnowledgeBases_CreateKnowledgeBase_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import dialogflow_v2beta1 - - -async def sample_create_knowledge_base(): - # Create a client - client = dialogflow_v2beta1.KnowledgeBasesAsyncClient() - - # Initialize request argument(s) - knowledge_base = dialogflow_v2beta1.KnowledgeBase() - knowledge_base.display_name = "display_name_value" - - request = dialogflow_v2beta1.CreateKnowledgeBaseRequest( - parent="parent_value", - knowledge_base=knowledge_base, - ) - - # Make the request - response = await client.create_knowledge_base(request=request) - - # Handle the response - print(response) - -# [END dialogflow_v2beta1_generated_KnowledgeBases_CreateKnowledgeBase_async] diff --git a/owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_knowledge_bases_create_knowledge_base_sync.py b/owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_knowledge_bases_create_knowledge_base_sync.py deleted file mode 100644 index 5647847a4..000000000 --- a/owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_knowledge_bases_create_knowledge_base_sync.py +++ /dev/null @@ -1,56 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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. -# -# Generated code. DO NOT EDIT! -# -# Snippet for CreateKnowledgeBase -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-dialogflow - - -# [START dialogflow_v2beta1_generated_KnowledgeBases_CreateKnowledgeBase_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import dialogflow_v2beta1 - - -def sample_create_knowledge_base(): - # Create a client - client = dialogflow_v2beta1.KnowledgeBasesClient() - - # Initialize request argument(s) - knowledge_base = dialogflow_v2beta1.KnowledgeBase() - knowledge_base.display_name = "display_name_value" - - request = dialogflow_v2beta1.CreateKnowledgeBaseRequest( - parent="parent_value", - knowledge_base=knowledge_base, - ) - - # Make the request - response = client.create_knowledge_base(request=request) - - # Handle the response - print(response) - -# [END dialogflow_v2beta1_generated_KnowledgeBases_CreateKnowledgeBase_sync] diff --git a/owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_knowledge_bases_delete_knowledge_base_async.py b/owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_knowledge_bases_delete_knowledge_base_async.py deleted file mode 100644 index 51810a05a..000000000 --- a/owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_knowledge_bases_delete_knowledge_base_async.py +++ /dev/null @@ -1,50 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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. -# -# Generated code. DO NOT EDIT! -# -# Snippet for DeleteKnowledgeBase -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-dialogflow - - -# [START dialogflow_v2beta1_generated_KnowledgeBases_DeleteKnowledgeBase_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import dialogflow_v2beta1 - - -async def sample_delete_knowledge_base(): - # Create a client - client = dialogflow_v2beta1.KnowledgeBasesAsyncClient() - - # Initialize request argument(s) - request = dialogflow_v2beta1.DeleteKnowledgeBaseRequest( - name="name_value", - ) - - # Make the request - await client.delete_knowledge_base(request=request) - - -# [END dialogflow_v2beta1_generated_KnowledgeBases_DeleteKnowledgeBase_async] diff --git a/owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_knowledge_bases_delete_knowledge_base_sync.py b/owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_knowledge_bases_delete_knowledge_base_sync.py deleted file mode 100644 index e952f715c..000000000 --- a/owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_knowledge_bases_delete_knowledge_base_sync.py +++ /dev/null @@ -1,50 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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. -# -# Generated code. DO NOT EDIT! -# -# Snippet for DeleteKnowledgeBase -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-dialogflow - - -# [START dialogflow_v2beta1_generated_KnowledgeBases_DeleteKnowledgeBase_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import dialogflow_v2beta1 - - -def sample_delete_knowledge_base(): - # Create a client - client = dialogflow_v2beta1.KnowledgeBasesClient() - - # Initialize request argument(s) - request = dialogflow_v2beta1.DeleteKnowledgeBaseRequest( - name="name_value", - ) - - # Make the request - client.delete_knowledge_base(request=request) - - -# [END dialogflow_v2beta1_generated_KnowledgeBases_DeleteKnowledgeBase_sync] diff --git a/owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_knowledge_bases_get_knowledge_base_async.py b/owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_knowledge_bases_get_knowledge_base_async.py deleted file mode 100644 index 848ddf3d5..000000000 --- a/owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_knowledge_bases_get_knowledge_base_async.py +++ /dev/null @@ -1,52 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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. -# -# Generated code. DO NOT EDIT! -# -# Snippet for GetKnowledgeBase -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-dialogflow - - -# [START dialogflow_v2beta1_generated_KnowledgeBases_GetKnowledgeBase_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import dialogflow_v2beta1 - - -async def sample_get_knowledge_base(): - # Create a client - client = dialogflow_v2beta1.KnowledgeBasesAsyncClient() - - # Initialize request argument(s) - request = dialogflow_v2beta1.GetKnowledgeBaseRequest( - name="name_value", - ) - - # Make the request - response = await client.get_knowledge_base(request=request) - - # Handle the response - print(response) - -# [END dialogflow_v2beta1_generated_KnowledgeBases_GetKnowledgeBase_async] diff --git a/owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_knowledge_bases_get_knowledge_base_sync.py b/owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_knowledge_bases_get_knowledge_base_sync.py deleted file mode 100644 index 2c5dabe8c..000000000 --- a/owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_knowledge_bases_get_knowledge_base_sync.py +++ /dev/null @@ -1,52 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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. -# -# Generated code. DO NOT EDIT! -# -# Snippet for GetKnowledgeBase -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-dialogflow - - -# [START dialogflow_v2beta1_generated_KnowledgeBases_GetKnowledgeBase_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import dialogflow_v2beta1 - - -def sample_get_knowledge_base(): - # Create a client - client = dialogflow_v2beta1.KnowledgeBasesClient() - - # Initialize request argument(s) - request = dialogflow_v2beta1.GetKnowledgeBaseRequest( - name="name_value", - ) - - # Make the request - response = client.get_knowledge_base(request=request) - - # Handle the response - print(response) - -# [END dialogflow_v2beta1_generated_KnowledgeBases_GetKnowledgeBase_sync] diff --git a/owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_knowledge_bases_list_knowledge_bases_async.py b/owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_knowledge_bases_list_knowledge_bases_async.py deleted file mode 100644 index 64fe96445..000000000 --- a/owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_knowledge_bases_list_knowledge_bases_async.py +++ /dev/null @@ -1,53 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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. -# -# Generated code. DO NOT EDIT! -# -# Snippet for ListKnowledgeBases -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-dialogflow - - -# [START dialogflow_v2beta1_generated_KnowledgeBases_ListKnowledgeBases_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import dialogflow_v2beta1 - - -async def sample_list_knowledge_bases(): - # Create a client - client = dialogflow_v2beta1.KnowledgeBasesAsyncClient() - - # Initialize request argument(s) - request = dialogflow_v2beta1.ListKnowledgeBasesRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_knowledge_bases(request=request) - - # Handle the response - async for response in page_result: - print(response) - -# [END dialogflow_v2beta1_generated_KnowledgeBases_ListKnowledgeBases_async] diff --git a/owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_knowledge_bases_list_knowledge_bases_sync.py b/owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_knowledge_bases_list_knowledge_bases_sync.py deleted file mode 100644 index 66368524d..000000000 --- a/owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_knowledge_bases_list_knowledge_bases_sync.py +++ /dev/null @@ -1,53 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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. -# -# Generated code. DO NOT EDIT! -# -# Snippet for ListKnowledgeBases -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-dialogflow - - -# [START dialogflow_v2beta1_generated_KnowledgeBases_ListKnowledgeBases_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import dialogflow_v2beta1 - - -def sample_list_knowledge_bases(): - # Create a client - client = dialogflow_v2beta1.KnowledgeBasesClient() - - # Initialize request argument(s) - request = dialogflow_v2beta1.ListKnowledgeBasesRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_knowledge_bases(request=request) - - # Handle the response - for response in page_result: - print(response) - -# [END dialogflow_v2beta1_generated_KnowledgeBases_ListKnowledgeBases_sync] diff --git a/owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_knowledge_bases_update_knowledge_base_async.py b/owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_knowledge_bases_update_knowledge_base_async.py deleted file mode 100644 index e2d5727c5..000000000 --- a/owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_knowledge_bases_update_knowledge_base_async.py +++ /dev/null @@ -1,55 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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. -# -# Generated code. DO NOT EDIT! -# -# Snippet for UpdateKnowledgeBase -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-dialogflow - - -# [START dialogflow_v2beta1_generated_KnowledgeBases_UpdateKnowledgeBase_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import dialogflow_v2beta1 - - -async def sample_update_knowledge_base(): - # Create a client - client = dialogflow_v2beta1.KnowledgeBasesAsyncClient() - - # Initialize request argument(s) - knowledge_base = dialogflow_v2beta1.KnowledgeBase() - knowledge_base.display_name = "display_name_value" - - request = dialogflow_v2beta1.UpdateKnowledgeBaseRequest( - knowledge_base=knowledge_base, - ) - - # Make the request - response = await client.update_knowledge_base(request=request) - - # Handle the response - print(response) - -# [END dialogflow_v2beta1_generated_KnowledgeBases_UpdateKnowledgeBase_async] diff --git a/owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_knowledge_bases_update_knowledge_base_sync.py b/owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_knowledge_bases_update_knowledge_base_sync.py deleted file mode 100644 index 482359a0e..000000000 --- a/owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_knowledge_bases_update_knowledge_base_sync.py +++ /dev/null @@ -1,55 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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. -# -# Generated code. DO NOT EDIT! -# -# Snippet for UpdateKnowledgeBase -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-dialogflow - - -# [START dialogflow_v2beta1_generated_KnowledgeBases_UpdateKnowledgeBase_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import dialogflow_v2beta1 - - -def sample_update_knowledge_base(): - # Create a client - client = dialogflow_v2beta1.KnowledgeBasesClient() - - # Initialize request argument(s) - knowledge_base = dialogflow_v2beta1.KnowledgeBase() - knowledge_base.display_name = "display_name_value" - - request = dialogflow_v2beta1.UpdateKnowledgeBaseRequest( - knowledge_base=knowledge_base, - ) - - # Make the request - response = client.update_knowledge_base(request=request) - - # Handle the response - print(response) - -# [END dialogflow_v2beta1_generated_KnowledgeBases_UpdateKnowledgeBase_sync] diff --git a/owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_participants_analyze_content_async.py b/owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_participants_analyze_content_async.py deleted file mode 100644 index f0163e837..000000000 --- a/owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_participants_analyze_content_async.py +++ /dev/null @@ -1,52 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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. -# -# Generated code. DO NOT EDIT! -# -# Snippet for AnalyzeContent -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-dialogflow - - -# [START dialogflow_v2beta1_generated_Participants_AnalyzeContent_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import dialogflow_v2beta1 - - -async def sample_analyze_content(): - # Create a client - client = dialogflow_v2beta1.ParticipantsAsyncClient() - - # Initialize request argument(s) - request = dialogflow_v2beta1.AnalyzeContentRequest( - participant="participant_value", - ) - - # Make the request - response = await client.analyze_content(request=request) - - # Handle the response - print(response) - -# [END dialogflow_v2beta1_generated_Participants_AnalyzeContent_async] diff --git a/owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_participants_analyze_content_sync.py b/owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_participants_analyze_content_sync.py deleted file mode 100644 index 6e71aa802..000000000 --- a/owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_participants_analyze_content_sync.py +++ /dev/null @@ -1,52 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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. -# -# Generated code. DO NOT EDIT! -# -# Snippet for AnalyzeContent -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-dialogflow - - -# [START dialogflow_v2beta1_generated_Participants_AnalyzeContent_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import dialogflow_v2beta1 - - -def sample_analyze_content(): - # Create a client - client = dialogflow_v2beta1.ParticipantsClient() - - # Initialize request argument(s) - request = dialogflow_v2beta1.AnalyzeContentRequest( - participant="participant_value", - ) - - # Make the request - response = client.analyze_content(request=request) - - # Handle the response - print(response) - -# [END dialogflow_v2beta1_generated_Participants_AnalyzeContent_sync] diff --git a/owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_participants_compile_suggestion_async.py b/owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_participants_compile_suggestion_async.py deleted file mode 100644 index f61f61893..000000000 --- a/owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_participants_compile_suggestion_async.py +++ /dev/null @@ -1,51 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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. -# -# Generated code. DO NOT EDIT! -# -# Snippet for CompileSuggestion -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-dialogflow - - -# [START dialogflow_v2beta1_generated_Participants_CompileSuggestion_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import dialogflow_v2beta1 - - -async def sample_compile_suggestion(): - # Create a client - client = dialogflow_v2beta1.ParticipantsAsyncClient() - - # Initialize request argument(s) - request = dialogflow_v2beta1.CompileSuggestionRequest( - ) - - # Make the request - response = await client.compile_suggestion(request=request) - - # Handle the response - print(response) - -# [END dialogflow_v2beta1_generated_Participants_CompileSuggestion_async] diff --git a/owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_participants_compile_suggestion_sync.py b/owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_participants_compile_suggestion_sync.py deleted file mode 100644 index 18ea58309..000000000 --- a/owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_participants_compile_suggestion_sync.py +++ /dev/null @@ -1,51 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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. -# -# Generated code. DO NOT EDIT! -# -# Snippet for CompileSuggestion -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-dialogflow - - -# [START dialogflow_v2beta1_generated_Participants_CompileSuggestion_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import dialogflow_v2beta1 - - -def sample_compile_suggestion(): - # Create a client - client = dialogflow_v2beta1.ParticipantsClient() - - # Initialize request argument(s) - request = dialogflow_v2beta1.CompileSuggestionRequest( - ) - - # Make the request - response = client.compile_suggestion(request=request) - - # Handle the response - print(response) - -# [END dialogflow_v2beta1_generated_Participants_CompileSuggestion_sync] diff --git a/owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_participants_create_participant_async.py b/owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_participants_create_participant_async.py deleted file mode 100644 index 1a34742b5..000000000 --- a/owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_participants_create_participant_async.py +++ /dev/null @@ -1,52 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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. -# -# Generated code. DO NOT EDIT! -# -# Snippet for CreateParticipant -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-dialogflow - - -# [START dialogflow_v2beta1_generated_Participants_CreateParticipant_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import dialogflow_v2beta1 - - -async def sample_create_participant(): - # Create a client - client = dialogflow_v2beta1.ParticipantsAsyncClient() - - # Initialize request argument(s) - request = dialogflow_v2beta1.CreateParticipantRequest( - parent="parent_value", - ) - - # Make the request - response = await client.create_participant(request=request) - - # Handle the response - print(response) - -# [END dialogflow_v2beta1_generated_Participants_CreateParticipant_async] diff --git a/owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_participants_create_participant_sync.py b/owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_participants_create_participant_sync.py deleted file mode 100644 index dacb11d32..000000000 --- a/owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_participants_create_participant_sync.py +++ /dev/null @@ -1,52 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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. -# -# Generated code. DO NOT EDIT! -# -# Snippet for CreateParticipant -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-dialogflow - - -# [START dialogflow_v2beta1_generated_Participants_CreateParticipant_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import dialogflow_v2beta1 - - -def sample_create_participant(): - # Create a client - client = dialogflow_v2beta1.ParticipantsClient() - - # Initialize request argument(s) - request = dialogflow_v2beta1.CreateParticipantRequest( - parent="parent_value", - ) - - # Make the request - response = client.create_participant(request=request) - - # Handle the response - print(response) - -# [END dialogflow_v2beta1_generated_Participants_CreateParticipant_sync] diff --git a/owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_participants_get_participant_async.py b/owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_participants_get_participant_async.py deleted file mode 100644 index 98a9dacd9..000000000 --- a/owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_participants_get_participant_async.py +++ /dev/null @@ -1,52 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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. -# -# Generated code. DO NOT EDIT! -# -# Snippet for GetParticipant -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-dialogflow - - -# [START dialogflow_v2beta1_generated_Participants_GetParticipant_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import dialogflow_v2beta1 - - -async def sample_get_participant(): - # Create a client - client = dialogflow_v2beta1.ParticipantsAsyncClient() - - # Initialize request argument(s) - request = dialogflow_v2beta1.GetParticipantRequest( - name="name_value", - ) - - # Make the request - response = await client.get_participant(request=request) - - # Handle the response - print(response) - -# [END dialogflow_v2beta1_generated_Participants_GetParticipant_async] diff --git a/owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_participants_get_participant_sync.py b/owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_participants_get_participant_sync.py deleted file mode 100644 index 72cfda4d7..000000000 --- a/owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_participants_get_participant_sync.py +++ /dev/null @@ -1,52 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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. -# -# Generated code. DO NOT EDIT! -# -# Snippet for GetParticipant -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-dialogflow - - -# [START dialogflow_v2beta1_generated_Participants_GetParticipant_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import dialogflow_v2beta1 - - -def sample_get_participant(): - # Create a client - client = dialogflow_v2beta1.ParticipantsClient() - - # Initialize request argument(s) - request = dialogflow_v2beta1.GetParticipantRequest( - name="name_value", - ) - - # Make the request - response = client.get_participant(request=request) - - # Handle the response - print(response) - -# [END dialogflow_v2beta1_generated_Participants_GetParticipant_sync] diff --git a/owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_participants_list_participants_async.py b/owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_participants_list_participants_async.py deleted file mode 100644 index 37956a359..000000000 --- a/owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_participants_list_participants_async.py +++ /dev/null @@ -1,53 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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. -# -# Generated code. DO NOT EDIT! -# -# Snippet for ListParticipants -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-dialogflow - - -# [START dialogflow_v2beta1_generated_Participants_ListParticipants_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import dialogflow_v2beta1 - - -async def sample_list_participants(): - # Create a client - client = dialogflow_v2beta1.ParticipantsAsyncClient() - - # Initialize request argument(s) - request = dialogflow_v2beta1.ListParticipantsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_participants(request=request) - - # Handle the response - async for response in page_result: - print(response) - -# [END dialogflow_v2beta1_generated_Participants_ListParticipants_async] diff --git a/owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_participants_list_participants_sync.py b/owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_participants_list_participants_sync.py deleted file mode 100644 index 712daa802..000000000 --- a/owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_participants_list_participants_sync.py +++ /dev/null @@ -1,53 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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. -# -# Generated code. DO NOT EDIT! -# -# Snippet for ListParticipants -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-dialogflow - - -# [START dialogflow_v2beta1_generated_Participants_ListParticipants_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import dialogflow_v2beta1 - - -def sample_list_participants(): - # Create a client - client = dialogflow_v2beta1.ParticipantsClient() - - # Initialize request argument(s) - request = dialogflow_v2beta1.ListParticipantsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_participants(request=request) - - # Handle the response - for response in page_result: - print(response) - -# [END dialogflow_v2beta1_generated_Participants_ListParticipants_sync] diff --git a/owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_participants_list_suggestions_async.py b/owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_participants_list_suggestions_async.py deleted file mode 100644 index e8baf480d..000000000 --- a/owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_participants_list_suggestions_async.py +++ /dev/null @@ -1,52 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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. -# -# Generated code. DO NOT EDIT! -# -# Snippet for ListSuggestions -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-dialogflow - - -# [START dialogflow_v2beta1_generated_Participants_ListSuggestions_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import dialogflow_v2beta1 - - -async def sample_list_suggestions(): - # Create a client - client = dialogflow_v2beta1.ParticipantsAsyncClient() - - # Initialize request argument(s) - request = dialogflow_v2beta1.ListSuggestionsRequest( - ) - - # Make the request - page_result = client.list_suggestions(request=request) - - # Handle the response - async for response in page_result: - print(response) - -# [END dialogflow_v2beta1_generated_Participants_ListSuggestions_async] diff --git a/owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_participants_list_suggestions_sync.py b/owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_participants_list_suggestions_sync.py deleted file mode 100644 index 6aad719cf..000000000 --- a/owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_participants_list_suggestions_sync.py +++ /dev/null @@ -1,52 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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. -# -# Generated code. DO NOT EDIT! -# -# Snippet for ListSuggestions -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-dialogflow - - -# [START dialogflow_v2beta1_generated_Participants_ListSuggestions_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import dialogflow_v2beta1 - - -def sample_list_suggestions(): - # Create a client - client = dialogflow_v2beta1.ParticipantsClient() - - # Initialize request argument(s) - request = dialogflow_v2beta1.ListSuggestionsRequest( - ) - - # Make the request - page_result = client.list_suggestions(request=request) - - # Handle the response - for response in page_result: - print(response) - -# [END dialogflow_v2beta1_generated_Participants_ListSuggestions_sync] diff --git a/owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_participants_streaming_analyze_content_async.py b/owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_participants_streaming_analyze_content_async.py deleted file mode 100644 index e090b36b4..000000000 --- a/owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_participants_streaming_analyze_content_async.py +++ /dev/null @@ -1,64 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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. -# -# Generated code. DO NOT EDIT! -# -# Snippet for StreamingAnalyzeContent -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-dialogflow - - -# [START dialogflow_v2beta1_generated_Participants_StreamingAnalyzeContent_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import dialogflow_v2beta1 - - -async def sample_streaming_analyze_content(): - # Create a client - client = dialogflow_v2beta1.ParticipantsAsyncClient() - - # Initialize request argument(s) - request = dialogflow_v2beta1.StreamingAnalyzeContentRequest( - input_audio=b'input_audio_blob', - participant="participant_value", - ) - - # This method expects an iterator which contains - # 'dialogflow_v2beta1.StreamingAnalyzeContentRequest' objects - # Here we create a generator that yields a single `request` for - # demonstrative purposes. - requests = [request] - - def request_generator(): - for request in requests: - yield request - - # Make the request - stream = await client.streaming_analyze_content(requests=request_generator()) - - # Handle the response - async for response in stream: - print(response) - -# [END dialogflow_v2beta1_generated_Participants_StreamingAnalyzeContent_async] diff --git a/owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_participants_streaming_analyze_content_sync.py b/owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_participants_streaming_analyze_content_sync.py deleted file mode 100644 index 1ef8a3eec..000000000 --- a/owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_participants_streaming_analyze_content_sync.py +++ /dev/null @@ -1,64 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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. -# -# Generated code. DO NOT EDIT! -# -# Snippet for StreamingAnalyzeContent -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-dialogflow - - -# [START dialogflow_v2beta1_generated_Participants_StreamingAnalyzeContent_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import dialogflow_v2beta1 - - -def sample_streaming_analyze_content(): - # Create a client - client = dialogflow_v2beta1.ParticipantsClient() - - # Initialize request argument(s) - request = dialogflow_v2beta1.StreamingAnalyzeContentRequest( - input_audio=b'input_audio_blob', - participant="participant_value", - ) - - # This method expects an iterator which contains - # 'dialogflow_v2beta1.StreamingAnalyzeContentRequest' objects - # Here we create a generator that yields a single `request` for - # demonstrative purposes. - requests = [request] - - def request_generator(): - for request in requests: - yield request - - # Make the request - stream = client.streaming_analyze_content(requests=request_generator()) - - # Handle the response - for response in stream: - print(response) - -# [END dialogflow_v2beta1_generated_Participants_StreamingAnalyzeContent_sync] diff --git a/owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_participants_suggest_articles_async.py b/owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_participants_suggest_articles_async.py deleted file mode 100644 index 3e14eee7e..000000000 --- a/owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_participants_suggest_articles_async.py +++ /dev/null @@ -1,52 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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. -# -# Generated code. DO NOT EDIT! -# -# Snippet for SuggestArticles -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-dialogflow - - -# [START dialogflow_v2beta1_generated_Participants_SuggestArticles_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import dialogflow_v2beta1 - - -async def sample_suggest_articles(): - # Create a client - client = dialogflow_v2beta1.ParticipantsAsyncClient() - - # Initialize request argument(s) - request = dialogflow_v2beta1.SuggestArticlesRequest( - parent="parent_value", - ) - - # Make the request - response = await client.suggest_articles(request=request) - - # Handle the response - print(response) - -# [END dialogflow_v2beta1_generated_Participants_SuggestArticles_async] diff --git a/owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_participants_suggest_articles_sync.py b/owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_participants_suggest_articles_sync.py deleted file mode 100644 index 93ce94e30..000000000 --- a/owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_participants_suggest_articles_sync.py +++ /dev/null @@ -1,52 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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. -# -# Generated code. DO NOT EDIT! -# -# Snippet for SuggestArticles -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-dialogflow - - -# [START dialogflow_v2beta1_generated_Participants_SuggestArticles_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import dialogflow_v2beta1 - - -def sample_suggest_articles(): - # Create a client - client = dialogflow_v2beta1.ParticipantsClient() - - # Initialize request argument(s) - request = dialogflow_v2beta1.SuggestArticlesRequest( - parent="parent_value", - ) - - # Make the request - response = client.suggest_articles(request=request) - - # Handle the response - print(response) - -# [END dialogflow_v2beta1_generated_Participants_SuggestArticles_sync] diff --git a/owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_participants_suggest_faq_answers_async.py b/owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_participants_suggest_faq_answers_async.py deleted file mode 100644 index a76058077..000000000 --- a/owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_participants_suggest_faq_answers_async.py +++ /dev/null @@ -1,52 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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. -# -# Generated code. DO NOT EDIT! -# -# Snippet for SuggestFaqAnswers -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-dialogflow - - -# [START dialogflow_v2beta1_generated_Participants_SuggestFaqAnswers_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import dialogflow_v2beta1 - - -async def sample_suggest_faq_answers(): - # Create a client - client = dialogflow_v2beta1.ParticipantsAsyncClient() - - # Initialize request argument(s) - request = dialogflow_v2beta1.SuggestFaqAnswersRequest( - parent="parent_value", - ) - - # Make the request - response = await client.suggest_faq_answers(request=request) - - # Handle the response - print(response) - -# [END dialogflow_v2beta1_generated_Participants_SuggestFaqAnswers_async] diff --git a/owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_participants_suggest_faq_answers_sync.py b/owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_participants_suggest_faq_answers_sync.py deleted file mode 100644 index ca21d551c..000000000 --- a/owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_participants_suggest_faq_answers_sync.py +++ /dev/null @@ -1,52 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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. -# -# Generated code. DO NOT EDIT! -# -# Snippet for SuggestFaqAnswers -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-dialogflow - - -# [START dialogflow_v2beta1_generated_Participants_SuggestFaqAnswers_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import dialogflow_v2beta1 - - -def sample_suggest_faq_answers(): - # Create a client - client = dialogflow_v2beta1.ParticipantsClient() - - # Initialize request argument(s) - request = dialogflow_v2beta1.SuggestFaqAnswersRequest( - parent="parent_value", - ) - - # Make the request - response = client.suggest_faq_answers(request=request) - - # Handle the response - print(response) - -# [END dialogflow_v2beta1_generated_Participants_SuggestFaqAnswers_sync] diff --git a/owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_participants_suggest_smart_replies_async.py b/owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_participants_suggest_smart_replies_async.py deleted file mode 100644 index 762f30f52..000000000 --- a/owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_participants_suggest_smart_replies_async.py +++ /dev/null @@ -1,52 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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. -# -# Generated code. DO NOT EDIT! -# -# Snippet for SuggestSmartReplies -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-dialogflow - - -# [START dialogflow_v2beta1_generated_Participants_SuggestSmartReplies_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import dialogflow_v2beta1 - - -async def sample_suggest_smart_replies(): - # Create a client - client = dialogflow_v2beta1.ParticipantsAsyncClient() - - # Initialize request argument(s) - request = dialogflow_v2beta1.SuggestSmartRepliesRequest( - parent="parent_value", - ) - - # Make the request - response = await client.suggest_smart_replies(request=request) - - # Handle the response - print(response) - -# [END dialogflow_v2beta1_generated_Participants_SuggestSmartReplies_async] diff --git a/owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_participants_suggest_smart_replies_sync.py b/owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_participants_suggest_smart_replies_sync.py deleted file mode 100644 index cfe8e9c90..000000000 --- a/owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_participants_suggest_smart_replies_sync.py +++ /dev/null @@ -1,52 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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. -# -# Generated code. DO NOT EDIT! -# -# Snippet for SuggestSmartReplies -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-dialogflow - - -# [START dialogflow_v2beta1_generated_Participants_SuggestSmartReplies_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import dialogflow_v2beta1 - - -def sample_suggest_smart_replies(): - # Create a client - client = dialogflow_v2beta1.ParticipantsClient() - - # Initialize request argument(s) - request = dialogflow_v2beta1.SuggestSmartRepliesRequest( - parent="parent_value", - ) - - # Make the request - response = client.suggest_smart_replies(request=request) - - # Handle the response - print(response) - -# [END dialogflow_v2beta1_generated_Participants_SuggestSmartReplies_sync] diff --git a/owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_participants_update_participant_async.py b/owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_participants_update_participant_async.py deleted file mode 100644 index 516e7e5a9..000000000 --- a/owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_participants_update_participant_async.py +++ /dev/null @@ -1,51 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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. -# -# Generated code. DO NOT EDIT! -# -# Snippet for UpdateParticipant -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-dialogflow - - -# [START dialogflow_v2beta1_generated_Participants_UpdateParticipant_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import dialogflow_v2beta1 - - -async def sample_update_participant(): - # Create a client - client = dialogflow_v2beta1.ParticipantsAsyncClient() - - # Initialize request argument(s) - request = dialogflow_v2beta1.UpdateParticipantRequest( - ) - - # Make the request - response = await client.update_participant(request=request) - - # Handle the response - print(response) - -# [END dialogflow_v2beta1_generated_Participants_UpdateParticipant_async] diff --git a/owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_participants_update_participant_sync.py b/owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_participants_update_participant_sync.py deleted file mode 100644 index 3522fae2b..000000000 --- a/owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_participants_update_participant_sync.py +++ /dev/null @@ -1,51 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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. -# -# Generated code. DO NOT EDIT! -# -# Snippet for UpdateParticipant -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-dialogflow - - -# [START dialogflow_v2beta1_generated_Participants_UpdateParticipant_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import dialogflow_v2beta1 - - -def sample_update_participant(): - # Create a client - client = dialogflow_v2beta1.ParticipantsClient() - - # Initialize request argument(s) - request = dialogflow_v2beta1.UpdateParticipantRequest( - ) - - # Make the request - response = client.update_participant(request=request) - - # Handle the response - print(response) - -# [END dialogflow_v2beta1_generated_Participants_UpdateParticipant_sync] diff --git a/owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_session_entity_types_create_session_entity_type_async.py b/owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_session_entity_types_create_session_entity_type_async.py deleted file mode 100644 index 87abf0669..000000000 --- a/owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_session_entity_types_create_session_entity_type_async.py +++ /dev/null @@ -1,52 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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. -# -# Generated code. DO NOT EDIT! -# -# Snippet for CreateSessionEntityType -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-dialogflow - - -# [START dialogflow_v2beta1_generated_SessionEntityTypes_CreateSessionEntityType_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import dialogflow_v2beta1 - - -async def sample_create_session_entity_type(): - # Create a client - client = dialogflow_v2beta1.SessionEntityTypesAsyncClient() - - # Initialize request argument(s) - request = dialogflow_v2beta1.CreateSessionEntityTypeRequest( - parent="parent_value", - ) - - # Make the request - response = await client.create_session_entity_type(request=request) - - # Handle the response - print(response) - -# [END dialogflow_v2beta1_generated_SessionEntityTypes_CreateSessionEntityType_async] diff --git a/owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_session_entity_types_create_session_entity_type_sync.py b/owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_session_entity_types_create_session_entity_type_sync.py deleted file mode 100644 index e7f2a04b8..000000000 --- a/owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_session_entity_types_create_session_entity_type_sync.py +++ /dev/null @@ -1,52 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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. -# -# Generated code. DO NOT EDIT! -# -# Snippet for CreateSessionEntityType -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-dialogflow - - -# [START dialogflow_v2beta1_generated_SessionEntityTypes_CreateSessionEntityType_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import dialogflow_v2beta1 - - -def sample_create_session_entity_type(): - # Create a client - client = dialogflow_v2beta1.SessionEntityTypesClient() - - # Initialize request argument(s) - request = dialogflow_v2beta1.CreateSessionEntityTypeRequest( - parent="parent_value", - ) - - # Make the request - response = client.create_session_entity_type(request=request) - - # Handle the response - print(response) - -# [END dialogflow_v2beta1_generated_SessionEntityTypes_CreateSessionEntityType_sync] diff --git a/owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_session_entity_types_delete_session_entity_type_async.py b/owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_session_entity_types_delete_session_entity_type_async.py deleted file mode 100644 index 1af32cba4..000000000 --- a/owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_session_entity_types_delete_session_entity_type_async.py +++ /dev/null @@ -1,50 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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. -# -# Generated code. DO NOT EDIT! -# -# Snippet for DeleteSessionEntityType -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-dialogflow - - -# [START dialogflow_v2beta1_generated_SessionEntityTypes_DeleteSessionEntityType_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import dialogflow_v2beta1 - - -async def sample_delete_session_entity_type(): - # Create a client - client = dialogflow_v2beta1.SessionEntityTypesAsyncClient() - - # Initialize request argument(s) - request = dialogflow_v2beta1.DeleteSessionEntityTypeRequest( - name="name_value", - ) - - # Make the request - await client.delete_session_entity_type(request=request) - - -# [END dialogflow_v2beta1_generated_SessionEntityTypes_DeleteSessionEntityType_async] diff --git a/owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_session_entity_types_delete_session_entity_type_sync.py b/owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_session_entity_types_delete_session_entity_type_sync.py deleted file mode 100644 index 5c1fc7bf2..000000000 --- a/owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_session_entity_types_delete_session_entity_type_sync.py +++ /dev/null @@ -1,50 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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. -# -# Generated code. DO NOT EDIT! -# -# Snippet for DeleteSessionEntityType -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-dialogflow - - -# [START dialogflow_v2beta1_generated_SessionEntityTypes_DeleteSessionEntityType_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import dialogflow_v2beta1 - - -def sample_delete_session_entity_type(): - # Create a client - client = dialogflow_v2beta1.SessionEntityTypesClient() - - # Initialize request argument(s) - request = dialogflow_v2beta1.DeleteSessionEntityTypeRequest( - name="name_value", - ) - - # Make the request - client.delete_session_entity_type(request=request) - - -# [END dialogflow_v2beta1_generated_SessionEntityTypes_DeleteSessionEntityType_sync] diff --git a/owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_session_entity_types_get_session_entity_type_async.py b/owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_session_entity_types_get_session_entity_type_async.py deleted file mode 100644 index 468f362ae..000000000 --- a/owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_session_entity_types_get_session_entity_type_async.py +++ /dev/null @@ -1,52 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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. -# -# Generated code. DO NOT EDIT! -# -# Snippet for GetSessionEntityType -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-dialogflow - - -# [START dialogflow_v2beta1_generated_SessionEntityTypes_GetSessionEntityType_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import dialogflow_v2beta1 - - -async def sample_get_session_entity_type(): - # Create a client - client = dialogflow_v2beta1.SessionEntityTypesAsyncClient() - - # Initialize request argument(s) - request = dialogflow_v2beta1.GetSessionEntityTypeRequest( - name="name_value", - ) - - # Make the request - response = await client.get_session_entity_type(request=request) - - # Handle the response - print(response) - -# [END dialogflow_v2beta1_generated_SessionEntityTypes_GetSessionEntityType_async] diff --git a/owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_session_entity_types_get_session_entity_type_sync.py b/owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_session_entity_types_get_session_entity_type_sync.py deleted file mode 100644 index 143045866..000000000 --- a/owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_session_entity_types_get_session_entity_type_sync.py +++ /dev/null @@ -1,52 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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. -# -# Generated code. DO NOT EDIT! -# -# Snippet for GetSessionEntityType -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-dialogflow - - -# [START dialogflow_v2beta1_generated_SessionEntityTypes_GetSessionEntityType_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import dialogflow_v2beta1 - - -def sample_get_session_entity_type(): - # Create a client - client = dialogflow_v2beta1.SessionEntityTypesClient() - - # Initialize request argument(s) - request = dialogflow_v2beta1.GetSessionEntityTypeRequest( - name="name_value", - ) - - # Make the request - response = client.get_session_entity_type(request=request) - - # Handle the response - print(response) - -# [END dialogflow_v2beta1_generated_SessionEntityTypes_GetSessionEntityType_sync] diff --git a/owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_session_entity_types_list_session_entity_types_async.py b/owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_session_entity_types_list_session_entity_types_async.py deleted file mode 100644 index 2b6f867f2..000000000 --- a/owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_session_entity_types_list_session_entity_types_async.py +++ /dev/null @@ -1,53 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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. -# -# Generated code. DO NOT EDIT! -# -# Snippet for ListSessionEntityTypes -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-dialogflow - - -# [START dialogflow_v2beta1_generated_SessionEntityTypes_ListSessionEntityTypes_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import dialogflow_v2beta1 - - -async def sample_list_session_entity_types(): - # Create a client - client = dialogflow_v2beta1.SessionEntityTypesAsyncClient() - - # Initialize request argument(s) - request = dialogflow_v2beta1.ListSessionEntityTypesRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_session_entity_types(request=request) - - # Handle the response - async for response in page_result: - print(response) - -# [END dialogflow_v2beta1_generated_SessionEntityTypes_ListSessionEntityTypes_async] diff --git a/owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_session_entity_types_list_session_entity_types_sync.py b/owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_session_entity_types_list_session_entity_types_sync.py deleted file mode 100644 index 0f51f0451..000000000 --- a/owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_session_entity_types_list_session_entity_types_sync.py +++ /dev/null @@ -1,53 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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. -# -# Generated code. DO NOT EDIT! -# -# Snippet for ListSessionEntityTypes -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-dialogflow - - -# [START dialogflow_v2beta1_generated_SessionEntityTypes_ListSessionEntityTypes_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import dialogflow_v2beta1 - - -def sample_list_session_entity_types(): - # Create a client - client = dialogflow_v2beta1.SessionEntityTypesClient() - - # Initialize request argument(s) - request = dialogflow_v2beta1.ListSessionEntityTypesRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_session_entity_types(request=request) - - # Handle the response - for response in page_result: - print(response) - -# [END dialogflow_v2beta1_generated_SessionEntityTypes_ListSessionEntityTypes_sync] diff --git a/owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_session_entity_types_update_session_entity_type_async.py b/owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_session_entity_types_update_session_entity_type_async.py deleted file mode 100644 index d5c1f84cf..000000000 --- a/owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_session_entity_types_update_session_entity_type_async.py +++ /dev/null @@ -1,51 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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. -# -# Generated code. DO NOT EDIT! -# -# Snippet for UpdateSessionEntityType -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-dialogflow - - -# [START dialogflow_v2beta1_generated_SessionEntityTypes_UpdateSessionEntityType_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import dialogflow_v2beta1 - - -async def sample_update_session_entity_type(): - # Create a client - client = dialogflow_v2beta1.SessionEntityTypesAsyncClient() - - # Initialize request argument(s) - request = dialogflow_v2beta1.UpdateSessionEntityTypeRequest( - ) - - # Make the request - response = await client.update_session_entity_type(request=request) - - # Handle the response - print(response) - -# [END dialogflow_v2beta1_generated_SessionEntityTypes_UpdateSessionEntityType_async] diff --git a/owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_session_entity_types_update_session_entity_type_sync.py b/owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_session_entity_types_update_session_entity_type_sync.py deleted file mode 100644 index 2b1ae1fb5..000000000 --- a/owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_session_entity_types_update_session_entity_type_sync.py +++ /dev/null @@ -1,51 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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. -# -# Generated code. DO NOT EDIT! -# -# Snippet for UpdateSessionEntityType -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-dialogflow - - -# [START dialogflow_v2beta1_generated_SessionEntityTypes_UpdateSessionEntityType_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import dialogflow_v2beta1 - - -def sample_update_session_entity_type(): - # Create a client - client = dialogflow_v2beta1.SessionEntityTypesClient() - - # Initialize request argument(s) - request = dialogflow_v2beta1.UpdateSessionEntityTypeRequest( - ) - - # Make the request - response = client.update_session_entity_type(request=request) - - # Handle the response - print(response) - -# [END dialogflow_v2beta1_generated_SessionEntityTypes_UpdateSessionEntityType_sync] diff --git a/owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_sessions_detect_intent_async.py b/owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_sessions_detect_intent_async.py deleted file mode 100644 index 0dfc88e89..000000000 --- a/owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_sessions_detect_intent_async.py +++ /dev/null @@ -1,52 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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. -# -# Generated code. DO NOT EDIT! -# -# Snippet for DetectIntent -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-dialogflow - - -# [START dialogflow_v2beta1_generated_Sessions_DetectIntent_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import dialogflow_v2beta1 - - -async def sample_detect_intent(): - # Create a client - client = dialogflow_v2beta1.SessionsAsyncClient() - - # Initialize request argument(s) - request = dialogflow_v2beta1.DetectIntentRequest( - session="session_value", - ) - - # Make the request - response = await client.detect_intent(request=request) - - # Handle the response - print(response) - -# [END dialogflow_v2beta1_generated_Sessions_DetectIntent_async] diff --git a/owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_sessions_detect_intent_sync.py b/owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_sessions_detect_intent_sync.py deleted file mode 100644 index a469167c4..000000000 --- a/owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_sessions_detect_intent_sync.py +++ /dev/null @@ -1,52 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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. -# -# Generated code. DO NOT EDIT! -# -# Snippet for DetectIntent -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-dialogflow - - -# [START dialogflow_v2beta1_generated_Sessions_DetectIntent_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import dialogflow_v2beta1 - - -def sample_detect_intent(): - # Create a client - client = dialogflow_v2beta1.SessionsClient() - - # Initialize request argument(s) - request = dialogflow_v2beta1.DetectIntentRequest( - session="session_value", - ) - - # Make the request - response = client.detect_intent(request=request) - - # Handle the response - print(response) - -# [END dialogflow_v2beta1_generated_Sessions_DetectIntent_sync] diff --git a/owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_sessions_streaming_detect_intent_async.py b/owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_sessions_streaming_detect_intent_async.py deleted file mode 100644 index 51807779b..000000000 --- a/owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_sessions_streaming_detect_intent_async.py +++ /dev/null @@ -1,63 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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. -# -# Generated code. DO NOT EDIT! -# -# Snippet for StreamingDetectIntent -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-dialogflow - - -# [START dialogflow_v2beta1_generated_Sessions_StreamingDetectIntent_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import dialogflow_v2beta1 - - -async def sample_streaming_detect_intent(): - # Create a client - client = dialogflow_v2beta1.SessionsAsyncClient() - - # Initialize request argument(s) - request = dialogflow_v2beta1.StreamingDetectIntentRequest( - session="session_value", - ) - - # This method expects an iterator which contains - # 'dialogflow_v2beta1.StreamingDetectIntentRequest' objects - # Here we create a generator that yields a single `request` for - # demonstrative purposes. - requests = [request] - - def request_generator(): - for request in requests: - yield request - - # Make the request - stream = await client.streaming_detect_intent(requests=request_generator()) - - # Handle the response - async for response in stream: - print(response) - -# [END dialogflow_v2beta1_generated_Sessions_StreamingDetectIntent_async] diff --git a/owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_sessions_streaming_detect_intent_sync.py b/owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_sessions_streaming_detect_intent_sync.py deleted file mode 100644 index 77a71a9f8..000000000 --- a/owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_sessions_streaming_detect_intent_sync.py +++ /dev/null @@ -1,63 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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. -# -# Generated code. DO NOT EDIT! -# -# Snippet for StreamingDetectIntent -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-dialogflow - - -# [START dialogflow_v2beta1_generated_Sessions_StreamingDetectIntent_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import dialogflow_v2beta1 - - -def sample_streaming_detect_intent(): - # Create a client - client = dialogflow_v2beta1.SessionsClient() - - # Initialize request argument(s) - request = dialogflow_v2beta1.StreamingDetectIntentRequest( - session="session_value", - ) - - # This method expects an iterator which contains - # 'dialogflow_v2beta1.StreamingDetectIntentRequest' objects - # Here we create a generator that yields a single `request` for - # demonstrative purposes. - requests = [request] - - def request_generator(): - for request in requests: - yield request - - # Make the request - stream = client.streaming_detect_intent(requests=request_generator()) - - # Handle the response - for response in stream: - print(response) - -# [END dialogflow_v2beta1_generated_Sessions_StreamingDetectIntent_sync] diff --git a/owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_versions_create_version_async.py b/owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_versions_create_version_async.py deleted file mode 100644 index e78c7fbe4..000000000 --- a/owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_versions_create_version_async.py +++ /dev/null @@ -1,52 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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. -# -# Generated code. DO NOT EDIT! -# -# Snippet for CreateVersion -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-dialogflow - - -# [START dialogflow_v2beta1_generated_Versions_CreateVersion_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import dialogflow_v2beta1 - - -async def sample_create_version(): - # Create a client - client = dialogflow_v2beta1.VersionsAsyncClient() - - # Initialize request argument(s) - request = dialogflow_v2beta1.CreateVersionRequest( - parent="parent_value", - ) - - # Make the request - response = await client.create_version(request=request) - - # Handle the response - print(response) - -# [END dialogflow_v2beta1_generated_Versions_CreateVersion_async] diff --git a/owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_versions_create_version_sync.py b/owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_versions_create_version_sync.py deleted file mode 100644 index 7c0799c8d..000000000 --- a/owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_versions_create_version_sync.py +++ /dev/null @@ -1,52 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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. -# -# Generated code. DO NOT EDIT! -# -# Snippet for CreateVersion -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-dialogflow - - -# [START dialogflow_v2beta1_generated_Versions_CreateVersion_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import dialogflow_v2beta1 - - -def sample_create_version(): - # Create a client - client = dialogflow_v2beta1.VersionsClient() - - # Initialize request argument(s) - request = dialogflow_v2beta1.CreateVersionRequest( - parent="parent_value", - ) - - # Make the request - response = client.create_version(request=request) - - # Handle the response - print(response) - -# [END dialogflow_v2beta1_generated_Versions_CreateVersion_sync] diff --git a/owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_versions_delete_version_async.py b/owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_versions_delete_version_async.py deleted file mode 100644 index 77f50607a..000000000 --- a/owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_versions_delete_version_async.py +++ /dev/null @@ -1,50 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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. -# -# Generated code. DO NOT EDIT! -# -# Snippet for DeleteVersion -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-dialogflow - - -# [START dialogflow_v2beta1_generated_Versions_DeleteVersion_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import dialogflow_v2beta1 - - -async def sample_delete_version(): - # Create a client - client = dialogflow_v2beta1.VersionsAsyncClient() - - # Initialize request argument(s) - request = dialogflow_v2beta1.DeleteVersionRequest( - name="name_value", - ) - - # Make the request - await client.delete_version(request=request) - - -# [END dialogflow_v2beta1_generated_Versions_DeleteVersion_async] diff --git a/owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_versions_delete_version_sync.py b/owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_versions_delete_version_sync.py deleted file mode 100644 index 874df61f5..000000000 --- a/owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_versions_delete_version_sync.py +++ /dev/null @@ -1,50 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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. -# -# Generated code. DO NOT EDIT! -# -# Snippet for DeleteVersion -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-dialogflow - - -# [START dialogflow_v2beta1_generated_Versions_DeleteVersion_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import dialogflow_v2beta1 - - -def sample_delete_version(): - # Create a client - client = dialogflow_v2beta1.VersionsClient() - - # Initialize request argument(s) - request = dialogflow_v2beta1.DeleteVersionRequest( - name="name_value", - ) - - # Make the request - client.delete_version(request=request) - - -# [END dialogflow_v2beta1_generated_Versions_DeleteVersion_sync] diff --git a/owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_versions_get_version_async.py b/owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_versions_get_version_async.py deleted file mode 100644 index e94eb2850..000000000 --- a/owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_versions_get_version_async.py +++ /dev/null @@ -1,52 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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. -# -# Generated code. DO NOT EDIT! -# -# Snippet for GetVersion -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-dialogflow - - -# [START dialogflow_v2beta1_generated_Versions_GetVersion_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import dialogflow_v2beta1 - - -async def sample_get_version(): - # Create a client - client = dialogflow_v2beta1.VersionsAsyncClient() - - # Initialize request argument(s) - request = dialogflow_v2beta1.GetVersionRequest( - name="name_value", - ) - - # Make the request - response = await client.get_version(request=request) - - # Handle the response - print(response) - -# [END dialogflow_v2beta1_generated_Versions_GetVersion_async] diff --git a/owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_versions_get_version_sync.py b/owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_versions_get_version_sync.py deleted file mode 100644 index aa77130f3..000000000 --- a/owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_versions_get_version_sync.py +++ /dev/null @@ -1,52 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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. -# -# Generated code. DO NOT EDIT! -# -# Snippet for GetVersion -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-dialogflow - - -# [START dialogflow_v2beta1_generated_Versions_GetVersion_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import dialogflow_v2beta1 - - -def sample_get_version(): - # Create a client - client = dialogflow_v2beta1.VersionsClient() - - # Initialize request argument(s) - request = dialogflow_v2beta1.GetVersionRequest( - name="name_value", - ) - - # Make the request - response = client.get_version(request=request) - - # Handle the response - print(response) - -# [END dialogflow_v2beta1_generated_Versions_GetVersion_sync] diff --git a/owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_versions_list_versions_async.py b/owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_versions_list_versions_async.py deleted file mode 100644 index ac03abdef..000000000 --- a/owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_versions_list_versions_async.py +++ /dev/null @@ -1,53 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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. -# -# Generated code. DO NOT EDIT! -# -# Snippet for ListVersions -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-dialogflow - - -# [START dialogflow_v2beta1_generated_Versions_ListVersions_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import dialogflow_v2beta1 - - -async def sample_list_versions(): - # Create a client - client = dialogflow_v2beta1.VersionsAsyncClient() - - # Initialize request argument(s) - request = dialogflow_v2beta1.ListVersionsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_versions(request=request) - - # Handle the response - async for response in page_result: - print(response) - -# [END dialogflow_v2beta1_generated_Versions_ListVersions_async] diff --git a/owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_versions_list_versions_sync.py b/owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_versions_list_versions_sync.py deleted file mode 100644 index 875e5591a..000000000 --- a/owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_versions_list_versions_sync.py +++ /dev/null @@ -1,53 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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. -# -# Generated code. DO NOT EDIT! -# -# Snippet for ListVersions -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-dialogflow - - -# [START dialogflow_v2beta1_generated_Versions_ListVersions_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import dialogflow_v2beta1 - - -def sample_list_versions(): - # Create a client - client = dialogflow_v2beta1.VersionsClient() - - # Initialize request argument(s) - request = dialogflow_v2beta1.ListVersionsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_versions(request=request) - - # Handle the response - for response in page_result: - print(response) - -# [END dialogflow_v2beta1_generated_Versions_ListVersions_sync] diff --git a/owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_versions_update_version_async.py b/owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_versions_update_version_async.py deleted file mode 100644 index 85514b674..000000000 --- a/owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_versions_update_version_async.py +++ /dev/null @@ -1,51 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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. -# -# Generated code. DO NOT EDIT! -# -# Snippet for UpdateVersion -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-dialogflow - - -# [START dialogflow_v2beta1_generated_Versions_UpdateVersion_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import dialogflow_v2beta1 - - -async def sample_update_version(): - # Create a client - client = dialogflow_v2beta1.VersionsAsyncClient() - - # Initialize request argument(s) - request = dialogflow_v2beta1.UpdateVersionRequest( - ) - - # Make the request - response = await client.update_version(request=request) - - # Handle the response - print(response) - -# [END dialogflow_v2beta1_generated_Versions_UpdateVersion_async] diff --git a/owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_versions_update_version_sync.py b/owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_versions_update_version_sync.py deleted file mode 100644 index 2ca9d8bf8..000000000 --- a/owl-bot-staging/v2beta1/samples/generated_samples/dialogflow_v2beta1_generated_versions_update_version_sync.py +++ /dev/null @@ -1,51 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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. -# -# Generated code. DO NOT EDIT! -# -# Snippet for UpdateVersion -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-dialogflow - - -# [START dialogflow_v2beta1_generated_Versions_UpdateVersion_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import dialogflow_v2beta1 - - -def sample_update_version(): - # Create a client - client = dialogflow_v2beta1.VersionsClient() - - # Initialize request argument(s) - request = dialogflow_v2beta1.UpdateVersionRequest( - ) - - # Make the request - response = client.update_version(request=request) - - # Handle the response - print(response) - -# [END dialogflow_v2beta1_generated_Versions_UpdateVersion_sync] diff --git a/owl-bot-staging/v2beta1/samples/generated_samples/snippet_metadata_google.cloud.dialogflow.v2beta1.json b/owl-bot-staging/v2beta1/samples/generated_samples/snippet_metadata_google.cloud.dialogflow.v2beta1.json deleted file mode 100644 index 9860e03a7..000000000 --- a/owl-bot-staging/v2beta1/samples/generated_samples/snippet_metadata_google.cloud.dialogflow.v2beta1.json +++ /dev/null @@ -1,15031 +0,0 @@ -{ - "clientLibrary": { - "apis": [ - { - "id": "google.cloud.dialogflow.v2beta1", - "version": "v2beta1" - } - ], - "language": "PYTHON", - "name": "google-cloud-dialogflow", - "version": "0.1.0" - }, - "snippets": [ - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.dialogflow_v2beta1.AgentsAsyncClient", - "shortName": "AgentsAsyncClient" - }, - "fullName": "google.cloud.dialogflow_v2beta1.AgentsAsyncClient.delete_agent", - "method": { - "fullName": "google.cloud.dialogflow.v2beta1.Agents.DeleteAgent", - "service": { - "fullName": "google.cloud.dialogflow.v2beta1.Agents", - "shortName": "Agents" - }, - "shortName": "DeleteAgent" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.dialogflow_v2beta1.types.DeleteAgentRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "shortName": "delete_agent" - }, - "description": "Sample for DeleteAgent", - "file": "dialogflow_v2beta1_generated_agents_delete_agent_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "dialogflow_v2beta1_generated_Agents_DeleteAgent_async", - "segments": [ - { - "end": 49, - "start": 27, - "type": "FULL" - }, - { - "end": 49, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 50, - "type": "RESPONSE_HANDLING" - } - ], - "title": "dialogflow_v2beta1_generated_agents_delete_agent_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.dialogflow_v2beta1.AgentsClient", - "shortName": "AgentsClient" - }, - "fullName": "google.cloud.dialogflow_v2beta1.AgentsClient.delete_agent", - "method": { - "fullName": "google.cloud.dialogflow.v2beta1.Agents.DeleteAgent", - "service": { - "fullName": "google.cloud.dialogflow.v2beta1.Agents", - "shortName": "Agents" - }, - "shortName": "DeleteAgent" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.dialogflow_v2beta1.types.DeleteAgentRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "shortName": "delete_agent" - }, - "description": "Sample for DeleteAgent", - "file": "dialogflow_v2beta1_generated_agents_delete_agent_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "dialogflow_v2beta1_generated_Agents_DeleteAgent_sync", - "segments": [ - { - "end": 49, - "start": 27, - "type": "FULL" - }, - { - "end": 49, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 50, - "type": "RESPONSE_HANDLING" - } - ], - "title": "dialogflow_v2beta1_generated_agents_delete_agent_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.dialogflow_v2beta1.AgentsAsyncClient", - "shortName": "AgentsAsyncClient" - }, - "fullName": "google.cloud.dialogflow_v2beta1.AgentsAsyncClient.export_agent", - "method": { - "fullName": "google.cloud.dialogflow.v2beta1.Agents.ExportAgent", - "service": { - "fullName": "google.cloud.dialogflow.v2beta1.Agents", - "shortName": "Agents" - }, - "shortName": "ExportAgent" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.dialogflow_v2beta1.types.ExportAgentRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.api_core.operation_async.AsyncOperation", - "shortName": "export_agent" - }, - "description": "Sample for ExportAgent", - "file": "dialogflow_v2beta1_generated_agents_export_agent_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "dialogflow_v2beta1_generated_Agents_ExportAgent_async", - "segments": [ - { - "end": 55, - "start": 27, - "type": "FULL" - }, - { - "end": 55, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 52, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 56, - "start": 53, - "type": "RESPONSE_HANDLING" - } - ], - "title": "dialogflow_v2beta1_generated_agents_export_agent_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.dialogflow_v2beta1.AgentsClient", - "shortName": "AgentsClient" - }, - "fullName": "google.cloud.dialogflow_v2beta1.AgentsClient.export_agent", - "method": { - "fullName": "google.cloud.dialogflow.v2beta1.Agents.ExportAgent", - "service": { - "fullName": "google.cloud.dialogflow.v2beta1.Agents", - "shortName": "Agents" - }, - "shortName": "ExportAgent" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.dialogflow_v2beta1.types.ExportAgentRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.api_core.operation.Operation", - "shortName": "export_agent" - }, - "description": "Sample for ExportAgent", - "file": "dialogflow_v2beta1_generated_agents_export_agent_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "dialogflow_v2beta1_generated_Agents_ExportAgent_sync", - "segments": [ - { - "end": 55, - "start": 27, - "type": "FULL" - }, - { - "end": 55, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 52, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 56, - "start": 53, - "type": "RESPONSE_HANDLING" - } - ], - "title": "dialogflow_v2beta1_generated_agents_export_agent_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.dialogflow_v2beta1.AgentsAsyncClient", - "shortName": "AgentsAsyncClient" - }, - "fullName": "google.cloud.dialogflow_v2beta1.AgentsAsyncClient.get_agent", - "method": { - "fullName": "google.cloud.dialogflow.v2beta1.Agents.GetAgent", - "service": { - "fullName": "google.cloud.dialogflow.v2beta1.Agents", - "shortName": "Agents" - }, - "shortName": "GetAgent" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.dialogflow_v2beta1.types.GetAgentRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.dialogflow_v2beta1.types.Agent", - "shortName": "get_agent" - }, - "description": "Sample for GetAgent", - "file": "dialogflow_v2beta1_generated_agents_get_agent_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "dialogflow_v2beta1_generated_Agents_GetAgent_async", - "segments": [ - { - "end": 51, - "start": 27, - "type": "FULL" - }, - { - "end": 51, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 48, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 52, - "start": 49, - "type": "RESPONSE_HANDLING" - } - ], - "title": "dialogflow_v2beta1_generated_agents_get_agent_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.dialogflow_v2beta1.AgentsClient", - "shortName": "AgentsClient" - }, - "fullName": "google.cloud.dialogflow_v2beta1.AgentsClient.get_agent", - "method": { - "fullName": "google.cloud.dialogflow.v2beta1.Agents.GetAgent", - "service": { - "fullName": "google.cloud.dialogflow.v2beta1.Agents", - "shortName": "Agents" - }, - "shortName": "GetAgent" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.dialogflow_v2beta1.types.GetAgentRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.dialogflow_v2beta1.types.Agent", - "shortName": "get_agent" - }, - "description": "Sample for GetAgent", - "file": "dialogflow_v2beta1_generated_agents_get_agent_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "dialogflow_v2beta1_generated_Agents_GetAgent_sync", - "segments": [ - { - "end": 51, - "start": 27, - "type": "FULL" - }, - { - "end": 51, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 48, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 52, - "start": 49, - "type": "RESPONSE_HANDLING" - } - ], - "title": "dialogflow_v2beta1_generated_agents_get_agent_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.dialogflow_v2beta1.AgentsAsyncClient", - "shortName": "AgentsAsyncClient" - }, - "fullName": "google.cloud.dialogflow_v2beta1.AgentsAsyncClient.get_validation_result", - "method": { - "fullName": "google.cloud.dialogflow.v2beta1.Agents.GetValidationResult", - "service": { - "fullName": "google.cloud.dialogflow.v2beta1.Agents", - "shortName": "Agents" - }, - "shortName": "GetValidationResult" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.dialogflow_v2beta1.types.GetValidationResultRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.dialogflow_v2beta1.types.ValidationResult", - "shortName": "get_validation_result" - }, - "description": "Sample for GetValidationResult", - "file": "dialogflow_v2beta1_generated_agents_get_validation_result_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "dialogflow_v2beta1_generated_Agents_GetValidationResult_async", - "segments": [ - { - "end": 51, - "start": 27, - "type": "FULL" - }, - { - "end": 51, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 48, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 52, - "start": 49, - "type": "RESPONSE_HANDLING" - } - ], - "title": "dialogflow_v2beta1_generated_agents_get_validation_result_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.dialogflow_v2beta1.AgentsClient", - "shortName": "AgentsClient" - }, - "fullName": "google.cloud.dialogflow_v2beta1.AgentsClient.get_validation_result", - "method": { - "fullName": "google.cloud.dialogflow.v2beta1.Agents.GetValidationResult", - "service": { - "fullName": "google.cloud.dialogflow.v2beta1.Agents", - "shortName": "Agents" - }, - "shortName": "GetValidationResult" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.dialogflow_v2beta1.types.GetValidationResultRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.dialogflow_v2beta1.types.ValidationResult", - "shortName": "get_validation_result" - }, - "description": "Sample for GetValidationResult", - "file": "dialogflow_v2beta1_generated_agents_get_validation_result_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "dialogflow_v2beta1_generated_Agents_GetValidationResult_sync", - "segments": [ - { - "end": 51, - "start": 27, - "type": "FULL" - }, - { - "end": 51, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 48, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 52, - "start": 49, - "type": "RESPONSE_HANDLING" - } - ], - "title": "dialogflow_v2beta1_generated_agents_get_validation_result_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.dialogflow_v2beta1.AgentsAsyncClient", - "shortName": "AgentsAsyncClient" - }, - "fullName": "google.cloud.dialogflow_v2beta1.AgentsAsyncClient.import_agent", - "method": { - "fullName": "google.cloud.dialogflow.v2beta1.Agents.ImportAgent", - "service": { - "fullName": "google.cloud.dialogflow.v2beta1.Agents", - "shortName": "Agents" - }, - "shortName": "ImportAgent" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.dialogflow_v2beta1.types.ImportAgentRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.api_core.operation_async.AsyncOperation", - "shortName": "import_agent" - }, - "description": "Sample for ImportAgent", - "file": "dialogflow_v2beta1_generated_agents_import_agent_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "dialogflow_v2beta1_generated_Agents_ImportAgent_async", - "segments": [ - { - "end": 56, - "start": 27, - "type": "FULL" - }, - { - "end": 56, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 46, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 53, - "start": 47, - "type": "REQUEST_EXECUTION" - }, - { - "end": 57, - "start": 54, - "type": "RESPONSE_HANDLING" - } - ], - "title": "dialogflow_v2beta1_generated_agents_import_agent_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.dialogflow_v2beta1.AgentsClient", - "shortName": "AgentsClient" - }, - "fullName": "google.cloud.dialogflow_v2beta1.AgentsClient.import_agent", - "method": { - "fullName": "google.cloud.dialogflow.v2beta1.Agents.ImportAgent", - "service": { - "fullName": "google.cloud.dialogflow.v2beta1.Agents", - "shortName": "Agents" - }, - "shortName": "ImportAgent" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.dialogflow_v2beta1.types.ImportAgentRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.api_core.operation.Operation", - "shortName": "import_agent" - }, - "description": "Sample for ImportAgent", - "file": "dialogflow_v2beta1_generated_agents_import_agent_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "dialogflow_v2beta1_generated_Agents_ImportAgent_sync", - "segments": [ - { - "end": 56, - "start": 27, - "type": "FULL" - }, - { - "end": 56, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 46, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 53, - "start": 47, - "type": "REQUEST_EXECUTION" - }, - { - "end": 57, - "start": 54, - "type": "RESPONSE_HANDLING" - } - ], - "title": "dialogflow_v2beta1_generated_agents_import_agent_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.dialogflow_v2beta1.AgentsAsyncClient", - "shortName": "AgentsAsyncClient" - }, - "fullName": "google.cloud.dialogflow_v2beta1.AgentsAsyncClient.restore_agent", - "method": { - "fullName": "google.cloud.dialogflow.v2beta1.Agents.RestoreAgent", - "service": { - "fullName": "google.cloud.dialogflow.v2beta1.Agents", - "shortName": "Agents" - }, - "shortName": "RestoreAgent" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.dialogflow_v2beta1.types.RestoreAgentRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.api_core.operation_async.AsyncOperation", - "shortName": "restore_agent" - }, - "description": "Sample for RestoreAgent", - "file": "dialogflow_v2beta1_generated_agents_restore_agent_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "dialogflow_v2beta1_generated_Agents_RestoreAgent_async", - "segments": [ - { - "end": 56, - "start": 27, - "type": "FULL" - }, - { - "end": 56, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 46, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 53, - "start": 47, - "type": "REQUEST_EXECUTION" - }, - { - "end": 57, - "start": 54, - "type": "RESPONSE_HANDLING" - } - ], - "title": "dialogflow_v2beta1_generated_agents_restore_agent_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.dialogflow_v2beta1.AgentsClient", - "shortName": "AgentsClient" - }, - "fullName": "google.cloud.dialogflow_v2beta1.AgentsClient.restore_agent", - "method": { - "fullName": "google.cloud.dialogflow.v2beta1.Agents.RestoreAgent", - "service": { - "fullName": "google.cloud.dialogflow.v2beta1.Agents", - "shortName": "Agents" - }, - "shortName": "RestoreAgent" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.dialogflow_v2beta1.types.RestoreAgentRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.api_core.operation.Operation", - "shortName": "restore_agent" - }, - "description": "Sample for RestoreAgent", - "file": "dialogflow_v2beta1_generated_agents_restore_agent_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "dialogflow_v2beta1_generated_Agents_RestoreAgent_sync", - "segments": [ - { - "end": 56, - "start": 27, - "type": "FULL" - }, - { - "end": 56, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 46, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 53, - "start": 47, - "type": "REQUEST_EXECUTION" - }, - { - "end": 57, - "start": 54, - "type": "RESPONSE_HANDLING" - } - ], - "title": "dialogflow_v2beta1_generated_agents_restore_agent_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.dialogflow_v2beta1.AgentsAsyncClient", - "shortName": "AgentsAsyncClient" - }, - "fullName": "google.cloud.dialogflow_v2beta1.AgentsAsyncClient.search_agents", - "method": { - "fullName": "google.cloud.dialogflow.v2beta1.Agents.SearchAgents", - "service": { - "fullName": "google.cloud.dialogflow.v2beta1.Agents", - "shortName": "Agents" - }, - "shortName": "SearchAgents" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.dialogflow_v2beta1.types.SearchAgentsRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.dialogflow_v2beta1.services.agents.pagers.SearchAgentsAsyncPager", - "shortName": "search_agents" - }, - "description": "Sample for SearchAgents", - "file": "dialogflow_v2beta1_generated_agents_search_agents_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "dialogflow_v2beta1_generated_Agents_SearchAgents_async", - "segments": [ - { - "end": 52, - "start": 27, - "type": "FULL" - }, - { - "end": 52, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 48, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 53, - "start": 49, - "type": "RESPONSE_HANDLING" - } - ], - "title": "dialogflow_v2beta1_generated_agents_search_agents_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.dialogflow_v2beta1.AgentsClient", - "shortName": "AgentsClient" - }, - "fullName": "google.cloud.dialogflow_v2beta1.AgentsClient.search_agents", - "method": { - "fullName": "google.cloud.dialogflow.v2beta1.Agents.SearchAgents", - "service": { - "fullName": "google.cloud.dialogflow.v2beta1.Agents", - "shortName": "Agents" - }, - "shortName": "SearchAgents" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.dialogflow_v2beta1.types.SearchAgentsRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.dialogflow_v2beta1.services.agents.pagers.SearchAgentsPager", - "shortName": "search_agents" - }, - "description": "Sample for SearchAgents", - "file": "dialogflow_v2beta1_generated_agents_search_agents_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "dialogflow_v2beta1_generated_Agents_SearchAgents_sync", - "segments": [ - { - "end": 52, - "start": 27, - "type": "FULL" - }, - { - "end": 52, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 48, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 53, - "start": 49, - "type": "RESPONSE_HANDLING" - } - ], - "title": "dialogflow_v2beta1_generated_agents_search_agents_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.dialogflow_v2beta1.AgentsAsyncClient", - "shortName": "AgentsAsyncClient" - }, - "fullName": "google.cloud.dialogflow_v2beta1.AgentsAsyncClient.set_agent", - "method": { - "fullName": "google.cloud.dialogflow.v2beta1.Agents.SetAgent", - "service": { - "fullName": "google.cloud.dialogflow.v2beta1.Agents", - "shortName": "Agents" - }, - "shortName": "SetAgent" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.dialogflow_v2beta1.types.SetAgentRequest" - }, - { - "name": "agent", - "type": "google.cloud.dialogflow_v2beta1.types.Agent" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.dialogflow_v2beta1.types.Agent", - "shortName": "set_agent" - }, - "description": "Sample for SetAgent", - "file": "dialogflow_v2beta1_generated_agents_set_agent_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "dialogflow_v2beta1_generated_Agents_SetAgent_async", - "segments": [ - { - "end": 54, - "start": 27, - "type": "FULL" - }, - { - "end": 54, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 48, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 51, - "start": 49, - "type": "REQUEST_EXECUTION" - }, - { - "end": 55, - "start": 52, - "type": "RESPONSE_HANDLING" - } - ], - "title": "dialogflow_v2beta1_generated_agents_set_agent_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.dialogflow_v2beta1.AgentsClient", - "shortName": "AgentsClient" - }, - "fullName": "google.cloud.dialogflow_v2beta1.AgentsClient.set_agent", - "method": { - "fullName": "google.cloud.dialogflow.v2beta1.Agents.SetAgent", - "service": { - "fullName": "google.cloud.dialogflow.v2beta1.Agents", - "shortName": "Agents" - }, - "shortName": "SetAgent" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.dialogflow_v2beta1.types.SetAgentRequest" - }, - { - "name": "agent", - "type": "google.cloud.dialogflow_v2beta1.types.Agent" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.dialogflow_v2beta1.types.Agent", - "shortName": "set_agent" - }, - "description": "Sample for SetAgent", - "file": "dialogflow_v2beta1_generated_agents_set_agent_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "dialogflow_v2beta1_generated_Agents_SetAgent_sync", - "segments": [ - { - "end": 54, - "start": 27, - "type": "FULL" - }, - { - "end": 54, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 48, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 51, - "start": 49, - "type": "REQUEST_EXECUTION" - }, - { - "end": 55, - "start": 52, - "type": "RESPONSE_HANDLING" - } - ], - "title": "dialogflow_v2beta1_generated_agents_set_agent_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.dialogflow_v2beta1.AgentsAsyncClient", - "shortName": "AgentsAsyncClient" - }, - "fullName": "google.cloud.dialogflow_v2beta1.AgentsAsyncClient.train_agent", - "method": { - "fullName": "google.cloud.dialogflow.v2beta1.Agents.TrainAgent", - "service": { - "fullName": "google.cloud.dialogflow.v2beta1.Agents", - "shortName": "Agents" - }, - "shortName": "TrainAgent" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.dialogflow_v2beta1.types.TrainAgentRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.api_core.operation_async.AsyncOperation", - "shortName": "train_agent" - }, - "description": "Sample for TrainAgent", - "file": "dialogflow_v2beta1_generated_agents_train_agent_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "dialogflow_v2beta1_generated_Agents_TrainAgent_async", - "segments": [ - { - "end": 55, - "start": 27, - "type": "FULL" - }, - { - "end": 55, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 52, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 56, - "start": 53, - "type": "RESPONSE_HANDLING" - } - ], - "title": "dialogflow_v2beta1_generated_agents_train_agent_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.dialogflow_v2beta1.AgentsClient", - "shortName": "AgentsClient" - }, - "fullName": "google.cloud.dialogflow_v2beta1.AgentsClient.train_agent", - "method": { - "fullName": "google.cloud.dialogflow.v2beta1.Agents.TrainAgent", - "service": { - "fullName": "google.cloud.dialogflow.v2beta1.Agents", - "shortName": "Agents" - }, - "shortName": "TrainAgent" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.dialogflow_v2beta1.types.TrainAgentRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.api_core.operation.Operation", - "shortName": "train_agent" - }, - "description": "Sample for TrainAgent", - "file": "dialogflow_v2beta1_generated_agents_train_agent_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "dialogflow_v2beta1_generated_Agents_TrainAgent_sync", - "segments": [ - { - "end": 55, - "start": 27, - "type": "FULL" - }, - { - "end": 55, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 52, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 56, - "start": 53, - "type": "RESPONSE_HANDLING" - } - ], - "title": "dialogflow_v2beta1_generated_agents_train_agent_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.dialogflow_v2beta1.AnswerRecordsAsyncClient", - "shortName": "AnswerRecordsAsyncClient" - }, - "fullName": "google.cloud.dialogflow_v2beta1.AnswerRecordsAsyncClient.get_answer_record", - "method": { - "fullName": "google.cloud.dialogflow.v2beta1.AnswerRecords.GetAnswerRecord", - "service": { - "fullName": "google.cloud.dialogflow.v2beta1.AnswerRecords", - "shortName": "AnswerRecords" - }, - "shortName": "GetAnswerRecord" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.dialogflow_v2beta1.types.GetAnswerRecordRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.dialogflow_v2beta1.types.AnswerRecord", - "shortName": "get_answer_record" - }, - "description": "Sample for GetAnswerRecord", - "file": "dialogflow_v2beta1_generated_answer_records_get_answer_record_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "dialogflow_v2beta1_generated_AnswerRecords_GetAnswerRecord_async", - "segments": [ - { - "end": 50, - "start": 27, - "type": "FULL" - }, - { - "end": 50, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 44, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 47, - "start": 45, - "type": "REQUEST_EXECUTION" - }, - { - "end": 51, - "start": 48, - "type": "RESPONSE_HANDLING" - } - ], - "title": "dialogflow_v2beta1_generated_answer_records_get_answer_record_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.dialogflow_v2beta1.AnswerRecordsClient", - "shortName": "AnswerRecordsClient" - }, - "fullName": "google.cloud.dialogflow_v2beta1.AnswerRecordsClient.get_answer_record", - "method": { - "fullName": "google.cloud.dialogflow.v2beta1.AnswerRecords.GetAnswerRecord", - "service": { - "fullName": "google.cloud.dialogflow.v2beta1.AnswerRecords", - "shortName": "AnswerRecords" - }, - "shortName": "GetAnswerRecord" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.dialogflow_v2beta1.types.GetAnswerRecordRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.dialogflow_v2beta1.types.AnswerRecord", - "shortName": "get_answer_record" - }, - "description": "Sample for GetAnswerRecord", - "file": "dialogflow_v2beta1_generated_answer_records_get_answer_record_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "dialogflow_v2beta1_generated_AnswerRecords_GetAnswerRecord_sync", - "segments": [ - { - "end": 50, - "start": 27, - "type": "FULL" - }, - { - "end": 50, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 44, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 47, - "start": 45, - "type": "REQUEST_EXECUTION" - }, - { - "end": 51, - "start": 48, - "type": "RESPONSE_HANDLING" - } - ], - "title": "dialogflow_v2beta1_generated_answer_records_get_answer_record_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.dialogflow_v2beta1.AnswerRecordsAsyncClient", - "shortName": "AnswerRecordsAsyncClient" - }, - "fullName": "google.cloud.dialogflow_v2beta1.AnswerRecordsAsyncClient.list_answer_records", - "method": { - "fullName": "google.cloud.dialogflow.v2beta1.AnswerRecords.ListAnswerRecords", - "service": { - "fullName": "google.cloud.dialogflow.v2beta1.AnswerRecords", - "shortName": "AnswerRecords" - }, - "shortName": "ListAnswerRecords" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.dialogflow_v2beta1.types.ListAnswerRecordsRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.dialogflow_v2beta1.services.answer_records.pagers.ListAnswerRecordsAsyncPager", - "shortName": "list_answer_records" - }, - "description": "Sample for ListAnswerRecords", - "file": "dialogflow_v2beta1_generated_answer_records_list_answer_records_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "dialogflow_v2beta1_generated_AnswerRecords_ListAnswerRecords_async", - "segments": [ - { - "end": 51, - "start": 27, - "type": "FULL" - }, - { - "end": 51, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 44, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 47, - "start": 45, - "type": "REQUEST_EXECUTION" - }, - { - "end": 52, - "start": 48, - "type": "RESPONSE_HANDLING" - } - ], - "title": "dialogflow_v2beta1_generated_answer_records_list_answer_records_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.dialogflow_v2beta1.AnswerRecordsClient", - "shortName": "AnswerRecordsClient" - }, - "fullName": "google.cloud.dialogflow_v2beta1.AnswerRecordsClient.list_answer_records", - "method": { - "fullName": "google.cloud.dialogflow.v2beta1.AnswerRecords.ListAnswerRecords", - "service": { - "fullName": "google.cloud.dialogflow.v2beta1.AnswerRecords", - "shortName": "AnswerRecords" - }, - "shortName": "ListAnswerRecords" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.dialogflow_v2beta1.types.ListAnswerRecordsRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.dialogflow_v2beta1.services.answer_records.pagers.ListAnswerRecordsPager", - "shortName": "list_answer_records" - }, - "description": "Sample for ListAnswerRecords", - "file": "dialogflow_v2beta1_generated_answer_records_list_answer_records_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "dialogflow_v2beta1_generated_AnswerRecords_ListAnswerRecords_sync", - "segments": [ - { - "end": 51, - "start": 27, - "type": "FULL" - }, - { - "end": 51, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 44, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 47, - "start": 45, - "type": "REQUEST_EXECUTION" - }, - { - "end": 52, - "start": 48, - "type": "RESPONSE_HANDLING" - } - ], - "title": "dialogflow_v2beta1_generated_answer_records_list_answer_records_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.dialogflow_v2beta1.AnswerRecordsAsyncClient", - "shortName": "AnswerRecordsAsyncClient" - }, - "fullName": "google.cloud.dialogflow_v2beta1.AnswerRecordsAsyncClient.update_answer_record", - "method": { - "fullName": "google.cloud.dialogflow.v2beta1.AnswerRecords.UpdateAnswerRecord", - "service": { - "fullName": "google.cloud.dialogflow.v2beta1.AnswerRecords", - "shortName": "AnswerRecords" - }, - "shortName": "UpdateAnswerRecord" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.dialogflow_v2beta1.types.UpdateAnswerRecordRequest" - }, - { - "name": "answer_record", - "type": "google.cloud.dialogflow_v2beta1.types.AnswerRecord" - }, - { - "name": "update_mask", - "type": "google.protobuf.field_mask_pb2.FieldMask" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.dialogflow_v2beta1.types.AnswerRecord", - "shortName": "update_answer_record" - }, - "description": "Sample for UpdateAnswerRecord", - "file": "dialogflow_v2beta1_generated_answer_records_update_answer_record_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "dialogflow_v2beta1_generated_AnswerRecords_UpdateAnswerRecord_async", - "segments": [ - { - "end": 50, - "start": 27, - "type": "FULL" - }, - { - "end": 50, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 44, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 47, - "start": 45, - "type": "REQUEST_EXECUTION" - }, - { - "end": 51, - "start": 48, - "type": "RESPONSE_HANDLING" - } - ], - "title": "dialogflow_v2beta1_generated_answer_records_update_answer_record_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.dialogflow_v2beta1.AnswerRecordsClient", - "shortName": "AnswerRecordsClient" - }, - "fullName": "google.cloud.dialogflow_v2beta1.AnswerRecordsClient.update_answer_record", - "method": { - "fullName": "google.cloud.dialogflow.v2beta1.AnswerRecords.UpdateAnswerRecord", - "service": { - "fullName": "google.cloud.dialogflow.v2beta1.AnswerRecords", - "shortName": "AnswerRecords" - }, - "shortName": "UpdateAnswerRecord" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.dialogflow_v2beta1.types.UpdateAnswerRecordRequest" - }, - { - "name": "answer_record", - "type": "google.cloud.dialogflow_v2beta1.types.AnswerRecord" - }, - { - "name": "update_mask", - "type": "google.protobuf.field_mask_pb2.FieldMask" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.dialogflow_v2beta1.types.AnswerRecord", - "shortName": "update_answer_record" - }, - "description": "Sample for UpdateAnswerRecord", - "file": "dialogflow_v2beta1_generated_answer_records_update_answer_record_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "dialogflow_v2beta1_generated_AnswerRecords_UpdateAnswerRecord_sync", - "segments": [ - { - "end": 50, - "start": 27, - "type": "FULL" - }, - { - "end": 50, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 44, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 47, - "start": 45, - "type": "REQUEST_EXECUTION" - }, - { - "end": 51, - "start": 48, - "type": "RESPONSE_HANDLING" - } - ], - "title": "dialogflow_v2beta1_generated_answer_records_update_answer_record_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.dialogflow_v2beta1.ContextsAsyncClient", - "shortName": "ContextsAsyncClient" - }, - "fullName": "google.cloud.dialogflow_v2beta1.ContextsAsyncClient.create_context", - "method": { - "fullName": "google.cloud.dialogflow.v2beta1.Contexts.CreateContext", - "service": { - "fullName": "google.cloud.dialogflow.v2beta1.Contexts", - "shortName": "Contexts" - }, - "shortName": "CreateContext" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.dialogflow_v2beta1.types.CreateContextRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "context", - "type": "google.cloud.dialogflow_v2beta1.types.Context" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.dialogflow_v2beta1.types.Context", - "shortName": "create_context" - }, - "description": "Sample for CreateContext", - "file": "dialogflow_v2beta1_generated_contexts_create_context_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "dialogflow_v2beta1_generated_Contexts_CreateContext_async", - "segments": [ - { - "end": 51, - "start": 27, - "type": "FULL" - }, - { - "end": 51, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 48, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 52, - "start": 49, - "type": "RESPONSE_HANDLING" - } - ], - "title": "dialogflow_v2beta1_generated_contexts_create_context_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.dialogflow_v2beta1.ContextsClient", - "shortName": "ContextsClient" - }, - "fullName": "google.cloud.dialogflow_v2beta1.ContextsClient.create_context", - "method": { - "fullName": "google.cloud.dialogflow.v2beta1.Contexts.CreateContext", - "service": { - "fullName": "google.cloud.dialogflow.v2beta1.Contexts", - "shortName": "Contexts" - }, - "shortName": "CreateContext" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.dialogflow_v2beta1.types.CreateContextRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "context", - "type": "google.cloud.dialogflow_v2beta1.types.Context" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.dialogflow_v2beta1.types.Context", - "shortName": "create_context" - }, - "description": "Sample for CreateContext", - "file": "dialogflow_v2beta1_generated_contexts_create_context_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "dialogflow_v2beta1_generated_Contexts_CreateContext_sync", - "segments": [ - { - "end": 51, - "start": 27, - "type": "FULL" - }, - { - "end": 51, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 48, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 52, - "start": 49, - "type": "RESPONSE_HANDLING" - } - ], - "title": "dialogflow_v2beta1_generated_contexts_create_context_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.dialogflow_v2beta1.ContextsAsyncClient", - "shortName": "ContextsAsyncClient" - }, - "fullName": "google.cloud.dialogflow_v2beta1.ContextsAsyncClient.delete_all_contexts", - "method": { - "fullName": "google.cloud.dialogflow.v2beta1.Contexts.DeleteAllContexts", - "service": { - "fullName": "google.cloud.dialogflow.v2beta1.Contexts", - "shortName": "Contexts" - }, - "shortName": "DeleteAllContexts" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.dialogflow_v2beta1.types.DeleteAllContextsRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "shortName": "delete_all_contexts" - }, - "description": "Sample for DeleteAllContexts", - "file": "dialogflow_v2beta1_generated_contexts_delete_all_contexts_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "dialogflow_v2beta1_generated_Contexts_DeleteAllContexts_async", - "segments": [ - { - "end": 49, - "start": 27, - "type": "FULL" - }, - { - "end": 49, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 50, - "type": "RESPONSE_HANDLING" - } - ], - "title": "dialogflow_v2beta1_generated_contexts_delete_all_contexts_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.dialogflow_v2beta1.ContextsClient", - "shortName": "ContextsClient" - }, - "fullName": "google.cloud.dialogflow_v2beta1.ContextsClient.delete_all_contexts", - "method": { - "fullName": "google.cloud.dialogflow.v2beta1.Contexts.DeleteAllContexts", - "service": { - "fullName": "google.cloud.dialogflow.v2beta1.Contexts", - "shortName": "Contexts" - }, - "shortName": "DeleteAllContexts" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.dialogflow_v2beta1.types.DeleteAllContextsRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "shortName": "delete_all_contexts" - }, - "description": "Sample for DeleteAllContexts", - "file": "dialogflow_v2beta1_generated_contexts_delete_all_contexts_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "dialogflow_v2beta1_generated_Contexts_DeleteAllContexts_sync", - "segments": [ - { - "end": 49, - "start": 27, - "type": "FULL" - }, - { - "end": 49, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 50, - "type": "RESPONSE_HANDLING" - } - ], - "title": "dialogflow_v2beta1_generated_contexts_delete_all_contexts_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.dialogflow_v2beta1.ContextsAsyncClient", - "shortName": "ContextsAsyncClient" - }, - "fullName": "google.cloud.dialogflow_v2beta1.ContextsAsyncClient.delete_context", - "method": { - "fullName": "google.cloud.dialogflow.v2beta1.Contexts.DeleteContext", - "service": { - "fullName": "google.cloud.dialogflow.v2beta1.Contexts", - "shortName": "Contexts" - }, - "shortName": "DeleteContext" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.dialogflow_v2beta1.types.DeleteContextRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "shortName": "delete_context" - }, - "description": "Sample for DeleteContext", - "file": "dialogflow_v2beta1_generated_contexts_delete_context_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "dialogflow_v2beta1_generated_Contexts_DeleteContext_async", - "segments": [ - { - "end": 49, - "start": 27, - "type": "FULL" - }, - { - "end": 49, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 50, - "type": "RESPONSE_HANDLING" - } - ], - "title": "dialogflow_v2beta1_generated_contexts_delete_context_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.dialogflow_v2beta1.ContextsClient", - "shortName": "ContextsClient" - }, - "fullName": "google.cloud.dialogflow_v2beta1.ContextsClient.delete_context", - "method": { - "fullName": "google.cloud.dialogflow.v2beta1.Contexts.DeleteContext", - "service": { - "fullName": "google.cloud.dialogflow.v2beta1.Contexts", - "shortName": "Contexts" - }, - "shortName": "DeleteContext" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.dialogflow_v2beta1.types.DeleteContextRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "shortName": "delete_context" - }, - "description": "Sample for DeleteContext", - "file": "dialogflow_v2beta1_generated_contexts_delete_context_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "dialogflow_v2beta1_generated_Contexts_DeleteContext_sync", - "segments": [ - { - "end": 49, - "start": 27, - "type": "FULL" - }, - { - "end": 49, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 50, - "type": "RESPONSE_HANDLING" - } - ], - "title": "dialogflow_v2beta1_generated_contexts_delete_context_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.dialogflow_v2beta1.ContextsAsyncClient", - "shortName": "ContextsAsyncClient" - }, - "fullName": "google.cloud.dialogflow_v2beta1.ContextsAsyncClient.get_context", - "method": { - "fullName": "google.cloud.dialogflow.v2beta1.Contexts.GetContext", - "service": { - "fullName": "google.cloud.dialogflow.v2beta1.Contexts", - "shortName": "Contexts" - }, - "shortName": "GetContext" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.dialogflow_v2beta1.types.GetContextRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.dialogflow_v2beta1.types.Context", - "shortName": "get_context" - }, - "description": "Sample for GetContext", - "file": "dialogflow_v2beta1_generated_contexts_get_context_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "dialogflow_v2beta1_generated_Contexts_GetContext_async", - "segments": [ - { - "end": 51, - "start": 27, - "type": "FULL" - }, - { - "end": 51, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 48, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 52, - "start": 49, - "type": "RESPONSE_HANDLING" - } - ], - "title": "dialogflow_v2beta1_generated_contexts_get_context_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.dialogflow_v2beta1.ContextsClient", - "shortName": "ContextsClient" - }, - "fullName": "google.cloud.dialogflow_v2beta1.ContextsClient.get_context", - "method": { - "fullName": "google.cloud.dialogflow.v2beta1.Contexts.GetContext", - "service": { - "fullName": "google.cloud.dialogflow.v2beta1.Contexts", - "shortName": "Contexts" - }, - "shortName": "GetContext" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.dialogflow_v2beta1.types.GetContextRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.dialogflow_v2beta1.types.Context", - "shortName": "get_context" - }, - "description": "Sample for GetContext", - "file": "dialogflow_v2beta1_generated_contexts_get_context_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "dialogflow_v2beta1_generated_Contexts_GetContext_sync", - "segments": [ - { - "end": 51, - "start": 27, - "type": "FULL" - }, - { - "end": 51, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 48, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 52, - "start": 49, - "type": "RESPONSE_HANDLING" - } - ], - "title": "dialogflow_v2beta1_generated_contexts_get_context_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.dialogflow_v2beta1.ContextsAsyncClient", - "shortName": "ContextsAsyncClient" - }, - "fullName": "google.cloud.dialogflow_v2beta1.ContextsAsyncClient.list_contexts", - "method": { - "fullName": "google.cloud.dialogflow.v2beta1.Contexts.ListContexts", - "service": { - "fullName": "google.cloud.dialogflow.v2beta1.Contexts", - "shortName": "Contexts" - }, - "shortName": "ListContexts" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.dialogflow_v2beta1.types.ListContextsRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.dialogflow_v2beta1.services.contexts.pagers.ListContextsAsyncPager", - "shortName": "list_contexts" - }, - "description": "Sample for ListContexts", - "file": "dialogflow_v2beta1_generated_contexts_list_contexts_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "dialogflow_v2beta1_generated_Contexts_ListContexts_async", - "segments": [ - { - "end": 52, - "start": 27, - "type": "FULL" - }, - { - "end": 52, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 48, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 53, - "start": 49, - "type": "RESPONSE_HANDLING" - } - ], - "title": "dialogflow_v2beta1_generated_contexts_list_contexts_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.dialogflow_v2beta1.ContextsClient", - "shortName": "ContextsClient" - }, - "fullName": "google.cloud.dialogflow_v2beta1.ContextsClient.list_contexts", - "method": { - "fullName": "google.cloud.dialogflow.v2beta1.Contexts.ListContexts", - "service": { - "fullName": "google.cloud.dialogflow.v2beta1.Contexts", - "shortName": "Contexts" - }, - "shortName": "ListContexts" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.dialogflow_v2beta1.types.ListContextsRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.dialogflow_v2beta1.services.contexts.pagers.ListContextsPager", - "shortName": "list_contexts" - }, - "description": "Sample for ListContexts", - "file": "dialogflow_v2beta1_generated_contexts_list_contexts_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "dialogflow_v2beta1_generated_Contexts_ListContexts_sync", - "segments": [ - { - "end": 52, - "start": 27, - "type": "FULL" - }, - { - "end": 52, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 48, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 53, - "start": 49, - "type": "RESPONSE_HANDLING" - } - ], - "title": "dialogflow_v2beta1_generated_contexts_list_contexts_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.dialogflow_v2beta1.ContextsAsyncClient", - "shortName": "ContextsAsyncClient" - }, - "fullName": "google.cloud.dialogflow_v2beta1.ContextsAsyncClient.update_context", - "method": { - "fullName": "google.cloud.dialogflow.v2beta1.Contexts.UpdateContext", - "service": { - "fullName": "google.cloud.dialogflow.v2beta1.Contexts", - "shortName": "Contexts" - }, - "shortName": "UpdateContext" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.dialogflow_v2beta1.types.UpdateContextRequest" - }, - { - "name": "context", - "type": "google.cloud.dialogflow_v2beta1.types.Context" - }, - { - "name": "update_mask", - "type": "google.protobuf.field_mask_pb2.FieldMask" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.dialogflow_v2beta1.types.Context", - "shortName": "update_context" - }, - "description": "Sample for UpdateContext", - "file": "dialogflow_v2beta1_generated_contexts_update_context_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "dialogflow_v2beta1_generated_Contexts_UpdateContext_async", - "segments": [ - { - "end": 50, - "start": 27, - "type": "FULL" - }, - { - "end": 50, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 44, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 47, - "start": 45, - "type": "REQUEST_EXECUTION" - }, - { - "end": 51, - "start": 48, - "type": "RESPONSE_HANDLING" - } - ], - "title": "dialogflow_v2beta1_generated_contexts_update_context_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.dialogflow_v2beta1.ContextsClient", - "shortName": "ContextsClient" - }, - "fullName": "google.cloud.dialogflow_v2beta1.ContextsClient.update_context", - "method": { - "fullName": "google.cloud.dialogflow.v2beta1.Contexts.UpdateContext", - "service": { - "fullName": "google.cloud.dialogflow.v2beta1.Contexts", - "shortName": "Contexts" - }, - "shortName": "UpdateContext" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.dialogflow_v2beta1.types.UpdateContextRequest" - }, - { - "name": "context", - "type": "google.cloud.dialogflow_v2beta1.types.Context" - }, - { - "name": "update_mask", - "type": "google.protobuf.field_mask_pb2.FieldMask" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.dialogflow_v2beta1.types.Context", - "shortName": "update_context" - }, - "description": "Sample for UpdateContext", - "file": "dialogflow_v2beta1_generated_contexts_update_context_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "dialogflow_v2beta1_generated_Contexts_UpdateContext_sync", - "segments": [ - { - "end": 50, - "start": 27, - "type": "FULL" - }, - { - "end": 50, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 44, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 47, - "start": 45, - "type": "REQUEST_EXECUTION" - }, - { - "end": 51, - "start": 48, - "type": "RESPONSE_HANDLING" - } - ], - "title": "dialogflow_v2beta1_generated_contexts_update_context_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.dialogflow_v2beta1.ConversationProfilesAsyncClient", - "shortName": "ConversationProfilesAsyncClient" - }, - "fullName": "google.cloud.dialogflow_v2beta1.ConversationProfilesAsyncClient.clear_suggestion_feature_config", - "method": { - "fullName": "google.cloud.dialogflow.v2beta1.ConversationProfiles.ClearSuggestionFeatureConfig", - "service": { - "fullName": "google.cloud.dialogflow.v2beta1.ConversationProfiles", - "shortName": "ConversationProfiles" - }, - "shortName": "ClearSuggestionFeatureConfig" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.dialogflow_v2beta1.types.ClearSuggestionFeatureConfigRequest" - }, - { - "name": "conversation_profile", - "type": "str" - }, - { - "name": "participant_role", - "type": "google.cloud.dialogflow_v2beta1.types.Participant.Role" - }, - { - "name": "suggestion_feature_type", - "type": "google.cloud.dialogflow_v2beta1.types.SuggestionFeature.Type" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.api_core.operation_async.AsyncOperation", - "shortName": "clear_suggestion_feature_config" - }, - "description": "Sample for ClearSuggestionFeatureConfig", - "file": "dialogflow_v2beta1_generated_conversation_profiles_clear_suggestion_feature_config_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "dialogflow_v2beta1_generated_ConversationProfiles_ClearSuggestionFeatureConfig_async", - "segments": [ - { - "end": 57, - "start": 27, - "type": "FULL" - }, - { - "end": 57, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 47, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 54, - "start": 48, - "type": "REQUEST_EXECUTION" - }, - { - "end": 58, - "start": 55, - "type": "RESPONSE_HANDLING" - } - ], - "title": "dialogflow_v2beta1_generated_conversation_profiles_clear_suggestion_feature_config_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.dialogflow_v2beta1.ConversationProfilesClient", - "shortName": "ConversationProfilesClient" - }, - "fullName": "google.cloud.dialogflow_v2beta1.ConversationProfilesClient.clear_suggestion_feature_config", - "method": { - "fullName": "google.cloud.dialogflow.v2beta1.ConversationProfiles.ClearSuggestionFeatureConfig", - "service": { - "fullName": "google.cloud.dialogflow.v2beta1.ConversationProfiles", - "shortName": "ConversationProfiles" - }, - "shortName": "ClearSuggestionFeatureConfig" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.dialogflow_v2beta1.types.ClearSuggestionFeatureConfigRequest" - }, - { - "name": "conversation_profile", - "type": "str" - }, - { - "name": "participant_role", - "type": "google.cloud.dialogflow_v2beta1.types.Participant.Role" - }, - { - "name": "suggestion_feature_type", - "type": "google.cloud.dialogflow_v2beta1.types.SuggestionFeature.Type" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.api_core.operation.Operation", - "shortName": "clear_suggestion_feature_config" - }, - "description": "Sample for ClearSuggestionFeatureConfig", - "file": "dialogflow_v2beta1_generated_conversation_profiles_clear_suggestion_feature_config_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "dialogflow_v2beta1_generated_ConversationProfiles_ClearSuggestionFeatureConfig_sync", - "segments": [ - { - "end": 57, - "start": 27, - "type": "FULL" - }, - { - "end": 57, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 47, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 54, - "start": 48, - "type": "REQUEST_EXECUTION" - }, - { - "end": 58, - "start": 55, - "type": "RESPONSE_HANDLING" - } - ], - "title": "dialogflow_v2beta1_generated_conversation_profiles_clear_suggestion_feature_config_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.dialogflow_v2beta1.ConversationProfilesAsyncClient", - "shortName": "ConversationProfilesAsyncClient" - }, - "fullName": "google.cloud.dialogflow_v2beta1.ConversationProfilesAsyncClient.create_conversation_profile", - "method": { - "fullName": "google.cloud.dialogflow.v2beta1.ConversationProfiles.CreateConversationProfile", - "service": { - "fullName": "google.cloud.dialogflow.v2beta1.ConversationProfiles", - "shortName": "ConversationProfiles" - }, - "shortName": "CreateConversationProfile" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.dialogflow_v2beta1.types.CreateConversationProfileRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "conversation_profile", - "type": "google.cloud.dialogflow_v2beta1.types.ConversationProfile" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.dialogflow_v2beta1.types.ConversationProfile", - "shortName": "create_conversation_profile" - }, - "description": "Sample for CreateConversationProfile", - "file": "dialogflow_v2beta1_generated_conversation_profiles_create_conversation_profile_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "dialogflow_v2beta1_generated_ConversationProfiles_CreateConversationProfile_async", - "segments": [ - { - "end": 55, - "start": 27, - "type": "FULL" - }, - { - "end": 55, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 49, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 52, - "start": 50, - "type": "REQUEST_EXECUTION" - }, - { - "end": 56, - "start": 53, - "type": "RESPONSE_HANDLING" - } - ], - "title": "dialogflow_v2beta1_generated_conversation_profiles_create_conversation_profile_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.dialogflow_v2beta1.ConversationProfilesClient", - "shortName": "ConversationProfilesClient" - }, - "fullName": "google.cloud.dialogflow_v2beta1.ConversationProfilesClient.create_conversation_profile", - "method": { - "fullName": "google.cloud.dialogflow.v2beta1.ConversationProfiles.CreateConversationProfile", - "service": { - "fullName": "google.cloud.dialogflow.v2beta1.ConversationProfiles", - "shortName": "ConversationProfiles" - }, - "shortName": "CreateConversationProfile" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.dialogflow_v2beta1.types.CreateConversationProfileRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "conversation_profile", - "type": "google.cloud.dialogflow_v2beta1.types.ConversationProfile" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.dialogflow_v2beta1.types.ConversationProfile", - "shortName": "create_conversation_profile" - }, - "description": "Sample for CreateConversationProfile", - "file": "dialogflow_v2beta1_generated_conversation_profiles_create_conversation_profile_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "dialogflow_v2beta1_generated_ConversationProfiles_CreateConversationProfile_sync", - "segments": [ - { - "end": 55, - "start": 27, - "type": "FULL" - }, - { - "end": 55, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 49, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 52, - "start": 50, - "type": "REQUEST_EXECUTION" - }, - { - "end": 56, - "start": 53, - "type": "RESPONSE_HANDLING" - } - ], - "title": "dialogflow_v2beta1_generated_conversation_profiles_create_conversation_profile_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.dialogflow_v2beta1.ConversationProfilesAsyncClient", - "shortName": "ConversationProfilesAsyncClient" - }, - "fullName": "google.cloud.dialogflow_v2beta1.ConversationProfilesAsyncClient.delete_conversation_profile", - "method": { - "fullName": "google.cloud.dialogflow.v2beta1.ConversationProfiles.DeleteConversationProfile", - "service": { - "fullName": "google.cloud.dialogflow.v2beta1.ConversationProfiles", - "shortName": "ConversationProfiles" - }, - "shortName": "DeleteConversationProfile" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.dialogflow_v2beta1.types.DeleteConversationProfileRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "shortName": "delete_conversation_profile" - }, - "description": "Sample for DeleteConversationProfile", - "file": "dialogflow_v2beta1_generated_conversation_profiles_delete_conversation_profile_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "dialogflow_v2beta1_generated_ConversationProfiles_DeleteConversationProfile_async", - "segments": [ - { - "end": 49, - "start": 27, - "type": "FULL" - }, - { - "end": 49, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 50, - "type": "RESPONSE_HANDLING" - } - ], - "title": "dialogflow_v2beta1_generated_conversation_profiles_delete_conversation_profile_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.dialogflow_v2beta1.ConversationProfilesClient", - "shortName": "ConversationProfilesClient" - }, - "fullName": "google.cloud.dialogflow_v2beta1.ConversationProfilesClient.delete_conversation_profile", - "method": { - "fullName": "google.cloud.dialogflow.v2beta1.ConversationProfiles.DeleteConversationProfile", - "service": { - "fullName": "google.cloud.dialogflow.v2beta1.ConversationProfiles", - "shortName": "ConversationProfiles" - }, - "shortName": "DeleteConversationProfile" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.dialogflow_v2beta1.types.DeleteConversationProfileRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "shortName": "delete_conversation_profile" - }, - "description": "Sample for DeleteConversationProfile", - "file": "dialogflow_v2beta1_generated_conversation_profiles_delete_conversation_profile_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "dialogflow_v2beta1_generated_ConversationProfiles_DeleteConversationProfile_sync", - "segments": [ - { - "end": 49, - "start": 27, - "type": "FULL" - }, - { - "end": 49, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 50, - "type": "RESPONSE_HANDLING" - } - ], - "title": "dialogflow_v2beta1_generated_conversation_profiles_delete_conversation_profile_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.dialogflow_v2beta1.ConversationProfilesAsyncClient", - "shortName": "ConversationProfilesAsyncClient" - }, - "fullName": "google.cloud.dialogflow_v2beta1.ConversationProfilesAsyncClient.get_conversation_profile", - "method": { - "fullName": "google.cloud.dialogflow.v2beta1.ConversationProfiles.GetConversationProfile", - "service": { - "fullName": "google.cloud.dialogflow.v2beta1.ConversationProfiles", - "shortName": "ConversationProfiles" - }, - "shortName": "GetConversationProfile" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.dialogflow_v2beta1.types.GetConversationProfileRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.dialogflow_v2beta1.types.ConversationProfile", - "shortName": "get_conversation_profile" - }, - "description": "Sample for GetConversationProfile", - "file": "dialogflow_v2beta1_generated_conversation_profiles_get_conversation_profile_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "dialogflow_v2beta1_generated_ConversationProfiles_GetConversationProfile_async", - "segments": [ - { - "end": 51, - "start": 27, - "type": "FULL" - }, - { - "end": 51, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 48, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 52, - "start": 49, - "type": "RESPONSE_HANDLING" - } - ], - "title": "dialogflow_v2beta1_generated_conversation_profiles_get_conversation_profile_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.dialogflow_v2beta1.ConversationProfilesClient", - "shortName": "ConversationProfilesClient" - }, - "fullName": "google.cloud.dialogflow_v2beta1.ConversationProfilesClient.get_conversation_profile", - "method": { - "fullName": "google.cloud.dialogflow.v2beta1.ConversationProfiles.GetConversationProfile", - "service": { - "fullName": "google.cloud.dialogflow.v2beta1.ConversationProfiles", - "shortName": "ConversationProfiles" - }, - "shortName": "GetConversationProfile" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.dialogflow_v2beta1.types.GetConversationProfileRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.dialogflow_v2beta1.types.ConversationProfile", - "shortName": "get_conversation_profile" - }, - "description": "Sample for GetConversationProfile", - "file": "dialogflow_v2beta1_generated_conversation_profiles_get_conversation_profile_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "dialogflow_v2beta1_generated_ConversationProfiles_GetConversationProfile_sync", - "segments": [ - { - "end": 51, - "start": 27, - "type": "FULL" - }, - { - "end": 51, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 48, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 52, - "start": 49, - "type": "RESPONSE_HANDLING" - } - ], - "title": "dialogflow_v2beta1_generated_conversation_profiles_get_conversation_profile_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.dialogflow_v2beta1.ConversationProfilesAsyncClient", - "shortName": "ConversationProfilesAsyncClient" - }, - "fullName": "google.cloud.dialogflow_v2beta1.ConversationProfilesAsyncClient.list_conversation_profiles", - "method": { - "fullName": "google.cloud.dialogflow.v2beta1.ConversationProfiles.ListConversationProfiles", - "service": { - "fullName": "google.cloud.dialogflow.v2beta1.ConversationProfiles", - "shortName": "ConversationProfiles" - }, - "shortName": "ListConversationProfiles" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.dialogflow_v2beta1.types.ListConversationProfilesRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.dialogflow_v2beta1.services.conversation_profiles.pagers.ListConversationProfilesAsyncPager", - "shortName": "list_conversation_profiles" - }, - "description": "Sample for ListConversationProfiles", - "file": "dialogflow_v2beta1_generated_conversation_profiles_list_conversation_profiles_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "dialogflow_v2beta1_generated_ConversationProfiles_ListConversationProfiles_async", - "segments": [ - { - "end": 52, - "start": 27, - "type": "FULL" - }, - { - "end": 52, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 48, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 53, - "start": 49, - "type": "RESPONSE_HANDLING" - } - ], - "title": "dialogflow_v2beta1_generated_conversation_profiles_list_conversation_profiles_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.dialogflow_v2beta1.ConversationProfilesClient", - "shortName": "ConversationProfilesClient" - }, - "fullName": "google.cloud.dialogflow_v2beta1.ConversationProfilesClient.list_conversation_profiles", - "method": { - "fullName": "google.cloud.dialogflow.v2beta1.ConversationProfiles.ListConversationProfiles", - "service": { - "fullName": "google.cloud.dialogflow.v2beta1.ConversationProfiles", - "shortName": "ConversationProfiles" - }, - "shortName": "ListConversationProfiles" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.dialogflow_v2beta1.types.ListConversationProfilesRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.dialogflow_v2beta1.services.conversation_profiles.pagers.ListConversationProfilesPager", - "shortName": "list_conversation_profiles" - }, - "description": "Sample for ListConversationProfiles", - "file": "dialogflow_v2beta1_generated_conversation_profiles_list_conversation_profiles_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "dialogflow_v2beta1_generated_ConversationProfiles_ListConversationProfiles_sync", - "segments": [ - { - "end": 52, - "start": 27, - "type": "FULL" - }, - { - "end": 52, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 48, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 53, - "start": 49, - "type": "RESPONSE_HANDLING" - } - ], - "title": "dialogflow_v2beta1_generated_conversation_profiles_list_conversation_profiles_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.dialogflow_v2beta1.ConversationProfilesAsyncClient", - "shortName": "ConversationProfilesAsyncClient" - }, - "fullName": "google.cloud.dialogflow_v2beta1.ConversationProfilesAsyncClient.set_suggestion_feature_config", - "method": { - "fullName": "google.cloud.dialogflow.v2beta1.ConversationProfiles.SetSuggestionFeatureConfig", - "service": { - "fullName": "google.cloud.dialogflow.v2beta1.ConversationProfiles", - "shortName": "ConversationProfiles" - }, - "shortName": "SetSuggestionFeatureConfig" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.dialogflow_v2beta1.types.SetSuggestionFeatureConfigRequest" - }, - { - "name": "conversation_profile", - "type": "str" - }, - { - "name": "participant_role", - "type": "google.cloud.dialogflow_v2beta1.types.Participant.Role" - }, - { - "name": "suggestion_feature_config", - "type": "google.cloud.dialogflow_v2beta1.types.HumanAgentAssistantConfig.SuggestionFeatureConfig" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.api_core.operation_async.AsyncOperation", - "shortName": "set_suggestion_feature_config" - }, - "description": "Sample for SetSuggestionFeatureConfig", - "file": "dialogflow_v2beta1_generated_conversation_profiles_set_suggestion_feature_config_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "dialogflow_v2beta1_generated_ConversationProfiles_SetSuggestionFeatureConfig_async", - "segments": [ - { - "end": 56, - "start": 27, - "type": "FULL" - }, - { - "end": 56, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 46, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 53, - "start": 47, - "type": "REQUEST_EXECUTION" - }, - { - "end": 57, - "start": 54, - "type": "RESPONSE_HANDLING" - } - ], - "title": "dialogflow_v2beta1_generated_conversation_profiles_set_suggestion_feature_config_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.dialogflow_v2beta1.ConversationProfilesClient", - "shortName": "ConversationProfilesClient" - }, - "fullName": "google.cloud.dialogflow_v2beta1.ConversationProfilesClient.set_suggestion_feature_config", - "method": { - "fullName": "google.cloud.dialogflow.v2beta1.ConversationProfiles.SetSuggestionFeatureConfig", - "service": { - "fullName": "google.cloud.dialogflow.v2beta1.ConversationProfiles", - "shortName": "ConversationProfiles" - }, - "shortName": "SetSuggestionFeatureConfig" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.dialogflow_v2beta1.types.SetSuggestionFeatureConfigRequest" - }, - { - "name": "conversation_profile", - "type": "str" - }, - { - "name": "participant_role", - "type": "google.cloud.dialogflow_v2beta1.types.Participant.Role" - }, - { - "name": "suggestion_feature_config", - "type": "google.cloud.dialogflow_v2beta1.types.HumanAgentAssistantConfig.SuggestionFeatureConfig" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.api_core.operation.Operation", - "shortName": "set_suggestion_feature_config" - }, - "description": "Sample for SetSuggestionFeatureConfig", - "file": "dialogflow_v2beta1_generated_conversation_profiles_set_suggestion_feature_config_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "dialogflow_v2beta1_generated_ConversationProfiles_SetSuggestionFeatureConfig_sync", - "segments": [ - { - "end": 56, - "start": 27, - "type": "FULL" - }, - { - "end": 56, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 46, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 53, - "start": 47, - "type": "REQUEST_EXECUTION" - }, - { - "end": 57, - "start": 54, - "type": "RESPONSE_HANDLING" - } - ], - "title": "dialogflow_v2beta1_generated_conversation_profiles_set_suggestion_feature_config_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.dialogflow_v2beta1.ConversationProfilesAsyncClient", - "shortName": "ConversationProfilesAsyncClient" - }, - "fullName": "google.cloud.dialogflow_v2beta1.ConversationProfilesAsyncClient.update_conversation_profile", - "method": { - "fullName": "google.cloud.dialogflow.v2beta1.ConversationProfiles.UpdateConversationProfile", - "service": { - "fullName": "google.cloud.dialogflow.v2beta1.ConversationProfiles", - "shortName": "ConversationProfiles" - }, - "shortName": "UpdateConversationProfile" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.dialogflow_v2beta1.types.UpdateConversationProfileRequest" - }, - { - "name": "conversation_profile", - "type": "google.cloud.dialogflow_v2beta1.types.ConversationProfile" - }, - { - "name": "update_mask", - "type": "google.protobuf.field_mask_pb2.FieldMask" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.dialogflow_v2beta1.types.ConversationProfile", - "shortName": "update_conversation_profile" - }, - "description": "Sample for UpdateConversationProfile", - "file": "dialogflow_v2beta1_generated_conversation_profiles_update_conversation_profile_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "dialogflow_v2beta1_generated_ConversationProfiles_UpdateConversationProfile_async", - "segments": [ - { - "end": 54, - "start": 27, - "type": "FULL" - }, - { - "end": 54, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 48, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 51, - "start": 49, - "type": "REQUEST_EXECUTION" - }, - { - "end": 55, - "start": 52, - "type": "RESPONSE_HANDLING" - } - ], - "title": "dialogflow_v2beta1_generated_conversation_profiles_update_conversation_profile_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.dialogflow_v2beta1.ConversationProfilesClient", - "shortName": "ConversationProfilesClient" - }, - "fullName": "google.cloud.dialogflow_v2beta1.ConversationProfilesClient.update_conversation_profile", - "method": { - "fullName": "google.cloud.dialogflow.v2beta1.ConversationProfiles.UpdateConversationProfile", - "service": { - "fullName": "google.cloud.dialogflow.v2beta1.ConversationProfiles", - "shortName": "ConversationProfiles" - }, - "shortName": "UpdateConversationProfile" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.dialogflow_v2beta1.types.UpdateConversationProfileRequest" - }, - { - "name": "conversation_profile", - "type": "google.cloud.dialogflow_v2beta1.types.ConversationProfile" - }, - { - "name": "update_mask", - "type": "google.protobuf.field_mask_pb2.FieldMask" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.dialogflow_v2beta1.types.ConversationProfile", - "shortName": "update_conversation_profile" - }, - "description": "Sample for UpdateConversationProfile", - "file": "dialogflow_v2beta1_generated_conversation_profiles_update_conversation_profile_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "dialogflow_v2beta1_generated_ConversationProfiles_UpdateConversationProfile_sync", - "segments": [ - { - "end": 54, - "start": 27, - "type": "FULL" - }, - { - "end": 54, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 48, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 51, - "start": 49, - "type": "REQUEST_EXECUTION" - }, - { - "end": 55, - "start": 52, - "type": "RESPONSE_HANDLING" - } - ], - "title": "dialogflow_v2beta1_generated_conversation_profiles_update_conversation_profile_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.dialogflow_v2beta1.ConversationsAsyncClient", - "shortName": "ConversationsAsyncClient" - }, - "fullName": "google.cloud.dialogflow_v2beta1.ConversationsAsyncClient.batch_create_messages", - "method": { - "fullName": "google.cloud.dialogflow.v2beta1.Conversations.BatchCreateMessages", - "service": { - "fullName": "google.cloud.dialogflow.v2beta1.Conversations", - "shortName": "Conversations" - }, - "shortName": "BatchCreateMessages" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.dialogflow_v2beta1.types.BatchCreateMessagesRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.dialogflow_v2beta1.types.BatchCreateMessagesResponse", - "shortName": "batch_create_messages" - }, - "description": "Sample for BatchCreateMessages", - "file": "dialogflow_v2beta1_generated_conversations_batch_create_messages_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "dialogflow_v2beta1_generated_Conversations_BatchCreateMessages_async", - "segments": [ - { - "end": 56, - "start": 27, - "type": "FULL" - }, - { - "end": 56, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 50, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 53, - "start": 51, - "type": "REQUEST_EXECUTION" - }, - { - "end": 57, - "start": 54, - "type": "RESPONSE_HANDLING" - } - ], - "title": "dialogflow_v2beta1_generated_conversations_batch_create_messages_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.dialogflow_v2beta1.ConversationsClient", - "shortName": "ConversationsClient" - }, - "fullName": "google.cloud.dialogflow_v2beta1.ConversationsClient.batch_create_messages", - "method": { - "fullName": "google.cloud.dialogflow.v2beta1.Conversations.BatchCreateMessages", - "service": { - "fullName": "google.cloud.dialogflow.v2beta1.Conversations", - "shortName": "Conversations" - }, - "shortName": "BatchCreateMessages" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.dialogflow_v2beta1.types.BatchCreateMessagesRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.dialogflow_v2beta1.types.BatchCreateMessagesResponse", - "shortName": "batch_create_messages" - }, - "description": "Sample for BatchCreateMessages", - "file": "dialogflow_v2beta1_generated_conversations_batch_create_messages_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "dialogflow_v2beta1_generated_Conversations_BatchCreateMessages_sync", - "segments": [ - { - "end": 56, - "start": 27, - "type": "FULL" - }, - { - "end": 56, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 50, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 53, - "start": 51, - "type": "REQUEST_EXECUTION" - }, - { - "end": 57, - "start": 54, - "type": "RESPONSE_HANDLING" - } - ], - "title": "dialogflow_v2beta1_generated_conversations_batch_create_messages_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.dialogflow_v2beta1.ConversationsAsyncClient", - "shortName": "ConversationsAsyncClient" - }, - "fullName": "google.cloud.dialogflow_v2beta1.ConversationsAsyncClient.complete_conversation", - "method": { - "fullName": "google.cloud.dialogflow.v2beta1.Conversations.CompleteConversation", - "service": { - "fullName": "google.cloud.dialogflow.v2beta1.Conversations", - "shortName": "Conversations" - }, - "shortName": "CompleteConversation" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.dialogflow_v2beta1.types.CompleteConversationRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.dialogflow_v2beta1.types.Conversation", - "shortName": "complete_conversation" - }, - "description": "Sample for CompleteConversation", - "file": "dialogflow_v2beta1_generated_conversations_complete_conversation_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "dialogflow_v2beta1_generated_Conversations_CompleteConversation_async", - "segments": [ - { - "end": 51, - "start": 27, - "type": "FULL" - }, - { - "end": 51, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 48, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 52, - "start": 49, - "type": "RESPONSE_HANDLING" - } - ], - "title": "dialogflow_v2beta1_generated_conversations_complete_conversation_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.dialogflow_v2beta1.ConversationsClient", - "shortName": "ConversationsClient" - }, - "fullName": "google.cloud.dialogflow_v2beta1.ConversationsClient.complete_conversation", - "method": { - "fullName": "google.cloud.dialogflow.v2beta1.Conversations.CompleteConversation", - "service": { - "fullName": "google.cloud.dialogflow.v2beta1.Conversations", - "shortName": "Conversations" - }, - "shortName": "CompleteConversation" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.dialogflow_v2beta1.types.CompleteConversationRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.dialogflow_v2beta1.types.Conversation", - "shortName": "complete_conversation" - }, - "description": "Sample for CompleteConversation", - "file": "dialogflow_v2beta1_generated_conversations_complete_conversation_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "dialogflow_v2beta1_generated_Conversations_CompleteConversation_sync", - "segments": [ - { - "end": 51, - "start": 27, - "type": "FULL" - }, - { - "end": 51, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 48, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 52, - "start": 49, - "type": "RESPONSE_HANDLING" - } - ], - "title": "dialogflow_v2beta1_generated_conversations_complete_conversation_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.dialogflow_v2beta1.ConversationsAsyncClient", - "shortName": "ConversationsAsyncClient" - }, - "fullName": "google.cloud.dialogflow_v2beta1.ConversationsAsyncClient.create_conversation", - "method": { - "fullName": "google.cloud.dialogflow.v2beta1.Conversations.CreateConversation", - "service": { - "fullName": "google.cloud.dialogflow.v2beta1.Conversations", - "shortName": "Conversations" - }, - "shortName": "CreateConversation" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.dialogflow_v2beta1.types.CreateConversationRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "conversation", - "type": "google.cloud.dialogflow_v2beta1.types.Conversation" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.dialogflow_v2beta1.types.Conversation", - "shortName": "create_conversation" - }, - "description": "Sample for CreateConversation", - "file": "dialogflow_v2beta1_generated_conversations_create_conversation_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "dialogflow_v2beta1_generated_Conversations_CreateConversation_async", - "segments": [ - { - "end": 55, - "start": 27, - "type": "FULL" - }, - { - "end": 55, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 49, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 52, - "start": 50, - "type": "REQUEST_EXECUTION" - }, - { - "end": 56, - "start": 53, - "type": "RESPONSE_HANDLING" - } - ], - "title": "dialogflow_v2beta1_generated_conversations_create_conversation_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.dialogflow_v2beta1.ConversationsClient", - "shortName": "ConversationsClient" - }, - "fullName": "google.cloud.dialogflow_v2beta1.ConversationsClient.create_conversation", - "method": { - "fullName": "google.cloud.dialogflow.v2beta1.Conversations.CreateConversation", - "service": { - "fullName": "google.cloud.dialogflow.v2beta1.Conversations", - "shortName": "Conversations" - }, - "shortName": "CreateConversation" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.dialogflow_v2beta1.types.CreateConversationRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "conversation", - "type": "google.cloud.dialogflow_v2beta1.types.Conversation" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.dialogflow_v2beta1.types.Conversation", - "shortName": "create_conversation" - }, - "description": "Sample for CreateConversation", - "file": "dialogflow_v2beta1_generated_conversations_create_conversation_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "dialogflow_v2beta1_generated_Conversations_CreateConversation_sync", - "segments": [ - { - "end": 55, - "start": 27, - "type": "FULL" - }, - { - "end": 55, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 49, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 52, - "start": 50, - "type": "REQUEST_EXECUTION" - }, - { - "end": 56, - "start": 53, - "type": "RESPONSE_HANDLING" - } - ], - "title": "dialogflow_v2beta1_generated_conversations_create_conversation_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.dialogflow_v2beta1.ConversationsAsyncClient", - "shortName": "ConversationsAsyncClient" - }, - "fullName": "google.cloud.dialogflow_v2beta1.ConversationsAsyncClient.get_conversation", - "method": { - "fullName": "google.cloud.dialogflow.v2beta1.Conversations.GetConversation", - "service": { - "fullName": "google.cloud.dialogflow.v2beta1.Conversations", - "shortName": "Conversations" - }, - "shortName": "GetConversation" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.dialogflow_v2beta1.types.GetConversationRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.dialogflow_v2beta1.types.Conversation", - "shortName": "get_conversation" - }, - "description": "Sample for GetConversation", - "file": "dialogflow_v2beta1_generated_conversations_get_conversation_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "dialogflow_v2beta1_generated_Conversations_GetConversation_async", - "segments": [ - { - "end": 51, - "start": 27, - "type": "FULL" - }, - { - "end": 51, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 48, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 52, - "start": 49, - "type": "RESPONSE_HANDLING" - } - ], - "title": "dialogflow_v2beta1_generated_conversations_get_conversation_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.dialogflow_v2beta1.ConversationsClient", - "shortName": "ConversationsClient" - }, - "fullName": "google.cloud.dialogflow_v2beta1.ConversationsClient.get_conversation", - "method": { - "fullName": "google.cloud.dialogflow.v2beta1.Conversations.GetConversation", - "service": { - "fullName": "google.cloud.dialogflow.v2beta1.Conversations", - "shortName": "Conversations" - }, - "shortName": "GetConversation" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.dialogflow_v2beta1.types.GetConversationRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.dialogflow_v2beta1.types.Conversation", - "shortName": "get_conversation" - }, - "description": "Sample for GetConversation", - "file": "dialogflow_v2beta1_generated_conversations_get_conversation_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "dialogflow_v2beta1_generated_Conversations_GetConversation_sync", - "segments": [ - { - "end": 51, - "start": 27, - "type": "FULL" - }, - { - "end": 51, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 48, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 52, - "start": 49, - "type": "RESPONSE_HANDLING" - } - ], - "title": "dialogflow_v2beta1_generated_conversations_get_conversation_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.dialogflow_v2beta1.ConversationsAsyncClient", - "shortName": "ConversationsAsyncClient" - }, - "fullName": "google.cloud.dialogflow_v2beta1.ConversationsAsyncClient.list_conversations", - "method": { - "fullName": "google.cloud.dialogflow.v2beta1.Conversations.ListConversations", - "service": { - "fullName": "google.cloud.dialogflow.v2beta1.Conversations", - "shortName": "Conversations" - }, - "shortName": "ListConversations" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.dialogflow_v2beta1.types.ListConversationsRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.dialogflow_v2beta1.services.conversations.pagers.ListConversationsAsyncPager", - "shortName": "list_conversations" - }, - "description": "Sample for ListConversations", - "file": "dialogflow_v2beta1_generated_conversations_list_conversations_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "dialogflow_v2beta1_generated_Conversations_ListConversations_async", - "segments": [ - { - "end": 52, - "start": 27, - "type": "FULL" - }, - { - "end": 52, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 48, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 53, - "start": 49, - "type": "RESPONSE_HANDLING" - } - ], - "title": "dialogflow_v2beta1_generated_conversations_list_conversations_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.dialogflow_v2beta1.ConversationsClient", - "shortName": "ConversationsClient" - }, - "fullName": "google.cloud.dialogflow_v2beta1.ConversationsClient.list_conversations", - "method": { - "fullName": "google.cloud.dialogflow.v2beta1.Conversations.ListConversations", - "service": { - "fullName": "google.cloud.dialogflow.v2beta1.Conversations", - "shortName": "Conversations" - }, - "shortName": "ListConversations" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.dialogflow_v2beta1.types.ListConversationsRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.dialogflow_v2beta1.services.conversations.pagers.ListConversationsPager", - "shortName": "list_conversations" - }, - "description": "Sample for ListConversations", - "file": "dialogflow_v2beta1_generated_conversations_list_conversations_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "dialogflow_v2beta1_generated_Conversations_ListConversations_sync", - "segments": [ - { - "end": 52, - "start": 27, - "type": "FULL" - }, - { - "end": 52, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 48, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 53, - "start": 49, - "type": "RESPONSE_HANDLING" - } - ], - "title": "dialogflow_v2beta1_generated_conversations_list_conversations_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.dialogflow_v2beta1.ConversationsAsyncClient", - "shortName": "ConversationsAsyncClient" - }, - "fullName": "google.cloud.dialogflow_v2beta1.ConversationsAsyncClient.list_messages", - "method": { - "fullName": "google.cloud.dialogflow.v2beta1.Conversations.ListMessages", - "service": { - "fullName": "google.cloud.dialogflow.v2beta1.Conversations", - "shortName": "Conversations" - }, - "shortName": "ListMessages" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.dialogflow_v2beta1.types.ListMessagesRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.dialogflow_v2beta1.services.conversations.pagers.ListMessagesAsyncPager", - "shortName": "list_messages" - }, - "description": "Sample for ListMessages", - "file": "dialogflow_v2beta1_generated_conversations_list_messages_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "dialogflow_v2beta1_generated_Conversations_ListMessages_async", - "segments": [ - { - "end": 52, - "start": 27, - "type": "FULL" - }, - { - "end": 52, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 48, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 53, - "start": 49, - "type": "RESPONSE_HANDLING" - } - ], - "title": "dialogflow_v2beta1_generated_conversations_list_messages_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.dialogflow_v2beta1.ConversationsClient", - "shortName": "ConversationsClient" - }, - "fullName": "google.cloud.dialogflow_v2beta1.ConversationsClient.list_messages", - "method": { - "fullName": "google.cloud.dialogflow.v2beta1.Conversations.ListMessages", - "service": { - "fullName": "google.cloud.dialogflow.v2beta1.Conversations", - "shortName": "Conversations" - }, - "shortName": "ListMessages" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.dialogflow_v2beta1.types.ListMessagesRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.dialogflow_v2beta1.services.conversations.pagers.ListMessagesPager", - "shortName": "list_messages" - }, - "description": "Sample for ListMessages", - "file": "dialogflow_v2beta1_generated_conversations_list_messages_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "dialogflow_v2beta1_generated_Conversations_ListMessages_sync", - "segments": [ - { - "end": 52, - "start": 27, - "type": "FULL" - }, - { - "end": 52, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 48, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 53, - "start": 49, - "type": "RESPONSE_HANDLING" - } - ], - "title": "dialogflow_v2beta1_generated_conversations_list_messages_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.dialogflow_v2beta1.ConversationsAsyncClient", - "shortName": "ConversationsAsyncClient" - }, - "fullName": "google.cloud.dialogflow_v2beta1.ConversationsAsyncClient.suggest_conversation_summary", - "method": { - "fullName": "google.cloud.dialogflow.v2beta1.Conversations.SuggestConversationSummary", - "service": { - "fullName": "google.cloud.dialogflow.v2beta1.Conversations", - "shortName": "Conversations" - }, - "shortName": "SuggestConversationSummary" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.dialogflow_v2beta1.types.SuggestConversationSummaryRequest" - }, - { - "name": "conversation", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.dialogflow_v2beta1.types.SuggestConversationSummaryResponse", - "shortName": "suggest_conversation_summary" - }, - "description": "Sample for SuggestConversationSummary", - "file": "dialogflow_v2beta1_generated_conversations_suggest_conversation_summary_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "dialogflow_v2beta1_generated_Conversations_SuggestConversationSummary_async", - "segments": [ - { - "end": 51, - "start": 27, - "type": "FULL" - }, - { - "end": 51, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 48, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 52, - "start": 49, - "type": "RESPONSE_HANDLING" - } - ], - "title": "dialogflow_v2beta1_generated_conversations_suggest_conversation_summary_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.dialogflow_v2beta1.ConversationsClient", - "shortName": "ConversationsClient" - }, - "fullName": "google.cloud.dialogflow_v2beta1.ConversationsClient.suggest_conversation_summary", - "method": { - "fullName": "google.cloud.dialogflow.v2beta1.Conversations.SuggestConversationSummary", - "service": { - "fullName": "google.cloud.dialogflow.v2beta1.Conversations", - "shortName": "Conversations" - }, - "shortName": "SuggestConversationSummary" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.dialogflow_v2beta1.types.SuggestConversationSummaryRequest" - }, - { - "name": "conversation", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.dialogflow_v2beta1.types.SuggestConversationSummaryResponse", - "shortName": "suggest_conversation_summary" - }, - "description": "Sample for SuggestConversationSummary", - "file": "dialogflow_v2beta1_generated_conversations_suggest_conversation_summary_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "dialogflow_v2beta1_generated_Conversations_SuggestConversationSummary_sync", - "segments": [ - { - "end": 51, - "start": 27, - "type": "FULL" - }, - { - "end": 51, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 48, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 52, - "start": 49, - "type": "RESPONSE_HANDLING" - } - ], - "title": "dialogflow_v2beta1_generated_conversations_suggest_conversation_summary_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.dialogflow_v2beta1.DocumentsAsyncClient", - "shortName": "DocumentsAsyncClient" - }, - "fullName": "google.cloud.dialogflow_v2beta1.DocumentsAsyncClient.create_document", - "method": { - "fullName": "google.cloud.dialogflow.v2beta1.Documents.CreateDocument", - "service": { - "fullName": "google.cloud.dialogflow.v2beta1.Documents", - "shortName": "Documents" - }, - "shortName": "CreateDocument" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.dialogflow_v2beta1.types.CreateDocumentRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "document", - "type": "google.cloud.dialogflow_v2beta1.types.Document" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.api_core.operation_async.AsyncOperation", - "shortName": "create_document" - }, - "description": "Sample for CreateDocument", - "file": "dialogflow_v2beta1_generated_documents_create_document_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "dialogflow_v2beta1_generated_Documents_CreateDocument_async", - "segments": [ - { - "end": 62, - "start": 27, - "type": "FULL" - }, - { - "end": 62, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 52, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 59, - "start": 53, - "type": "REQUEST_EXECUTION" - }, - { - "end": 63, - "start": 60, - "type": "RESPONSE_HANDLING" - } - ], - "title": "dialogflow_v2beta1_generated_documents_create_document_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.dialogflow_v2beta1.DocumentsClient", - "shortName": "DocumentsClient" - }, - "fullName": "google.cloud.dialogflow_v2beta1.DocumentsClient.create_document", - "method": { - "fullName": "google.cloud.dialogflow.v2beta1.Documents.CreateDocument", - "service": { - "fullName": "google.cloud.dialogflow.v2beta1.Documents", - "shortName": "Documents" - }, - "shortName": "CreateDocument" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.dialogflow_v2beta1.types.CreateDocumentRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "document", - "type": "google.cloud.dialogflow_v2beta1.types.Document" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.api_core.operation.Operation", - "shortName": "create_document" - }, - "description": "Sample for CreateDocument", - "file": "dialogflow_v2beta1_generated_documents_create_document_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "dialogflow_v2beta1_generated_Documents_CreateDocument_sync", - "segments": [ - { - "end": 62, - "start": 27, - "type": "FULL" - }, - { - "end": 62, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 52, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 59, - "start": 53, - "type": "REQUEST_EXECUTION" - }, - { - "end": 63, - "start": 60, - "type": "RESPONSE_HANDLING" - } - ], - "title": "dialogflow_v2beta1_generated_documents_create_document_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.dialogflow_v2beta1.DocumentsAsyncClient", - "shortName": "DocumentsAsyncClient" - }, - "fullName": "google.cloud.dialogflow_v2beta1.DocumentsAsyncClient.delete_document", - "method": { - "fullName": "google.cloud.dialogflow.v2beta1.Documents.DeleteDocument", - "service": { - "fullName": "google.cloud.dialogflow.v2beta1.Documents", - "shortName": "Documents" - }, - "shortName": "DeleteDocument" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.dialogflow_v2beta1.types.DeleteDocumentRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.api_core.operation_async.AsyncOperation", - "shortName": "delete_document" - }, - "description": "Sample for DeleteDocument", - "file": "dialogflow_v2beta1_generated_documents_delete_document_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "dialogflow_v2beta1_generated_Documents_DeleteDocument_async", - "segments": [ - { - "end": 55, - "start": 27, - "type": "FULL" - }, - { - "end": 55, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 52, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 56, - "start": 53, - "type": "RESPONSE_HANDLING" - } - ], - "title": "dialogflow_v2beta1_generated_documents_delete_document_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.dialogflow_v2beta1.DocumentsClient", - "shortName": "DocumentsClient" - }, - "fullName": "google.cloud.dialogflow_v2beta1.DocumentsClient.delete_document", - "method": { - "fullName": "google.cloud.dialogflow.v2beta1.Documents.DeleteDocument", - "service": { - "fullName": "google.cloud.dialogflow.v2beta1.Documents", - "shortName": "Documents" - }, - "shortName": "DeleteDocument" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.dialogflow_v2beta1.types.DeleteDocumentRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.api_core.operation.Operation", - "shortName": "delete_document" - }, - "description": "Sample for DeleteDocument", - "file": "dialogflow_v2beta1_generated_documents_delete_document_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "dialogflow_v2beta1_generated_Documents_DeleteDocument_sync", - "segments": [ - { - "end": 55, - "start": 27, - "type": "FULL" - }, - { - "end": 55, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 52, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 56, - "start": 53, - "type": "RESPONSE_HANDLING" - } - ], - "title": "dialogflow_v2beta1_generated_documents_delete_document_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.dialogflow_v2beta1.DocumentsAsyncClient", - "shortName": "DocumentsAsyncClient" - }, - "fullName": "google.cloud.dialogflow_v2beta1.DocumentsAsyncClient.get_document", - "method": { - "fullName": "google.cloud.dialogflow.v2beta1.Documents.GetDocument", - "service": { - "fullName": "google.cloud.dialogflow.v2beta1.Documents", - "shortName": "Documents" - }, - "shortName": "GetDocument" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.dialogflow_v2beta1.types.GetDocumentRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.dialogflow_v2beta1.types.Document", - "shortName": "get_document" - }, - "description": "Sample for GetDocument", - "file": "dialogflow_v2beta1_generated_documents_get_document_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "dialogflow_v2beta1_generated_Documents_GetDocument_async", - "segments": [ - { - "end": 51, - "start": 27, - "type": "FULL" - }, - { - "end": 51, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 48, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 52, - "start": 49, - "type": "RESPONSE_HANDLING" - } - ], - "title": "dialogflow_v2beta1_generated_documents_get_document_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.dialogflow_v2beta1.DocumentsClient", - "shortName": "DocumentsClient" - }, - "fullName": "google.cloud.dialogflow_v2beta1.DocumentsClient.get_document", - "method": { - "fullName": "google.cloud.dialogflow.v2beta1.Documents.GetDocument", - "service": { - "fullName": "google.cloud.dialogflow.v2beta1.Documents", - "shortName": "Documents" - }, - "shortName": "GetDocument" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.dialogflow_v2beta1.types.GetDocumentRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.dialogflow_v2beta1.types.Document", - "shortName": "get_document" - }, - "description": "Sample for GetDocument", - "file": "dialogflow_v2beta1_generated_documents_get_document_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "dialogflow_v2beta1_generated_Documents_GetDocument_sync", - "segments": [ - { - "end": 51, - "start": 27, - "type": "FULL" - }, - { - "end": 51, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 48, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 52, - "start": 49, - "type": "RESPONSE_HANDLING" - } - ], - "title": "dialogflow_v2beta1_generated_documents_get_document_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.dialogflow_v2beta1.DocumentsAsyncClient", - "shortName": "DocumentsAsyncClient" - }, - "fullName": "google.cloud.dialogflow_v2beta1.DocumentsAsyncClient.import_documents", - "method": { - "fullName": "google.cloud.dialogflow.v2beta1.Documents.ImportDocuments", - "service": { - "fullName": "google.cloud.dialogflow.v2beta1.Documents", - "shortName": "Documents" - }, - "shortName": "ImportDocuments" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.dialogflow_v2beta1.types.ImportDocumentsRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.api_core.operation_async.AsyncOperation", - "shortName": "import_documents" - }, - "description": "Sample for ImportDocuments", - "file": "dialogflow_v2beta1_generated_documents_import_documents_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "dialogflow_v2beta1_generated_Documents_ImportDocuments_async", - "segments": [ - { - "end": 64, - "start": 27, - "type": "FULL" - }, - { - "end": 64, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 54, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 61, - "start": 55, - "type": "REQUEST_EXECUTION" - }, - { - "end": 65, - "start": 62, - "type": "RESPONSE_HANDLING" - } - ], - "title": "dialogflow_v2beta1_generated_documents_import_documents_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.dialogflow_v2beta1.DocumentsClient", - "shortName": "DocumentsClient" - }, - "fullName": "google.cloud.dialogflow_v2beta1.DocumentsClient.import_documents", - "method": { - "fullName": "google.cloud.dialogflow.v2beta1.Documents.ImportDocuments", - "service": { - "fullName": "google.cloud.dialogflow.v2beta1.Documents", - "shortName": "Documents" - }, - "shortName": "ImportDocuments" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.dialogflow_v2beta1.types.ImportDocumentsRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.api_core.operation.Operation", - "shortName": "import_documents" - }, - "description": "Sample for ImportDocuments", - "file": "dialogflow_v2beta1_generated_documents_import_documents_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "dialogflow_v2beta1_generated_Documents_ImportDocuments_sync", - "segments": [ - { - "end": 64, - "start": 27, - "type": "FULL" - }, - { - "end": 64, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 54, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 61, - "start": 55, - "type": "REQUEST_EXECUTION" - }, - { - "end": 65, - "start": 62, - "type": "RESPONSE_HANDLING" - } - ], - "title": "dialogflow_v2beta1_generated_documents_import_documents_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.dialogflow_v2beta1.DocumentsAsyncClient", - "shortName": "DocumentsAsyncClient" - }, - "fullName": "google.cloud.dialogflow_v2beta1.DocumentsAsyncClient.list_documents", - "method": { - "fullName": "google.cloud.dialogflow.v2beta1.Documents.ListDocuments", - "service": { - "fullName": "google.cloud.dialogflow.v2beta1.Documents", - "shortName": "Documents" - }, - "shortName": "ListDocuments" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.dialogflow_v2beta1.types.ListDocumentsRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.dialogflow_v2beta1.services.documents.pagers.ListDocumentsAsyncPager", - "shortName": "list_documents" - }, - "description": "Sample for ListDocuments", - "file": "dialogflow_v2beta1_generated_documents_list_documents_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "dialogflow_v2beta1_generated_Documents_ListDocuments_async", - "segments": [ - { - "end": 52, - "start": 27, - "type": "FULL" - }, - { - "end": 52, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 48, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 53, - "start": 49, - "type": "RESPONSE_HANDLING" - } - ], - "title": "dialogflow_v2beta1_generated_documents_list_documents_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.dialogflow_v2beta1.DocumentsClient", - "shortName": "DocumentsClient" - }, - "fullName": "google.cloud.dialogflow_v2beta1.DocumentsClient.list_documents", - "method": { - "fullName": "google.cloud.dialogflow.v2beta1.Documents.ListDocuments", - "service": { - "fullName": "google.cloud.dialogflow.v2beta1.Documents", - "shortName": "Documents" - }, - "shortName": "ListDocuments" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.dialogflow_v2beta1.types.ListDocumentsRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.dialogflow_v2beta1.services.documents.pagers.ListDocumentsPager", - "shortName": "list_documents" - }, - "description": "Sample for ListDocuments", - "file": "dialogflow_v2beta1_generated_documents_list_documents_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "dialogflow_v2beta1_generated_Documents_ListDocuments_sync", - "segments": [ - { - "end": 52, - "start": 27, - "type": "FULL" - }, - { - "end": 52, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 48, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 53, - "start": 49, - "type": "RESPONSE_HANDLING" - } - ], - "title": "dialogflow_v2beta1_generated_documents_list_documents_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.dialogflow_v2beta1.DocumentsAsyncClient", - "shortName": "DocumentsAsyncClient" - }, - "fullName": "google.cloud.dialogflow_v2beta1.DocumentsAsyncClient.reload_document", - "method": { - "fullName": "google.cloud.dialogflow.v2beta1.Documents.ReloadDocument", - "service": { - "fullName": "google.cloud.dialogflow.v2beta1.Documents", - "shortName": "Documents" - }, - "shortName": "ReloadDocument" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.dialogflow_v2beta1.types.ReloadDocumentRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "gcs_source", - "type": "google.cloud.dialogflow_v2beta1.types.GcsSource" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.api_core.operation_async.AsyncOperation", - "shortName": "reload_document" - }, - "description": "Sample for ReloadDocument", - "file": "dialogflow_v2beta1_generated_documents_reload_document_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "dialogflow_v2beta1_generated_Documents_ReloadDocument_async", - "segments": [ - { - "end": 55, - "start": 27, - "type": "FULL" - }, - { - "end": 55, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 52, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 56, - "start": 53, - "type": "RESPONSE_HANDLING" - } - ], - "title": "dialogflow_v2beta1_generated_documents_reload_document_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.dialogflow_v2beta1.DocumentsClient", - "shortName": "DocumentsClient" - }, - "fullName": "google.cloud.dialogflow_v2beta1.DocumentsClient.reload_document", - "method": { - "fullName": "google.cloud.dialogflow.v2beta1.Documents.ReloadDocument", - "service": { - "fullName": "google.cloud.dialogflow.v2beta1.Documents", - "shortName": "Documents" - }, - "shortName": "ReloadDocument" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.dialogflow_v2beta1.types.ReloadDocumentRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "gcs_source", - "type": "google.cloud.dialogflow_v2beta1.types.GcsSource" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.api_core.operation.Operation", - "shortName": "reload_document" - }, - "description": "Sample for ReloadDocument", - "file": "dialogflow_v2beta1_generated_documents_reload_document_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "dialogflow_v2beta1_generated_Documents_ReloadDocument_sync", - "segments": [ - { - "end": 55, - "start": 27, - "type": "FULL" - }, - { - "end": 55, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 52, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 56, - "start": 53, - "type": "RESPONSE_HANDLING" - } - ], - "title": "dialogflow_v2beta1_generated_documents_reload_document_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.dialogflow_v2beta1.DocumentsAsyncClient", - "shortName": "DocumentsAsyncClient" - }, - "fullName": "google.cloud.dialogflow_v2beta1.DocumentsAsyncClient.update_document", - "method": { - "fullName": "google.cloud.dialogflow.v2beta1.Documents.UpdateDocument", - "service": { - "fullName": "google.cloud.dialogflow.v2beta1.Documents", - "shortName": "Documents" - }, - "shortName": "UpdateDocument" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.dialogflow_v2beta1.types.UpdateDocumentRequest" - }, - { - "name": "document", - "type": "google.cloud.dialogflow_v2beta1.types.Document" - }, - { - "name": "update_mask", - "type": "google.protobuf.field_mask_pb2.FieldMask" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.api_core.operation_async.AsyncOperation", - "shortName": "update_document" - }, - "description": "Sample for UpdateDocument", - "file": "dialogflow_v2beta1_generated_documents_update_document_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "dialogflow_v2beta1_generated_Documents_UpdateDocument_async", - "segments": [ - { - "end": 61, - "start": 27, - "type": "FULL" - }, - { - "end": 61, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 51, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 58, - "start": 52, - "type": "REQUEST_EXECUTION" - }, - { - "end": 62, - "start": 59, - "type": "RESPONSE_HANDLING" - } - ], - "title": "dialogflow_v2beta1_generated_documents_update_document_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.dialogflow_v2beta1.DocumentsClient", - "shortName": "DocumentsClient" - }, - "fullName": "google.cloud.dialogflow_v2beta1.DocumentsClient.update_document", - "method": { - "fullName": "google.cloud.dialogflow.v2beta1.Documents.UpdateDocument", - "service": { - "fullName": "google.cloud.dialogflow.v2beta1.Documents", - "shortName": "Documents" - }, - "shortName": "UpdateDocument" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.dialogflow_v2beta1.types.UpdateDocumentRequest" - }, - { - "name": "document", - "type": "google.cloud.dialogflow_v2beta1.types.Document" - }, - { - "name": "update_mask", - "type": "google.protobuf.field_mask_pb2.FieldMask" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.api_core.operation.Operation", - "shortName": "update_document" - }, - "description": "Sample for UpdateDocument", - "file": "dialogflow_v2beta1_generated_documents_update_document_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "dialogflow_v2beta1_generated_Documents_UpdateDocument_sync", - "segments": [ - { - "end": 61, - "start": 27, - "type": "FULL" - }, - { - "end": 61, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 51, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 58, - "start": 52, - "type": "REQUEST_EXECUTION" - }, - { - "end": 62, - "start": 59, - "type": "RESPONSE_HANDLING" - } - ], - "title": "dialogflow_v2beta1_generated_documents_update_document_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.dialogflow_v2beta1.EntityTypesAsyncClient", - "shortName": "EntityTypesAsyncClient" - }, - "fullName": "google.cloud.dialogflow_v2beta1.EntityTypesAsyncClient.batch_create_entities", - "method": { - "fullName": "google.cloud.dialogflow.v2beta1.EntityTypes.BatchCreateEntities", - "service": { - "fullName": "google.cloud.dialogflow.v2beta1.EntityTypes", - "shortName": "EntityTypes" - }, - "shortName": "BatchCreateEntities" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.dialogflow_v2beta1.types.BatchCreateEntitiesRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "entities", - "type": "MutableSequence[google.cloud.dialogflow_v2beta1.types.EntityType.Entity]" - }, - { - "name": "language_code", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.api_core.operation_async.AsyncOperation", - "shortName": "batch_create_entities" - }, - "description": "Sample for BatchCreateEntities", - "file": "dialogflow_v2beta1_generated_entity_types_batch_create_entities_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "dialogflow_v2beta1_generated_EntityTypes_BatchCreateEntities_async", - "segments": [ - { - "end": 59, - "start": 27, - "type": "FULL" - }, - { - "end": 59, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 49, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 56, - "start": 50, - "type": "REQUEST_EXECUTION" - }, - { - "end": 60, - "start": 57, - "type": "RESPONSE_HANDLING" - } - ], - "title": "dialogflow_v2beta1_generated_entity_types_batch_create_entities_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.dialogflow_v2beta1.EntityTypesClient", - "shortName": "EntityTypesClient" - }, - "fullName": "google.cloud.dialogflow_v2beta1.EntityTypesClient.batch_create_entities", - "method": { - "fullName": "google.cloud.dialogflow.v2beta1.EntityTypes.BatchCreateEntities", - "service": { - "fullName": "google.cloud.dialogflow.v2beta1.EntityTypes", - "shortName": "EntityTypes" - }, - "shortName": "BatchCreateEntities" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.dialogflow_v2beta1.types.BatchCreateEntitiesRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "entities", - "type": "MutableSequence[google.cloud.dialogflow_v2beta1.types.EntityType.Entity]" - }, - { - "name": "language_code", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.api_core.operation.Operation", - "shortName": "batch_create_entities" - }, - "description": "Sample for BatchCreateEntities", - "file": "dialogflow_v2beta1_generated_entity_types_batch_create_entities_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "dialogflow_v2beta1_generated_EntityTypes_BatchCreateEntities_sync", - "segments": [ - { - "end": 59, - "start": 27, - "type": "FULL" - }, - { - "end": 59, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 49, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 56, - "start": 50, - "type": "REQUEST_EXECUTION" - }, - { - "end": 60, - "start": 57, - "type": "RESPONSE_HANDLING" - } - ], - "title": "dialogflow_v2beta1_generated_entity_types_batch_create_entities_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.dialogflow_v2beta1.EntityTypesAsyncClient", - "shortName": "EntityTypesAsyncClient" - }, - "fullName": "google.cloud.dialogflow_v2beta1.EntityTypesAsyncClient.batch_delete_entities", - "method": { - "fullName": "google.cloud.dialogflow.v2beta1.EntityTypes.BatchDeleteEntities", - "service": { - "fullName": "google.cloud.dialogflow.v2beta1.EntityTypes", - "shortName": "EntityTypes" - }, - "shortName": "BatchDeleteEntities" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.dialogflow_v2beta1.types.BatchDeleteEntitiesRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "entity_values", - "type": "MutableSequence[str]" - }, - { - "name": "language_code", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.api_core.operation_async.AsyncOperation", - "shortName": "batch_delete_entities" - }, - "description": "Sample for BatchDeleteEntities", - "file": "dialogflow_v2beta1_generated_entity_types_batch_delete_entities_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "dialogflow_v2beta1_generated_EntityTypes_BatchDeleteEntities_async", - "segments": [ - { - "end": 56, - "start": 27, - "type": "FULL" - }, - { - "end": 56, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 46, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 53, - "start": 47, - "type": "REQUEST_EXECUTION" - }, - { - "end": 57, - "start": 54, - "type": "RESPONSE_HANDLING" - } - ], - "title": "dialogflow_v2beta1_generated_entity_types_batch_delete_entities_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.dialogflow_v2beta1.EntityTypesClient", - "shortName": "EntityTypesClient" - }, - "fullName": "google.cloud.dialogflow_v2beta1.EntityTypesClient.batch_delete_entities", - "method": { - "fullName": "google.cloud.dialogflow.v2beta1.EntityTypes.BatchDeleteEntities", - "service": { - "fullName": "google.cloud.dialogflow.v2beta1.EntityTypes", - "shortName": "EntityTypes" - }, - "shortName": "BatchDeleteEntities" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.dialogflow_v2beta1.types.BatchDeleteEntitiesRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "entity_values", - "type": "MutableSequence[str]" - }, - { - "name": "language_code", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.api_core.operation.Operation", - "shortName": "batch_delete_entities" - }, - "description": "Sample for BatchDeleteEntities", - "file": "dialogflow_v2beta1_generated_entity_types_batch_delete_entities_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "dialogflow_v2beta1_generated_EntityTypes_BatchDeleteEntities_sync", - "segments": [ - { - "end": 56, - "start": 27, - "type": "FULL" - }, - { - "end": 56, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 46, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 53, - "start": 47, - "type": "REQUEST_EXECUTION" - }, - { - "end": 57, - "start": 54, - "type": "RESPONSE_HANDLING" - } - ], - "title": "dialogflow_v2beta1_generated_entity_types_batch_delete_entities_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.dialogflow_v2beta1.EntityTypesAsyncClient", - "shortName": "EntityTypesAsyncClient" - }, - "fullName": "google.cloud.dialogflow_v2beta1.EntityTypesAsyncClient.batch_delete_entity_types", - "method": { - "fullName": "google.cloud.dialogflow.v2beta1.EntityTypes.BatchDeleteEntityTypes", - "service": { - "fullName": "google.cloud.dialogflow.v2beta1.EntityTypes", - "shortName": "EntityTypes" - }, - "shortName": "BatchDeleteEntityTypes" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.dialogflow_v2beta1.types.BatchDeleteEntityTypesRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "entity_type_names", - "type": "MutableSequence[str]" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.api_core.operation_async.AsyncOperation", - "shortName": "batch_delete_entity_types" - }, - "description": "Sample for BatchDeleteEntityTypes", - "file": "dialogflow_v2beta1_generated_entity_types_batch_delete_entity_types_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "dialogflow_v2beta1_generated_EntityTypes_BatchDeleteEntityTypes_async", - "segments": [ - { - "end": 56, - "start": 27, - "type": "FULL" - }, - { - "end": 56, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 46, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 53, - "start": 47, - "type": "REQUEST_EXECUTION" - }, - { - "end": 57, - "start": 54, - "type": "RESPONSE_HANDLING" - } - ], - "title": "dialogflow_v2beta1_generated_entity_types_batch_delete_entity_types_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.dialogflow_v2beta1.EntityTypesClient", - "shortName": "EntityTypesClient" - }, - "fullName": "google.cloud.dialogflow_v2beta1.EntityTypesClient.batch_delete_entity_types", - "method": { - "fullName": "google.cloud.dialogflow.v2beta1.EntityTypes.BatchDeleteEntityTypes", - "service": { - "fullName": "google.cloud.dialogflow.v2beta1.EntityTypes", - "shortName": "EntityTypes" - }, - "shortName": "BatchDeleteEntityTypes" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.dialogflow_v2beta1.types.BatchDeleteEntityTypesRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "entity_type_names", - "type": "MutableSequence[str]" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.api_core.operation.Operation", - "shortName": "batch_delete_entity_types" - }, - "description": "Sample for BatchDeleteEntityTypes", - "file": "dialogflow_v2beta1_generated_entity_types_batch_delete_entity_types_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "dialogflow_v2beta1_generated_EntityTypes_BatchDeleteEntityTypes_sync", - "segments": [ - { - "end": 56, - "start": 27, - "type": "FULL" - }, - { - "end": 56, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 46, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 53, - "start": 47, - "type": "REQUEST_EXECUTION" - }, - { - "end": 57, - "start": 54, - "type": "RESPONSE_HANDLING" - } - ], - "title": "dialogflow_v2beta1_generated_entity_types_batch_delete_entity_types_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.dialogflow_v2beta1.EntityTypesAsyncClient", - "shortName": "EntityTypesAsyncClient" - }, - "fullName": "google.cloud.dialogflow_v2beta1.EntityTypesAsyncClient.batch_update_entities", - "method": { - "fullName": "google.cloud.dialogflow.v2beta1.EntityTypes.BatchUpdateEntities", - "service": { - "fullName": "google.cloud.dialogflow.v2beta1.EntityTypes", - "shortName": "EntityTypes" - }, - "shortName": "BatchUpdateEntities" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.dialogflow_v2beta1.types.BatchUpdateEntitiesRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "entities", - "type": "MutableSequence[google.cloud.dialogflow_v2beta1.types.EntityType.Entity]" - }, - { - "name": "language_code", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.api_core.operation_async.AsyncOperation", - "shortName": "batch_update_entities" - }, - "description": "Sample for BatchUpdateEntities", - "file": "dialogflow_v2beta1_generated_entity_types_batch_update_entities_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "dialogflow_v2beta1_generated_EntityTypes_BatchUpdateEntities_async", - "segments": [ - { - "end": 59, - "start": 27, - "type": "FULL" - }, - { - "end": 59, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 49, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 56, - "start": 50, - "type": "REQUEST_EXECUTION" - }, - { - "end": 60, - "start": 57, - "type": "RESPONSE_HANDLING" - } - ], - "title": "dialogflow_v2beta1_generated_entity_types_batch_update_entities_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.dialogflow_v2beta1.EntityTypesClient", - "shortName": "EntityTypesClient" - }, - "fullName": "google.cloud.dialogflow_v2beta1.EntityTypesClient.batch_update_entities", - "method": { - "fullName": "google.cloud.dialogflow.v2beta1.EntityTypes.BatchUpdateEntities", - "service": { - "fullName": "google.cloud.dialogflow.v2beta1.EntityTypes", - "shortName": "EntityTypes" - }, - "shortName": "BatchUpdateEntities" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.dialogflow_v2beta1.types.BatchUpdateEntitiesRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "entities", - "type": "MutableSequence[google.cloud.dialogflow_v2beta1.types.EntityType.Entity]" - }, - { - "name": "language_code", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.api_core.operation.Operation", - "shortName": "batch_update_entities" - }, - "description": "Sample for BatchUpdateEntities", - "file": "dialogflow_v2beta1_generated_entity_types_batch_update_entities_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "dialogflow_v2beta1_generated_EntityTypes_BatchUpdateEntities_sync", - "segments": [ - { - "end": 59, - "start": 27, - "type": "FULL" - }, - { - "end": 59, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 49, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 56, - "start": 50, - "type": "REQUEST_EXECUTION" - }, - { - "end": 60, - "start": 57, - "type": "RESPONSE_HANDLING" - } - ], - "title": "dialogflow_v2beta1_generated_entity_types_batch_update_entities_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.dialogflow_v2beta1.EntityTypesAsyncClient", - "shortName": "EntityTypesAsyncClient" - }, - "fullName": "google.cloud.dialogflow_v2beta1.EntityTypesAsyncClient.batch_update_entity_types", - "method": { - "fullName": "google.cloud.dialogflow.v2beta1.EntityTypes.BatchUpdateEntityTypes", - "service": { - "fullName": "google.cloud.dialogflow.v2beta1.EntityTypes", - "shortName": "EntityTypes" - }, - "shortName": "BatchUpdateEntityTypes" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.dialogflow_v2beta1.types.BatchUpdateEntityTypesRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.api_core.operation_async.AsyncOperation", - "shortName": "batch_update_entity_types" - }, - "description": "Sample for BatchUpdateEntityTypes", - "file": "dialogflow_v2beta1_generated_entity_types_batch_update_entity_types_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "dialogflow_v2beta1_generated_EntityTypes_BatchUpdateEntityTypes_async", - "segments": [ - { - "end": 56, - "start": 27, - "type": "FULL" - }, - { - "end": 56, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 46, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 53, - "start": 47, - "type": "REQUEST_EXECUTION" - }, - { - "end": 57, - "start": 54, - "type": "RESPONSE_HANDLING" - } - ], - "title": "dialogflow_v2beta1_generated_entity_types_batch_update_entity_types_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.dialogflow_v2beta1.EntityTypesClient", - "shortName": "EntityTypesClient" - }, - "fullName": "google.cloud.dialogflow_v2beta1.EntityTypesClient.batch_update_entity_types", - "method": { - "fullName": "google.cloud.dialogflow.v2beta1.EntityTypes.BatchUpdateEntityTypes", - "service": { - "fullName": "google.cloud.dialogflow.v2beta1.EntityTypes", - "shortName": "EntityTypes" - }, - "shortName": "BatchUpdateEntityTypes" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.dialogflow_v2beta1.types.BatchUpdateEntityTypesRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.api_core.operation.Operation", - "shortName": "batch_update_entity_types" - }, - "description": "Sample for BatchUpdateEntityTypes", - "file": "dialogflow_v2beta1_generated_entity_types_batch_update_entity_types_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "dialogflow_v2beta1_generated_EntityTypes_BatchUpdateEntityTypes_sync", - "segments": [ - { - "end": 56, - "start": 27, - "type": "FULL" - }, - { - "end": 56, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 46, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 53, - "start": 47, - "type": "REQUEST_EXECUTION" - }, - { - "end": 57, - "start": 54, - "type": "RESPONSE_HANDLING" - } - ], - "title": "dialogflow_v2beta1_generated_entity_types_batch_update_entity_types_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.dialogflow_v2beta1.EntityTypesAsyncClient", - "shortName": "EntityTypesAsyncClient" - }, - "fullName": "google.cloud.dialogflow_v2beta1.EntityTypesAsyncClient.create_entity_type", - "method": { - "fullName": "google.cloud.dialogflow.v2beta1.EntityTypes.CreateEntityType", - "service": { - "fullName": "google.cloud.dialogflow.v2beta1.EntityTypes", - "shortName": "EntityTypes" - }, - "shortName": "CreateEntityType" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.dialogflow_v2beta1.types.CreateEntityTypeRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "entity_type", - "type": "google.cloud.dialogflow_v2beta1.types.EntityType" - }, - { - "name": "language_code", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.dialogflow_v2beta1.types.EntityType", - "shortName": "create_entity_type" - }, - "description": "Sample for CreateEntityType", - "file": "dialogflow_v2beta1_generated_entity_types_create_entity_type_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "dialogflow_v2beta1_generated_EntityTypes_CreateEntityType_async", - "segments": [ - { - "end": 56, - "start": 27, - "type": "FULL" - }, - { - "end": 56, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 50, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 53, - "start": 51, - "type": "REQUEST_EXECUTION" - }, - { - "end": 57, - "start": 54, - "type": "RESPONSE_HANDLING" - } - ], - "title": "dialogflow_v2beta1_generated_entity_types_create_entity_type_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.dialogflow_v2beta1.EntityTypesClient", - "shortName": "EntityTypesClient" - }, - "fullName": "google.cloud.dialogflow_v2beta1.EntityTypesClient.create_entity_type", - "method": { - "fullName": "google.cloud.dialogflow.v2beta1.EntityTypes.CreateEntityType", - "service": { - "fullName": "google.cloud.dialogflow.v2beta1.EntityTypes", - "shortName": "EntityTypes" - }, - "shortName": "CreateEntityType" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.dialogflow_v2beta1.types.CreateEntityTypeRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "entity_type", - "type": "google.cloud.dialogflow_v2beta1.types.EntityType" - }, - { - "name": "language_code", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.dialogflow_v2beta1.types.EntityType", - "shortName": "create_entity_type" - }, - "description": "Sample for CreateEntityType", - "file": "dialogflow_v2beta1_generated_entity_types_create_entity_type_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "dialogflow_v2beta1_generated_EntityTypes_CreateEntityType_sync", - "segments": [ - { - "end": 56, - "start": 27, - "type": "FULL" - }, - { - "end": 56, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 50, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 53, - "start": 51, - "type": "REQUEST_EXECUTION" - }, - { - "end": 57, - "start": 54, - "type": "RESPONSE_HANDLING" - } - ], - "title": "dialogflow_v2beta1_generated_entity_types_create_entity_type_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.dialogflow_v2beta1.EntityTypesAsyncClient", - "shortName": "EntityTypesAsyncClient" - }, - "fullName": "google.cloud.dialogflow_v2beta1.EntityTypesAsyncClient.delete_entity_type", - "method": { - "fullName": "google.cloud.dialogflow.v2beta1.EntityTypes.DeleteEntityType", - "service": { - "fullName": "google.cloud.dialogflow.v2beta1.EntityTypes", - "shortName": "EntityTypes" - }, - "shortName": "DeleteEntityType" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.dialogflow_v2beta1.types.DeleteEntityTypeRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "shortName": "delete_entity_type" - }, - "description": "Sample for DeleteEntityType", - "file": "dialogflow_v2beta1_generated_entity_types_delete_entity_type_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "dialogflow_v2beta1_generated_EntityTypes_DeleteEntityType_async", - "segments": [ - { - "end": 49, - "start": 27, - "type": "FULL" - }, - { - "end": 49, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 50, - "type": "RESPONSE_HANDLING" - } - ], - "title": "dialogflow_v2beta1_generated_entity_types_delete_entity_type_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.dialogflow_v2beta1.EntityTypesClient", - "shortName": "EntityTypesClient" - }, - "fullName": "google.cloud.dialogflow_v2beta1.EntityTypesClient.delete_entity_type", - "method": { - "fullName": "google.cloud.dialogflow.v2beta1.EntityTypes.DeleteEntityType", - "service": { - "fullName": "google.cloud.dialogflow.v2beta1.EntityTypes", - "shortName": "EntityTypes" - }, - "shortName": "DeleteEntityType" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.dialogflow_v2beta1.types.DeleteEntityTypeRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "shortName": "delete_entity_type" - }, - "description": "Sample for DeleteEntityType", - "file": "dialogflow_v2beta1_generated_entity_types_delete_entity_type_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "dialogflow_v2beta1_generated_EntityTypes_DeleteEntityType_sync", - "segments": [ - { - "end": 49, - "start": 27, - "type": "FULL" - }, - { - "end": 49, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 50, - "type": "RESPONSE_HANDLING" - } - ], - "title": "dialogflow_v2beta1_generated_entity_types_delete_entity_type_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.dialogflow_v2beta1.EntityTypesAsyncClient", - "shortName": "EntityTypesAsyncClient" - }, - "fullName": "google.cloud.dialogflow_v2beta1.EntityTypesAsyncClient.get_entity_type", - "method": { - "fullName": "google.cloud.dialogflow.v2beta1.EntityTypes.GetEntityType", - "service": { - "fullName": "google.cloud.dialogflow.v2beta1.EntityTypes", - "shortName": "EntityTypes" - }, - "shortName": "GetEntityType" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.dialogflow_v2beta1.types.GetEntityTypeRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "language_code", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.dialogflow_v2beta1.types.EntityType", - "shortName": "get_entity_type" - }, - "description": "Sample for GetEntityType", - "file": "dialogflow_v2beta1_generated_entity_types_get_entity_type_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "dialogflow_v2beta1_generated_EntityTypes_GetEntityType_async", - "segments": [ - { - "end": 51, - "start": 27, - "type": "FULL" - }, - { - "end": 51, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 48, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 52, - "start": 49, - "type": "RESPONSE_HANDLING" - } - ], - "title": "dialogflow_v2beta1_generated_entity_types_get_entity_type_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.dialogflow_v2beta1.EntityTypesClient", - "shortName": "EntityTypesClient" - }, - "fullName": "google.cloud.dialogflow_v2beta1.EntityTypesClient.get_entity_type", - "method": { - "fullName": "google.cloud.dialogflow.v2beta1.EntityTypes.GetEntityType", - "service": { - "fullName": "google.cloud.dialogflow.v2beta1.EntityTypes", - "shortName": "EntityTypes" - }, - "shortName": "GetEntityType" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.dialogflow_v2beta1.types.GetEntityTypeRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "language_code", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.dialogflow_v2beta1.types.EntityType", - "shortName": "get_entity_type" - }, - "description": "Sample for GetEntityType", - "file": "dialogflow_v2beta1_generated_entity_types_get_entity_type_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "dialogflow_v2beta1_generated_EntityTypes_GetEntityType_sync", - "segments": [ - { - "end": 51, - "start": 27, - "type": "FULL" - }, - { - "end": 51, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 48, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 52, - "start": 49, - "type": "RESPONSE_HANDLING" - } - ], - "title": "dialogflow_v2beta1_generated_entity_types_get_entity_type_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.dialogflow_v2beta1.EntityTypesAsyncClient", - "shortName": "EntityTypesAsyncClient" - }, - "fullName": "google.cloud.dialogflow_v2beta1.EntityTypesAsyncClient.list_entity_types", - "method": { - "fullName": "google.cloud.dialogflow.v2beta1.EntityTypes.ListEntityTypes", - "service": { - "fullName": "google.cloud.dialogflow.v2beta1.EntityTypes", - "shortName": "EntityTypes" - }, - "shortName": "ListEntityTypes" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.dialogflow_v2beta1.types.ListEntityTypesRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "language_code", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.dialogflow_v2beta1.services.entity_types.pagers.ListEntityTypesAsyncPager", - "shortName": "list_entity_types" - }, - "description": "Sample for ListEntityTypes", - "file": "dialogflow_v2beta1_generated_entity_types_list_entity_types_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "dialogflow_v2beta1_generated_EntityTypes_ListEntityTypes_async", - "segments": [ - { - "end": 52, - "start": 27, - "type": "FULL" - }, - { - "end": 52, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 48, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 53, - "start": 49, - "type": "RESPONSE_HANDLING" - } - ], - "title": "dialogflow_v2beta1_generated_entity_types_list_entity_types_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.dialogflow_v2beta1.EntityTypesClient", - "shortName": "EntityTypesClient" - }, - "fullName": "google.cloud.dialogflow_v2beta1.EntityTypesClient.list_entity_types", - "method": { - "fullName": "google.cloud.dialogflow.v2beta1.EntityTypes.ListEntityTypes", - "service": { - "fullName": "google.cloud.dialogflow.v2beta1.EntityTypes", - "shortName": "EntityTypes" - }, - "shortName": "ListEntityTypes" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.dialogflow_v2beta1.types.ListEntityTypesRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "language_code", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.dialogflow_v2beta1.services.entity_types.pagers.ListEntityTypesPager", - "shortName": "list_entity_types" - }, - "description": "Sample for ListEntityTypes", - "file": "dialogflow_v2beta1_generated_entity_types_list_entity_types_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "dialogflow_v2beta1_generated_EntityTypes_ListEntityTypes_sync", - "segments": [ - { - "end": 52, - "start": 27, - "type": "FULL" - }, - { - "end": 52, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 48, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 53, - "start": 49, - "type": "RESPONSE_HANDLING" - } - ], - "title": "dialogflow_v2beta1_generated_entity_types_list_entity_types_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.dialogflow_v2beta1.EntityTypesAsyncClient", - "shortName": "EntityTypesAsyncClient" - }, - "fullName": "google.cloud.dialogflow_v2beta1.EntityTypesAsyncClient.update_entity_type", - "method": { - "fullName": "google.cloud.dialogflow.v2beta1.EntityTypes.UpdateEntityType", - "service": { - "fullName": "google.cloud.dialogflow.v2beta1.EntityTypes", - "shortName": "EntityTypes" - }, - "shortName": "UpdateEntityType" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.dialogflow_v2beta1.types.UpdateEntityTypeRequest" - }, - { - "name": "entity_type", - "type": "google.cloud.dialogflow_v2beta1.types.EntityType" - }, - { - "name": "language_code", - "type": "str" - }, - { - "name": "update_mask", - "type": "google.protobuf.field_mask_pb2.FieldMask" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.dialogflow_v2beta1.types.EntityType", - "shortName": "update_entity_type" - }, - "description": "Sample for UpdateEntityType", - "file": "dialogflow_v2beta1_generated_entity_types_update_entity_type_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "dialogflow_v2beta1_generated_EntityTypes_UpdateEntityType_async", - "segments": [ - { - "end": 55, - "start": 27, - "type": "FULL" - }, - { - "end": 55, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 49, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 52, - "start": 50, - "type": "REQUEST_EXECUTION" - }, - { - "end": 56, - "start": 53, - "type": "RESPONSE_HANDLING" - } - ], - "title": "dialogflow_v2beta1_generated_entity_types_update_entity_type_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.dialogflow_v2beta1.EntityTypesClient", - "shortName": "EntityTypesClient" - }, - "fullName": "google.cloud.dialogflow_v2beta1.EntityTypesClient.update_entity_type", - "method": { - "fullName": "google.cloud.dialogflow.v2beta1.EntityTypes.UpdateEntityType", - "service": { - "fullName": "google.cloud.dialogflow.v2beta1.EntityTypes", - "shortName": "EntityTypes" - }, - "shortName": "UpdateEntityType" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.dialogflow_v2beta1.types.UpdateEntityTypeRequest" - }, - { - "name": "entity_type", - "type": "google.cloud.dialogflow_v2beta1.types.EntityType" - }, - { - "name": "language_code", - "type": "str" - }, - { - "name": "update_mask", - "type": "google.protobuf.field_mask_pb2.FieldMask" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.dialogflow_v2beta1.types.EntityType", - "shortName": "update_entity_type" - }, - "description": "Sample for UpdateEntityType", - "file": "dialogflow_v2beta1_generated_entity_types_update_entity_type_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "dialogflow_v2beta1_generated_EntityTypes_UpdateEntityType_sync", - "segments": [ - { - "end": 55, - "start": 27, - "type": "FULL" - }, - { - "end": 55, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 49, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 52, - "start": 50, - "type": "REQUEST_EXECUTION" - }, - { - "end": 56, - "start": 53, - "type": "RESPONSE_HANDLING" - } - ], - "title": "dialogflow_v2beta1_generated_entity_types_update_entity_type_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.dialogflow_v2beta1.EnvironmentsAsyncClient", - "shortName": "EnvironmentsAsyncClient" - }, - "fullName": "google.cloud.dialogflow_v2beta1.EnvironmentsAsyncClient.create_environment", - "method": { - "fullName": "google.cloud.dialogflow.v2beta1.Environments.CreateEnvironment", - "service": { - "fullName": "google.cloud.dialogflow.v2beta1.Environments", - "shortName": "Environments" - }, - "shortName": "CreateEnvironment" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.dialogflow_v2beta1.types.CreateEnvironmentRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.dialogflow_v2beta1.types.Environment", - "shortName": "create_environment" - }, - "description": "Sample for CreateEnvironment", - "file": "dialogflow_v2beta1_generated_environments_create_environment_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "dialogflow_v2beta1_generated_Environments_CreateEnvironment_async", - "segments": [ - { - "end": 52, - "start": 27, - "type": "FULL" - }, - { - "end": 52, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 46, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 49, - "start": 47, - "type": "REQUEST_EXECUTION" - }, - { - "end": 53, - "start": 50, - "type": "RESPONSE_HANDLING" - } - ], - "title": "dialogflow_v2beta1_generated_environments_create_environment_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.dialogflow_v2beta1.EnvironmentsClient", - "shortName": "EnvironmentsClient" - }, - "fullName": "google.cloud.dialogflow_v2beta1.EnvironmentsClient.create_environment", - "method": { - "fullName": "google.cloud.dialogflow.v2beta1.Environments.CreateEnvironment", - "service": { - "fullName": "google.cloud.dialogflow.v2beta1.Environments", - "shortName": "Environments" - }, - "shortName": "CreateEnvironment" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.dialogflow_v2beta1.types.CreateEnvironmentRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.dialogflow_v2beta1.types.Environment", - "shortName": "create_environment" - }, - "description": "Sample for CreateEnvironment", - "file": "dialogflow_v2beta1_generated_environments_create_environment_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "dialogflow_v2beta1_generated_Environments_CreateEnvironment_sync", - "segments": [ - { - "end": 52, - "start": 27, - "type": "FULL" - }, - { - "end": 52, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 46, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 49, - "start": 47, - "type": "REQUEST_EXECUTION" - }, - { - "end": 53, - "start": 50, - "type": "RESPONSE_HANDLING" - } - ], - "title": "dialogflow_v2beta1_generated_environments_create_environment_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.dialogflow_v2beta1.EnvironmentsAsyncClient", - "shortName": "EnvironmentsAsyncClient" - }, - "fullName": "google.cloud.dialogflow_v2beta1.EnvironmentsAsyncClient.delete_environment", - "method": { - "fullName": "google.cloud.dialogflow.v2beta1.Environments.DeleteEnvironment", - "service": { - "fullName": "google.cloud.dialogflow.v2beta1.Environments", - "shortName": "Environments" - }, - "shortName": "DeleteEnvironment" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.dialogflow_v2beta1.types.DeleteEnvironmentRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "shortName": "delete_environment" - }, - "description": "Sample for DeleteEnvironment", - "file": "dialogflow_v2beta1_generated_environments_delete_environment_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "dialogflow_v2beta1_generated_Environments_DeleteEnvironment_async", - "segments": [ - { - "end": 49, - "start": 27, - "type": "FULL" - }, - { - "end": 49, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 50, - "type": "RESPONSE_HANDLING" - } - ], - "title": "dialogflow_v2beta1_generated_environments_delete_environment_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.dialogflow_v2beta1.EnvironmentsClient", - "shortName": "EnvironmentsClient" - }, - "fullName": "google.cloud.dialogflow_v2beta1.EnvironmentsClient.delete_environment", - "method": { - "fullName": "google.cloud.dialogflow.v2beta1.Environments.DeleteEnvironment", - "service": { - "fullName": "google.cloud.dialogflow.v2beta1.Environments", - "shortName": "Environments" - }, - "shortName": "DeleteEnvironment" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.dialogflow_v2beta1.types.DeleteEnvironmentRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "shortName": "delete_environment" - }, - "description": "Sample for DeleteEnvironment", - "file": "dialogflow_v2beta1_generated_environments_delete_environment_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "dialogflow_v2beta1_generated_Environments_DeleteEnvironment_sync", - "segments": [ - { - "end": 49, - "start": 27, - "type": "FULL" - }, - { - "end": 49, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 50, - "type": "RESPONSE_HANDLING" - } - ], - "title": "dialogflow_v2beta1_generated_environments_delete_environment_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.dialogflow_v2beta1.EnvironmentsAsyncClient", - "shortName": "EnvironmentsAsyncClient" - }, - "fullName": "google.cloud.dialogflow_v2beta1.EnvironmentsAsyncClient.get_environment_history", - "method": { - "fullName": "google.cloud.dialogflow.v2beta1.Environments.GetEnvironmentHistory", - "service": { - "fullName": "google.cloud.dialogflow.v2beta1.Environments", - "shortName": "Environments" - }, - "shortName": "GetEnvironmentHistory" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.dialogflow_v2beta1.types.GetEnvironmentHistoryRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.dialogflow_v2beta1.services.environments.pagers.GetEnvironmentHistoryAsyncPager", - "shortName": "get_environment_history" - }, - "description": "Sample for GetEnvironmentHistory", - "file": "dialogflow_v2beta1_generated_environments_get_environment_history_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "dialogflow_v2beta1_generated_Environments_GetEnvironmentHistory_async", - "segments": [ - { - "end": 52, - "start": 27, - "type": "FULL" - }, - { - "end": 52, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 48, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 53, - "start": 49, - "type": "RESPONSE_HANDLING" - } - ], - "title": "dialogflow_v2beta1_generated_environments_get_environment_history_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.dialogflow_v2beta1.EnvironmentsClient", - "shortName": "EnvironmentsClient" - }, - "fullName": "google.cloud.dialogflow_v2beta1.EnvironmentsClient.get_environment_history", - "method": { - "fullName": "google.cloud.dialogflow.v2beta1.Environments.GetEnvironmentHistory", - "service": { - "fullName": "google.cloud.dialogflow.v2beta1.Environments", - "shortName": "Environments" - }, - "shortName": "GetEnvironmentHistory" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.dialogflow_v2beta1.types.GetEnvironmentHistoryRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.dialogflow_v2beta1.services.environments.pagers.GetEnvironmentHistoryPager", - "shortName": "get_environment_history" - }, - "description": "Sample for GetEnvironmentHistory", - "file": "dialogflow_v2beta1_generated_environments_get_environment_history_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "dialogflow_v2beta1_generated_Environments_GetEnvironmentHistory_sync", - "segments": [ - { - "end": 52, - "start": 27, - "type": "FULL" - }, - { - "end": 52, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 48, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 53, - "start": 49, - "type": "RESPONSE_HANDLING" - } - ], - "title": "dialogflow_v2beta1_generated_environments_get_environment_history_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.dialogflow_v2beta1.EnvironmentsAsyncClient", - "shortName": "EnvironmentsAsyncClient" - }, - "fullName": "google.cloud.dialogflow_v2beta1.EnvironmentsAsyncClient.get_environment", - "method": { - "fullName": "google.cloud.dialogflow.v2beta1.Environments.GetEnvironment", - "service": { - "fullName": "google.cloud.dialogflow.v2beta1.Environments", - "shortName": "Environments" - }, - "shortName": "GetEnvironment" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.dialogflow_v2beta1.types.GetEnvironmentRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.dialogflow_v2beta1.types.Environment", - "shortName": "get_environment" - }, - "description": "Sample for GetEnvironment", - "file": "dialogflow_v2beta1_generated_environments_get_environment_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "dialogflow_v2beta1_generated_Environments_GetEnvironment_async", - "segments": [ - { - "end": 51, - "start": 27, - "type": "FULL" - }, - { - "end": 51, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 48, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 52, - "start": 49, - "type": "RESPONSE_HANDLING" - } - ], - "title": "dialogflow_v2beta1_generated_environments_get_environment_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.dialogflow_v2beta1.EnvironmentsClient", - "shortName": "EnvironmentsClient" - }, - "fullName": "google.cloud.dialogflow_v2beta1.EnvironmentsClient.get_environment", - "method": { - "fullName": "google.cloud.dialogflow.v2beta1.Environments.GetEnvironment", - "service": { - "fullName": "google.cloud.dialogflow.v2beta1.Environments", - "shortName": "Environments" - }, - "shortName": "GetEnvironment" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.dialogflow_v2beta1.types.GetEnvironmentRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.dialogflow_v2beta1.types.Environment", - "shortName": "get_environment" - }, - "description": "Sample for GetEnvironment", - "file": "dialogflow_v2beta1_generated_environments_get_environment_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "dialogflow_v2beta1_generated_Environments_GetEnvironment_sync", - "segments": [ - { - "end": 51, - "start": 27, - "type": "FULL" - }, - { - "end": 51, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 48, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 52, - "start": 49, - "type": "RESPONSE_HANDLING" - } - ], - "title": "dialogflow_v2beta1_generated_environments_get_environment_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.dialogflow_v2beta1.EnvironmentsAsyncClient", - "shortName": "EnvironmentsAsyncClient" - }, - "fullName": "google.cloud.dialogflow_v2beta1.EnvironmentsAsyncClient.list_environments", - "method": { - "fullName": "google.cloud.dialogflow.v2beta1.Environments.ListEnvironments", - "service": { - "fullName": "google.cloud.dialogflow.v2beta1.Environments", - "shortName": "Environments" - }, - "shortName": "ListEnvironments" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.dialogflow_v2beta1.types.ListEnvironmentsRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.dialogflow_v2beta1.services.environments.pagers.ListEnvironmentsAsyncPager", - "shortName": "list_environments" - }, - "description": "Sample for ListEnvironments", - "file": "dialogflow_v2beta1_generated_environments_list_environments_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "dialogflow_v2beta1_generated_Environments_ListEnvironments_async", - "segments": [ - { - "end": 52, - "start": 27, - "type": "FULL" - }, - { - "end": 52, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 48, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 53, - "start": 49, - "type": "RESPONSE_HANDLING" - } - ], - "title": "dialogflow_v2beta1_generated_environments_list_environments_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.dialogflow_v2beta1.EnvironmentsClient", - "shortName": "EnvironmentsClient" - }, - "fullName": "google.cloud.dialogflow_v2beta1.EnvironmentsClient.list_environments", - "method": { - "fullName": "google.cloud.dialogflow.v2beta1.Environments.ListEnvironments", - "service": { - "fullName": "google.cloud.dialogflow.v2beta1.Environments", - "shortName": "Environments" - }, - "shortName": "ListEnvironments" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.dialogflow_v2beta1.types.ListEnvironmentsRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.dialogflow_v2beta1.services.environments.pagers.ListEnvironmentsPager", - "shortName": "list_environments" - }, - "description": "Sample for ListEnvironments", - "file": "dialogflow_v2beta1_generated_environments_list_environments_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "dialogflow_v2beta1_generated_Environments_ListEnvironments_sync", - "segments": [ - { - "end": 52, - "start": 27, - "type": "FULL" - }, - { - "end": 52, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 48, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 53, - "start": 49, - "type": "RESPONSE_HANDLING" - } - ], - "title": "dialogflow_v2beta1_generated_environments_list_environments_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.dialogflow_v2beta1.EnvironmentsAsyncClient", - "shortName": "EnvironmentsAsyncClient" - }, - "fullName": "google.cloud.dialogflow_v2beta1.EnvironmentsAsyncClient.update_environment", - "method": { - "fullName": "google.cloud.dialogflow.v2beta1.Environments.UpdateEnvironment", - "service": { - "fullName": "google.cloud.dialogflow.v2beta1.Environments", - "shortName": "Environments" - }, - "shortName": "UpdateEnvironment" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.dialogflow_v2beta1.types.UpdateEnvironmentRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.dialogflow_v2beta1.types.Environment", - "shortName": "update_environment" - }, - "description": "Sample for UpdateEnvironment", - "file": "dialogflow_v2beta1_generated_environments_update_environment_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "dialogflow_v2beta1_generated_Environments_UpdateEnvironment_async", - "segments": [ - { - "end": 50, - "start": 27, - "type": "FULL" - }, - { - "end": 50, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 44, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 47, - "start": 45, - "type": "REQUEST_EXECUTION" - }, - { - "end": 51, - "start": 48, - "type": "RESPONSE_HANDLING" - } - ], - "title": "dialogflow_v2beta1_generated_environments_update_environment_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.dialogflow_v2beta1.EnvironmentsClient", - "shortName": "EnvironmentsClient" - }, - "fullName": "google.cloud.dialogflow_v2beta1.EnvironmentsClient.update_environment", - "method": { - "fullName": "google.cloud.dialogflow.v2beta1.Environments.UpdateEnvironment", - "service": { - "fullName": "google.cloud.dialogflow.v2beta1.Environments", - "shortName": "Environments" - }, - "shortName": "UpdateEnvironment" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.dialogflow_v2beta1.types.UpdateEnvironmentRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.dialogflow_v2beta1.types.Environment", - "shortName": "update_environment" - }, - "description": "Sample for UpdateEnvironment", - "file": "dialogflow_v2beta1_generated_environments_update_environment_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "dialogflow_v2beta1_generated_Environments_UpdateEnvironment_sync", - "segments": [ - { - "end": 50, - "start": 27, - "type": "FULL" - }, - { - "end": 50, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 44, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 47, - "start": 45, - "type": "REQUEST_EXECUTION" - }, - { - "end": 51, - "start": 48, - "type": "RESPONSE_HANDLING" - } - ], - "title": "dialogflow_v2beta1_generated_environments_update_environment_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.dialogflow_v2beta1.FulfillmentsAsyncClient", - "shortName": "FulfillmentsAsyncClient" - }, - "fullName": "google.cloud.dialogflow_v2beta1.FulfillmentsAsyncClient.get_fulfillment", - "method": { - "fullName": "google.cloud.dialogflow.v2beta1.Fulfillments.GetFulfillment", - "service": { - "fullName": "google.cloud.dialogflow.v2beta1.Fulfillments", - "shortName": "Fulfillments" - }, - "shortName": "GetFulfillment" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.dialogflow_v2beta1.types.GetFulfillmentRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.dialogflow_v2beta1.types.Fulfillment", - "shortName": "get_fulfillment" - }, - "description": "Sample for GetFulfillment", - "file": "dialogflow_v2beta1_generated_fulfillments_get_fulfillment_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "dialogflow_v2beta1_generated_Fulfillments_GetFulfillment_async", - "segments": [ - { - "end": 51, - "start": 27, - "type": "FULL" - }, - { - "end": 51, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 48, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 52, - "start": 49, - "type": "RESPONSE_HANDLING" - } - ], - "title": "dialogflow_v2beta1_generated_fulfillments_get_fulfillment_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.dialogflow_v2beta1.FulfillmentsClient", - "shortName": "FulfillmentsClient" - }, - "fullName": "google.cloud.dialogflow_v2beta1.FulfillmentsClient.get_fulfillment", - "method": { - "fullName": "google.cloud.dialogflow.v2beta1.Fulfillments.GetFulfillment", - "service": { - "fullName": "google.cloud.dialogflow.v2beta1.Fulfillments", - "shortName": "Fulfillments" - }, - "shortName": "GetFulfillment" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.dialogflow_v2beta1.types.GetFulfillmentRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.dialogflow_v2beta1.types.Fulfillment", - "shortName": "get_fulfillment" - }, - "description": "Sample for GetFulfillment", - "file": "dialogflow_v2beta1_generated_fulfillments_get_fulfillment_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "dialogflow_v2beta1_generated_Fulfillments_GetFulfillment_sync", - "segments": [ - { - "end": 51, - "start": 27, - "type": "FULL" - }, - { - "end": 51, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 48, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 52, - "start": 49, - "type": "RESPONSE_HANDLING" - } - ], - "title": "dialogflow_v2beta1_generated_fulfillments_get_fulfillment_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.dialogflow_v2beta1.FulfillmentsAsyncClient", - "shortName": "FulfillmentsAsyncClient" - }, - "fullName": "google.cloud.dialogflow_v2beta1.FulfillmentsAsyncClient.update_fulfillment", - "method": { - "fullName": "google.cloud.dialogflow.v2beta1.Fulfillments.UpdateFulfillment", - "service": { - "fullName": "google.cloud.dialogflow.v2beta1.Fulfillments", - "shortName": "Fulfillments" - }, - "shortName": "UpdateFulfillment" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.dialogflow_v2beta1.types.UpdateFulfillmentRequest" - }, - { - "name": "fulfillment", - "type": "google.cloud.dialogflow_v2beta1.types.Fulfillment" - }, - { - "name": "update_mask", - "type": "google.protobuf.field_mask_pb2.FieldMask" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.dialogflow_v2beta1.types.Fulfillment", - "shortName": "update_fulfillment" - }, - "description": "Sample for UpdateFulfillment", - "file": "dialogflow_v2beta1_generated_fulfillments_update_fulfillment_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "dialogflow_v2beta1_generated_Fulfillments_UpdateFulfillment_async", - "segments": [ - { - "end": 55, - "start": 27, - "type": "FULL" - }, - { - "end": 55, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 49, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 52, - "start": 50, - "type": "REQUEST_EXECUTION" - }, - { - "end": 56, - "start": 53, - "type": "RESPONSE_HANDLING" - } - ], - "title": "dialogflow_v2beta1_generated_fulfillments_update_fulfillment_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.dialogflow_v2beta1.FulfillmentsClient", - "shortName": "FulfillmentsClient" - }, - "fullName": "google.cloud.dialogflow_v2beta1.FulfillmentsClient.update_fulfillment", - "method": { - "fullName": "google.cloud.dialogflow.v2beta1.Fulfillments.UpdateFulfillment", - "service": { - "fullName": "google.cloud.dialogflow.v2beta1.Fulfillments", - "shortName": "Fulfillments" - }, - "shortName": "UpdateFulfillment" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.dialogflow_v2beta1.types.UpdateFulfillmentRequest" - }, - { - "name": "fulfillment", - "type": "google.cloud.dialogflow_v2beta1.types.Fulfillment" - }, - { - "name": "update_mask", - "type": "google.protobuf.field_mask_pb2.FieldMask" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.dialogflow_v2beta1.types.Fulfillment", - "shortName": "update_fulfillment" - }, - "description": "Sample for UpdateFulfillment", - "file": "dialogflow_v2beta1_generated_fulfillments_update_fulfillment_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "dialogflow_v2beta1_generated_Fulfillments_UpdateFulfillment_sync", - "segments": [ - { - "end": 55, - "start": 27, - "type": "FULL" - }, - { - "end": 55, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 49, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 52, - "start": 50, - "type": "REQUEST_EXECUTION" - }, - { - "end": 56, - "start": 53, - "type": "RESPONSE_HANDLING" - } - ], - "title": "dialogflow_v2beta1_generated_fulfillments_update_fulfillment_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.dialogflow_v2beta1.IntentsAsyncClient", - "shortName": "IntentsAsyncClient" - }, - "fullName": "google.cloud.dialogflow_v2beta1.IntentsAsyncClient.batch_delete_intents", - "method": { - "fullName": "google.cloud.dialogflow.v2beta1.Intents.BatchDeleteIntents", - "service": { - "fullName": "google.cloud.dialogflow.v2beta1.Intents", - "shortName": "Intents" - }, - "shortName": "BatchDeleteIntents" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.dialogflow_v2beta1.types.BatchDeleteIntentsRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "intents", - "type": "MutableSequence[google.cloud.dialogflow_v2beta1.types.Intent]" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.api_core.operation_async.AsyncOperation", - "shortName": "batch_delete_intents" - }, - "description": "Sample for BatchDeleteIntents", - "file": "dialogflow_v2beta1_generated_intents_batch_delete_intents_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "dialogflow_v2beta1_generated_Intents_BatchDeleteIntents_async", - "segments": [ - { - "end": 59, - "start": 27, - "type": "FULL" - }, - { - "end": 59, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 49, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 56, - "start": 50, - "type": "REQUEST_EXECUTION" - }, - { - "end": 60, - "start": 57, - "type": "RESPONSE_HANDLING" - } - ], - "title": "dialogflow_v2beta1_generated_intents_batch_delete_intents_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.dialogflow_v2beta1.IntentsClient", - "shortName": "IntentsClient" - }, - "fullName": "google.cloud.dialogflow_v2beta1.IntentsClient.batch_delete_intents", - "method": { - "fullName": "google.cloud.dialogflow.v2beta1.Intents.BatchDeleteIntents", - "service": { - "fullName": "google.cloud.dialogflow.v2beta1.Intents", - "shortName": "Intents" - }, - "shortName": "BatchDeleteIntents" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.dialogflow_v2beta1.types.BatchDeleteIntentsRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "intents", - "type": "MutableSequence[google.cloud.dialogflow_v2beta1.types.Intent]" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.api_core.operation.Operation", - "shortName": "batch_delete_intents" - }, - "description": "Sample for BatchDeleteIntents", - "file": "dialogflow_v2beta1_generated_intents_batch_delete_intents_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "dialogflow_v2beta1_generated_Intents_BatchDeleteIntents_sync", - "segments": [ - { - "end": 59, - "start": 27, - "type": "FULL" - }, - { - "end": 59, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 49, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 56, - "start": 50, - "type": "REQUEST_EXECUTION" - }, - { - "end": 60, - "start": 57, - "type": "RESPONSE_HANDLING" - } - ], - "title": "dialogflow_v2beta1_generated_intents_batch_delete_intents_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.dialogflow_v2beta1.IntentsAsyncClient", - "shortName": "IntentsAsyncClient" - }, - "fullName": "google.cloud.dialogflow_v2beta1.IntentsAsyncClient.batch_update_intents", - "method": { - "fullName": "google.cloud.dialogflow.v2beta1.Intents.BatchUpdateIntents", - "service": { - "fullName": "google.cloud.dialogflow.v2beta1.Intents", - "shortName": "Intents" - }, - "shortName": "BatchUpdateIntents" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.dialogflow_v2beta1.types.BatchUpdateIntentsRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "intent_batch_uri", - "type": "str" - }, - { - "name": "intent_batch_inline", - "type": "google.cloud.dialogflow_v2beta1.types.IntentBatch" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.api_core.operation_async.AsyncOperation", - "shortName": "batch_update_intents" - }, - "description": "Sample for BatchUpdateIntents", - "file": "dialogflow_v2beta1_generated_intents_batch_update_intents_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "dialogflow_v2beta1_generated_Intents_BatchUpdateIntents_async", - "segments": [ - { - "end": 56, - "start": 27, - "type": "FULL" - }, - { - "end": 56, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 46, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 53, - "start": 47, - "type": "REQUEST_EXECUTION" - }, - { - "end": 57, - "start": 54, - "type": "RESPONSE_HANDLING" - } - ], - "title": "dialogflow_v2beta1_generated_intents_batch_update_intents_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.dialogflow_v2beta1.IntentsClient", - "shortName": "IntentsClient" - }, - "fullName": "google.cloud.dialogflow_v2beta1.IntentsClient.batch_update_intents", - "method": { - "fullName": "google.cloud.dialogflow.v2beta1.Intents.BatchUpdateIntents", - "service": { - "fullName": "google.cloud.dialogflow.v2beta1.Intents", - "shortName": "Intents" - }, - "shortName": "BatchUpdateIntents" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.dialogflow_v2beta1.types.BatchUpdateIntentsRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "intent_batch_uri", - "type": "str" - }, - { - "name": "intent_batch_inline", - "type": "google.cloud.dialogflow_v2beta1.types.IntentBatch" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.api_core.operation.Operation", - "shortName": "batch_update_intents" - }, - "description": "Sample for BatchUpdateIntents", - "file": "dialogflow_v2beta1_generated_intents_batch_update_intents_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "dialogflow_v2beta1_generated_Intents_BatchUpdateIntents_sync", - "segments": [ - { - "end": 56, - "start": 27, - "type": "FULL" - }, - { - "end": 56, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 46, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 53, - "start": 47, - "type": "REQUEST_EXECUTION" - }, - { - "end": 57, - "start": 54, - "type": "RESPONSE_HANDLING" - } - ], - "title": "dialogflow_v2beta1_generated_intents_batch_update_intents_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.dialogflow_v2beta1.IntentsAsyncClient", - "shortName": "IntentsAsyncClient" - }, - "fullName": "google.cloud.dialogflow_v2beta1.IntentsAsyncClient.create_intent", - "method": { - "fullName": "google.cloud.dialogflow.v2beta1.Intents.CreateIntent", - "service": { - "fullName": "google.cloud.dialogflow.v2beta1.Intents", - "shortName": "Intents" - }, - "shortName": "CreateIntent" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.dialogflow_v2beta1.types.CreateIntentRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "intent", - "type": "google.cloud.dialogflow_v2beta1.types.Intent" - }, - { - "name": "language_code", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.dialogflow_v2beta1.types.Intent", - "shortName": "create_intent" - }, - "description": "Sample for CreateIntent", - "file": "dialogflow_v2beta1_generated_intents_create_intent_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "dialogflow_v2beta1_generated_Intents_CreateIntent_async", - "segments": [ - { - "end": 55, - "start": 27, - "type": "FULL" - }, - { - "end": 55, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 49, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 52, - "start": 50, - "type": "REQUEST_EXECUTION" - }, - { - "end": 56, - "start": 53, - "type": "RESPONSE_HANDLING" - } - ], - "title": "dialogflow_v2beta1_generated_intents_create_intent_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.dialogflow_v2beta1.IntentsClient", - "shortName": "IntentsClient" - }, - "fullName": "google.cloud.dialogflow_v2beta1.IntentsClient.create_intent", - "method": { - "fullName": "google.cloud.dialogflow.v2beta1.Intents.CreateIntent", - "service": { - "fullName": "google.cloud.dialogflow.v2beta1.Intents", - "shortName": "Intents" - }, - "shortName": "CreateIntent" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.dialogflow_v2beta1.types.CreateIntentRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "intent", - "type": "google.cloud.dialogflow_v2beta1.types.Intent" - }, - { - "name": "language_code", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.dialogflow_v2beta1.types.Intent", - "shortName": "create_intent" - }, - "description": "Sample for CreateIntent", - "file": "dialogflow_v2beta1_generated_intents_create_intent_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "dialogflow_v2beta1_generated_Intents_CreateIntent_sync", - "segments": [ - { - "end": 55, - "start": 27, - "type": "FULL" - }, - { - "end": 55, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 49, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 52, - "start": 50, - "type": "REQUEST_EXECUTION" - }, - { - "end": 56, - "start": 53, - "type": "RESPONSE_HANDLING" - } - ], - "title": "dialogflow_v2beta1_generated_intents_create_intent_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.dialogflow_v2beta1.IntentsAsyncClient", - "shortName": "IntentsAsyncClient" - }, - "fullName": "google.cloud.dialogflow_v2beta1.IntentsAsyncClient.delete_intent", - "method": { - "fullName": "google.cloud.dialogflow.v2beta1.Intents.DeleteIntent", - "service": { - "fullName": "google.cloud.dialogflow.v2beta1.Intents", - "shortName": "Intents" - }, - "shortName": "DeleteIntent" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.dialogflow_v2beta1.types.DeleteIntentRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "shortName": "delete_intent" - }, - "description": "Sample for DeleteIntent", - "file": "dialogflow_v2beta1_generated_intents_delete_intent_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "dialogflow_v2beta1_generated_Intents_DeleteIntent_async", - "segments": [ - { - "end": 49, - "start": 27, - "type": "FULL" - }, - { - "end": 49, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 50, - "type": "RESPONSE_HANDLING" - } - ], - "title": "dialogflow_v2beta1_generated_intents_delete_intent_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.dialogflow_v2beta1.IntentsClient", - "shortName": "IntentsClient" - }, - "fullName": "google.cloud.dialogflow_v2beta1.IntentsClient.delete_intent", - "method": { - "fullName": "google.cloud.dialogflow.v2beta1.Intents.DeleteIntent", - "service": { - "fullName": "google.cloud.dialogflow.v2beta1.Intents", - "shortName": "Intents" - }, - "shortName": "DeleteIntent" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.dialogflow_v2beta1.types.DeleteIntentRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "shortName": "delete_intent" - }, - "description": "Sample for DeleteIntent", - "file": "dialogflow_v2beta1_generated_intents_delete_intent_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "dialogflow_v2beta1_generated_Intents_DeleteIntent_sync", - "segments": [ - { - "end": 49, - "start": 27, - "type": "FULL" - }, - { - "end": 49, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 50, - "type": "RESPONSE_HANDLING" - } - ], - "title": "dialogflow_v2beta1_generated_intents_delete_intent_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.dialogflow_v2beta1.IntentsAsyncClient", - "shortName": "IntentsAsyncClient" - }, - "fullName": "google.cloud.dialogflow_v2beta1.IntentsAsyncClient.get_intent", - "method": { - "fullName": "google.cloud.dialogflow.v2beta1.Intents.GetIntent", - "service": { - "fullName": "google.cloud.dialogflow.v2beta1.Intents", - "shortName": "Intents" - }, - "shortName": "GetIntent" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.dialogflow_v2beta1.types.GetIntentRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "language_code", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.dialogflow_v2beta1.types.Intent", - "shortName": "get_intent" - }, - "description": "Sample for GetIntent", - "file": "dialogflow_v2beta1_generated_intents_get_intent_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "dialogflow_v2beta1_generated_Intents_GetIntent_async", - "segments": [ - { - "end": 51, - "start": 27, - "type": "FULL" - }, - { - "end": 51, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 48, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 52, - "start": 49, - "type": "RESPONSE_HANDLING" - } - ], - "title": "dialogflow_v2beta1_generated_intents_get_intent_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.dialogflow_v2beta1.IntentsClient", - "shortName": "IntentsClient" - }, - "fullName": "google.cloud.dialogflow_v2beta1.IntentsClient.get_intent", - "method": { - "fullName": "google.cloud.dialogflow.v2beta1.Intents.GetIntent", - "service": { - "fullName": "google.cloud.dialogflow.v2beta1.Intents", - "shortName": "Intents" - }, - "shortName": "GetIntent" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.dialogflow_v2beta1.types.GetIntentRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "language_code", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.dialogflow_v2beta1.types.Intent", - "shortName": "get_intent" - }, - "description": "Sample for GetIntent", - "file": "dialogflow_v2beta1_generated_intents_get_intent_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "dialogflow_v2beta1_generated_Intents_GetIntent_sync", - "segments": [ - { - "end": 51, - "start": 27, - "type": "FULL" - }, - { - "end": 51, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 48, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 52, - "start": 49, - "type": "RESPONSE_HANDLING" - } - ], - "title": "dialogflow_v2beta1_generated_intents_get_intent_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.dialogflow_v2beta1.IntentsAsyncClient", - "shortName": "IntentsAsyncClient" - }, - "fullName": "google.cloud.dialogflow_v2beta1.IntentsAsyncClient.list_intents", - "method": { - "fullName": "google.cloud.dialogflow.v2beta1.Intents.ListIntents", - "service": { - "fullName": "google.cloud.dialogflow.v2beta1.Intents", - "shortName": "Intents" - }, - "shortName": "ListIntents" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.dialogflow_v2beta1.types.ListIntentsRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "language_code", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.dialogflow_v2beta1.services.intents.pagers.ListIntentsAsyncPager", - "shortName": "list_intents" - }, - "description": "Sample for ListIntents", - "file": "dialogflow_v2beta1_generated_intents_list_intents_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "dialogflow_v2beta1_generated_Intents_ListIntents_async", - "segments": [ - { - "end": 52, - "start": 27, - "type": "FULL" - }, - { - "end": 52, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 48, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 53, - "start": 49, - "type": "RESPONSE_HANDLING" - } - ], - "title": "dialogflow_v2beta1_generated_intents_list_intents_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.dialogflow_v2beta1.IntentsClient", - "shortName": "IntentsClient" - }, - "fullName": "google.cloud.dialogflow_v2beta1.IntentsClient.list_intents", - "method": { - "fullName": "google.cloud.dialogflow.v2beta1.Intents.ListIntents", - "service": { - "fullName": "google.cloud.dialogflow.v2beta1.Intents", - "shortName": "Intents" - }, - "shortName": "ListIntents" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.dialogflow_v2beta1.types.ListIntentsRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "language_code", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.dialogflow_v2beta1.services.intents.pagers.ListIntentsPager", - "shortName": "list_intents" - }, - "description": "Sample for ListIntents", - "file": "dialogflow_v2beta1_generated_intents_list_intents_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "dialogflow_v2beta1_generated_Intents_ListIntents_sync", - "segments": [ - { - "end": 52, - "start": 27, - "type": "FULL" - }, - { - "end": 52, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 48, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 53, - "start": 49, - "type": "RESPONSE_HANDLING" - } - ], - "title": "dialogflow_v2beta1_generated_intents_list_intents_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.dialogflow_v2beta1.IntentsAsyncClient", - "shortName": "IntentsAsyncClient" - }, - "fullName": "google.cloud.dialogflow_v2beta1.IntentsAsyncClient.update_intent", - "method": { - "fullName": "google.cloud.dialogflow.v2beta1.Intents.UpdateIntent", - "service": { - "fullName": "google.cloud.dialogflow.v2beta1.Intents", - "shortName": "Intents" - }, - "shortName": "UpdateIntent" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.dialogflow_v2beta1.types.UpdateIntentRequest" - }, - { - "name": "intent", - "type": "google.cloud.dialogflow_v2beta1.types.Intent" - }, - { - "name": "update_mask", - "type": "google.protobuf.field_mask_pb2.FieldMask" - }, - { - "name": "language_code", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.dialogflow_v2beta1.types.Intent", - "shortName": "update_intent" - }, - "description": "Sample for UpdateIntent", - "file": "dialogflow_v2beta1_generated_intents_update_intent_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "dialogflow_v2beta1_generated_Intents_UpdateIntent_async", - "segments": [ - { - "end": 54, - "start": 27, - "type": "FULL" - }, - { - "end": 54, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 48, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 51, - "start": 49, - "type": "REQUEST_EXECUTION" - }, - { - "end": 55, - "start": 52, - "type": "RESPONSE_HANDLING" - } - ], - "title": "dialogflow_v2beta1_generated_intents_update_intent_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.dialogflow_v2beta1.IntentsClient", - "shortName": "IntentsClient" - }, - "fullName": "google.cloud.dialogflow_v2beta1.IntentsClient.update_intent", - "method": { - "fullName": "google.cloud.dialogflow.v2beta1.Intents.UpdateIntent", - "service": { - "fullName": "google.cloud.dialogflow.v2beta1.Intents", - "shortName": "Intents" - }, - "shortName": "UpdateIntent" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.dialogflow_v2beta1.types.UpdateIntentRequest" - }, - { - "name": "intent", - "type": "google.cloud.dialogflow_v2beta1.types.Intent" - }, - { - "name": "update_mask", - "type": "google.protobuf.field_mask_pb2.FieldMask" - }, - { - "name": "language_code", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.dialogflow_v2beta1.types.Intent", - "shortName": "update_intent" - }, - "description": "Sample for UpdateIntent", - "file": "dialogflow_v2beta1_generated_intents_update_intent_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "dialogflow_v2beta1_generated_Intents_UpdateIntent_sync", - "segments": [ - { - "end": 54, - "start": 27, - "type": "FULL" - }, - { - "end": 54, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 48, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 51, - "start": 49, - "type": "REQUEST_EXECUTION" - }, - { - "end": 55, - "start": 52, - "type": "RESPONSE_HANDLING" - } - ], - "title": "dialogflow_v2beta1_generated_intents_update_intent_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.dialogflow_v2beta1.KnowledgeBasesAsyncClient", - "shortName": "KnowledgeBasesAsyncClient" - }, - "fullName": "google.cloud.dialogflow_v2beta1.KnowledgeBasesAsyncClient.create_knowledge_base", - "method": { - "fullName": "google.cloud.dialogflow.v2beta1.KnowledgeBases.CreateKnowledgeBase", - "service": { - "fullName": "google.cloud.dialogflow.v2beta1.KnowledgeBases", - "shortName": "KnowledgeBases" - }, - "shortName": "CreateKnowledgeBase" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.dialogflow_v2beta1.types.CreateKnowledgeBaseRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "knowledge_base", - "type": "google.cloud.dialogflow_v2beta1.types.KnowledgeBase" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.dialogflow_v2beta1.types.KnowledgeBase", - "shortName": "create_knowledge_base" - }, - "description": "Sample for CreateKnowledgeBase", - "file": "dialogflow_v2beta1_generated_knowledge_bases_create_knowledge_base_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "dialogflow_v2beta1_generated_KnowledgeBases_CreateKnowledgeBase_async", - "segments": [ - { - "end": 55, - "start": 27, - "type": "FULL" - }, - { - "end": 55, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 49, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 52, - "start": 50, - "type": "REQUEST_EXECUTION" - }, - { - "end": 56, - "start": 53, - "type": "RESPONSE_HANDLING" - } - ], - "title": "dialogflow_v2beta1_generated_knowledge_bases_create_knowledge_base_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.dialogflow_v2beta1.KnowledgeBasesClient", - "shortName": "KnowledgeBasesClient" - }, - "fullName": "google.cloud.dialogflow_v2beta1.KnowledgeBasesClient.create_knowledge_base", - "method": { - "fullName": "google.cloud.dialogflow.v2beta1.KnowledgeBases.CreateKnowledgeBase", - "service": { - "fullName": "google.cloud.dialogflow.v2beta1.KnowledgeBases", - "shortName": "KnowledgeBases" - }, - "shortName": "CreateKnowledgeBase" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.dialogflow_v2beta1.types.CreateKnowledgeBaseRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "knowledge_base", - "type": "google.cloud.dialogflow_v2beta1.types.KnowledgeBase" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.dialogflow_v2beta1.types.KnowledgeBase", - "shortName": "create_knowledge_base" - }, - "description": "Sample for CreateKnowledgeBase", - "file": "dialogflow_v2beta1_generated_knowledge_bases_create_knowledge_base_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "dialogflow_v2beta1_generated_KnowledgeBases_CreateKnowledgeBase_sync", - "segments": [ - { - "end": 55, - "start": 27, - "type": "FULL" - }, - { - "end": 55, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 49, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 52, - "start": 50, - "type": "REQUEST_EXECUTION" - }, - { - "end": 56, - "start": 53, - "type": "RESPONSE_HANDLING" - } - ], - "title": "dialogflow_v2beta1_generated_knowledge_bases_create_knowledge_base_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.dialogflow_v2beta1.KnowledgeBasesAsyncClient", - "shortName": "KnowledgeBasesAsyncClient" - }, - "fullName": "google.cloud.dialogflow_v2beta1.KnowledgeBasesAsyncClient.delete_knowledge_base", - "method": { - "fullName": "google.cloud.dialogflow.v2beta1.KnowledgeBases.DeleteKnowledgeBase", - "service": { - "fullName": "google.cloud.dialogflow.v2beta1.KnowledgeBases", - "shortName": "KnowledgeBases" - }, - "shortName": "DeleteKnowledgeBase" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.dialogflow_v2beta1.types.DeleteKnowledgeBaseRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "shortName": "delete_knowledge_base" - }, - "description": "Sample for DeleteKnowledgeBase", - "file": "dialogflow_v2beta1_generated_knowledge_bases_delete_knowledge_base_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "dialogflow_v2beta1_generated_KnowledgeBases_DeleteKnowledgeBase_async", - "segments": [ - { - "end": 49, - "start": 27, - "type": "FULL" - }, - { - "end": 49, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 50, - "type": "RESPONSE_HANDLING" - } - ], - "title": "dialogflow_v2beta1_generated_knowledge_bases_delete_knowledge_base_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.dialogflow_v2beta1.KnowledgeBasesClient", - "shortName": "KnowledgeBasesClient" - }, - "fullName": "google.cloud.dialogflow_v2beta1.KnowledgeBasesClient.delete_knowledge_base", - "method": { - "fullName": "google.cloud.dialogflow.v2beta1.KnowledgeBases.DeleteKnowledgeBase", - "service": { - "fullName": "google.cloud.dialogflow.v2beta1.KnowledgeBases", - "shortName": "KnowledgeBases" - }, - "shortName": "DeleteKnowledgeBase" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.dialogflow_v2beta1.types.DeleteKnowledgeBaseRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "shortName": "delete_knowledge_base" - }, - "description": "Sample for DeleteKnowledgeBase", - "file": "dialogflow_v2beta1_generated_knowledge_bases_delete_knowledge_base_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "dialogflow_v2beta1_generated_KnowledgeBases_DeleteKnowledgeBase_sync", - "segments": [ - { - "end": 49, - "start": 27, - "type": "FULL" - }, - { - "end": 49, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 50, - "type": "RESPONSE_HANDLING" - } - ], - "title": "dialogflow_v2beta1_generated_knowledge_bases_delete_knowledge_base_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.dialogflow_v2beta1.KnowledgeBasesAsyncClient", - "shortName": "KnowledgeBasesAsyncClient" - }, - "fullName": "google.cloud.dialogflow_v2beta1.KnowledgeBasesAsyncClient.get_knowledge_base", - "method": { - "fullName": "google.cloud.dialogflow.v2beta1.KnowledgeBases.GetKnowledgeBase", - "service": { - "fullName": "google.cloud.dialogflow.v2beta1.KnowledgeBases", - "shortName": "KnowledgeBases" - }, - "shortName": "GetKnowledgeBase" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.dialogflow_v2beta1.types.GetKnowledgeBaseRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.dialogflow_v2beta1.types.KnowledgeBase", - "shortName": "get_knowledge_base" - }, - "description": "Sample for GetKnowledgeBase", - "file": "dialogflow_v2beta1_generated_knowledge_bases_get_knowledge_base_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "dialogflow_v2beta1_generated_KnowledgeBases_GetKnowledgeBase_async", - "segments": [ - { - "end": 51, - "start": 27, - "type": "FULL" - }, - { - "end": 51, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 48, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 52, - "start": 49, - "type": "RESPONSE_HANDLING" - } - ], - "title": "dialogflow_v2beta1_generated_knowledge_bases_get_knowledge_base_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.dialogflow_v2beta1.KnowledgeBasesClient", - "shortName": "KnowledgeBasesClient" - }, - "fullName": "google.cloud.dialogflow_v2beta1.KnowledgeBasesClient.get_knowledge_base", - "method": { - "fullName": "google.cloud.dialogflow.v2beta1.KnowledgeBases.GetKnowledgeBase", - "service": { - "fullName": "google.cloud.dialogflow.v2beta1.KnowledgeBases", - "shortName": "KnowledgeBases" - }, - "shortName": "GetKnowledgeBase" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.dialogflow_v2beta1.types.GetKnowledgeBaseRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.dialogflow_v2beta1.types.KnowledgeBase", - "shortName": "get_knowledge_base" - }, - "description": "Sample for GetKnowledgeBase", - "file": "dialogflow_v2beta1_generated_knowledge_bases_get_knowledge_base_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "dialogflow_v2beta1_generated_KnowledgeBases_GetKnowledgeBase_sync", - "segments": [ - { - "end": 51, - "start": 27, - "type": "FULL" - }, - { - "end": 51, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 48, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 52, - "start": 49, - "type": "RESPONSE_HANDLING" - } - ], - "title": "dialogflow_v2beta1_generated_knowledge_bases_get_knowledge_base_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.dialogflow_v2beta1.KnowledgeBasesAsyncClient", - "shortName": "KnowledgeBasesAsyncClient" - }, - "fullName": "google.cloud.dialogflow_v2beta1.KnowledgeBasesAsyncClient.list_knowledge_bases", - "method": { - "fullName": "google.cloud.dialogflow.v2beta1.KnowledgeBases.ListKnowledgeBases", - "service": { - "fullName": "google.cloud.dialogflow.v2beta1.KnowledgeBases", - "shortName": "KnowledgeBases" - }, - "shortName": "ListKnowledgeBases" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.dialogflow_v2beta1.types.ListKnowledgeBasesRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.dialogflow_v2beta1.services.knowledge_bases.pagers.ListKnowledgeBasesAsyncPager", - "shortName": "list_knowledge_bases" - }, - "description": "Sample for ListKnowledgeBases", - "file": "dialogflow_v2beta1_generated_knowledge_bases_list_knowledge_bases_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "dialogflow_v2beta1_generated_KnowledgeBases_ListKnowledgeBases_async", - "segments": [ - { - "end": 52, - "start": 27, - "type": "FULL" - }, - { - "end": 52, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 48, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 53, - "start": 49, - "type": "RESPONSE_HANDLING" - } - ], - "title": "dialogflow_v2beta1_generated_knowledge_bases_list_knowledge_bases_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.dialogflow_v2beta1.KnowledgeBasesClient", - "shortName": "KnowledgeBasesClient" - }, - "fullName": "google.cloud.dialogflow_v2beta1.KnowledgeBasesClient.list_knowledge_bases", - "method": { - "fullName": "google.cloud.dialogflow.v2beta1.KnowledgeBases.ListKnowledgeBases", - "service": { - "fullName": "google.cloud.dialogflow.v2beta1.KnowledgeBases", - "shortName": "KnowledgeBases" - }, - "shortName": "ListKnowledgeBases" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.dialogflow_v2beta1.types.ListKnowledgeBasesRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.dialogflow_v2beta1.services.knowledge_bases.pagers.ListKnowledgeBasesPager", - "shortName": "list_knowledge_bases" - }, - "description": "Sample for ListKnowledgeBases", - "file": "dialogflow_v2beta1_generated_knowledge_bases_list_knowledge_bases_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "dialogflow_v2beta1_generated_KnowledgeBases_ListKnowledgeBases_sync", - "segments": [ - { - "end": 52, - "start": 27, - "type": "FULL" - }, - { - "end": 52, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 48, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 53, - "start": 49, - "type": "RESPONSE_HANDLING" - } - ], - "title": "dialogflow_v2beta1_generated_knowledge_bases_list_knowledge_bases_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.dialogflow_v2beta1.KnowledgeBasesAsyncClient", - "shortName": "KnowledgeBasesAsyncClient" - }, - "fullName": "google.cloud.dialogflow_v2beta1.KnowledgeBasesAsyncClient.update_knowledge_base", - "method": { - "fullName": "google.cloud.dialogflow.v2beta1.KnowledgeBases.UpdateKnowledgeBase", - "service": { - "fullName": "google.cloud.dialogflow.v2beta1.KnowledgeBases", - "shortName": "KnowledgeBases" - }, - "shortName": "UpdateKnowledgeBase" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.dialogflow_v2beta1.types.UpdateKnowledgeBaseRequest" - }, - { - "name": "knowledge_base", - "type": "google.cloud.dialogflow_v2beta1.types.KnowledgeBase" - }, - { - "name": "update_mask", - "type": "google.protobuf.field_mask_pb2.FieldMask" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.dialogflow_v2beta1.types.KnowledgeBase", - "shortName": "update_knowledge_base" - }, - "description": "Sample for UpdateKnowledgeBase", - "file": "dialogflow_v2beta1_generated_knowledge_bases_update_knowledge_base_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "dialogflow_v2beta1_generated_KnowledgeBases_UpdateKnowledgeBase_async", - "segments": [ - { - "end": 54, - "start": 27, - "type": "FULL" - }, - { - "end": 54, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 48, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 51, - "start": 49, - "type": "REQUEST_EXECUTION" - }, - { - "end": 55, - "start": 52, - "type": "RESPONSE_HANDLING" - } - ], - "title": "dialogflow_v2beta1_generated_knowledge_bases_update_knowledge_base_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.dialogflow_v2beta1.KnowledgeBasesClient", - "shortName": "KnowledgeBasesClient" - }, - "fullName": "google.cloud.dialogflow_v2beta1.KnowledgeBasesClient.update_knowledge_base", - "method": { - "fullName": "google.cloud.dialogflow.v2beta1.KnowledgeBases.UpdateKnowledgeBase", - "service": { - "fullName": "google.cloud.dialogflow.v2beta1.KnowledgeBases", - "shortName": "KnowledgeBases" - }, - "shortName": "UpdateKnowledgeBase" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.dialogflow_v2beta1.types.UpdateKnowledgeBaseRequest" - }, - { - "name": "knowledge_base", - "type": "google.cloud.dialogflow_v2beta1.types.KnowledgeBase" - }, - { - "name": "update_mask", - "type": "google.protobuf.field_mask_pb2.FieldMask" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.dialogflow_v2beta1.types.KnowledgeBase", - "shortName": "update_knowledge_base" - }, - "description": "Sample for UpdateKnowledgeBase", - "file": "dialogflow_v2beta1_generated_knowledge_bases_update_knowledge_base_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "dialogflow_v2beta1_generated_KnowledgeBases_UpdateKnowledgeBase_sync", - "segments": [ - { - "end": 54, - "start": 27, - "type": "FULL" - }, - { - "end": 54, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 48, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 51, - "start": 49, - "type": "REQUEST_EXECUTION" - }, - { - "end": 55, - "start": 52, - "type": "RESPONSE_HANDLING" - } - ], - "title": "dialogflow_v2beta1_generated_knowledge_bases_update_knowledge_base_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.dialogflow_v2beta1.ParticipantsAsyncClient", - "shortName": "ParticipantsAsyncClient" - }, - "fullName": "google.cloud.dialogflow_v2beta1.ParticipantsAsyncClient.analyze_content", - "method": { - "fullName": "google.cloud.dialogflow.v2beta1.Participants.AnalyzeContent", - "service": { - "fullName": "google.cloud.dialogflow.v2beta1.Participants", - "shortName": "Participants" - }, - "shortName": "AnalyzeContent" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.dialogflow_v2beta1.types.AnalyzeContentRequest" - }, - { - "name": "participant", - "type": "str" - }, - { - "name": "text_input", - "type": "google.cloud.dialogflow_v2beta1.types.TextInput" - }, - { - "name": "audio_input", - "type": "google.cloud.dialogflow_v2beta1.types.AudioInput" - }, - { - "name": "event_input", - "type": "google.cloud.dialogflow_v2beta1.types.EventInput" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.dialogflow_v2beta1.types.AnalyzeContentResponse", - "shortName": "analyze_content" - }, - "description": "Sample for AnalyzeContent", - "file": "dialogflow_v2beta1_generated_participants_analyze_content_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "dialogflow_v2beta1_generated_Participants_AnalyzeContent_async", - "segments": [ - { - "end": 51, - "start": 27, - "type": "FULL" - }, - { - "end": 51, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 48, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 52, - "start": 49, - "type": "RESPONSE_HANDLING" - } - ], - "title": "dialogflow_v2beta1_generated_participants_analyze_content_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.dialogflow_v2beta1.ParticipantsClient", - "shortName": "ParticipantsClient" - }, - "fullName": "google.cloud.dialogflow_v2beta1.ParticipantsClient.analyze_content", - "method": { - "fullName": "google.cloud.dialogflow.v2beta1.Participants.AnalyzeContent", - "service": { - "fullName": "google.cloud.dialogflow.v2beta1.Participants", - "shortName": "Participants" - }, - "shortName": "AnalyzeContent" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.dialogflow_v2beta1.types.AnalyzeContentRequest" - }, - { - "name": "participant", - "type": "str" - }, - { - "name": "text_input", - "type": "google.cloud.dialogflow_v2beta1.types.TextInput" - }, - { - "name": "audio_input", - "type": "google.cloud.dialogflow_v2beta1.types.AudioInput" - }, - { - "name": "event_input", - "type": "google.cloud.dialogflow_v2beta1.types.EventInput" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.dialogflow_v2beta1.types.AnalyzeContentResponse", - "shortName": "analyze_content" - }, - "description": "Sample for AnalyzeContent", - "file": "dialogflow_v2beta1_generated_participants_analyze_content_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "dialogflow_v2beta1_generated_Participants_AnalyzeContent_sync", - "segments": [ - { - "end": 51, - "start": 27, - "type": "FULL" - }, - { - "end": 51, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 48, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 52, - "start": 49, - "type": "RESPONSE_HANDLING" - } - ], - "title": "dialogflow_v2beta1_generated_participants_analyze_content_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.dialogflow_v2beta1.ParticipantsAsyncClient", - "shortName": "ParticipantsAsyncClient" - }, - "fullName": "google.cloud.dialogflow_v2beta1.ParticipantsAsyncClient.compile_suggestion", - "method": { - "fullName": "google.cloud.dialogflow.v2beta1.Participants.CompileSuggestion", - "service": { - "fullName": "google.cloud.dialogflow.v2beta1.Participants", - "shortName": "Participants" - }, - "shortName": "CompileSuggestion" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.dialogflow_v2beta1.types.CompileSuggestionRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.dialogflow_v2beta1.types.CompileSuggestionResponse", - "shortName": "compile_suggestion" - }, - "description": "Sample for CompileSuggestion", - "file": "dialogflow_v2beta1_generated_participants_compile_suggestion_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "dialogflow_v2beta1_generated_Participants_CompileSuggestion_async", - "segments": [ - { - "end": 50, - "start": 27, - "type": "FULL" - }, - { - "end": 50, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 44, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 47, - "start": 45, - "type": "REQUEST_EXECUTION" - }, - { - "end": 51, - "start": 48, - "type": "RESPONSE_HANDLING" - } - ], - "title": "dialogflow_v2beta1_generated_participants_compile_suggestion_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.dialogflow_v2beta1.ParticipantsClient", - "shortName": "ParticipantsClient" - }, - "fullName": "google.cloud.dialogflow_v2beta1.ParticipantsClient.compile_suggestion", - "method": { - "fullName": "google.cloud.dialogflow.v2beta1.Participants.CompileSuggestion", - "service": { - "fullName": "google.cloud.dialogflow.v2beta1.Participants", - "shortName": "Participants" - }, - "shortName": "CompileSuggestion" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.dialogflow_v2beta1.types.CompileSuggestionRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.dialogflow_v2beta1.types.CompileSuggestionResponse", - "shortName": "compile_suggestion" - }, - "description": "Sample for CompileSuggestion", - "file": "dialogflow_v2beta1_generated_participants_compile_suggestion_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "dialogflow_v2beta1_generated_Participants_CompileSuggestion_sync", - "segments": [ - { - "end": 50, - "start": 27, - "type": "FULL" - }, - { - "end": 50, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 44, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 47, - "start": 45, - "type": "REQUEST_EXECUTION" - }, - { - "end": 51, - "start": 48, - "type": "RESPONSE_HANDLING" - } - ], - "title": "dialogflow_v2beta1_generated_participants_compile_suggestion_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.dialogflow_v2beta1.ParticipantsAsyncClient", - "shortName": "ParticipantsAsyncClient" - }, - "fullName": "google.cloud.dialogflow_v2beta1.ParticipantsAsyncClient.create_participant", - "method": { - "fullName": "google.cloud.dialogflow.v2beta1.Participants.CreateParticipant", - "service": { - "fullName": "google.cloud.dialogflow.v2beta1.Participants", - "shortName": "Participants" - }, - "shortName": "CreateParticipant" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.dialogflow_v2beta1.types.CreateParticipantRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "participant", - "type": "google.cloud.dialogflow_v2beta1.types.Participant" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.dialogflow_v2beta1.types.Participant", - "shortName": "create_participant" - }, - "description": "Sample for CreateParticipant", - "file": "dialogflow_v2beta1_generated_participants_create_participant_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "dialogflow_v2beta1_generated_Participants_CreateParticipant_async", - "segments": [ - { - "end": 51, - "start": 27, - "type": "FULL" - }, - { - "end": 51, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 48, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 52, - "start": 49, - "type": "RESPONSE_HANDLING" - } - ], - "title": "dialogflow_v2beta1_generated_participants_create_participant_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.dialogflow_v2beta1.ParticipantsClient", - "shortName": "ParticipantsClient" - }, - "fullName": "google.cloud.dialogflow_v2beta1.ParticipantsClient.create_participant", - "method": { - "fullName": "google.cloud.dialogflow.v2beta1.Participants.CreateParticipant", - "service": { - "fullName": "google.cloud.dialogflow.v2beta1.Participants", - "shortName": "Participants" - }, - "shortName": "CreateParticipant" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.dialogflow_v2beta1.types.CreateParticipantRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "participant", - "type": "google.cloud.dialogflow_v2beta1.types.Participant" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.dialogflow_v2beta1.types.Participant", - "shortName": "create_participant" - }, - "description": "Sample for CreateParticipant", - "file": "dialogflow_v2beta1_generated_participants_create_participant_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "dialogflow_v2beta1_generated_Participants_CreateParticipant_sync", - "segments": [ - { - "end": 51, - "start": 27, - "type": "FULL" - }, - { - "end": 51, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 48, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 52, - "start": 49, - "type": "RESPONSE_HANDLING" - } - ], - "title": "dialogflow_v2beta1_generated_participants_create_participant_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.dialogflow_v2beta1.ParticipantsAsyncClient", - "shortName": "ParticipantsAsyncClient" - }, - "fullName": "google.cloud.dialogflow_v2beta1.ParticipantsAsyncClient.get_participant", - "method": { - "fullName": "google.cloud.dialogflow.v2beta1.Participants.GetParticipant", - "service": { - "fullName": "google.cloud.dialogflow.v2beta1.Participants", - "shortName": "Participants" - }, - "shortName": "GetParticipant" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.dialogflow_v2beta1.types.GetParticipantRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.dialogflow_v2beta1.types.Participant", - "shortName": "get_participant" - }, - "description": "Sample for GetParticipant", - "file": "dialogflow_v2beta1_generated_participants_get_participant_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "dialogflow_v2beta1_generated_Participants_GetParticipant_async", - "segments": [ - { - "end": 51, - "start": 27, - "type": "FULL" - }, - { - "end": 51, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 48, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 52, - "start": 49, - "type": "RESPONSE_HANDLING" - } - ], - "title": "dialogflow_v2beta1_generated_participants_get_participant_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.dialogflow_v2beta1.ParticipantsClient", - "shortName": "ParticipantsClient" - }, - "fullName": "google.cloud.dialogflow_v2beta1.ParticipantsClient.get_participant", - "method": { - "fullName": "google.cloud.dialogflow.v2beta1.Participants.GetParticipant", - "service": { - "fullName": "google.cloud.dialogflow.v2beta1.Participants", - "shortName": "Participants" - }, - "shortName": "GetParticipant" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.dialogflow_v2beta1.types.GetParticipantRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.dialogflow_v2beta1.types.Participant", - "shortName": "get_participant" - }, - "description": "Sample for GetParticipant", - "file": "dialogflow_v2beta1_generated_participants_get_participant_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "dialogflow_v2beta1_generated_Participants_GetParticipant_sync", - "segments": [ - { - "end": 51, - "start": 27, - "type": "FULL" - }, - { - "end": 51, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 48, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 52, - "start": 49, - "type": "RESPONSE_HANDLING" - } - ], - "title": "dialogflow_v2beta1_generated_participants_get_participant_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.dialogflow_v2beta1.ParticipantsAsyncClient", - "shortName": "ParticipantsAsyncClient" - }, - "fullName": "google.cloud.dialogflow_v2beta1.ParticipantsAsyncClient.list_participants", - "method": { - "fullName": "google.cloud.dialogflow.v2beta1.Participants.ListParticipants", - "service": { - "fullName": "google.cloud.dialogflow.v2beta1.Participants", - "shortName": "Participants" - }, - "shortName": "ListParticipants" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.dialogflow_v2beta1.types.ListParticipantsRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.dialogflow_v2beta1.services.participants.pagers.ListParticipantsAsyncPager", - "shortName": "list_participants" - }, - "description": "Sample for ListParticipants", - "file": "dialogflow_v2beta1_generated_participants_list_participants_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "dialogflow_v2beta1_generated_Participants_ListParticipants_async", - "segments": [ - { - "end": 52, - "start": 27, - "type": "FULL" - }, - { - "end": 52, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 48, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 53, - "start": 49, - "type": "RESPONSE_HANDLING" - } - ], - "title": "dialogflow_v2beta1_generated_participants_list_participants_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.dialogflow_v2beta1.ParticipantsClient", - "shortName": "ParticipantsClient" - }, - "fullName": "google.cloud.dialogflow_v2beta1.ParticipantsClient.list_participants", - "method": { - "fullName": "google.cloud.dialogflow.v2beta1.Participants.ListParticipants", - "service": { - "fullName": "google.cloud.dialogflow.v2beta1.Participants", - "shortName": "Participants" - }, - "shortName": "ListParticipants" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.dialogflow_v2beta1.types.ListParticipantsRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.dialogflow_v2beta1.services.participants.pagers.ListParticipantsPager", - "shortName": "list_participants" - }, - "description": "Sample for ListParticipants", - "file": "dialogflow_v2beta1_generated_participants_list_participants_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "dialogflow_v2beta1_generated_Participants_ListParticipants_sync", - "segments": [ - { - "end": 52, - "start": 27, - "type": "FULL" - }, - { - "end": 52, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 48, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 53, - "start": 49, - "type": "RESPONSE_HANDLING" - } - ], - "title": "dialogflow_v2beta1_generated_participants_list_participants_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.dialogflow_v2beta1.ParticipantsAsyncClient", - "shortName": "ParticipantsAsyncClient" - }, - "fullName": "google.cloud.dialogflow_v2beta1.ParticipantsAsyncClient.list_suggestions", - "method": { - "fullName": "google.cloud.dialogflow.v2beta1.Participants.ListSuggestions", - "service": { - "fullName": "google.cloud.dialogflow.v2beta1.Participants", - "shortName": "Participants" - }, - "shortName": "ListSuggestions" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.dialogflow_v2beta1.types.ListSuggestionsRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.dialogflow_v2beta1.services.participants.pagers.ListSuggestionsAsyncPager", - "shortName": "list_suggestions" - }, - "description": "Sample for ListSuggestions", - "file": "dialogflow_v2beta1_generated_participants_list_suggestions_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "dialogflow_v2beta1_generated_Participants_ListSuggestions_async", - "segments": [ - { - "end": 51, - "start": 27, - "type": "FULL" - }, - { - "end": 51, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 44, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 47, - "start": 45, - "type": "REQUEST_EXECUTION" - }, - { - "end": 52, - "start": 48, - "type": "RESPONSE_HANDLING" - } - ], - "title": "dialogflow_v2beta1_generated_participants_list_suggestions_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.dialogflow_v2beta1.ParticipantsClient", - "shortName": "ParticipantsClient" - }, - "fullName": "google.cloud.dialogflow_v2beta1.ParticipantsClient.list_suggestions", - "method": { - "fullName": "google.cloud.dialogflow.v2beta1.Participants.ListSuggestions", - "service": { - "fullName": "google.cloud.dialogflow.v2beta1.Participants", - "shortName": "Participants" - }, - "shortName": "ListSuggestions" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.dialogflow_v2beta1.types.ListSuggestionsRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.dialogflow_v2beta1.services.participants.pagers.ListSuggestionsPager", - "shortName": "list_suggestions" - }, - "description": "Sample for ListSuggestions", - "file": "dialogflow_v2beta1_generated_participants_list_suggestions_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "dialogflow_v2beta1_generated_Participants_ListSuggestions_sync", - "segments": [ - { - "end": 51, - "start": 27, - "type": "FULL" - }, - { - "end": 51, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 44, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 47, - "start": 45, - "type": "REQUEST_EXECUTION" - }, - { - "end": 52, - "start": 48, - "type": "RESPONSE_HANDLING" - } - ], - "title": "dialogflow_v2beta1_generated_participants_list_suggestions_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.dialogflow_v2beta1.ParticipantsAsyncClient", - "shortName": "ParticipantsAsyncClient" - }, - "fullName": "google.cloud.dialogflow_v2beta1.ParticipantsAsyncClient.streaming_analyze_content", - "method": { - "fullName": "google.cloud.dialogflow.v2beta1.Participants.StreamingAnalyzeContent", - "service": { - "fullName": "google.cloud.dialogflow.v2beta1.Participants", - "shortName": "Participants" - }, - "shortName": "StreamingAnalyzeContent" - }, - "parameters": [ - { - "name": "requests", - "type": "Iterator[google.cloud.dialogflow_v2beta1.types.StreamingAnalyzeContentRequest]" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "Iterable[google.cloud.dialogflow_v2beta1.types.StreamingAnalyzeContentResponse]", - "shortName": "streaming_analyze_content" - }, - "description": "Sample for StreamingAnalyzeContent", - "file": "dialogflow_v2beta1_generated_participants_streaming_analyze_content_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "dialogflow_v2beta1_generated_Participants_StreamingAnalyzeContent_async", - "segments": [ - { - "end": 63, - "start": 27, - "type": "FULL" - }, - { - "end": 63, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 56, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 59, - "start": 57, - "type": "REQUEST_EXECUTION" - }, - { - "end": 64, - "start": 60, - "type": "RESPONSE_HANDLING" - } - ], - "title": "dialogflow_v2beta1_generated_participants_streaming_analyze_content_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.dialogflow_v2beta1.ParticipantsClient", - "shortName": "ParticipantsClient" - }, - "fullName": "google.cloud.dialogflow_v2beta1.ParticipantsClient.streaming_analyze_content", - "method": { - "fullName": "google.cloud.dialogflow.v2beta1.Participants.StreamingAnalyzeContent", - "service": { - "fullName": "google.cloud.dialogflow.v2beta1.Participants", - "shortName": "Participants" - }, - "shortName": "StreamingAnalyzeContent" - }, - "parameters": [ - { - "name": "requests", - "type": "Iterator[google.cloud.dialogflow_v2beta1.types.StreamingAnalyzeContentRequest]" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "Iterable[google.cloud.dialogflow_v2beta1.types.StreamingAnalyzeContentResponse]", - "shortName": "streaming_analyze_content" - }, - "description": "Sample for StreamingAnalyzeContent", - "file": "dialogflow_v2beta1_generated_participants_streaming_analyze_content_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "dialogflow_v2beta1_generated_Participants_StreamingAnalyzeContent_sync", - "segments": [ - { - "end": 63, - "start": 27, - "type": "FULL" - }, - { - "end": 63, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 56, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 59, - "start": 57, - "type": "REQUEST_EXECUTION" - }, - { - "end": 64, - "start": 60, - "type": "RESPONSE_HANDLING" - } - ], - "title": "dialogflow_v2beta1_generated_participants_streaming_analyze_content_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.dialogflow_v2beta1.ParticipantsAsyncClient", - "shortName": "ParticipantsAsyncClient" - }, - "fullName": "google.cloud.dialogflow_v2beta1.ParticipantsAsyncClient.suggest_articles", - "method": { - "fullName": "google.cloud.dialogflow.v2beta1.Participants.SuggestArticles", - "service": { - "fullName": "google.cloud.dialogflow.v2beta1.Participants", - "shortName": "Participants" - }, - "shortName": "SuggestArticles" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.dialogflow_v2beta1.types.SuggestArticlesRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.dialogflow_v2beta1.types.SuggestArticlesResponse", - "shortName": "suggest_articles" - }, - "description": "Sample for SuggestArticles", - "file": "dialogflow_v2beta1_generated_participants_suggest_articles_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "dialogflow_v2beta1_generated_Participants_SuggestArticles_async", - "segments": [ - { - "end": 51, - "start": 27, - "type": "FULL" - }, - { - "end": 51, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 48, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 52, - "start": 49, - "type": "RESPONSE_HANDLING" - } - ], - "title": "dialogflow_v2beta1_generated_participants_suggest_articles_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.dialogflow_v2beta1.ParticipantsClient", - "shortName": "ParticipantsClient" - }, - "fullName": "google.cloud.dialogflow_v2beta1.ParticipantsClient.suggest_articles", - "method": { - "fullName": "google.cloud.dialogflow.v2beta1.Participants.SuggestArticles", - "service": { - "fullName": "google.cloud.dialogflow.v2beta1.Participants", - "shortName": "Participants" - }, - "shortName": "SuggestArticles" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.dialogflow_v2beta1.types.SuggestArticlesRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.dialogflow_v2beta1.types.SuggestArticlesResponse", - "shortName": "suggest_articles" - }, - "description": "Sample for SuggestArticles", - "file": "dialogflow_v2beta1_generated_participants_suggest_articles_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "dialogflow_v2beta1_generated_Participants_SuggestArticles_sync", - "segments": [ - { - "end": 51, - "start": 27, - "type": "FULL" - }, - { - "end": 51, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 48, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 52, - "start": 49, - "type": "RESPONSE_HANDLING" - } - ], - "title": "dialogflow_v2beta1_generated_participants_suggest_articles_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.dialogflow_v2beta1.ParticipantsAsyncClient", - "shortName": "ParticipantsAsyncClient" - }, - "fullName": "google.cloud.dialogflow_v2beta1.ParticipantsAsyncClient.suggest_faq_answers", - "method": { - "fullName": "google.cloud.dialogflow.v2beta1.Participants.SuggestFaqAnswers", - "service": { - "fullName": "google.cloud.dialogflow.v2beta1.Participants", - "shortName": "Participants" - }, - "shortName": "SuggestFaqAnswers" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.dialogflow_v2beta1.types.SuggestFaqAnswersRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.dialogflow_v2beta1.types.SuggestFaqAnswersResponse", - "shortName": "suggest_faq_answers" - }, - "description": "Sample for SuggestFaqAnswers", - "file": "dialogflow_v2beta1_generated_participants_suggest_faq_answers_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "dialogflow_v2beta1_generated_Participants_SuggestFaqAnswers_async", - "segments": [ - { - "end": 51, - "start": 27, - "type": "FULL" - }, - { - "end": 51, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 48, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 52, - "start": 49, - "type": "RESPONSE_HANDLING" - } - ], - "title": "dialogflow_v2beta1_generated_participants_suggest_faq_answers_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.dialogflow_v2beta1.ParticipantsClient", - "shortName": "ParticipantsClient" - }, - "fullName": "google.cloud.dialogflow_v2beta1.ParticipantsClient.suggest_faq_answers", - "method": { - "fullName": "google.cloud.dialogflow.v2beta1.Participants.SuggestFaqAnswers", - "service": { - "fullName": "google.cloud.dialogflow.v2beta1.Participants", - "shortName": "Participants" - }, - "shortName": "SuggestFaqAnswers" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.dialogflow_v2beta1.types.SuggestFaqAnswersRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.dialogflow_v2beta1.types.SuggestFaqAnswersResponse", - "shortName": "suggest_faq_answers" - }, - "description": "Sample for SuggestFaqAnswers", - "file": "dialogflow_v2beta1_generated_participants_suggest_faq_answers_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "dialogflow_v2beta1_generated_Participants_SuggestFaqAnswers_sync", - "segments": [ - { - "end": 51, - "start": 27, - "type": "FULL" - }, - { - "end": 51, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 48, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 52, - "start": 49, - "type": "RESPONSE_HANDLING" - } - ], - "title": "dialogflow_v2beta1_generated_participants_suggest_faq_answers_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.dialogflow_v2beta1.ParticipantsAsyncClient", - "shortName": "ParticipantsAsyncClient" - }, - "fullName": "google.cloud.dialogflow_v2beta1.ParticipantsAsyncClient.suggest_smart_replies", - "method": { - "fullName": "google.cloud.dialogflow.v2beta1.Participants.SuggestSmartReplies", - "service": { - "fullName": "google.cloud.dialogflow.v2beta1.Participants", - "shortName": "Participants" - }, - "shortName": "SuggestSmartReplies" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.dialogflow_v2beta1.types.SuggestSmartRepliesRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.dialogflow_v2beta1.types.SuggestSmartRepliesResponse", - "shortName": "suggest_smart_replies" - }, - "description": "Sample for SuggestSmartReplies", - "file": "dialogflow_v2beta1_generated_participants_suggest_smart_replies_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "dialogflow_v2beta1_generated_Participants_SuggestSmartReplies_async", - "segments": [ - { - "end": 51, - "start": 27, - "type": "FULL" - }, - { - "end": 51, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 48, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 52, - "start": 49, - "type": "RESPONSE_HANDLING" - } - ], - "title": "dialogflow_v2beta1_generated_participants_suggest_smart_replies_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.dialogflow_v2beta1.ParticipantsClient", - "shortName": "ParticipantsClient" - }, - "fullName": "google.cloud.dialogflow_v2beta1.ParticipantsClient.suggest_smart_replies", - "method": { - "fullName": "google.cloud.dialogflow.v2beta1.Participants.SuggestSmartReplies", - "service": { - "fullName": "google.cloud.dialogflow.v2beta1.Participants", - "shortName": "Participants" - }, - "shortName": "SuggestSmartReplies" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.dialogflow_v2beta1.types.SuggestSmartRepliesRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.dialogflow_v2beta1.types.SuggestSmartRepliesResponse", - "shortName": "suggest_smart_replies" - }, - "description": "Sample for SuggestSmartReplies", - "file": "dialogflow_v2beta1_generated_participants_suggest_smart_replies_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "dialogflow_v2beta1_generated_Participants_SuggestSmartReplies_sync", - "segments": [ - { - "end": 51, - "start": 27, - "type": "FULL" - }, - { - "end": 51, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 48, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 52, - "start": 49, - "type": "RESPONSE_HANDLING" - } - ], - "title": "dialogflow_v2beta1_generated_participants_suggest_smart_replies_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.dialogflow_v2beta1.ParticipantsAsyncClient", - "shortName": "ParticipantsAsyncClient" - }, - "fullName": "google.cloud.dialogflow_v2beta1.ParticipantsAsyncClient.update_participant", - "method": { - "fullName": "google.cloud.dialogflow.v2beta1.Participants.UpdateParticipant", - "service": { - "fullName": "google.cloud.dialogflow.v2beta1.Participants", - "shortName": "Participants" - }, - "shortName": "UpdateParticipant" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.dialogflow_v2beta1.types.UpdateParticipantRequest" - }, - { - "name": "participant", - "type": "google.cloud.dialogflow_v2beta1.types.Participant" - }, - { - "name": "update_mask", - "type": "google.protobuf.field_mask_pb2.FieldMask" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.dialogflow_v2beta1.types.Participant", - "shortName": "update_participant" - }, - "description": "Sample for UpdateParticipant", - "file": "dialogflow_v2beta1_generated_participants_update_participant_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "dialogflow_v2beta1_generated_Participants_UpdateParticipant_async", - "segments": [ - { - "end": 50, - "start": 27, - "type": "FULL" - }, - { - "end": 50, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 44, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 47, - "start": 45, - "type": "REQUEST_EXECUTION" - }, - { - "end": 51, - "start": 48, - "type": "RESPONSE_HANDLING" - } - ], - "title": "dialogflow_v2beta1_generated_participants_update_participant_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.dialogflow_v2beta1.ParticipantsClient", - "shortName": "ParticipantsClient" - }, - "fullName": "google.cloud.dialogflow_v2beta1.ParticipantsClient.update_participant", - "method": { - "fullName": "google.cloud.dialogflow.v2beta1.Participants.UpdateParticipant", - "service": { - "fullName": "google.cloud.dialogflow.v2beta1.Participants", - "shortName": "Participants" - }, - "shortName": "UpdateParticipant" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.dialogflow_v2beta1.types.UpdateParticipantRequest" - }, - { - "name": "participant", - "type": "google.cloud.dialogflow_v2beta1.types.Participant" - }, - { - "name": "update_mask", - "type": "google.protobuf.field_mask_pb2.FieldMask" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.dialogflow_v2beta1.types.Participant", - "shortName": "update_participant" - }, - "description": "Sample for UpdateParticipant", - "file": "dialogflow_v2beta1_generated_participants_update_participant_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "dialogflow_v2beta1_generated_Participants_UpdateParticipant_sync", - "segments": [ - { - "end": 50, - "start": 27, - "type": "FULL" - }, - { - "end": 50, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 44, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 47, - "start": 45, - "type": "REQUEST_EXECUTION" - }, - { - "end": 51, - "start": 48, - "type": "RESPONSE_HANDLING" - } - ], - "title": "dialogflow_v2beta1_generated_participants_update_participant_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.dialogflow_v2beta1.SessionEntityTypesAsyncClient", - "shortName": "SessionEntityTypesAsyncClient" - }, - "fullName": "google.cloud.dialogflow_v2beta1.SessionEntityTypesAsyncClient.create_session_entity_type", - "method": { - "fullName": "google.cloud.dialogflow.v2beta1.SessionEntityTypes.CreateSessionEntityType", - "service": { - "fullName": "google.cloud.dialogflow.v2beta1.SessionEntityTypes", - "shortName": "SessionEntityTypes" - }, - "shortName": "CreateSessionEntityType" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.dialogflow_v2beta1.types.CreateSessionEntityTypeRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "session_entity_type", - "type": "google.cloud.dialogflow_v2beta1.types.SessionEntityType" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.dialogflow_v2beta1.types.SessionEntityType", - "shortName": "create_session_entity_type" - }, - "description": "Sample for CreateSessionEntityType", - "file": "dialogflow_v2beta1_generated_session_entity_types_create_session_entity_type_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "dialogflow_v2beta1_generated_SessionEntityTypes_CreateSessionEntityType_async", - "segments": [ - { - "end": 51, - "start": 27, - "type": "FULL" - }, - { - "end": 51, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 48, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 52, - "start": 49, - "type": "RESPONSE_HANDLING" - } - ], - "title": "dialogflow_v2beta1_generated_session_entity_types_create_session_entity_type_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.dialogflow_v2beta1.SessionEntityTypesClient", - "shortName": "SessionEntityTypesClient" - }, - "fullName": "google.cloud.dialogflow_v2beta1.SessionEntityTypesClient.create_session_entity_type", - "method": { - "fullName": "google.cloud.dialogflow.v2beta1.SessionEntityTypes.CreateSessionEntityType", - "service": { - "fullName": "google.cloud.dialogflow.v2beta1.SessionEntityTypes", - "shortName": "SessionEntityTypes" - }, - "shortName": "CreateSessionEntityType" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.dialogflow_v2beta1.types.CreateSessionEntityTypeRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "session_entity_type", - "type": "google.cloud.dialogflow_v2beta1.types.SessionEntityType" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.dialogflow_v2beta1.types.SessionEntityType", - "shortName": "create_session_entity_type" - }, - "description": "Sample for CreateSessionEntityType", - "file": "dialogflow_v2beta1_generated_session_entity_types_create_session_entity_type_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "dialogflow_v2beta1_generated_SessionEntityTypes_CreateSessionEntityType_sync", - "segments": [ - { - "end": 51, - "start": 27, - "type": "FULL" - }, - { - "end": 51, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 48, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 52, - "start": 49, - "type": "RESPONSE_HANDLING" - } - ], - "title": "dialogflow_v2beta1_generated_session_entity_types_create_session_entity_type_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.dialogflow_v2beta1.SessionEntityTypesAsyncClient", - "shortName": "SessionEntityTypesAsyncClient" - }, - "fullName": "google.cloud.dialogflow_v2beta1.SessionEntityTypesAsyncClient.delete_session_entity_type", - "method": { - "fullName": "google.cloud.dialogflow.v2beta1.SessionEntityTypes.DeleteSessionEntityType", - "service": { - "fullName": "google.cloud.dialogflow.v2beta1.SessionEntityTypes", - "shortName": "SessionEntityTypes" - }, - "shortName": "DeleteSessionEntityType" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.dialogflow_v2beta1.types.DeleteSessionEntityTypeRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "shortName": "delete_session_entity_type" - }, - "description": "Sample for DeleteSessionEntityType", - "file": "dialogflow_v2beta1_generated_session_entity_types_delete_session_entity_type_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "dialogflow_v2beta1_generated_SessionEntityTypes_DeleteSessionEntityType_async", - "segments": [ - { - "end": 49, - "start": 27, - "type": "FULL" - }, - { - "end": 49, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 50, - "type": "RESPONSE_HANDLING" - } - ], - "title": "dialogflow_v2beta1_generated_session_entity_types_delete_session_entity_type_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.dialogflow_v2beta1.SessionEntityTypesClient", - "shortName": "SessionEntityTypesClient" - }, - "fullName": "google.cloud.dialogflow_v2beta1.SessionEntityTypesClient.delete_session_entity_type", - "method": { - "fullName": "google.cloud.dialogflow.v2beta1.SessionEntityTypes.DeleteSessionEntityType", - "service": { - "fullName": "google.cloud.dialogflow.v2beta1.SessionEntityTypes", - "shortName": "SessionEntityTypes" - }, - "shortName": "DeleteSessionEntityType" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.dialogflow_v2beta1.types.DeleteSessionEntityTypeRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "shortName": "delete_session_entity_type" - }, - "description": "Sample for DeleteSessionEntityType", - "file": "dialogflow_v2beta1_generated_session_entity_types_delete_session_entity_type_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "dialogflow_v2beta1_generated_SessionEntityTypes_DeleteSessionEntityType_sync", - "segments": [ - { - "end": 49, - "start": 27, - "type": "FULL" - }, - { - "end": 49, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 50, - "type": "RESPONSE_HANDLING" - } - ], - "title": "dialogflow_v2beta1_generated_session_entity_types_delete_session_entity_type_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.dialogflow_v2beta1.SessionEntityTypesAsyncClient", - "shortName": "SessionEntityTypesAsyncClient" - }, - "fullName": "google.cloud.dialogflow_v2beta1.SessionEntityTypesAsyncClient.get_session_entity_type", - "method": { - "fullName": "google.cloud.dialogflow.v2beta1.SessionEntityTypes.GetSessionEntityType", - "service": { - "fullName": "google.cloud.dialogflow.v2beta1.SessionEntityTypes", - "shortName": "SessionEntityTypes" - }, - "shortName": "GetSessionEntityType" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.dialogflow_v2beta1.types.GetSessionEntityTypeRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.dialogflow_v2beta1.types.SessionEntityType", - "shortName": "get_session_entity_type" - }, - "description": "Sample for GetSessionEntityType", - "file": "dialogflow_v2beta1_generated_session_entity_types_get_session_entity_type_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "dialogflow_v2beta1_generated_SessionEntityTypes_GetSessionEntityType_async", - "segments": [ - { - "end": 51, - "start": 27, - "type": "FULL" - }, - { - "end": 51, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 48, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 52, - "start": 49, - "type": "RESPONSE_HANDLING" - } - ], - "title": "dialogflow_v2beta1_generated_session_entity_types_get_session_entity_type_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.dialogflow_v2beta1.SessionEntityTypesClient", - "shortName": "SessionEntityTypesClient" - }, - "fullName": "google.cloud.dialogflow_v2beta1.SessionEntityTypesClient.get_session_entity_type", - "method": { - "fullName": "google.cloud.dialogflow.v2beta1.SessionEntityTypes.GetSessionEntityType", - "service": { - "fullName": "google.cloud.dialogflow.v2beta1.SessionEntityTypes", - "shortName": "SessionEntityTypes" - }, - "shortName": "GetSessionEntityType" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.dialogflow_v2beta1.types.GetSessionEntityTypeRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.dialogflow_v2beta1.types.SessionEntityType", - "shortName": "get_session_entity_type" - }, - "description": "Sample for GetSessionEntityType", - "file": "dialogflow_v2beta1_generated_session_entity_types_get_session_entity_type_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "dialogflow_v2beta1_generated_SessionEntityTypes_GetSessionEntityType_sync", - "segments": [ - { - "end": 51, - "start": 27, - "type": "FULL" - }, - { - "end": 51, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 48, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 52, - "start": 49, - "type": "RESPONSE_HANDLING" - } - ], - "title": "dialogflow_v2beta1_generated_session_entity_types_get_session_entity_type_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.dialogflow_v2beta1.SessionEntityTypesAsyncClient", - "shortName": "SessionEntityTypesAsyncClient" - }, - "fullName": "google.cloud.dialogflow_v2beta1.SessionEntityTypesAsyncClient.list_session_entity_types", - "method": { - "fullName": "google.cloud.dialogflow.v2beta1.SessionEntityTypes.ListSessionEntityTypes", - "service": { - "fullName": "google.cloud.dialogflow.v2beta1.SessionEntityTypes", - "shortName": "SessionEntityTypes" - }, - "shortName": "ListSessionEntityTypes" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.dialogflow_v2beta1.types.ListSessionEntityTypesRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.dialogflow_v2beta1.services.session_entity_types.pagers.ListSessionEntityTypesAsyncPager", - "shortName": "list_session_entity_types" - }, - "description": "Sample for ListSessionEntityTypes", - "file": "dialogflow_v2beta1_generated_session_entity_types_list_session_entity_types_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "dialogflow_v2beta1_generated_SessionEntityTypes_ListSessionEntityTypes_async", - "segments": [ - { - "end": 52, - "start": 27, - "type": "FULL" - }, - { - "end": 52, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 48, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 53, - "start": 49, - "type": "RESPONSE_HANDLING" - } - ], - "title": "dialogflow_v2beta1_generated_session_entity_types_list_session_entity_types_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.dialogflow_v2beta1.SessionEntityTypesClient", - "shortName": "SessionEntityTypesClient" - }, - "fullName": "google.cloud.dialogflow_v2beta1.SessionEntityTypesClient.list_session_entity_types", - "method": { - "fullName": "google.cloud.dialogflow.v2beta1.SessionEntityTypes.ListSessionEntityTypes", - "service": { - "fullName": "google.cloud.dialogflow.v2beta1.SessionEntityTypes", - "shortName": "SessionEntityTypes" - }, - "shortName": "ListSessionEntityTypes" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.dialogflow_v2beta1.types.ListSessionEntityTypesRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.dialogflow_v2beta1.services.session_entity_types.pagers.ListSessionEntityTypesPager", - "shortName": "list_session_entity_types" - }, - "description": "Sample for ListSessionEntityTypes", - "file": "dialogflow_v2beta1_generated_session_entity_types_list_session_entity_types_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "dialogflow_v2beta1_generated_SessionEntityTypes_ListSessionEntityTypes_sync", - "segments": [ - { - "end": 52, - "start": 27, - "type": "FULL" - }, - { - "end": 52, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 48, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 53, - "start": 49, - "type": "RESPONSE_HANDLING" - } - ], - "title": "dialogflow_v2beta1_generated_session_entity_types_list_session_entity_types_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.dialogflow_v2beta1.SessionEntityTypesAsyncClient", - "shortName": "SessionEntityTypesAsyncClient" - }, - "fullName": "google.cloud.dialogflow_v2beta1.SessionEntityTypesAsyncClient.update_session_entity_type", - "method": { - "fullName": "google.cloud.dialogflow.v2beta1.SessionEntityTypes.UpdateSessionEntityType", - "service": { - "fullName": "google.cloud.dialogflow.v2beta1.SessionEntityTypes", - "shortName": "SessionEntityTypes" - }, - "shortName": "UpdateSessionEntityType" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.dialogflow_v2beta1.types.UpdateSessionEntityTypeRequest" - }, - { - "name": "session_entity_type", - "type": "google.cloud.dialogflow_v2beta1.types.SessionEntityType" - }, - { - "name": "update_mask", - "type": "google.protobuf.field_mask_pb2.FieldMask" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.dialogflow_v2beta1.types.SessionEntityType", - "shortName": "update_session_entity_type" - }, - "description": "Sample for UpdateSessionEntityType", - "file": "dialogflow_v2beta1_generated_session_entity_types_update_session_entity_type_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "dialogflow_v2beta1_generated_SessionEntityTypes_UpdateSessionEntityType_async", - "segments": [ - { - "end": 50, - "start": 27, - "type": "FULL" - }, - { - "end": 50, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 44, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 47, - "start": 45, - "type": "REQUEST_EXECUTION" - }, - { - "end": 51, - "start": 48, - "type": "RESPONSE_HANDLING" - } - ], - "title": "dialogflow_v2beta1_generated_session_entity_types_update_session_entity_type_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.dialogflow_v2beta1.SessionEntityTypesClient", - "shortName": "SessionEntityTypesClient" - }, - "fullName": "google.cloud.dialogflow_v2beta1.SessionEntityTypesClient.update_session_entity_type", - "method": { - "fullName": "google.cloud.dialogflow.v2beta1.SessionEntityTypes.UpdateSessionEntityType", - "service": { - "fullName": "google.cloud.dialogflow.v2beta1.SessionEntityTypes", - "shortName": "SessionEntityTypes" - }, - "shortName": "UpdateSessionEntityType" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.dialogflow_v2beta1.types.UpdateSessionEntityTypeRequest" - }, - { - "name": "session_entity_type", - "type": "google.cloud.dialogflow_v2beta1.types.SessionEntityType" - }, - { - "name": "update_mask", - "type": "google.protobuf.field_mask_pb2.FieldMask" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.dialogflow_v2beta1.types.SessionEntityType", - "shortName": "update_session_entity_type" - }, - "description": "Sample for UpdateSessionEntityType", - "file": "dialogflow_v2beta1_generated_session_entity_types_update_session_entity_type_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "dialogflow_v2beta1_generated_SessionEntityTypes_UpdateSessionEntityType_sync", - "segments": [ - { - "end": 50, - "start": 27, - "type": "FULL" - }, - { - "end": 50, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 44, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 47, - "start": 45, - "type": "REQUEST_EXECUTION" - }, - { - "end": 51, - "start": 48, - "type": "RESPONSE_HANDLING" - } - ], - "title": "dialogflow_v2beta1_generated_session_entity_types_update_session_entity_type_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.dialogflow_v2beta1.SessionsAsyncClient", - "shortName": "SessionsAsyncClient" - }, - "fullName": "google.cloud.dialogflow_v2beta1.SessionsAsyncClient.detect_intent", - "method": { - "fullName": "google.cloud.dialogflow.v2beta1.Sessions.DetectIntent", - "service": { - "fullName": "google.cloud.dialogflow.v2beta1.Sessions", - "shortName": "Sessions" - }, - "shortName": "DetectIntent" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.dialogflow_v2beta1.types.DetectIntentRequest" - }, - { - "name": "session", - "type": "str" - }, - { - "name": "query_input", - "type": "google.cloud.dialogflow_v2beta1.types.QueryInput" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.dialogflow_v2beta1.types.DetectIntentResponse", - "shortName": "detect_intent" - }, - "description": "Sample for DetectIntent", - "file": "dialogflow_v2beta1_generated_sessions_detect_intent_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "dialogflow_v2beta1_generated_Sessions_DetectIntent_async", - "segments": [ - { - "end": 51, - "start": 27, - "type": "FULL" - }, - { - "end": 51, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 48, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 52, - "start": 49, - "type": "RESPONSE_HANDLING" - } - ], - "title": "dialogflow_v2beta1_generated_sessions_detect_intent_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.dialogflow_v2beta1.SessionsClient", - "shortName": "SessionsClient" - }, - "fullName": "google.cloud.dialogflow_v2beta1.SessionsClient.detect_intent", - "method": { - "fullName": "google.cloud.dialogflow.v2beta1.Sessions.DetectIntent", - "service": { - "fullName": "google.cloud.dialogflow.v2beta1.Sessions", - "shortName": "Sessions" - }, - "shortName": "DetectIntent" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.dialogflow_v2beta1.types.DetectIntentRequest" - }, - { - "name": "session", - "type": "str" - }, - { - "name": "query_input", - "type": "google.cloud.dialogflow_v2beta1.types.QueryInput" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.dialogflow_v2beta1.types.DetectIntentResponse", - "shortName": "detect_intent" - }, - "description": "Sample for DetectIntent", - "file": "dialogflow_v2beta1_generated_sessions_detect_intent_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "dialogflow_v2beta1_generated_Sessions_DetectIntent_sync", - "segments": [ - { - "end": 51, - "start": 27, - "type": "FULL" - }, - { - "end": 51, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 48, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 52, - "start": 49, - "type": "RESPONSE_HANDLING" - } - ], - "title": "dialogflow_v2beta1_generated_sessions_detect_intent_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.dialogflow_v2beta1.SessionsAsyncClient", - "shortName": "SessionsAsyncClient" - }, - "fullName": "google.cloud.dialogflow_v2beta1.SessionsAsyncClient.streaming_detect_intent", - "method": { - "fullName": "google.cloud.dialogflow.v2beta1.Sessions.StreamingDetectIntent", - "service": { - "fullName": "google.cloud.dialogflow.v2beta1.Sessions", - "shortName": "Sessions" - }, - "shortName": "StreamingDetectIntent" - }, - "parameters": [ - { - "name": "requests", - "type": "Iterator[google.cloud.dialogflow_v2beta1.types.StreamingDetectIntentRequest]" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "Iterable[google.cloud.dialogflow_v2beta1.types.StreamingDetectIntentResponse]", - "shortName": "streaming_detect_intent" - }, - "description": "Sample for StreamingDetectIntent", - "file": "dialogflow_v2beta1_generated_sessions_streaming_detect_intent_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "dialogflow_v2beta1_generated_Sessions_StreamingDetectIntent_async", - "segments": [ - { - "end": 62, - "start": 27, - "type": "FULL" - }, - { - "end": 62, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 55, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 58, - "start": 56, - "type": "REQUEST_EXECUTION" - }, - { - "end": 63, - "start": 59, - "type": "RESPONSE_HANDLING" - } - ], - "title": "dialogflow_v2beta1_generated_sessions_streaming_detect_intent_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.dialogflow_v2beta1.SessionsClient", - "shortName": "SessionsClient" - }, - "fullName": "google.cloud.dialogflow_v2beta1.SessionsClient.streaming_detect_intent", - "method": { - "fullName": "google.cloud.dialogflow.v2beta1.Sessions.StreamingDetectIntent", - "service": { - "fullName": "google.cloud.dialogflow.v2beta1.Sessions", - "shortName": "Sessions" - }, - "shortName": "StreamingDetectIntent" - }, - "parameters": [ - { - "name": "requests", - "type": "Iterator[google.cloud.dialogflow_v2beta1.types.StreamingDetectIntentRequest]" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "Iterable[google.cloud.dialogflow_v2beta1.types.StreamingDetectIntentResponse]", - "shortName": "streaming_detect_intent" - }, - "description": "Sample for StreamingDetectIntent", - "file": "dialogflow_v2beta1_generated_sessions_streaming_detect_intent_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "dialogflow_v2beta1_generated_Sessions_StreamingDetectIntent_sync", - "segments": [ - { - "end": 62, - "start": 27, - "type": "FULL" - }, - { - "end": 62, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 55, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 58, - "start": 56, - "type": "REQUEST_EXECUTION" - }, - { - "end": 63, - "start": 59, - "type": "RESPONSE_HANDLING" - } - ], - "title": "dialogflow_v2beta1_generated_sessions_streaming_detect_intent_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.dialogflow_v2beta1.VersionsAsyncClient", - "shortName": "VersionsAsyncClient" - }, - "fullName": "google.cloud.dialogflow_v2beta1.VersionsAsyncClient.create_version", - "method": { - "fullName": "google.cloud.dialogflow.v2beta1.Versions.CreateVersion", - "service": { - "fullName": "google.cloud.dialogflow.v2beta1.Versions", - "shortName": "Versions" - }, - "shortName": "CreateVersion" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.dialogflow_v2beta1.types.CreateVersionRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "version", - "type": "google.cloud.dialogflow_v2beta1.types.Version" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.dialogflow_v2beta1.types.Version", - "shortName": "create_version" - }, - "description": "Sample for CreateVersion", - "file": "dialogflow_v2beta1_generated_versions_create_version_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "dialogflow_v2beta1_generated_Versions_CreateVersion_async", - "segments": [ - { - "end": 51, - "start": 27, - "type": "FULL" - }, - { - "end": 51, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 48, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 52, - "start": 49, - "type": "RESPONSE_HANDLING" - } - ], - "title": "dialogflow_v2beta1_generated_versions_create_version_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.dialogflow_v2beta1.VersionsClient", - "shortName": "VersionsClient" - }, - "fullName": "google.cloud.dialogflow_v2beta1.VersionsClient.create_version", - "method": { - "fullName": "google.cloud.dialogflow.v2beta1.Versions.CreateVersion", - "service": { - "fullName": "google.cloud.dialogflow.v2beta1.Versions", - "shortName": "Versions" - }, - "shortName": "CreateVersion" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.dialogflow_v2beta1.types.CreateVersionRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "version", - "type": "google.cloud.dialogflow_v2beta1.types.Version" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.dialogflow_v2beta1.types.Version", - "shortName": "create_version" - }, - "description": "Sample for CreateVersion", - "file": "dialogflow_v2beta1_generated_versions_create_version_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "dialogflow_v2beta1_generated_Versions_CreateVersion_sync", - "segments": [ - { - "end": 51, - "start": 27, - "type": "FULL" - }, - { - "end": 51, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 48, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 52, - "start": 49, - "type": "RESPONSE_HANDLING" - } - ], - "title": "dialogflow_v2beta1_generated_versions_create_version_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.dialogflow_v2beta1.VersionsAsyncClient", - "shortName": "VersionsAsyncClient" - }, - "fullName": "google.cloud.dialogflow_v2beta1.VersionsAsyncClient.delete_version", - "method": { - "fullName": "google.cloud.dialogflow.v2beta1.Versions.DeleteVersion", - "service": { - "fullName": "google.cloud.dialogflow.v2beta1.Versions", - "shortName": "Versions" - }, - "shortName": "DeleteVersion" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.dialogflow_v2beta1.types.DeleteVersionRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "shortName": "delete_version" - }, - "description": "Sample for DeleteVersion", - "file": "dialogflow_v2beta1_generated_versions_delete_version_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "dialogflow_v2beta1_generated_Versions_DeleteVersion_async", - "segments": [ - { - "end": 49, - "start": 27, - "type": "FULL" - }, - { - "end": 49, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 50, - "type": "RESPONSE_HANDLING" - } - ], - "title": "dialogflow_v2beta1_generated_versions_delete_version_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.dialogflow_v2beta1.VersionsClient", - "shortName": "VersionsClient" - }, - "fullName": "google.cloud.dialogflow_v2beta1.VersionsClient.delete_version", - "method": { - "fullName": "google.cloud.dialogflow.v2beta1.Versions.DeleteVersion", - "service": { - "fullName": "google.cloud.dialogflow.v2beta1.Versions", - "shortName": "Versions" - }, - "shortName": "DeleteVersion" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.dialogflow_v2beta1.types.DeleteVersionRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "shortName": "delete_version" - }, - "description": "Sample for DeleteVersion", - "file": "dialogflow_v2beta1_generated_versions_delete_version_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "dialogflow_v2beta1_generated_Versions_DeleteVersion_sync", - "segments": [ - { - "end": 49, - "start": 27, - "type": "FULL" - }, - { - "end": 49, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 50, - "type": "RESPONSE_HANDLING" - } - ], - "title": "dialogflow_v2beta1_generated_versions_delete_version_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.dialogflow_v2beta1.VersionsAsyncClient", - "shortName": "VersionsAsyncClient" - }, - "fullName": "google.cloud.dialogflow_v2beta1.VersionsAsyncClient.get_version", - "method": { - "fullName": "google.cloud.dialogflow.v2beta1.Versions.GetVersion", - "service": { - "fullName": "google.cloud.dialogflow.v2beta1.Versions", - "shortName": "Versions" - }, - "shortName": "GetVersion" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.dialogflow_v2beta1.types.GetVersionRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.dialogflow_v2beta1.types.Version", - "shortName": "get_version" - }, - "description": "Sample for GetVersion", - "file": "dialogflow_v2beta1_generated_versions_get_version_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "dialogflow_v2beta1_generated_Versions_GetVersion_async", - "segments": [ - { - "end": 51, - "start": 27, - "type": "FULL" - }, - { - "end": 51, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 48, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 52, - "start": 49, - "type": "RESPONSE_HANDLING" - } - ], - "title": "dialogflow_v2beta1_generated_versions_get_version_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.dialogflow_v2beta1.VersionsClient", - "shortName": "VersionsClient" - }, - "fullName": "google.cloud.dialogflow_v2beta1.VersionsClient.get_version", - "method": { - "fullName": "google.cloud.dialogflow.v2beta1.Versions.GetVersion", - "service": { - "fullName": "google.cloud.dialogflow.v2beta1.Versions", - "shortName": "Versions" - }, - "shortName": "GetVersion" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.dialogflow_v2beta1.types.GetVersionRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.dialogflow_v2beta1.types.Version", - "shortName": "get_version" - }, - "description": "Sample for GetVersion", - "file": "dialogflow_v2beta1_generated_versions_get_version_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "dialogflow_v2beta1_generated_Versions_GetVersion_sync", - "segments": [ - { - "end": 51, - "start": 27, - "type": "FULL" - }, - { - "end": 51, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 48, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 52, - "start": 49, - "type": "RESPONSE_HANDLING" - } - ], - "title": "dialogflow_v2beta1_generated_versions_get_version_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.dialogflow_v2beta1.VersionsAsyncClient", - "shortName": "VersionsAsyncClient" - }, - "fullName": "google.cloud.dialogflow_v2beta1.VersionsAsyncClient.list_versions", - "method": { - "fullName": "google.cloud.dialogflow.v2beta1.Versions.ListVersions", - "service": { - "fullName": "google.cloud.dialogflow.v2beta1.Versions", - "shortName": "Versions" - }, - "shortName": "ListVersions" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.dialogflow_v2beta1.types.ListVersionsRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.dialogflow_v2beta1.services.versions.pagers.ListVersionsAsyncPager", - "shortName": "list_versions" - }, - "description": "Sample for ListVersions", - "file": "dialogflow_v2beta1_generated_versions_list_versions_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "dialogflow_v2beta1_generated_Versions_ListVersions_async", - "segments": [ - { - "end": 52, - "start": 27, - "type": "FULL" - }, - { - "end": 52, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 48, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 53, - "start": 49, - "type": "RESPONSE_HANDLING" - } - ], - "title": "dialogflow_v2beta1_generated_versions_list_versions_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.dialogflow_v2beta1.VersionsClient", - "shortName": "VersionsClient" - }, - "fullName": "google.cloud.dialogflow_v2beta1.VersionsClient.list_versions", - "method": { - "fullName": "google.cloud.dialogflow.v2beta1.Versions.ListVersions", - "service": { - "fullName": "google.cloud.dialogflow.v2beta1.Versions", - "shortName": "Versions" - }, - "shortName": "ListVersions" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.dialogflow_v2beta1.types.ListVersionsRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.dialogflow_v2beta1.services.versions.pagers.ListVersionsPager", - "shortName": "list_versions" - }, - "description": "Sample for ListVersions", - "file": "dialogflow_v2beta1_generated_versions_list_versions_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "dialogflow_v2beta1_generated_Versions_ListVersions_sync", - "segments": [ - { - "end": 52, - "start": 27, - "type": "FULL" - }, - { - "end": 52, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 48, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 53, - "start": 49, - "type": "RESPONSE_HANDLING" - } - ], - "title": "dialogflow_v2beta1_generated_versions_list_versions_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.dialogflow_v2beta1.VersionsAsyncClient", - "shortName": "VersionsAsyncClient" - }, - "fullName": "google.cloud.dialogflow_v2beta1.VersionsAsyncClient.update_version", - "method": { - "fullName": "google.cloud.dialogflow.v2beta1.Versions.UpdateVersion", - "service": { - "fullName": "google.cloud.dialogflow.v2beta1.Versions", - "shortName": "Versions" - }, - "shortName": "UpdateVersion" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.dialogflow_v2beta1.types.UpdateVersionRequest" - }, - { - "name": "version", - "type": "google.cloud.dialogflow_v2beta1.types.Version" - }, - { - "name": "update_mask", - "type": "google.protobuf.field_mask_pb2.FieldMask" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.dialogflow_v2beta1.types.Version", - "shortName": "update_version" - }, - "description": "Sample for UpdateVersion", - "file": "dialogflow_v2beta1_generated_versions_update_version_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "dialogflow_v2beta1_generated_Versions_UpdateVersion_async", - "segments": [ - { - "end": 50, - "start": 27, - "type": "FULL" - }, - { - "end": 50, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 44, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 47, - "start": 45, - "type": "REQUEST_EXECUTION" - }, - { - "end": 51, - "start": 48, - "type": "RESPONSE_HANDLING" - } - ], - "title": "dialogflow_v2beta1_generated_versions_update_version_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.dialogflow_v2beta1.VersionsClient", - "shortName": "VersionsClient" - }, - "fullName": "google.cloud.dialogflow_v2beta1.VersionsClient.update_version", - "method": { - "fullName": "google.cloud.dialogflow.v2beta1.Versions.UpdateVersion", - "service": { - "fullName": "google.cloud.dialogflow.v2beta1.Versions", - "shortName": "Versions" - }, - "shortName": "UpdateVersion" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.dialogflow_v2beta1.types.UpdateVersionRequest" - }, - { - "name": "version", - "type": "google.cloud.dialogflow_v2beta1.types.Version" - }, - { - "name": "update_mask", - "type": "google.protobuf.field_mask_pb2.FieldMask" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.dialogflow_v2beta1.types.Version", - "shortName": "update_version" - }, - "description": "Sample for UpdateVersion", - "file": "dialogflow_v2beta1_generated_versions_update_version_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "dialogflow_v2beta1_generated_Versions_UpdateVersion_sync", - "segments": [ - { - "end": 50, - "start": 27, - "type": "FULL" - }, - { - "end": 50, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 44, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 47, - "start": 45, - "type": "REQUEST_EXECUTION" - }, - { - "end": 51, - "start": 48, - "type": "RESPONSE_HANDLING" - } - ], - "title": "dialogflow_v2beta1_generated_versions_update_version_sync.py" - } - ] -} diff --git a/owl-bot-staging/v2beta1/scripts/fixup_dialogflow_v2beta1_keywords.py b/owl-bot-staging/v2beta1/scripts/fixup_dialogflow_v2beta1_keywords.py deleted file mode 100644 index 5f973a106..000000000 --- a/owl-bot-staging/v2beta1/scripts/fixup_dialogflow_v2beta1_keywords.py +++ /dev/null @@ -1,267 +0,0 @@ -#! /usr/bin/env python3 -# -*- coding: utf-8 -*- -# Copyright 2022 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 argparse -import os -import libcst as cst -import pathlib -import sys -from typing import (Any, Callable, Dict, List, Sequence, Tuple) - - -def partition( - predicate: Callable[[Any], bool], - iterator: Sequence[Any] -) -> Tuple[List[Any], List[Any]]: - """A stable, out-of-place partition.""" - results = ([], []) - - for i in iterator: - results[int(predicate(i))].append(i) - - # Returns trueList, falseList - return results[1], results[0] - - -class dialogflowCallTransformer(cst.CSTTransformer): - CTRL_PARAMS: Tuple[str] = ('retry', 'timeout', 'metadata') - METHOD_TO_PARAMS: Dict[str, Tuple[str]] = { - 'analyze_content': ('participant', 'text_input', 'audio_input', 'event_input', 'reply_audio_config', 'query_params', 'assist_query_params', 'cx_parameters', 'cx_current_page', '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', ), - 'clear_suggestion_feature_config': ('conversation_profile', 'participant_role', 'suggestion_feature_type', ), - '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', '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', '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', ), - 'set_suggestion_feature_config': ('conversation_profile', 'participant_role', 'suggestion_feature_config', ), - 'streaming_analyze_content': ('participant', 'audio_config', 'text_config', 'reply_audio_config', 'input_audio', 'input_text', 'input_dtmf', 'query_params', 'assist_query_params', 'cx_parameters', 'cx_current_page', 'enable_partial_automated_agent_reply', ), - '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', 'assist_query_params', ), - 'suggest_conversation_summary': ('conversation', 'latest_message', 'context_size', 'assist_query_params', ), - 'suggest_faq_answers': ('parent', 'latest_message', 'context_size', 'assist_query_params', ), - '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: - try: - key = original.func.attr.value - kword_params = self.METHOD_TO_PARAMS[key] - except (AttributeError, KeyError): - # Either not a method from the API or too convoluted to be sure. - return updated - - # If the existing code is valid, keyword args come after positional args. - # Therefore, all positional args must map to the first parameters. - args, kwargs = partition(lambda a: not bool(a.keyword), updated.args) - if any(k.keyword.value == "request" for k in kwargs): - # We've already fixed this file, don't fix it again. - return updated - - kwargs, ctrl_kwargs = partition( - lambda a: a.keyword.value not in self.CTRL_PARAMS, - kwargs - ) - - args, ctrl_args = args[:len(kword_params)], args[len(kword_params):] - ctrl_kwargs.extend(cst.Arg(value=a.value, keyword=cst.Name(value=ctrl)) - for a, ctrl in zip(ctrl_args, self.CTRL_PARAMS)) - - request_arg = cst.Arg( - value=cst.Dict([ - cst.DictElement( - cst.SimpleString("'{}'".format(name)), -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 - # those could have been passed positionally or by keyword. - for name, arg in zip(kword_params, args + kwargs)]), - keyword=cst.Name("request") - ) - - return updated.with_changes( - args=[request_arg] + ctrl_kwargs - ) - - -def fix_files( - in_dir: pathlib.Path, - out_dir: pathlib.Path, - *, - transformer=dialogflowCallTransformer(), -): - """Duplicate the input dir to the output dir, fixing file method calls. - - Preconditions: - * in_dir is a real directory - * out_dir is a real, empty directory - """ - pyfile_gen = ( - pathlib.Path(os.path.join(root, f)) - for root, _, files in os.walk(in_dir) - for f in files if os.path.splitext(f)[1] == ".py" - ) - - for fpath in pyfile_gen: - with open(fpath, 'r') as f: - src = f.read() - - # Parse the code and insert method call fixes. - tree = cst.parse_module(src) - updated = tree.visit(transformer) - - # Create the path and directory structure for the new file. - updated_path = out_dir.joinpath(fpath.relative_to(in_dir)) - updated_path.parent.mkdir(parents=True, exist_ok=True) - - # Generate the updated source file at the corresponding path. - with open(updated_path, 'w') as f: - f.write(updated.code) - - -if __name__ == '__main__': - parser = argparse.ArgumentParser( - description="""Fix up source that uses the dialogflow client library. - -The existing sources are NOT overwritten but are copied to output_dir with changes made. - -Note: This tool operates at a best-effort level at converting positional - parameters in client method calls to keyword based parameters. - Cases where it WILL FAIL include - A) * or ** expansion in a method call. - B) Calls via function or method alias (includes free function calls) - C) Indirect or dispatched calls (e.g. the method is looked up dynamically) - - These all constitute false negatives. The tool will also detect false - positives when an API method shares a name with another method. -""") - parser.add_argument( - '-d', - '--input-directory', - required=True, - dest='input_dir', - help='the input directory to walk for python files to fix up', - ) - parser.add_argument( - '-o', - '--output-directory', - required=True, - dest='output_dir', - help='the directory to output files fixed via un-flattening', - ) - args = parser.parse_args() - input_dir = pathlib.Path(args.input_dir) - output_dir = pathlib.Path(args.output_dir) - if not input_dir.is_dir(): - print( - f"input directory '{input_dir}' does not exist or is not a directory", - file=sys.stderr, - ) - sys.exit(-1) - - if not output_dir.is_dir(): - print( - f"output directory '{output_dir}' does not exist or is not a directory", - file=sys.stderr, - ) - sys.exit(-1) - - if os.listdir(output_dir): - print( - f"output directory '{output_dir}' is not empty", - file=sys.stderr, - ) - sys.exit(-1) - - fix_files(input_dir, output_dir) diff --git a/owl-bot-staging/v2beta1/setup.py b/owl-bot-staging/v2beta1/setup.py deleted file mode 100644 index 7a69d39a7..000000000 --- a/owl-bot-staging/v2beta1/setup.py +++ /dev/null @@ -1,90 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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 io -import os - -import setuptools # type: ignore - -package_root = os.path.abspath(os.path.dirname(__file__)) - -name = 'google-cloud-dialogflow' - - -description = "Google Cloud Dialogflow API client library" - -version = {} -with open(os.path.join(package_root, 'google/cloud/dialogflow/gapic_version.py')) as fp: - exec(fp.read(), version) -version = version["__version__"] - -if version[0] == "0": - release_status = "Development Status :: 4 - Beta" -else: - release_status = "Development Status :: 5 - Production/Stable" - -dependencies = [ - "google-api-core[grpc] >= 1.34.0, <3.0.0dev,!=2.0.*,!=2.1.*,!=2.2.*,!=2.3.*,!=2.4.*,!=2.5.*,!=2.6.*,!=2.7.*,!=2.8.*,!=2.9.*,!=2.10.*", - "proto-plus >= 1.22.0, <2.0.0dev", - "proto-plus >= 1.22.2, <2.0.0dev; python_version>='3.11'", - "protobuf>=3.19.5,<5.0.0dev,!=3.20.0,!=3.20.1,!=4.21.0,!=4.21.1,!=4.21.2,!=4.21.3,!=4.21.4,!=4.21.5", -] -url = "https://github.com/googleapis/python-dialogflow" - -package_root = os.path.abspath(os.path.dirname(__file__)) - -readme_filename = os.path.join(package_root, "README.rst") -with io.open(readme_filename, encoding="utf-8") as readme_file: - readme = readme_file.read() - -packages = [ - package - for package in setuptools.PEP420PackageFinder.find() - if package.startswith("google") -] - -namespaces = ["google", "google.cloud"] - -setuptools.setup( - name=name, - version=version, - description=description, - long_description=readme, - author="Google LLC", - author_email="googleapis-packages@google.com", - license="Apache 2.0", - url=url, - classifiers=[ - release_status, - "Intended Audience :: Developers", - "License :: OSI Approved :: Apache Software License", - "Programming Language :: Python", - "Programming Language :: Python :: 3", - "Programming Language :: Python :: 3.7", - "Programming Language :: Python :: 3.8", - "Programming Language :: Python :: 3.9", - "Programming Language :: Python :: 3.10", - "Programming Language :: Python :: 3.11", - "Operating System :: OS Independent", - "Topic :: Internet", - ], - platforms="Posix; MacOS X; Windows", - packages=packages, - python_requires=">=3.7", - namespace_packages=namespaces, - install_requires=dependencies, - include_package_data=True, - zip_safe=False, -) diff --git a/owl-bot-staging/v2beta1/testing/constraints-3.10.txt b/owl-bot-staging/v2beta1/testing/constraints-3.10.txt deleted file mode 100644 index ed7f9aed2..000000000 --- a/owl-bot-staging/v2beta1/testing/constraints-3.10.txt +++ /dev/null @@ -1,6 +0,0 @@ -# -*- coding: utf-8 -*- -# This constraints file is required for unit tests. -# List all library dependencies and extras in this file. -google-api-core -proto-plus -protobuf diff --git a/owl-bot-staging/v2beta1/testing/constraints-3.11.txt b/owl-bot-staging/v2beta1/testing/constraints-3.11.txt deleted file mode 100644 index ed7f9aed2..000000000 --- a/owl-bot-staging/v2beta1/testing/constraints-3.11.txt +++ /dev/null @@ -1,6 +0,0 @@ -# -*- coding: utf-8 -*- -# This constraints file is required for unit tests. -# List all library dependencies and extras in this file. -google-api-core -proto-plus -protobuf diff --git a/owl-bot-staging/v2beta1/testing/constraints-3.12.txt b/owl-bot-staging/v2beta1/testing/constraints-3.12.txt deleted file mode 100644 index ed7f9aed2..000000000 --- a/owl-bot-staging/v2beta1/testing/constraints-3.12.txt +++ /dev/null @@ -1,6 +0,0 @@ -# -*- coding: utf-8 -*- -# This constraints file is required for unit tests. -# List all library dependencies and extras in this file. -google-api-core -proto-plus -protobuf diff --git a/owl-bot-staging/v2beta1/testing/constraints-3.7.txt b/owl-bot-staging/v2beta1/testing/constraints-3.7.txt deleted file mode 100644 index 6c44adfea..000000000 --- a/owl-bot-staging/v2beta1/testing/constraints-3.7.txt +++ /dev/null @@ -1,9 +0,0 @@ -# This constraints file is used to check that lower bounds -# are correct in setup.py -# List all library dependencies and extras in this file. -# Pin the version to the lower bound. -# e.g., if setup.py has "google-cloud-foo >= 1.14.0, < 2.0.0dev", -# Then this file should have google-cloud-foo==1.14.0 -google-api-core==1.34.0 -proto-plus==1.22.0 -protobuf==3.19.5 diff --git a/owl-bot-staging/v2beta1/testing/constraints-3.8.txt b/owl-bot-staging/v2beta1/testing/constraints-3.8.txt deleted file mode 100644 index ed7f9aed2..000000000 --- a/owl-bot-staging/v2beta1/testing/constraints-3.8.txt +++ /dev/null @@ -1,6 +0,0 @@ -# -*- coding: utf-8 -*- -# This constraints file is required for unit tests. -# List all library dependencies and extras in this file. -google-api-core -proto-plus -protobuf diff --git a/owl-bot-staging/v2beta1/testing/constraints-3.9.txt b/owl-bot-staging/v2beta1/testing/constraints-3.9.txt deleted file mode 100644 index ed7f9aed2..000000000 --- a/owl-bot-staging/v2beta1/testing/constraints-3.9.txt +++ /dev/null @@ -1,6 +0,0 @@ -# -*- coding: utf-8 -*- -# This constraints file is required for unit tests. -# List all library dependencies and extras in this file. -google-api-core -proto-plus -protobuf diff --git a/owl-bot-staging/v2beta1/tests/__init__.py b/owl-bot-staging/v2beta1/tests/__init__.py deleted file mode 100644 index 231bc1250..000000000 --- a/owl-bot-staging/v2beta1/tests/__init__.py +++ /dev/null @@ -1,16 +0,0 @@ - -# -*- coding: utf-8 -*- -# Copyright 2022 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/owl-bot-staging/v2beta1/tests/unit/__init__.py b/owl-bot-staging/v2beta1/tests/unit/__init__.py deleted file mode 100644 index 231bc1250..000000000 --- a/owl-bot-staging/v2beta1/tests/unit/__init__.py +++ /dev/null @@ -1,16 +0,0 @@ - -# -*- coding: utf-8 -*- -# Copyright 2022 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/owl-bot-staging/v2beta1/tests/unit/gapic/__init__.py b/owl-bot-staging/v2beta1/tests/unit/gapic/__init__.py deleted file mode 100644 index 231bc1250..000000000 --- a/owl-bot-staging/v2beta1/tests/unit/gapic/__init__.py +++ /dev/null @@ -1,16 +0,0 @@ - -# -*- coding: utf-8 -*- -# Copyright 2022 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/owl-bot-staging/v2beta1/tests/unit/gapic/dialogflow_v2beta1/__init__.py b/owl-bot-staging/v2beta1/tests/unit/gapic/dialogflow_v2beta1/__init__.py deleted file mode 100644 index 231bc1250..000000000 --- a/owl-bot-staging/v2beta1/tests/unit/gapic/dialogflow_v2beta1/__init__.py +++ /dev/null @@ -1,16 +0,0 @@ - -# -*- coding: utf-8 -*- -# Copyright 2022 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/owl-bot-staging/v2beta1/tests/unit/gapic/dialogflow_v2beta1/test_agents.py b/owl-bot-staging/v2beta1/tests/unit/gapic/dialogflow_v2beta1/test_agents.py deleted file mode 100644 index e884acf55..000000000 --- a/owl-bot-staging/v2beta1/tests/unit/gapic/dialogflow_v2beta1/test_agents.py +++ /dev/null @@ -1,6310 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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 -# try/except added for compatibility with python < 3.8 -try: - from unittest import mock - from unittest.mock import AsyncMock # pragma: NO COVER -except ImportError: # pragma: NO COVER - import mock - -import grpc -from grpc.experimental import aio -from collections.abc import Iterable -from google.protobuf import json_format -import json -import math -import pytest -from proto.marshal.rules.dates import DurationRule, TimestampRule -from proto.marshal.rules import wrappers -from requests import Response -from requests import Request, PreparedRequest -from requests.sessions import Session -from google.protobuf import json_format - -from google.api_core import client_options -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 -from google.api_core import operation_async # type: ignore -from google.api_core import operations_v1 -from google.api_core import path_template -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.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.cloud.location import locations_pb2 -from google.longrunning import operations_pb2 -from google.oauth2 import service_account -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 -import google.auth - - -def client_cert_source_callback(): - return b"cert bytes", b"key bytes" - - -# If default endpoint is localhost, then default mtls endpoint will be the same. -# This method modifies the default endpoint so the client can produce a different -# mtls endpoint for endpoint testing purposes. -def modify_default_endpoint(client): - return "foo.googleapis.com" if ("localhost" in client.DEFAULT_ENDPOINT) else client.DEFAULT_ENDPOINT - - -def test__get_default_mtls_endpoint(): - api_endpoint = "example.googleapis.com" - api_mtls_endpoint = "example.mtls.googleapis.com" - sandbox_endpoint = "example.sandbox.googleapis.com" - sandbox_mtls_endpoint = "example.mtls.sandbox.googleapis.com" - non_googleapi = "api.example.com" - - assert AgentsClient._get_default_mtls_endpoint(None) is None - assert AgentsClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint - assert AgentsClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint - assert AgentsClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint - assert AgentsClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint - assert AgentsClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi - - -@pytest.mark.parametrize("client_class,transport_name", [ - (AgentsClient, "grpc"), - (AgentsAsyncClient, "grpc_asyncio"), - (AgentsClient, "rest"), -]) -def test_agents_client_from_service_account_info(client_class, transport_name): - 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, transport=transport_name) - assert client.transport._credentials == creds - assert isinstance(client, client_class) - - assert client.transport._host == ( - 'dialogflow.googleapis.com:443' - if transport_name in ['grpc', 'grpc_asyncio'] - else - 'https://dialogflow.googleapis.com' - ) - - -@pytest.mark.parametrize("transport_class,transport_name", [ - (transports.AgentsGrpcTransport, "grpc"), - (transports.AgentsGrpcAsyncIOTransport, "grpc_asyncio"), - (transports.AgentsRestTransport, "rest"), -]) -def test_agents_client_service_account_always_use_jwt(transport_class, transport_name): - with mock.patch.object(service_account.Credentials, 'with_always_use_jwt_access', create=True) as use_jwt: - creds = service_account.Credentials(None, None, None) - transport = transport_class(credentials=creds, always_use_jwt_access=True) - use_jwt.assert_called_once_with(True) - - with mock.patch.object(service_account.Credentials, 'with_always_use_jwt_access', create=True) as use_jwt: - creds = service_account.Credentials(None, None, None) - transport = transport_class(credentials=creds, always_use_jwt_access=False) - use_jwt.assert_not_called() - - -@pytest.mark.parametrize("client_class,transport_name", [ - (AgentsClient, "grpc"), - (AgentsAsyncClient, "grpc_asyncio"), - (AgentsClient, "rest"), -]) -def test_agents_client_from_service_account_file(client_class, transport_name): - 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", transport=transport_name) - assert client.transport._credentials == creds - assert isinstance(client, client_class) - - client = client_class.from_service_account_json("dummy/file/path.json", transport=transport_name) - assert client.transport._credentials == creds - assert isinstance(client, client_class) - - assert client.transport._host == ( - 'dialogflow.googleapis.com:443' - if transport_name in ['grpc', 'grpc_asyncio'] - else - 'https://dialogflow.googleapis.com' - ) - - -def test_agents_client_get_transport_class(): - transport = AgentsClient.get_transport_class() - available_transports = [ - transports.AgentsGrpcTransport, - transports.AgentsRestTransport, - ] - assert transport in available_transports - - transport = AgentsClient.get_transport_class("grpc") - assert transport == transports.AgentsGrpcTransport - - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (AgentsClient, transports.AgentsGrpcTransport, "grpc"), - (AgentsAsyncClient, transports.AgentsGrpcAsyncIOTransport, "grpc_asyncio"), - (AgentsClient, transports.AgentsRestTransport, "rest"), -]) -@mock.patch.object(AgentsClient, "DEFAULT_ENDPOINT", modify_default_endpoint(AgentsClient)) -@mock.patch.object(AgentsAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(AgentsAsyncClient)) -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=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(AgentsClient, 'get_transport_class') as gtc: - client = client_class(transport=transport_name) - gtc.assert_called() - - # Check the case api_endpoint is provided. - options = client_options.ClientOptions(api_endpoint="squid.clam.whelk") - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(transport=transport_name, client_options=options) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host="squid.clam.whelk", - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is - # "never". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is - # "always". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_MTLS_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # 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(transport=transport_name) - - # 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(transport=transport_name) - - # 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, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id="octopus", - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - # Check the case api_endpoint is provided - options = client_options.ClientOptions(api_audience="https://language.googleapis.com") - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience="https://language.googleapis.com" - ) - -@pytest.mark.parametrize("client_class,transport_class,transport_name,use_client_cert_env", [ - (AgentsClient, transports.AgentsGrpcTransport, "grpc", "true"), - (AgentsAsyncClient, transports.AgentsGrpcAsyncIOTransport, "grpc_asyncio", "true"), - (AgentsClient, transports.AgentsGrpcTransport, "grpc", "false"), - (AgentsAsyncClient, transports.AgentsGrpcAsyncIOTransport, "grpc_asyncio", "false"), - (AgentsClient, transports.AgentsRestTransport, "rest", "true"), - (AgentsClient, transports.AgentsRestTransport, "rest", "false"), -]) -@mock.patch.object(AgentsClient, "DEFAULT_ENDPOINT", modify_default_endpoint(AgentsClient)) -@mock.patch.object(AgentsAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(AgentsAsyncClient)) -@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) -def test_agents_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, transport=transport_name) - - if use_client_cert_env == "false": - expected_client_cert_source = None - expected_host = client.DEFAULT_ENDPOINT - else: - expected_client_cert_source = client_cert_source_callback - expected_host = client.DEFAULT_MTLS_ENDPOINT - - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=expected_host, - scopes=None, - client_cert_source_for_mtls=expected_client_cert_source, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case ADC client cert is provided. Whether client cert is used depends on - # GOOGLE_API_USE_CLIENT_CERTIFICATE value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): - with mock.patch.object(transport_class, '__init__') as patched: - with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): - with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=client_cert_source_callback): - if use_client_cert_env == "false": - expected_host = client.DEFAULT_ENDPOINT - expected_client_cert_source = None - else: - expected_host = client.DEFAULT_MTLS_ENDPOINT - expected_client_cert_source = client_cert_source_callback - - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=expected_host, - scopes=None, - client_cert_source_for_mtls=expected_client_cert_source, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case client_cert_source and ADC client cert are not provided. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): - with mock.patch.object(transport_class, '__init__') as patched: - with mock.patch("google.auth.transport.mtls.has_default_client_cert_source", return_value=False): - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - -@pytest.mark.parametrize("client_class", [ - AgentsClient, AgentsAsyncClient -]) -@mock.patch.object(AgentsClient, "DEFAULT_ENDPOINT", modify_default_endpoint(AgentsClient)) -@mock.patch.object(AgentsAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(AgentsAsyncClient)) -def test_agents_client_get_mtls_endpoint_and_cert_source(client_class): - mock_client_cert_source = mock.Mock() - - # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "true". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - mock_api_endpoint = "foo" - options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) - assert api_endpoint == mock_api_endpoint - assert cert_source == mock_client_cert_source - - # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "false". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): - mock_client_cert_source = mock.Mock() - mock_api_endpoint = "foo" - options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) - assert api_endpoint == mock_api_endpoint - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "never". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_ENDPOINT - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "always". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert doesn't exist. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=False): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_ENDPOINT - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert exists. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - 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=mock_client_cert_source): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT - assert cert_source == mock_client_cert_source - - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (AgentsClient, transports.AgentsGrpcTransport, "grpc"), - (AgentsAsyncClient, transports.AgentsGrpcAsyncIOTransport, "grpc_asyncio"), - (AgentsClient, transports.AgentsRestTransport, "rest"), -]) -def test_agents_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, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=["1", "2"], - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - -@pytest.mark.parametrize("client_class,transport_class,transport_name,grpc_helpers", [ - (AgentsClient, transports.AgentsGrpcTransport, "grpc", grpc_helpers), - (AgentsAsyncClient, transports.AgentsGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), - (AgentsClient, transports.AgentsRestTransport, "rest", None), -]) -def test_agents_client_client_options_credentials_file(client_class, transport_class, transport_name, grpc_helpers): - # 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, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file="credentials.json", - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - -def test_agents_client_client_options_from_dict(): - with mock.patch('google.cloud.dialogflow_v2beta1.services.agents.transports.AgentsGrpcTransport.__init__') as grpc_transport: - grpc_transport.return_value = None - client = AgentsClient( - client_options={'api_endpoint': 'squid.clam.whelk'} - ) - grpc_transport.assert_called_once_with( - credentials=None, - credentials_file=None, - host="squid.clam.whelk", - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - -@pytest.mark.parametrize("client_class,transport_class,transport_name,grpc_helpers", [ - (AgentsClient, transports.AgentsGrpcTransport, "grpc", grpc_helpers), - (AgentsAsyncClient, transports.AgentsGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), -]) -def test_agents_client_create_channel_credentials_file(client_class, transport_class, transport_name, grpc_helpers): - # 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, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file="credentials.json", - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # test that the credentials from file are saved and used as the credentials. - with mock.patch.object( - google.auth, "load_credentials_from_file", autospec=True - ) as load_creds, mock.patch.object( - google.auth, "default", autospec=True - ) as adc, mock.patch.object( - grpc_helpers, "create_channel" - ) as create_channel: - creds = ga_credentials.AnonymousCredentials() - file_creds = ga_credentials.AnonymousCredentials() - load_creds.return_value = (file_creds, None) - adc.return_value = (creds, None) - client = client_class(client_options=options, transport=transport_name) - create_channel.assert_called_with( - "dialogflow.googleapis.com:443", - credentials=file_creds, - credentials_file=None, - quota_project_id=None, - default_scopes=( - 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/dialogflow', -), - scopes=None, - default_host="dialogflow.googleapis.com", - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - -@pytest.mark.parametrize("request_type", [ - agent.GetAgentRequest, - dict, -]) -def test_get_agent(request_type, transport: str = 'grpc'): - client = AgentsClient( - 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_agent), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = agent.Agent( - parent='parent_value', - display_name='display_name_value', - default_language_code='default_language_code_value', - supported_language_codes=['supported_language_codes_value'], - time_zone='time_zone_value', - description='description_value', - avatar_uri='avatar_uri_value', - enable_logging=True, - match_mode=agent.Agent.MatchMode.MATCH_MODE_HYBRID, - classification_threshold=0.25520000000000004, - 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.25520000000000004, rel_tol=1e-6) - assert response.api_version == agent.Agent.ApiVersion.API_VERSION_V1 - assert response.tier == agent.Agent.Tier.TIER_STANDARD - - -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=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_agent), - '__call__') as call: - client.get_agent() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == agent.GetAgentRequest() - -@pytest.mark.asyncio -async def test_get_agent_async(transport: str = 'grpc_asyncio', request_type=agent.GetAgentRequest): - client = AgentsAsyncClient( - 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_agent), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(agent.Agent( - parent='parent_value', - display_name='display_name_value', - default_language_code='default_language_code_value', - supported_language_codes=['supported_language_codes_value'], - time_zone='time_zone_value', - description='description_value', - avatar_uri='avatar_uri_value', - enable_logging=True, - match_mode=agent.Agent.MatchMode.MATCH_MODE_HYBRID, - classification_threshold=0.25520000000000004, - api_version=agent.Agent.ApiVersion.API_VERSION_V1, - 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.25520000000000004, rel_tol=1e-6) - assert response.api_version == agent.Agent.ApiVersion.API_VERSION_V1 - assert response.tier == agent.Agent.Tier.TIER_STANDARD - - -@pytest.mark.asyncio -async def test_get_agent_async_from_dict(): - await test_get_agent_async(request_type=dict) - - -def test_get_agent_field_headers(): - 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. - 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_agent_field_headers_async(): - 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. - 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_agent_flattened(): - 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', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - arg = args[0].parent - mock_val = 'parent_value' - assert arg == mock_val - - -def test_get_agent_flattened_error(): - client = AgentsClient( - 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_agent( - agent.GetAgentRequest(), - parent='parent_value', - ) - -@pytest.mark.asyncio -async def test_get_agent_flattened_async(): - 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: - # Designate an appropriate return value for the call. - call.return_value = agent.Agent() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(agent.Agent()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.get_agent( - 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] - arg = args[0].parent - mock_val = 'parent_value' - assert arg == mock_val - -@pytest.mark.asyncio -async def test_get_agent_flattened_error_async(): - client = AgentsAsyncClient( - 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_agent( - agent.GetAgentRequest(), - parent='parent_value', - ) - - -@pytest.mark.parametrize("request_type", [ - gcd_agent.SetAgentRequest, - dict, -]) -def test_set_agent(request_type, transport: str = 'grpc'): - client = AgentsClient( - 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.set_agent), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcd_agent.Agent( - parent='parent_value', - display_name='display_name_value', - default_language_code='default_language_code_value', - supported_language_codes=['supported_language_codes_value'], - time_zone='time_zone_value', - description='description_value', - avatar_uri='avatar_uri_value', - enable_logging=True, - match_mode=gcd_agent.Agent.MatchMode.MATCH_MODE_HYBRID, - classification_threshold=0.25520000000000004, - 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.25520000000000004, rel_tol=1e-6) - assert response.api_version == gcd_agent.Agent.ApiVersion.API_VERSION_V1 - assert response.tier == gcd_agent.Agent.Tier.TIER_STANDARD - - -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=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.set_agent), - '__call__') as call: - client.set_agent() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == gcd_agent.SetAgentRequest() - -@pytest.mark.asyncio -async def test_set_agent_async(transport: str = 'grpc_asyncio', request_type=gcd_agent.SetAgentRequest): - client = AgentsAsyncClient( - 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.set_agent), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gcd_agent.Agent( - parent='parent_value', - display_name='display_name_value', - default_language_code='default_language_code_value', - supported_language_codes=['supported_language_codes_value'], - time_zone='time_zone_value', - description='description_value', - avatar_uri='avatar_uri_value', - enable_logging=True, - match_mode=gcd_agent.Agent.MatchMode.MATCH_MODE_HYBRID, - classification_threshold=0.25520000000000004, - api_version=gcd_agent.Agent.ApiVersion.API_VERSION_V1, - 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.25520000000000004, rel_tol=1e-6) - assert response.api_version == gcd_agent.Agent.ApiVersion.API_VERSION_V1 - assert response.tier == gcd_agent.Agent.Tier.TIER_STANDARD - - -@pytest.mark.asyncio -async def test_set_agent_async_from_dict(): - await test_set_agent_async(request_type=dict) - - -def test_set_agent_field_headers(): - 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 = '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. - 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', - 'agent.parent=parent_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_set_agent_field_headers_async(): - 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 = '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. - 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', - 'agent.parent=parent_value', - ) in kw['metadata'] - - -def test_set_agent_flattened(): - 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'), - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - arg = args[0].agent - mock_val = gcd_agent.Agent(parent='parent_value') - assert arg == mock_val - - -def test_set_agent_flattened_error(): - client = AgentsClient( - 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.set_agent( - gcd_agent.SetAgentRequest(), - agent=gcd_agent.Agent(parent='parent_value'), - ) - -@pytest.mark.asyncio -async def test_set_agent_flattened_async(): - 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: - # Designate an appropriate return value for the call. - call.return_value = gcd_agent.Agent() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcd_agent.Agent()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.set_agent( - agent=gcd_agent.Agent(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] - arg = args[0].agent - mock_val = gcd_agent.Agent(parent='parent_value') - assert arg == mock_val - -@pytest.mark.asyncio -async def test_set_agent_flattened_error_async(): - client = AgentsAsyncClient( - 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.set_agent( - gcd_agent.SetAgentRequest(), - agent=gcd_agent.Agent(parent='parent_value'), - ) - - -@pytest.mark.parametrize("request_type", [ - agent.DeleteAgentRequest, - dict, -]) -def test_delete_agent(request_type, transport: str = 'grpc'): - client = AgentsClient( - 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_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. - assert response is None - - -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=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_agent), - '__call__') as call: - client.delete_agent() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == agent.DeleteAgentRequest() - -@pytest.mark.asyncio -async def test_delete_agent_async(transport: str = 'grpc_asyncio', request_type=agent.DeleteAgentRequest): - client = AgentsAsyncClient( - 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_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. - assert response is None - - -@pytest.mark.asyncio -async def test_delete_agent_async_from_dict(): - await test_delete_agent_async(request_type=dict) - - -def test_delete_agent_field_headers(): - 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. - 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_delete_agent_field_headers_async(): - 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. - 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_delete_agent_flattened(): - 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', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - arg = args[0].parent - mock_val = 'parent_value' - assert arg == mock_val - - -def test_delete_agent_flattened_error(): - client = AgentsClient( - 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_agent( - agent.DeleteAgentRequest(), - parent='parent_value', - ) - -@pytest.mark.asyncio -async def test_delete_agent_flattened_async(): - 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: - # 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_agent( - 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] - arg = args[0].parent - mock_val = 'parent_value' - assert arg == mock_val - -@pytest.mark.asyncio -async def test_delete_agent_flattened_error_async(): - client = AgentsAsyncClient( - 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_agent( - agent.DeleteAgentRequest(), - parent='parent_value', - ) - - -@pytest.mark.parametrize("request_type", [ - agent.SearchAgentsRequest, - dict, -]) -def test_search_agents(request_type, transport: str = 'grpc'): - client = AgentsClient( - 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.search_agents), - '__call__') as call: - # Designate an appropriate return value for the call. - 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' - - -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=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.search_agents), - '__call__') as call: - client.search_agents() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == agent.SearchAgentsRequest() - -@pytest.mark.asyncio -async def test_search_agents_async(transport: str = 'grpc_asyncio', request_type=agent.SearchAgentsRequest): - client = AgentsAsyncClient( - 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.search_agents), - '__call__') as call: - # Designate an appropriate return value for the call. - 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' - - -@pytest.mark.asyncio -async def test_search_agents_async_from_dict(): - await test_search_agents_async(request_type=dict) - - -def test_search_agents_field_headers(): - 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. - 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_search_agents_field_headers_async(): - 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. - with mock.patch.object( - type(client.transport.search_agents), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(agent.SearchAgentsResponse()) - 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] == 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_search_agents_flattened(): - 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', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - arg = args[0].parent - mock_val = 'parent_value' - assert arg == mock_val - - -def test_search_agents_flattened_error(): - client = AgentsClient( - 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.search_agents( - agent.SearchAgentsRequest(), - parent='parent_value', - ) - -@pytest.mark.asyncio -async def test_search_agents_flattened_async(): - 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: - # Designate an appropriate return value for the call. - call.return_value = agent.SearchAgentsResponse() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(agent.SearchAgentsResponse()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.search_agents( - 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] - arg = args[0].parent - mock_val = 'parent_value' - assert arg == mock_val - -@pytest.mark.asyncio -async def test_search_agents_flattened_error_async(): - client = AgentsAsyncClient( - 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.search_agents( - agent.SearchAgentsRequest(), - parent='parent_value', - ) - - -def test_search_agents_pager(transport_name: str = "grpc"): - client = AgentsClient( - credentials=ga_credentials.AnonymousCredentials, - transport=transport_name, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.search_agents), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - agent.SearchAgentsResponse( - agents=[ - agent.Agent(), - agent.Agent(), - agent.Agent(), - ], - next_page_token='abc', - ), - agent.SearchAgentsResponse( - agents=[], - next_page_token='def', - ), - agent.SearchAgentsResponse( - agents=[ - agent.Agent(), - ], - next_page_token='ghi', - ), - agent.SearchAgentsResponse( - agents=[ - agent.Agent(), - agent.Agent(), - ], - ), - RuntimeError, - ) - - metadata = () - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ('parent', ''), - )), - ) - pager = client.search_agents(request={}) - - assert pager._metadata == metadata - - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, agent.Agent) - for i in results) -def test_search_agents_pages(transport_name: str = "grpc"): - client = AgentsClient( - credentials=ga_credentials.AnonymousCredentials, - transport=transport_name, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.search_agents), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - agent.SearchAgentsResponse( - agents=[ - agent.Agent(), - agent.Agent(), - agent.Agent(), - ], - next_page_token='abc', - ), - agent.SearchAgentsResponse( - agents=[], - next_page_token='def', - ), - agent.SearchAgentsResponse( - agents=[ - agent.Agent(), - ], - next_page_token='ghi', - ), - agent.SearchAgentsResponse( - agents=[ - agent.Agent(), - agent.Agent(), - ], - ), - RuntimeError, - ) - pages = list(client.search_agents(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_search_agents_async_pager(): - 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__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - agent.SearchAgentsResponse( - agents=[ - agent.Agent(), - agent.Agent(), - agent.Agent(), - ], - next_page_token='abc', - ), - agent.SearchAgentsResponse( - agents=[], - next_page_token='def', - ), - agent.SearchAgentsResponse( - agents=[ - agent.Agent(), - ], - next_page_token='ghi', - ), - agent.SearchAgentsResponse( - agents=[ - agent.Agent(), - agent.Agent(), - ], - ), - RuntimeError, - ) - async_pager = await client.search_agents(request={},) - assert async_pager.next_page_token == 'abc' - responses = [] - async for response in async_pager: # pragma: no branch - responses.append(response) - - assert len(responses) == 6 - assert all(isinstance(i, agent.Agent) - for i in responses) - - -@pytest.mark.asyncio -async def test_search_agents_async_pages(): - 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__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - agent.SearchAgentsResponse( - agents=[ - agent.Agent(), - agent.Agent(), - agent.Agent(), - ], - next_page_token='abc', - ), - agent.SearchAgentsResponse( - agents=[], - next_page_token='def', - ), - agent.SearchAgentsResponse( - agents=[ - agent.Agent(), - ], - next_page_token='ghi', - ), - agent.SearchAgentsResponse( - agents=[ - agent.Agent(), - agent.Agent(), - ], - ), - RuntimeError, - ) - pages = [] - async for page_ in (await client.search_agents(request={})).pages: # pragma: no branch - pages.append(page_) - for page_, token in zip(pages, ['abc','def','ghi', '']): - assert page_.raw_page.next_page_token == token - -@pytest.mark.parametrize("request_type", [ - agent.TrainAgentRequest, - dict, -]) -def test_train_agent(request_type, transport: str = 'grpc'): - client = AgentsClient( - 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.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. - assert isinstance(response, future.Future) - - -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=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.train_agent), - '__call__') as call: - client.train_agent() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == agent.TrainAgentRequest() - -@pytest.mark.asyncio -async def test_train_agent_async(transport: str = 'grpc_asyncio', request_type=agent.TrainAgentRequest): - client = AgentsAsyncClient( - 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.train_agent), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name='operations/spam') - ) - response = await client.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. - assert isinstance(response, future.Future) - - -@pytest.mark.asyncio -async def test_train_agent_async_from_dict(): - await test_train_agent_async(request_type=dict) - - -def test_train_agent_field_headers(): - 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. - 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_train_agent_field_headers_async(): - 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. - with mock.patch.object( - type(client.transport.train_agent), - '__call__') as call: - 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. - 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_train_agent_flattened(): - 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', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - arg = args[0].parent - mock_val = 'parent_value' - assert arg == mock_val - - -def test_train_agent_flattened_error(): - client = AgentsClient( - 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.train_agent( - agent.TrainAgentRequest(), - parent='parent_value', - ) - -@pytest.mark.asyncio -async def test_train_agent_flattened_async(): - 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: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/op') - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name='operations/spam') - ) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.train_agent( - 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] - arg = args[0].parent - mock_val = 'parent_value' - assert arg == mock_val - -@pytest.mark.asyncio -async def test_train_agent_flattened_error_async(): - client = AgentsAsyncClient( - 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.train_agent( - agent.TrainAgentRequest(), - parent='parent_value', - ) - - -@pytest.mark.parametrize("request_type", [ - agent.ExportAgentRequest, - dict, -]) -def test_export_agent(request_type, transport: str = 'grpc'): - client = AgentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.export_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. - assert isinstance(response, future.Future) - - -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=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.export_agent), - '__call__') as call: - client.export_agent() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == agent.ExportAgentRequest() - -@pytest.mark.asyncio -async def test_export_agent_async(transport: str = 'grpc_asyncio', request_type=agent.ExportAgentRequest): - client = AgentsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.export_agent), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name='operations/spam') - ) - response = await client.export_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. - assert isinstance(response, future.Future) - - -@pytest.mark.asyncio -async def test_export_agent_async_from_dict(): - await test_export_agent_async(request_type=dict) - - -def test_export_agent_field_headers(): - 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. - 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_export_agent_field_headers_async(): - 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. - with mock.patch.object( - type(client.transport.export_agent), - '__call__') as call: - 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. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'parent=parent_value', - ) in kw['metadata'] - - -def test_export_agent_flattened(): - 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', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - arg = args[0].parent - mock_val = 'parent_value' - assert arg == mock_val - - -def test_export_agent_flattened_error(): - client = AgentsClient( - 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.export_agent( - agent.ExportAgentRequest(), - parent='parent_value', - ) - -@pytest.mark.asyncio -async def test_export_agent_flattened_async(): - 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: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/op') - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name='operations/spam') - ) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.export_agent( - 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] - arg = args[0].parent - mock_val = 'parent_value' - assert arg == mock_val - -@pytest.mark.asyncio -async def test_export_agent_flattened_error_async(): - client = AgentsAsyncClient( - 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.export_agent( - agent.ExportAgentRequest(), - parent='parent_value', - ) - - -@pytest.mark.parametrize("request_type", [ - agent.ImportAgentRequest, - dict, -]) -def test_import_agent(request_type, transport: str = 'grpc'): - client = AgentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.import_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. - assert isinstance(response, future.Future) - - -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=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.import_agent), - '__call__') as call: - client.import_agent() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == agent.ImportAgentRequest() - -@pytest.mark.asyncio -async def test_import_agent_async(transport: str = 'grpc_asyncio', request_type=agent.ImportAgentRequest): - client = AgentsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.import_agent), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name='operations/spam') - ) - response = await client.import_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. - assert isinstance(response, future.Future) - - -@pytest.mark.asyncio -async def test_import_agent_async_from_dict(): - await test_import_agent_async(request_type=dict) - - -def test_import_agent_field_headers(): - 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. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'parent=parent_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_import_agent_field_headers_async(): - 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. - with mock.patch.object( - type(client.transport.import_agent), - '__call__') as call: - 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. - 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'] - - -@pytest.mark.parametrize("request_type", [ - agent.RestoreAgentRequest, - dict, -]) -def test_restore_agent(request_type, transport: str = 'grpc'): - client = AgentsClient( - 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.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. - assert isinstance(response, future.Future) - - -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=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.restore_agent), - '__call__') as call: - client.restore_agent() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == agent.RestoreAgentRequest() - -@pytest.mark.asyncio -async def test_restore_agent_async(transport: str = 'grpc_asyncio', request_type=agent.RestoreAgentRequest): - client = AgentsAsyncClient( - 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.restore_agent), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name='operations/spam') - ) - response = await client.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. - assert isinstance(response, future.Future) - - -@pytest.mark.asyncio -async def test_restore_agent_async_from_dict(): - await test_restore_agent_async(request_type=dict) - - -def test_restore_agent_field_headers(): - 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. - 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_restore_agent_field_headers_async(): - 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. - with mock.patch.object( - type(client.transport.restore_agent), - '__call__') as call: - 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. - 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'] - - -@pytest.mark.parametrize("request_type", [ - agent.GetValidationResultRequest, - dict, -]) -def test_get_validation_result(request_type, transport: str = 'grpc'): - client = AgentsClient( - 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_validation_result), - '__call__') 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) - - -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=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_validation_result), - '__call__') as call: - client.get_validation_result() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == agent.GetValidationResultRequest() - -@pytest.mark.asyncio -async def test_get_validation_result_async(transport: str = 'grpc_asyncio', request_type=agent.GetValidationResultRequest): - client = AgentsAsyncClient( - 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_validation_result), - '__call__') as call: - # Designate an appropriate return value for the call. - 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. - assert isinstance(response, validation_result.ValidationResult) - - -@pytest.mark.asyncio -async def test_get_validation_result_async_from_dict(): - await test_get_validation_result_async(request_type=dict) - - -def test_get_validation_result_field_headers(): - 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. - with mock.patch.object( - 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. - 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_validation_result_field_headers_async(): - 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. - with mock.patch.object( - type(client.transport.get_validation_result), - '__call__') as call: - 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. - 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'] - - -@pytest.mark.parametrize("request_type", [ - agent.GetAgentRequest, - dict, -]) -def test_get_agent_rest(request_type): - client = AgentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = agent.Agent( - parent='parent_value', - display_name='display_name_value', - default_language_code='default_language_code_value', - supported_language_codes=['supported_language_codes_value'], - time_zone='time_zone_value', - description='description_value', - avatar_uri='avatar_uri_value', - enable_logging=True, - match_mode=agent.Agent.MatchMode.MATCH_MODE_HYBRID, - classification_threshold=0.25520000000000004, - api_version=agent.Agent.ApiVersion.API_VERSION_V1, - tier=agent.Agent.Tier.TIER_STANDARD, - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - pb_return_value = agent.Agent.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.get_agent(request) - - # 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.25520000000000004, rel_tol=1e-6) - assert response.api_version == agent.Agent.ApiVersion.API_VERSION_V1 - assert response.tier == agent.Agent.Tier.TIER_STANDARD - - -def test_get_agent_rest_required_fields(request_type=agent.GetAgentRequest): - transport_class = transports.AgentsRestTransport - - request_init = {} - request_init["parent"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - including_default_value_fields=False, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_agent._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["parent"] = 'parent_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_agent._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "parent" in jsonified_request - assert jsonified_request["parent"] == 'parent_value' - - client = AgentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = agent.Agent() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "get", - 'query_params': pb_request, - } - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - - pb_return_value = agent.Agent.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.get_agent(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_get_agent_rest_unset_required_fields(): - transport = transports.AgentsRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.get_agent._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("parent", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_get_agent_rest_interceptors(null_interceptor): - transport = transports.AgentsRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.AgentsRestInterceptor(), - ) - client = AgentsClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.AgentsRestInterceptor, "post_get_agent") as post, \ - mock.patch.object(transports.AgentsRestInterceptor, "pre_get_agent") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = agent.GetAgentRequest.pb(agent.GetAgentRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = agent.Agent.to_json(agent.Agent()) - - request = agent.GetAgentRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = agent.Agent() - - client.get_agent(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_get_agent_rest_bad_request(transport: str = 'rest', request_type=agent.GetAgentRequest): - client = AgentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.get_agent(request) - - -def test_get_agent_rest_flattened(): - client = AgentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = agent.Agent() - - # get arguments that satisfy an http rule for this method - sample_request = {'parent': 'projects/sample1'} - - # get truthy value for each flattened field - mock_args = dict( - parent='parent_value', - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - pb_return_value = agent.Agent.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.get_agent(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v2beta1/{parent=projects/*}/agent" % client.transport._host, args[1]) - - -def test_get_agent_rest_flattened_error(transport: str = 'rest'): - client = AgentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.get_agent( - agent.GetAgentRequest(), - parent='parent_value', - ) - - -def test_get_agent_rest_error(): - client = AgentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - gcd_agent.SetAgentRequest, - dict, -]) -def test_set_agent_rest(request_type): - client = AgentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'agent': {'parent': 'projects/sample1'}} - request_init["agent"] = {'parent': 'projects/sample1', 'display_name': 'display_name_value', 'default_language_code': 'default_language_code_value', 'supported_language_codes': ['supported_language_codes_value1', 'supported_language_codes_value2'], 'time_zone': 'time_zone_value', 'description': 'description_value', 'avatar_uri': 'avatar_uri_value', 'enable_logging': True, 'match_mode': 1, 'classification_threshold': 0.25520000000000004, 'api_version': 1, 'tier': 1} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = gcd_agent.Agent( - parent='parent_value', - display_name='display_name_value', - default_language_code='default_language_code_value', - supported_language_codes=['supported_language_codes_value'], - time_zone='time_zone_value', - description='description_value', - avatar_uri='avatar_uri_value', - enable_logging=True, - match_mode=gcd_agent.Agent.MatchMode.MATCH_MODE_HYBRID, - classification_threshold=0.25520000000000004, - api_version=gcd_agent.Agent.ApiVersion.API_VERSION_V1, - tier=gcd_agent.Agent.Tier.TIER_STANDARD, - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - pb_return_value = gcd_agent.Agent.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.set_agent(request) - - # 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.25520000000000004, rel_tol=1e-6) - assert response.api_version == gcd_agent.Agent.ApiVersion.API_VERSION_V1 - assert response.tier == gcd_agent.Agent.Tier.TIER_STANDARD - - -def test_set_agent_rest_required_fields(request_type=gcd_agent.SetAgentRequest): - transport_class = transports.AgentsRestTransport - - request_init = {} - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - including_default_value_fields=False, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).set_agent._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).set_agent._get_unset_required_fields(jsonified_request) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("update_mask", )) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - - client = AgentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = gcd_agent.Agent() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "post", - 'query_params': pb_request, - } - transcode_result['body'] = pb_request - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - - pb_return_value = gcd_agent.Agent.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.set_agent(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_set_agent_rest_unset_required_fields(): - transport = transports.AgentsRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.set_agent._get_unset_required_fields({}) - assert set(unset_fields) == (set(("updateMask", )) & set(("agent", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_set_agent_rest_interceptors(null_interceptor): - transport = transports.AgentsRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.AgentsRestInterceptor(), - ) - client = AgentsClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.AgentsRestInterceptor, "post_set_agent") as post, \ - mock.patch.object(transports.AgentsRestInterceptor, "pre_set_agent") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = gcd_agent.SetAgentRequest.pb(gcd_agent.SetAgentRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = gcd_agent.Agent.to_json(gcd_agent.Agent()) - - request = gcd_agent.SetAgentRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = gcd_agent.Agent() - - client.set_agent(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_set_agent_rest_bad_request(transport: str = 'rest', request_type=gcd_agent.SetAgentRequest): - client = AgentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'agent': {'parent': 'projects/sample1'}} - request_init["agent"] = {'parent': 'projects/sample1', 'display_name': 'display_name_value', 'default_language_code': 'default_language_code_value', 'supported_language_codes': ['supported_language_codes_value1', 'supported_language_codes_value2'], 'time_zone': 'time_zone_value', 'description': 'description_value', 'avatar_uri': 'avatar_uri_value', 'enable_logging': True, 'match_mode': 1, 'classification_threshold': 0.25520000000000004, 'api_version': 1, 'tier': 1} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.set_agent(request) - - -def test_set_agent_rest_flattened(): - client = AgentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = gcd_agent.Agent() - - # get arguments that satisfy an http rule for this method - sample_request = {'agent': {'parent': 'projects/sample1'}} - - # get truthy value for each flattened field - mock_args = dict( - agent=gcd_agent.Agent(parent='parent_value'), - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - pb_return_value = gcd_agent.Agent.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.set_agent(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v2beta1/{agent.parent=projects/*}/agent" % client.transport._host, args[1]) - - -def test_set_agent_rest_flattened_error(transport: str = 'rest'): - client = AgentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.set_agent( - gcd_agent.SetAgentRequest(), - agent=gcd_agent.Agent(parent='parent_value'), - ) - - -def test_set_agent_rest_error(): - client = AgentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - agent.DeleteAgentRequest, - dict, -]) -def test_delete_agent_rest(request_type): - client = AgentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = None - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = '' - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.delete_agent(request) - - # Establish that the response is the type that we expect. - assert response is None - - -def test_delete_agent_rest_required_fields(request_type=agent.DeleteAgentRequest): - transport_class = transports.AgentsRestTransport - - request_init = {} - request_init["parent"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - including_default_value_fields=False, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).delete_agent._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["parent"] = 'parent_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).delete_agent._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "parent" in jsonified_request - assert jsonified_request["parent"] == 'parent_value' - - client = AgentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = None - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "delete", - 'query_params': pb_request, - } - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - json_return_value = '' - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.delete_agent(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_delete_agent_rest_unset_required_fields(): - transport = transports.AgentsRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.delete_agent._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("parent", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_delete_agent_rest_interceptors(null_interceptor): - transport = transports.AgentsRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.AgentsRestInterceptor(), - ) - client = AgentsClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.AgentsRestInterceptor, "pre_delete_agent") as pre: - pre.assert_not_called() - pb_message = agent.DeleteAgentRequest.pb(agent.DeleteAgentRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - - request = agent.DeleteAgentRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - - client.delete_agent(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - - -def test_delete_agent_rest_bad_request(transport: str = 'rest', request_type=agent.DeleteAgentRequest): - client = AgentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.delete_agent(request) - - -def test_delete_agent_rest_flattened(): - client = AgentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = None - - # get arguments that satisfy an http rule for this method - sample_request = {'parent': 'projects/sample1'} - - # get truthy value for each flattened field - mock_args = dict( - parent='parent_value', - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = '' - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.delete_agent(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v2beta1/{parent=projects/*}/agent" % client.transport._host, args[1]) - - -def test_delete_agent_rest_flattened_error(transport: str = 'rest'): - client = AgentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.delete_agent( - agent.DeleteAgentRequest(), - parent='parent_value', - ) - - -def test_delete_agent_rest_error(): - client = AgentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - agent.SearchAgentsRequest, - dict, -]) -def test_search_agents_rest(request_type): - client = AgentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = agent.SearchAgentsResponse( - next_page_token='next_page_token_value', - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - pb_return_value = agent.SearchAgentsResponse.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.search_agents(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.SearchAgentsPager) - assert response.next_page_token == 'next_page_token_value' - - -def test_search_agents_rest_required_fields(request_type=agent.SearchAgentsRequest): - transport_class = transports.AgentsRestTransport - - request_init = {} - request_init["parent"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - including_default_value_fields=False, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).search_agents._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["parent"] = 'parent_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).search_agents._get_unset_required_fields(jsonified_request) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("page_size", "page_token", )) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "parent" in jsonified_request - assert jsonified_request["parent"] == 'parent_value' - - client = AgentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = agent.SearchAgentsResponse() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "get", - 'query_params': pb_request, - } - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - - pb_return_value = agent.SearchAgentsResponse.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.search_agents(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_search_agents_rest_unset_required_fields(): - transport = transports.AgentsRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.search_agents._get_unset_required_fields({}) - assert set(unset_fields) == (set(("pageSize", "pageToken", )) & set(("parent", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_search_agents_rest_interceptors(null_interceptor): - transport = transports.AgentsRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.AgentsRestInterceptor(), - ) - client = AgentsClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.AgentsRestInterceptor, "post_search_agents") as post, \ - mock.patch.object(transports.AgentsRestInterceptor, "pre_search_agents") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = agent.SearchAgentsRequest.pb(agent.SearchAgentsRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = agent.SearchAgentsResponse.to_json(agent.SearchAgentsResponse()) - - request = agent.SearchAgentsRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = agent.SearchAgentsResponse() - - client.search_agents(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_search_agents_rest_bad_request(transport: str = 'rest', request_type=agent.SearchAgentsRequest): - client = AgentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.search_agents(request) - - -def test_search_agents_rest_flattened(): - client = AgentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = agent.SearchAgentsResponse() - - # get arguments that satisfy an http rule for this method - sample_request = {'parent': 'projects/sample1'} - - # get truthy value for each flattened field - mock_args = dict( - parent='parent_value', - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - pb_return_value = agent.SearchAgentsResponse.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.search_agents(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v2beta1/{parent=projects/*}/agent:search" % client.transport._host, args[1]) - - -def test_search_agents_rest_flattened_error(transport: str = 'rest'): - client = AgentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.search_agents( - agent.SearchAgentsRequest(), - parent='parent_value', - ) - - -def test_search_agents_rest_pager(transport: str = 'rest'): - client = AgentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # TODO(kbandes): remove this mock unless there's a good reason for it. - #with mock.patch.object(path_template, 'transcode') as transcode: - # Set the response as a series of pages - response = ( - agent.SearchAgentsResponse( - agents=[ - agent.Agent(), - agent.Agent(), - agent.Agent(), - ], - next_page_token='abc', - ), - agent.SearchAgentsResponse( - agents=[], - next_page_token='def', - ), - agent.SearchAgentsResponse( - agents=[ - agent.Agent(), - ], - next_page_token='ghi', - ), - agent.SearchAgentsResponse( - agents=[ - agent.Agent(), - agent.Agent(), - ], - ), - ) - # Two responses for two calls - response = response + response - - # Wrap the values into proper Response objs - response = tuple(agent.SearchAgentsResponse.to_json(x) for x in response) - return_values = tuple(Response() for i in response) - for return_val, response_val in zip(return_values, response): - return_val._content = response_val.encode('UTF-8') - return_val.status_code = 200 - req.side_effect = return_values - - sample_request = {'parent': 'projects/sample1'} - - pager = client.search_agents(request=sample_request) - - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, agent.Agent) - for i in results) - - pages = list(client.search_agents(request=sample_request).pages) - for page_, token in zip(pages, ['abc','def','ghi', '']): - assert page_.raw_page.next_page_token == token - - -@pytest.mark.parametrize("request_type", [ - agent.TrainAgentRequest, - dict, -]) -def test_train_agent_rest(request_type): - client = AgentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name='operations/spam') - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.train_agent(request) - - # Establish that the response is the type that we expect. - assert response.operation.name == "operations/spam" - - -def test_train_agent_rest_required_fields(request_type=agent.TrainAgentRequest): - transport_class = transports.AgentsRestTransport - - request_init = {} - request_init["parent"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - including_default_value_fields=False, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).train_agent._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["parent"] = 'parent_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).train_agent._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "parent" in jsonified_request - assert jsonified_request["parent"] == 'parent_value' - - client = AgentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name='operations/spam') - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "post", - 'query_params': pb_request, - } - transcode_result['body'] = pb_request - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.train_agent(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_train_agent_rest_unset_required_fields(): - transport = transports.AgentsRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.train_agent._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("parent", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_train_agent_rest_interceptors(null_interceptor): - transport = transports.AgentsRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.AgentsRestInterceptor(), - ) - client = AgentsClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(operation.Operation, "_set_result_from_operation"), \ - mock.patch.object(transports.AgentsRestInterceptor, "post_train_agent") as post, \ - mock.patch.object(transports.AgentsRestInterceptor, "pre_train_agent") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = agent.TrainAgentRequest.pb(agent.TrainAgentRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = json_format.MessageToJson(operations_pb2.Operation()) - - request = agent.TrainAgentRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = operations_pb2.Operation() - - client.train_agent(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_train_agent_rest_bad_request(transport: str = 'rest', request_type=agent.TrainAgentRequest): - client = AgentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.train_agent(request) - - -def test_train_agent_rest_flattened(): - client = AgentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name='operations/spam') - - # get arguments that satisfy an http rule for this method - sample_request = {'parent': 'projects/sample1'} - - # get truthy value for each flattened field - mock_args = dict( - parent='parent_value', - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.train_agent(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v2beta1/{parent=projects/*}/agent:train" % client.transport._host, args[1]) - - -def test_train_agent_rest_flattened_error(transport: str = 'rest'): - client = AgentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.train_agent( - agent.TrainAgentRequest(), - parent='parent_value', - ) - - -def test_train_agent_rest_error(): - client = AgentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - agent.ExportAgentRequest, - dict, -]) -def test_export_agent_rest(request_type): - client = AgentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name='operations/spam') - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.export_agent(request) - - # Establish that the response is the type that we expect. - assert response.operation.name == "operations/spam" - - -def test_export_agent_rest_required_fields(request_type=agent.ExportAgentRequest): - transport_class = transports.AgentsRestTransport - - request_init = {} - request_init["parent"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - including_default_value_fields=False, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).export_agent._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["parent"] = 'parent_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).export_agent._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "parent" in jsonified_request - assert jsonified_request["parent"] == 'parent_value' - - client = AgentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name='operations/spam') - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "post", - 'query_params': pb_request, - } - transcode_result['body'] = pb_request - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.export_agent(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_export_agent_rest_unset_required_fields(): - transport = transports.AgentsRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.export_agent._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("parent", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_export_agent_rest_interceptors(null_interceptor): - transport = transports.AgentsRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.AgentsRestInterceptor(), - ) - client = AgentsClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(operation.Operation, "_set_result_from_operation"), \ - mock.patch.object(transports.AgentsRestInterceptor, "post_export_agent") as post, \ - mock.patch.object(transports.AgentsRestInterceptor, "pre_export_agent") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = agent.ExportAgentRequest.pb(agent.ExportAgentRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = json_format.MessageToJson(operations_pb2.Operation()) - - request = agent.ExportAgentRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = operations_pb2.Operation() - - client.export_agent(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_export_agent_rest_bad_request(transport: str = 'rest', request_type=agent.ExportAgentRequest): - client = AgentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.export_agent(request) - - -def test_export_agent_rest_flattened(): - client = AgentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name='operations/spam') - - # get arguments that satisfy an http rule for this method - sample_request = {'parent': 'projects/sample1'} - - # get truthy value for each flattened field - mock_args = dict( - parent='parent_value', - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.export_agent(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v2beta1/{parent=projects/*}/agent:export" % client.transport._host, args[1]) - - -def test_export_agent_rest_flattened_error(transport: str = 'rest'): - client = AgentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.export_agent( - agent.ExportAgentRequest(), - parent='parent_value', - ) - - -def test_export_agent_rest_error(): - client = AgentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - agent.ImportAgentRequest, - dict, -]) -def test_import_agent_rest(request_type): - client = AgentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name='operations/spam') - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.import_agent(request) - - # Establish that the response is the type that we expect. - assert response.operation.name == "operations/spam" - - -def test_import_agent_rest_required_fields(request_type=agent.ImportAgentRequest): - transport_class = transports.AgentsRestTransport - - request_init = {} - request_init["parent"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - including_default_value_fields=False, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).import_agent._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["parent"] = 'parent_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).import_agent._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "parent" in jsonified_request - assert jsonified_request["parent"] == 'parent_value' - - client = AgentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name='operations/spam') - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "post", - 'query_params': pb_request, - } - transcode_result['body'] = pb_request - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.import_agent(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_import_agent_rest_unset_required_fields(): - transport = transports.AgentsRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.import_agent._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("parent", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_import_agent_rest_interceptors(null_interceptor): - transport = transports.AgentsRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.AgentsRestInterceptor(), - ) - client = AgentsClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(operation.Operation, "_set_result_from_operation"), \ - mock.patch.object(transports.AgentsRestInterceptor, "post_import_agent") as post, \ - mock.patch.object(transports.AgentsRestInterceptor, "pre_import_agent") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = agent.ImportAgentRequest.pb(agent.ImportAgentRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = json_format.MessageToJson(operations_pb2.Operation()) - - request = agent.ImportAgentRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = operations_pb2.Operation() - - client.import_agent(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_import_agent_rest_bad_request(transport: str = 'rest', request_type=agent.ImportAgentRequest): - client = AgentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.import_agent(request) - - -def test_import_agent_rest_error(): - client = AgentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - agent.RestoreAgentRequest, - dict, -]) -def test_restore_agent_rest(request_type): - client = AgentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name='operations/spam') - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.restore_agent(request) - - # Establish that the response is the type that we expect. - assert response.operation.name == "operations/spam" - - -def test_restore_agent_rest_required_fields(request_type=agent.RestoreAgentRequest): - transport_class = transports.AgentsRestTransport - - request_init = {} - request_init["parent"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - including_default_value_fields=False, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).restore_agent._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["parent"] = 'parent_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).restore_agent._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "parent" in jsonified_request - assert jsonified_request["parent"] == 'parent_value' - - client = AgentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name='operations/spam') - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "post", - 'query_params': pb_request, - } - transcode_result['body'] = pb_request - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.restore_agent(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_restore_agent_rest_unset_required_fields(): - transport = transports.AgentsRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.restore_agent._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("parent", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_restore_agent_rest_interceptors(null_interceptor): - transport = transports.AgentsRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.AgentsRestInterceptor(), - ) - client = AgentsClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(operation.Operation, "_set_result_from_operation"), \ - mock.patch.object(transports.AgentsRestInterceptor, "post_restore_agent") as post, \ - mock.patch.object(transports.AgentsRestInterceptor, "pre_restore_agent") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = agent.RestoreAgentRequest.pb(agent.RestoreAgentRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = json_format.MessageToJson(operations_pb2.Operation()) - - request = agent.RestoreAgentRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = operations_pb2.Operation() - - client.restore_agent(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_restore_agent_rest_bad_request(transport: str = 'rest', request_type=agent.RestoreAgentRequest): - client = AgentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.restore_agent(request) - - -def test_restore_agent_rest_error(): - client = AgentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - agent.GetValidationResultRequest, - dict, -]) -def test_get_validation_result_rest(request_type): - client = AgentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = validation_result.ValidationResult( - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - pb_return_value = validation_result.ValidationResult.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.get_validation_result(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, validation_result.ValidationResult) - - -def test_get_validation_result_rest_required_fields(request_type=agent.GetValidationResultRequest): - transport_class = transports.AgentsRestTransport - - request_init = {} - request_init["parent"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - including_default_value_fields=False, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_validation_result._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["parent"] = 'parent_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_validation_result._get_unset_required_fields(jsonified_request) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("language_code", )) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "parent" in jsonified_request - assert jsonified_request["parent"] == 'parent_value' - - client = AgentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = validation_result.ValidationResult() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "get", - 'query_params': pb_request, - } - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - - pb_return_value = validation_result.ValidationResult.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.get_validation_result(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_get_validation_result_rest_unset_required_fields(): - transport = transports.AgentsRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.get_validation_result._get_unset_required_fields({}) - assert set(unset_fields) == (set(("languageCode", )) & set(("parent", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_get_validation_result_rest_interceptors(null_interceptor): - transport = transports.AgentsRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.AgentsRestInterceptor(), - ) - client = AgentsClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.AgentsRestInterceptor, "post_get_validation_result") as post, \ - mock.patch.object(transports.AgentsRestInterceptor, "pre_get_validation_result") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = agent.GetValidationResultRequest.pb(agent.GetValidationResultRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = validation_result.ValidationResult.to_json(validation_result.ValidationResult()) - - request = agent.GetValidationResultRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = validation_result.ValidationResult() - - client.get_validation_result(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_get_validation_result_rest_bad_request(transport: str = 'rest', request_type=agent.GetValidationResultRequest): - client = AgentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.get_validation_result(request) - - -def test_get_validation_result_rest_error(): - client = AgentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -def test_credentials_transport_error(): - # It is an error to provide credentials and a transport instance. - transport = transports.AgentsGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = AgentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # It is an error to provide a credentials file and a transport instance. - transport = transports.AgentsGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = AgentsClient( - client_options={"credentials_file": "credentials.json"}, - transport=transport, - ) - - # It is an error to provide an api_key and a transport instance. - transport = transports.AgentsGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - options = client_options.ClientOptions() - options.api_key = "api_key" - with pytest.raises(ValueError): - client = AgentsClient( - client_options=options, - transport=transport, - ) - - # It is an error to provide an api_key and a credential. - options = mock.Mock() - options.api_key = "api_key" - with pytest.raises(ValueError): - client = AgentsClient( - client_options=options, - credentials=ga_credentials.AnonymousCredentials() - ) - - # It is an error to provide scopes and a transport instance. - transport = transports.AgentsGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = AgentsClient( - client_options={"scopes": ["1", "2"]}, - transport=transport, - ) - - -def test_transport_instance(): - # A client may be instantiated with a custom transport instance. - transport = transports.AgentsGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - client = AgentsClient(transport=transport) - assert client.transport is transport - -def test_transport_get_channel(): - # A client may be instantiated with a custom transport instance. - transport = transports.AgentsGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - - transport = transports.AgentsGrpcAsyncIOTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - -@pytest.mark.parametrize("transport_class", [ - transports.AgentsGrpcTransport, - transports.AgentsGrpcAsyncIOTransport, - transports.AgentsRestTransport, -]) -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() - -@pytest.mark.parametrize("transport_name", [ - "grpc", - "rest", -]) -def test_transport_kind(transport_name): - transport = AgentsClient.get_transport_class(transport_name)( - credentials=ga_credentials.AnonymousCredentials(), - ) - assert transport.kind == transport_name - -def test_transport_grpc_default(): - # A client should use the gRPC transport by default. - 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(core_exceptions.DuplicateCredentialArgs): - transport = transports.AgentsTransport( - credentials=ga_credentials.AnonymousCredentials(), - credentials_file="credentials.json" - ) - - -def test_agents_base_transport(): - # Instantiate the base transport. - with mock.patch('google.cloud.dialogflow_v2beta1.services.agents.transports.AgentsTransport.__init__') as Transport: - Transport.return_value = None - transport = transports.AgentsTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Every method on the transport should just blindly - # raise NotImplementedError. - methods = ( - 'get_agent', - 'set_agent', - 'delete_agent', - 'search_agents', - 'train_agent', - 'export_agent', - 'import_agent', - 'restore_agent', - 'get_validation_result', - 'get_location', - 'list_locations', - 'get_operation', - 'cancel_operation', - 'list_operations', - ) - for method in methods: - with pytest.raises(NotImplementedError): - getattr(transport, method)(request=object()) - - with pytest.raises(NotImplementedError): - transport.close() - - # Additionally, the LRO client (a property) should - # also raise NotImplementedError - with pytest.raises(NotImplementedError): - transport.operations_client - - # Catch all for all remaining methods and properties - remainder = [ - 'kind', - ] - for r in remainder: - with pytest.raises(NotImplementedError): - getattr(transport, r)() - - -def test_agents_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.agents.transports.AgentsTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.AgentsTransport( - credentials_file="credentials.json", - quota_project_id="octopus", - ) - load_creds.assert_called_once_with("credentials.json", - scopes=None, - default_scopes=( - 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/dialogflow', -), - quota_project_id="octopus", - ) - - -def test_agents_base_transport_with_adc(): - # Test the default credentials are used if credentials and credentials_file are None. - with mock.patch.object(google.auth, 'default', autospec=True) as adc, mock.patch('google.cloud.dialogflow_v2beta1.services.agents.transports.AgentsTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.AgentsTransport() - adc.assert_called_once() - - -def test_agents_auth_adc(): - # If no credentials are provided, we should use ADC credentials. - with mock.patch.object(google.auth, 'default', autospec=True) as adc: - 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, - ) - - -@pytest.mark.parametrize( - "transport_class", - [ - transports.AgentsGrpcTransport, - transports.AgentsGrpcAsyncIOTransport, - ], -) -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(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, - transports.AgentsRestTransport, - ], -) -def test_agents_transport_auth_gdch_credentials(transport_class): - host = 'https://language.com' - api_audience_tests = [None, 'https://language2.com'] - api_audience_expect = [host, 'https://language2.com'] - for t, e in zip(api_audience_tests, api_audience_expect): - with mock.patch.object(google.auth, 'default', autospec=True) as adc: - gdch_mock = mock.MagicMock() - type(gdch_mock).with_gdch_audience = mock.PropertyMock(return_value=gdch_mock) - adc.return_value = (gdch_mock, None) - transport_class(host=host, api_audience=t) - gdch_mock.with_gdch_audience.assert_called_once_with( - e - ) - - -@pytest.mark.parametrize( - "transport_class,grpc_helpers", - [ - (transports.AgentsGrpcTransport, grpc_helpers), - (transports.AgentsGrpcAsyncIOTransport, grpc_helpers_async) - ], -) -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", [transports.AgentsGrpcTransport, transports.AgentsGrpcAsyncIOTransport]) -def test_agents_grpc_transport_client_cert_source_for_mtls( - transport_class -): - cred = ga_credentials.AnonymousCredentials() - - # Check ssl_channel_credentials is used if provided. - with mock.patch.object(transport_class, "create_channel") as mock_create_channel: - mock_ssl_channel_creds = mock.Mock() - transport_class( - host="squid.clam.whelk", - credentials=cred, - ssl_channel_credentials=mock_ssl_channel_creds - ) - mock_create_channel.assert_called_once_with( - "squid.clam.whelk:443", - credentials=cred, - credentials_file=None, - scopes=None, - ssl_credentials=mock_ssl_channel_creds, - quota_project_id=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - # Check if ssl_channel_credentials is not provided, then client_cert_source_for_mtls - # is used. - with mock.patch.object(transport_class, "create_channel", return_value=mock.Mock()): - with mock.patch("grpc.ssl_channel_credentials") as mock_ssl_cred: - transport_class( - credentials=cred, - client_cert_source_for_mtls=client_cert_source_callback - ) - expected_cert, expected_key = client_cert_source_callback() - mock_ssl_cred.assert_called_once_with( - certificate_chain=expected_cert, - private_key=expected_key - ) - -def test_agents_http_transport_client_cert_source_for_mtls(): - cred = ga_credentials.AnonymousCredentials() - with mock.patch("google.auth.transport.requests.AuthorizedSession.configure_mtls_channel") as mock_configure_mtls_channel: - transports.AgentsRestTransport ( - credentials=cred, - client_cert_source_for_mtls=client_cert_source_callback - ) - mock_configure_mtls_channel.assert_called_once_with(client_cert_source_callback) - - -def test_agents_rest_lro_client(): - client = AgentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - transport = client.transport - - # Ensure that we have a api-core operations client. - assert isinstance( - transport.operations_client, - operations_v1.AbstractOperationsClient, - ) - - # Ensure that subsequent calls to the property send the exact same object. - assert transport.operations_client is transport.operations_client - - -@pytest.mark.parametrize("transport_name", [ - "grpc", - "grpc_asyncio", - "rest", -]) -def test_agents_host_no_port(transport_name): - client = AgentsClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='dialogflow.googleapis.com'), - transport=transport_name, - ) - assert client.transport._host == ( - 'dialogflow.googleapis.com:443' - if transport_name in ['grpc', 'grpc_asyncio'] - else 'https://dialogflow.googleapis.com' - ) - -@pytest.mark.parametrize("transport_name", [ - "grpc", - "grpc_asyncio", - "rest", -]) -def test_agents_host_with_port(transport_name): - client = AgentsClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='dialogflow.googleapis.com:8000'), - transport=transport_name, - ) - assert client.transport._host == ( - 'dialogflow.googleapis.com:8000' - if transport_name in ['grpc', 'grpc_asyncio'] - else 'https://dialogflow.googleapis.com:8000' - ) - -@pytest.mark.parametrize("transport_name", [ - "rest", -]) -def test_agents_client_transport_session_collision(transport_name): - creds1 = ga_credentials.AnonymousCredentials() - creds2 = ga_credentials.AnonymousCredentials() - client1 = AgentsClient( - credentials=creds1, - transport=transport_name, - ) - client2 = AgentsClient( - credentials=creds2, - transport=transport_name, - ) - session1 = client1.transport.get_agent._session - session2 = client2.transport.get_agent._session - assert session1 != session2 - session1 = client1.transport.set_agent._session - session2 = client2.transport.set_agent._session - assert session1 != session2 - session1 = client1.transport.delete_agent._session - session2 = client2.transport.delete_agent._session - assert session1 != session2 - session1 = client1.transport.search_agents._session - session2 = client2.transport.search_agents._session - assert session1 != session2 - session1 = client1.transport.train_agent._session - session2 = client2.transport.train_agent._session - assert session1 != session2 - session1 = client1.transport.export_agent._session - session2 = client2.transport.export_agent._session - assert session1 != session2 - session1 = client1.transport.import_agent._session - session2 = client2.transport.import_agent._session - assert session1 != session2 - session1 = client1.transport.restore_agent._session - session2 = client2.transport.restore_agent._session - assert session1 != session2 - session1 = client1.transport.get_validation_result._session - session2 = client2.transport.get_validation_result._session - assert session1 != session2 -def test_agents_grpc_transport_channel(): - channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.AgentsGrpcTransport( - 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_agents_grpc_asyncio_transport_channel(): - channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.AgentsGrpcAsyncIOTransport( - 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.AgentsGrpcTransport, transports.AgentsGrpcAsyncIOTransport]) -def test_agents_transport_channel_mtls_with_client_cert_source( - transport_class -): - with mock.patch("grpc.ssl_channel_credentials", autospec=True) as grpc_ssl_channel_cred: - with mock.patch.object(transport_class, "create_channel") as grpc_create_channel: - mock_ssl_cred = mock.Mock() - grpc_ssl_channel_cred.return_value = mock_ssl_cred - - mock_grpc_channel = mock.Mock() - grpc_create_channel.return_value = mock_grpc_channel - - cred = ga_credentials.AnonymousCredentials() - with pytest.warns(DeprecationWarning): - with mock.patch.object(google.auth, 'default') as adc: - adc.return_value = (cred, None) - transport = transport_class( - host="squid.clam.whelk", - api_mtls_endpoint="mtls.squid.clam.whelk", - client_cert_source=client_cert_source_callback, - ) - adc.assert_called_once() - - grpc_ssl_channel_cred.assert_called_once_with( - certificate_chain=b"cert bytes", private_key=b"key bytes" - ) - grpc_create_channel.assert_called_once_with( - "mtls.squid.clam.whelk:443", - credentials=cred, - credentials_file=None, - scopes=None, - ssl_credentials=mock_ssl_cred, - quota_project_id=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - assert transport.grpc_channel == mock_grpc_channel - assert transport._ssl_channel_credentials == mock_ssl_cred - - -# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are -# removed from grpc/grpc_asyncio transport constructor. -@pytest.mark.parametrize("transport_class", [transports.AgentsGrpcTransport, transports.AgentsGrpcAsyncIOTransport]) -def test_agents_transport_channel_mtls_with_adc( - transport_class -): - mock_ssl_cred = mock.Mock() - with mock.patch.multiple( - "google.auth.transport.grpc.SslCredentials", - __init__=mock.Mock(return_value=None), - ssl_credentials=mock.PropertyMock(return_value=mock_ssl_cred), - ): - with mock.patch.object(transport_class, "create_channel") as grpc_create_channel: - mock_grpc_channel = mock.Mock() - grpc_create_channel.return_value = mock_grpc_channel - mock_cred = mock.Mock() - - with pytest.warns(DeprecationWarning): - transport = transport_class( - host="squid.clam.whelk", - credentials=mock_cred, - api_mtls_endpoint="mtls.squid.clam.whelk", - client_cert_source=None, - ) - - grpc_create_channel.assert_called_once_with( - "mtls.squid.clam.whelk:443", - credentials=mock_cred, - credentials_file=None, - scopes=None, - ssl_credentials=mock_ssl_cred, - quota_project_id=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - assert transport.grpc_channel == mock_grpc_channel - - -def test_agents_grpc_lro_client(): - client = AgentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - transport = client.transport - - # Ensure that we have a api-core operations client. - assert isinstance( - transport.operations_client, - operations_v1.OperationsClient, - ) - - # Ensure that subsequent calls to the property send the exact same object. - assert transport.operations_client is transport.operations_client - - -def test_agents_grpc_lro_async_client(): - client = AgentsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc_asyncio', - ) - transport = client.transport - - # Ensure that we have a api-core operations client. - assert isinstance( - transport.operations_client, - operations_v1.OperationsAsyncClient, - ) - - # Ensure that subsequent calls to the property send the exact same object. - assert transport.operations_client is transport.operations_client - - -def test_agent_path(): - project = "squid" - expected = "projects/{project}/agent".format(project=project, ) - actual = AgentsClient.agent_path(project) - assert expected == actual - - -def test_parse_agent_path(): - expected = { - "project": "clam", - } - path = AgentsClient.agent_path(**expected) - - # Check that the path construction is reversible. - actual = AgentsClient.parse_agent_path(path) - assert expected == actual - -def test_common_billing_account_path(): - billing_account = "whelk" - expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) - actual = AgentsClient.common_billing_account_path(billing_account) - assert expected == actual - - -def test_parse_common_billing_account_path(): - expected = { - "billing_account": "octopus", - } - path = AgentsClient.common_billing_account_path(**expected) - - # Check that the path construction is reversible. - actual = AgentsClient.parse_common_billing_account_path(path) - assert expected == actual - -def test_common_folder_path(): - folder = "oyster" - expected = "folders/{folder}".format(folder=folder, ) - actual = AgentsClient.common_folder_path(folder) - assert expected == actual - - -def test_parse_common_folder_path(): - expected = { - "folder": "nudibranch", - } - path = AgentsClient.common_folder_path(**expected) - - # Check that the path construction is reversible. - actual = AgentsClient.parse_common_folder_path(path) - assert expected == actual - -def test_common_organization_path(): - organization = "cuttlefish" - expected = "organizations/{organization}".format(organization=organization, ) - actual = AgentsClient.common_organization_path(organization) - assert expected == actual - - -def test_parse_common_organization_path(): - expected = { - "organization": "mussel", - } - path = AgentsClient.common_organization_path(**expected) - - # Check that the path construction is reversible. - actual = AgentsClient.parse_common_organization_path(path) - assert expected == actual - -def test_common_project_path(): - project = "winkle" - expected = "projects/{project}".format(project=project, ) - actual = AgentsClient.common_project_path(project) - assert expected == actual - - -def test_parse_common_project_path(): - expected = { - "project": "nautilus", - } - path = AgentsClient.common_project_path(**expected) - - # Check that the path construction is reversible. - actual = AgentsClient.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 = AgentsClient.common_location_path(project, location) - assert expected == actual - - -def test_parse_common_location_path(): - expected = { - "project": "squid", - "location": "clam", - } - path = AgentsClient.common_location_path(**expected) - - # Check that the path construction is reversible. - actual = AgentsClient.parse_common_location_path(path) - assert expected == actual - - -def test_client_with_default_client_info(): - client_info = gapic_v1.client_info.ClientInfo() - - with mock.patch.object(transports.AgentsTransport, '_prep_wrapped_messages') as prep: - client = AgentsClient( - credentials=ga_credentials.AnonymousCredentials(), - client_info=client_info, - ) - prep.assert_called_once_with(client_info) - - with mock.patch.object(transports.AgentsTransport, '_prep_wrapped_messages') as prep: - transport_class = AgentsClient.get_transport_class() - transport = transport_class( - credentials=ga_credentials.AnonymousCredentials(), - client_info=client_info, - ) - prep.assert_called_once_with(client_info) - -@pytest.mark.asyncio -async def test_transport_close_async(): - client = AgentsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - with mock.patch.object(type(getattr(client.transport, "grpc_channel")), "close") as close: - async with client: - close.assert_not_called() - close.assert_called_once() - - -def test_get_location_rest_bad_request(transport: str = 'rest', request_type=locations_pb2.GetLocationRequest): - client = AgentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - request = request_type() - request = json_format.ParseDict({'name': 'projects/sample1/locations/sample2'}, request) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.get_location(request) - -@pytest.mark.parametrize("request_type", [ - locations_pb2.GetLocationRequest, - dict, -]) -def test_get_location_rest(request_type): - client = AgentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request_init = {'name': 'projects/sample1/locations/sample2'} - request = request_type(**request_init) - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = locations_pb2.Location() - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.get_location(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, locations_pb2.Location) - -def test_list_locations_rest_bad_request(transport: str = 'rest', request_type=locations_pb2.ListLocationsRequest): - client = AgentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - request = request_type() - request = json_format.ParseDict({'name': 'projects/sample1'}, request) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.list_locations(request) - -@pytest.mark.parametrize("request_type", [ - locations_pb2.ListLocationsRequest, - dict, -]) -def test_list_locations_rest(request_type): - client = AgentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request_init = {'name': 'projects/sample1'} - request = request_type(**request_init) - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = locations_pb2.ListLocationsResponse() - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.list_locations(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, locations_pb2.ListLocationsResponse) - -def test_cancel_operation_rest_bad_request(transport: str = 'rest', request_type=operations_pb2.CancelOperationRequest): - client = AgentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - request = request_type() - request = json_format.ParseDict({'name': 'projects/sample1/operations/sample2'}, request) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.cancel_operation(request) - -@pytest.mark.parametrize("request_type", [ - operations_pb2.CancelOperationRequest, - dict, -]) -def test_cancel_operation_rest(request_type): - client = AgentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request_init = {'name': 'projects/sample1/operations/sample2'} - request = request_type(**request_init) - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = None - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = '{}' - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.cancel_operation(request) - - # Establish that the response is the type that we expect. - assert response is None - -def test_get_operation_rest_bad_request(transport: str = 'rest', request_type=operations_pb2.GetOperationRequest): - client = AgentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - request = request_type() - request = json_format.ParseDict({'name': 'projects/sample1/operations/sample2'}, request) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.get_operation(request) - -@pytest.mark.parametrize("request_type", [ - operations_pb2.GetOperationRequest, - dict, -]) -def test_get_operation_rest(request_type): - client = AgentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request_init = {'name': 'projects/sample1/operations/sample2'} - request = request_type(**request_init) - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation() - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.get_operation(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, operations_pb2.Operation) - -def test_list_operations_rest_bad_request(transport: str = 'rest', request_type=operations_pb2.ListOperationsRequest): - client = AgentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - request = request_type() - request = json_format.ParseDict({'name': 'projects/sample1'}, request) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.list_operations(request) - -@pytest.mark.parametrize("request_type", [ - operations_pb2.ListOperationsRequest, - dict, -]) -def test_list_operations_rest(request_type): - client = AgentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request_init = {'name': 'projects/sample1'} - request = request_type(**request_init) - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = operations_pb2.ListOperationsResponse() - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.list_operations(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, operations_pb2.ListOperationsResponse) - - -def test_cancel_operation(transport: str = "grpc"): - client = AgentsClient( - 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 = operations_pb2.CancelOperationRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = None - response = client.cancel_operation(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 response is the type that we expect. - assert response is None -@pytest.mark.asyncio -async def test_cancel_operation_async(transport: str = "grpc"): - client = AgentsAsyncClient( - 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 = operations_pb2.CancelOperationRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - None - ) - response = await client.cancel_operation(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 response is the type that we expect. - assert response is None - -def test_cancel_operation_field_headers(): - 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 = operations_pb2.CancelOperationRequest() - request.name = "locations" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call: - call.return_value = None - - client.cancel_operation(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=locations",) in kw["metadata"] -@pytest.mark.asyncio -async def test_cancel_operation_field_headers_async(): - 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 = operations_pb2.CancelOperationRequest() - request.name = "locations" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - None - ) - await client.cancel_operation(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=locations",) in kw["metadata"] - -def test_cancel_operation_from_dict(): - 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.cancel_operation), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = None - - response = client.cancel_operation( - request={ - "name": "locations", - } - ) - call.assert_called() -@pytest.mark.asyncio -async def test_cancel_operation_from_dict_async(): - 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.cancel_operation), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - None - ) - response = await client.cancel_operation( - request={ - "name": "locations", - } - ) - call.assert_called() - - -def test_get_operation(transport: str = "grpc"): - client = AgentsClient( - 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 = operations_pb2.GetOperationRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_operation), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation() - response = client.get_operation(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 response is the type that we expect. - assert isinstance(response, operations_pb2.Operation) -@pytest.mark.asyncio -async def test_get_operation_async(transport: str = "grpc"): - client = AgentsAsyncClient( - 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 = operations_pb2.GetOperationRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_operation), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation() - ) - response = await client.get_operation(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 response is the type that we expect. - assert isinstance(response, operations_pb2.Operation) - -def test_get_operation_field_headers(): - 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 = operations_pb2.GetOperationRequest() - request.name = "locations" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_operation), "__call__") as call: - call.return_value = operations_pb2.Operation() - - client.get_operation(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=locations",) in kw["metadata"] -@pytest.mark.asyncio -async def test_get_operation_field_headers_async(): - 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 = operations_pb2.GetOperationRequest() - request.name = "locations" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_operation), "__call__") as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation() - ) - await client.get_operation(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=locations",) in kw["metadata"] - -def test_get_operation_from_dict(): - 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_operation), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation() - - response = client.get_operation( - request={ - "name": "locations", - } - ) - call.assert_called() -@pytest.mark.asyncio -async def test_get_operation_from_dict_async(): - 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_operation), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation() - ) - response = await client.get_operation( - request={ - "name": "locations", - } - ) - call.assert_called() - - -def test_list_operations(transport: str = "grpc"): - client = AgentsClient( - 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 = operations_pb2.ListOperationsRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_operations), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.ListOperationsResponse() - response = client.list_operations(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 response is the type that we expect. - assert isinstance(response, operations_pb2.ListOperationsResponse) -@pytest.mark.asyncio -async def test_list_operations_async(transport: str = "grpc"): - client = AgentsAsyncClient( - 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 = operations_pb2.ListOperationsRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_operations), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.ListOperationsResponse() - ) - response = await client.list_operations(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 response is the type that we expect. - assert isinstance(response, operations_pb2.ListOperationsResponse) - -def test_list_operations_field_headers(): - 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 = operations_pb2.ListOperationsRequest() - request.name = "locations" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_operations), "__call__") as call: - call.return_value = operations_pb2.ListOperationsResponse() - - client.list_operations(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=locations",) in kw["metadata"] -@pytest.mark.asyncio -async def test_list_operations_field_headers_async(): - 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 = operations_pb2.ListOperationsRequest() - request.name = "locations" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_operations), "__call__") as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.ListOperationsResponse() - ) - await client.list_operations(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=locations",) in kw["metadata"] - -def test_list_operations_from_dict(): - client = AgentsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_operations), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.ListOperationsResponse() - - response = client.list_operations( - request={ - "name": "locations", - } - ) - call.assert_called() -@pytest.mark.asyncio -async def test_list_operations_from_dict_async(): - client = AgentsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_operations), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.ListOperationsResponse() - ) - response = await client.list_operations( - request={ - "name": "locations", - } - ) - call.assert_called() - - -def test_list_locations(transport: str = "grpc"): - client = AgentsClient( - 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 = locations_pb2.ListLocationsRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_locations), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = locations_pb2.ListLocationsResponse() - response = client.list_locations(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 response is the type that we expect. - assert isinstance(response, locations_pb2.ListLocationsResponse) -@pytest.mark.asyncio -async def test_list_locations_async(transport: str = "grpc"): - client = AgentsAsyncClient( - 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 = locations_pb2.ListLocationsRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_locations), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - locations_pb2.ListLocationsResponse() - ) - response = await client.list_locations(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 response is the type that we expect. - assert isinstance(response, locations_pb2.ListLocationsResponse) - -def test_list_locations_field_headers(): - 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 = locations_pb2.ListLocationsRequest() - request.name = "locations" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_locations), "__call__") as call: - call.return_value = locations_pb2.ListLocationsResponse() - - client.list_locations(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=locations",) in kw["metadata"] -@pytest.mark.asyncio -async def test_list_locations_field_headers_async(): - 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 = locations_pb2.ListLocationsRequest() - request.name = "locations" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_locations), "__call__") as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - locations_pb2.ListLocationsResponse() - ) - await client.list_locations(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=locations",) in kw["metadata"] - -def test_list_locations_from_dict(): - client = AgentsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_locations), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = locations_pb2.ListLocationsResponse() - - response = client.list_locations( - request={ - "name": "locations", - } - ) - call.assert_called() -@pytest.mark.asyncio -async def test_list_locations_from_dict_async(): - client = AgentsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_locations), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - locations_pb2.ListLocationsResponse() - ) - response = await client.list_locations( - request={ - "name": "locations", - } - ) - call.assert_called() - - -def test_get_location(transport: str = "grpc"): - client = AgentsClient( - 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 = locations_pb2.GetLocationRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_location), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = locations_pb2.Location() - response = client.get_location(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 response is the type that we expect. - assert isinstance(response, locations_pb2.Location) -@pytest.mark.asyncio -async def test_get_location_async(transport: str = "grpc_asyncio"): - client = AgentsAsyncClient( - 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 = locations_pb2.GetLocationRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_location), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - locations_pb2.Location() - ) - response = await client.get_location(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 response is the type that we expect. - assert isinstance(response, locations_pb2.Location) - -def test_get_location_field_headers(): - 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 = locations_pb2.GetLocationRequest() - request.name = "locations/abc" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_location), "__call__") as call: - call.return_value = locations_pb2.Location() - - client.get_location(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=locations/abc",) in kw["metadata"] -@pytest.mark.asyncio -async def test_get_location_field_headers_async(): - 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 = locations_pb2.GetLocationRequest() - request.name = "locations/abc" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_location), "__call__") as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - locations_pb2.Location() - ) - await client.get_location(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=locations/abc",) in kw["metadata"] - -def test_get_location_from_dict(): - client = AgentsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_locations), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = locations_pb2.Location() - - response = client.get_location( - request={ - "name": "locations/abc", - } - ) - call.assert_called() -@pytest.mark.asyncio -async def test_get_location_from_dict_async(): - client = AgentsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_locations), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - locations_pb2.Location() - ) - response = await client.get_location( - request={ - "name": "locations", - } - ) - call.assert_called() - - -def test_transport_close(): - transports = { - "rest": "_session", - "grpc": "_grpc_channel", - } - - for transport, close_name in transports.items(): - client = AgentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport - ) - with mock.patch.object(type(getattr(client.transport, close_name)), "close") as close: - with client: - close.assert_not_called() - close.assert_called_once() - -def test_client_ctx(): - transports = [ - 'rest', - 'grpc', - ] - for transport in transports: - client = AgentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport - ) - # Test client calls underlying transport. - with mock.patch.object(type(client.transport), "close") as close: - close.assert_not_called() - with client: - pass - close.assert_called() - -@pytest.mark.parametrize("client_class,transport_class", [ - (AgentsClient, transports.AgentsGrpcTransport), - (AgentsAsyncClient, transports.AgentsGrpcAsyncIOTransport), -]) -def test_api_key_credentials(client_class, transport_class): - with mock.patch.object( - google.auth._default, "get_api_key_credentials", create=True - ) as get_api_key_credentials: - mock_cred = mock.Mock() - get_api_key_credentials.return_value = mock_cred - options = client_options.ClientOptions() - options.api_key = "api_key" - 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=mock_cred, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) diff --git a/owl-bot-staging/v2beta1/tests/unit/gapic/dialogflow_v2beta1/test_answer_records.py b/owl-bot-staging/v2beta1/tests/unit/gapic/dialogflow_v2beta1/test_answer_records.py deleted file mode 100644 index 5eb8a4508..000000000 --- a/owl-bot-staging/v2beta1/tests/unit/gapic/dialogflow_v2beta1/test_answer_records.py +++ /dev/null @@ -1,3483 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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 -# try/except added for compatibility with python < 3.8 -try: - from unittest import mock - from unittest.mock import AsyncMock # pragma: NO COVER -except ImportError: # pragma: NO COVER - import mock - -import grpc -from grpc.experimental import aio -from collections.abc import Iterable -from google.protobuf import json_format -import json -import math -import pytest -from proto.marshal.rules.dates import DurationRule, TimestampRule -from proto.marshal.rules import wrappers -from requests import Response -from requests import Request, PreparedRequest -from requests.sessions import Session -from google.protobuf import json_format - -from google.api_core import client_options -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import grpc_helpers -from google.api_core import grpc_helpers_async -from google.api_core import path_template -from google.auth import credentials as ga_credentials -from google.auth.exceptions import MutualTLSChannelError -from google.cloud.dialogflow_v2beta1.services.answer_records import AnswerRecordsAsyncClient -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.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.cloud.location import locations_pb2 -from google.longrunning import operations_pb2 -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 - - -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 AnswerRecordsClient._get_default_mtls_endpoint(None) is None - assert AnswerRecordsClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint - assert AnswerRecordsClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint - assert AnswerRecordsClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint - assert AnswerRecordsClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint - assert AnswerRecordsClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi - - -@pytest.mark.parametrize("client_class,transport_name", [ - (AnswerRecordsClient, "grpc"), - (AnswerRecordsAsyncClient, "grpc_asyncio"), - (AnswerRecordsClient, "rest"), -]) -def test_answer_records_client_from_service_account_info(client_class, transport_name): - 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, transport=transport_name) - assert client.transport._credentials == creds - assert isinstance(client, client_class) - - assert client.transport._host == ( - 'dialogflow.googleapis.com:443' - if transport_name in ['grpc', 'grpc_asyncio'] - else - 'https://dialogflow.googleapis.com' - ) - - -@pytest.mark.parametrize("transport_class,transport_name", [ - (transports.AnswerRecordsGrpcTransport, "grpc"), - (transports.AnswerRecordsGrpcAsyncIOTransport, "grpc_asyncio"), - (transports.AnswerRecordsRestTransport, "rest"), -]) -def test_answer_records_client_service_account_always_use_jwt(transport_class, transport_name): - with mock.patch.object(service_account.Credentials, 'with_always_use_jwt_access', create=True) as use_jwt: - creds = service_account.Credentials(None, None, None) - transport = transport_class(credentials=creds, always_use_jwt_access=True) - use_jwt.assert_called_once_with(True) - - with mock.patch.object(service_account.Credentials, 'with_always_use_jwt_access', create=True) as use_jwt: - creds = service_account.Credentials(None, None, None) - transport = transport_class(credentials=creds, always_use_jwt_access=False) - use_jwt.assert_not_called() - - -@pytest.mark.parametrize("client_class,transport_name", [ - (AnswerRecordsClient, "grpc"), - (AnswerRecordsAsyncClient, "grpc_asyncio"), - (AnswerRecordsClient, "rest"), -]) -def test_answer_records_client_from_service_account_file(client_class, transport_name): - 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", transport=transport_name) - assert client.transport._credentials == creds - assert isinstance(client, client_class) - - client = client_class.from_service_account_json("dummy/file/path.json", transport=transport_name) - assert client.transport._credentials == creds - assert isinstance(client, client_class) - - assert client.transport._host == ( - 'dialogflow.googleapis.com:443' - if transport_name in ['grpc', 'grpc_asyncio'] - else - 'https://dialogflow.googleapis.com' - ) - - -def test_answer_records_client_get_transport_class(): - transport = AnswerRecordsClient.get_transport_class() - available_transports = [ - transports.AnswerRecordsGrpcTransport, - transports.AnswerRecordsRestTransport, - ] - assert transport in available_transports - - transport = AnswerRecordsClient.get_transport_class("grpc") - assert transport == transports.AnswerRecordsGrpcTransport - - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (AnswerRecordsClient, transports.AnswerRecordsGrpcTransport, "grpc"), - (AnswerRecordsAsyncClient, transports.AnswerRecordsGrpcAsyncIOTransport, "grpc_asyncio"), - (AnswerRecordsClient, transports.AnswerRecordsRestTransport, "rest"), -]) -@mock.patch.object(AnswerRecordsClient, "DEFAULT_ENDPOINT", modify_default_endpoint(AnswerRecordsClient)) -@mock.patch.object(AnswerRecordsAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(AnswerRecordsAsyncClient)) -def test_answer_records_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(AnswerRecordsClient, '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(AnswerRecordsClient, 'get_transport_class') as gtc: - client = client_class(transport=transport_name) - gtc.assert_called() - - # Check the case api_endpoint is provided. - options = client_options.ClientOptions(api_endpoint="squid.clam.whelk") - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(transport=transport_name, client_options=options) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host="squid.clam.whelk", - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is - # "never". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is - # "always". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_MTLS_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # 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(transport=transport_name) - - # 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(transport=transport_name) - - # 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, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id="octopus", - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - # Check the case api_endpoint is provided - options = client_options.ClientOptions(api_audience="https://language.googleapis.com") - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience="https://language.googleapis.com" - ) - -@pytest.mark.parametrize("client_class,transport_class,transport_name,use_client_cert_env", [ - (AnswerRecordsClient, transports.AnswerRecordsGrpcTransport, "grpc", "true"), - (AnswerRecordsAsyncClient, transports.AnswerRecordsGrpcAsyncIOTransport, "grpc_asyncio", "true"), - (AnswerRecordsClient, transports.AnswerRecordsGrpcTransport, "grpc", "false"), - (AnswerRecordsAsyncClient, transports.AnswerRecordsGrpcAsyncIOTransport, "grpc_asyncio", "false"), - (AnswerRecordsClient, transports.AnswerRecordsRestTransport, "rest", "true"), - (AnswerRecordsClient, transports.AnswerRecordsRestTransport, "rest", "false"), -]) -@mock.patch.object(AnswerRecordsClient, "DEFAULT_ENDPOINT", modify_default_endpoint(AnswerRecordsClient)) -@mock.patch.object(AnswerRecordsAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(AnswerRecordsAsyncClient)) -@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) -def test_answer_records_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, transport=transport_name) - - if use_client_cert_env == "false": - expected_client_cert_source = None - expected_host = client.DEFAULT_ENDPOINT - else: - expected_client_cert_source = client_cert_source_callback - expected_host = client.DEFAULT_MTLS_ENDPOINT - - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=expected_host, - scopes=None, - client_cert_source_for_mtls=expected_client_cert_source, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case ADC client cert is provided. Whether client cert is used depends on - # GOOGLE_API_USE_CLIENT_CERTIFICATE value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): - with mock.patch.object(transport_class, '__init__') as patched: - with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): - with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=client_cert_source_callback): - if use_client_cert_env == "false": - expected_host = client.DEFAULT_ENDPOINT - expected_client_cert_source = None - else: - expected_host = client.DEFAULT_MTLS_ENDPOINT - expected_client_cert_source = client_cert_source_callback - - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=expected_host, - scopes=None, - client_cert_source_for_mtls=expected_client_cert_source, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case client_cert_source and ADC client cert are not provided. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): - with mock.patch.object(transport_class, '__init__') as patched: - with mock.patch("google.auth.transport.mtls.has_default_client_cert_source", return_value=False): - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - -@pytest.mark.parametrize("client_class", [ - AnswerRecordsClient, AnswerRecordsAsyncClient -]) -@mock.patch.object(AnswerRecordsClient, "DEFAULT_ENDPOINT", modify_default_endpoint(AnswerRecordsClient)) -@mock.patch.object(AnswerRecordsAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(AnswerRecordsAsyncClient)) -def test_answer_records_client_get_mtls_endpoint_and_cert_source(client_class): - mock_client_cert_source = mock.Mock() - - # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "true". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - mock_api_endpoint = "foo" - options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) - assert api_endpoint == mock_api_endpoint - assert cert_source == mock_client_cert_source - - # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "false". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): - mock_client_cert_source = mock.Mock() - mock_api_endpoint = "foo" - options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) - assert api_endpoint == mock_api_endpoint - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "never". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_ENDPOINT - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "always". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert doesn't exist. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=False): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_ENDPOINT - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert exists. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - 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=mock_client_cert_source): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT - assert cert_source == mock_client_cert_source - - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (AnswerRecordsClient, transports.AnswerRecordsGrpcTransport, "grpc"), - (AnswerRecordsAsyncClient, transports.AnswerRecordsGrpcAsyncIOTransport, "grpc_asyncio"), - (AnswerRecordsClient, transports.AnswerRecordsRestTransport, "rest"), -]) -def test_answer_records_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, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=["1", "2"], - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - -@pytest.mark.parametrize("client_class,transport_class,transport_name,grpc_helpers", [ - (AnswerRecordsClient, transports.AnswerRecordsGrpcTransport, "grpc", grpc_helpers), - (AnswerRecordsAsyncClient, transports.AnswerRecordsGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), - (AnswerRecordsClient, transports.AnswerRecordsRestTransport, "rest", None), -]) -def test_answer_records_client_client_options_credentials_file(client_class, transport_class, transport_name, grpc_helpers): - # 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, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file="credentials.json", - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - -def test_answer_records_client_client_options_from_dict(): - with mock.patch('google.cloud.dialogflow_v2beta1.services.answer_records.transports.AnswerRecordsGrpcTransport.__init__') as grpc_transport: - grpc_transport.return_value = None - client = AnswerRecordsClient( - client_options={'api_endpoint': 'squid.clam.whelk'} - ) - grpc_transport.assert_called_once_with( - credentials=None, - credentials_file=None, - host="squid.clam.whelk", - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - -@pytest.mark.parametrize("client_class,transport_class,transport_name,grpc_helpers", [ - (AnswerRecordsClient, transports.AnswerRecordsGrpcTransport, "grpc", grpc_helpers), - (AnswerRecordsAsyncClient, transports.AnswerRecordsGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), -]) -def test_answer_records_client_create_channel_credentials_file(client_class, transport_class, transport_name, grpc_helpers): - # 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, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file="credentials.json", - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # test that the credentials from file are saved and used as the credentials. - with mock.patch.object( - google.auth, "load_credentials_from_file", autospec=True - ) as load_creds, mock.patch.object( - google.auth, "default", autospec=True - ) as adc, mock.patch.object( - grpc_helpers, "create_channel" - ) as create_channel: - creds = ga_credentials.AnonymousCredentials() - file_creds = ga_credentials.AnonymousCredentials() - load_creds.return_value = (file_creds, None) - adc.return_value = (creds, None) - client = client_class(client_options=options, transport=transport_name) - create_channel.assert_called_with( - "dialogflow.googleapis.com:443", - credentials=file_creds, - credentials_file=None, - quota_project_id=None, - default_scopes=( - 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/dialogflow', -), - scopes=None, - default_host="dialogflow.googleapis.com", - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - -@pytest.mark.parametrize("request_type", [ - answer_record.GetAnswerRecordRequest, - dict, -]) -def test_get_answer_record(request_type, transport: str = 'grpc'): - client = AnswerRecordsClient( - 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_answer_record), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = answer_record.AnswerRecord( - name='name_value', - agent_assistant_record=answer_record.AgentAssistantRecord(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' - - -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=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_answer_record), - '__call__') as call: - client.get_answer_record() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == answer_record.GetAnswerRecordRequest() - -@pytest.mark.asyncio -async def test_get_answer_record_async(transport: str = 'grpc_asyncio', request_type=answer_record.GetAnswerRecordRequest): - client = AnswerRecordsAsyncClient( - 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_answer_record), - '__call__') as call: - # Designate an appropriate return value for the call. - 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' - - -@pytest.mark.asyncio -async def test_get_answer_record_async_from_dict(): - await test_get_answer_record_async(request_type=dict) - - -def test_get_answer_record_field_headers(): - 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. - with mock.patch.object( - 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. - 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_answer_record_field_headers_async(): - 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. - with mock.patch.object( - type(client.transport.get_answer_record), - '__call__') as call: - 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. - 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'] - - -@pytest.mark.parametrize("request_type", [ - answer_record.ListAnswerRecordsRequest, - dict, -]) -def test_list_answer_records(request_type, transport: str = 'grpc'): - client = AnswerRecordsClient( - 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_answer_records), - '__call__') as call: - # Designate an appropriate return value for the call. - 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' - - -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=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_answer_records), - '__call__') as call: - client.list_answer_records() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == answer_record.ListAnswerRecordsRequest() - -@pytest.mark.asyncio -async def test_list_answer_records_async(transport: str = 'grpc_asyncio', request_type=answer_record.ListAnswerRecordsRequest): - client = AnswerRecordsAsyncClient( - 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_answer_records), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(answer_record.ListAnswerRecordsResponse( - 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' - - -@pytest.mark.asyncio -async def test_list_answer_records_async_from_dict(): - await test_list_answer_records_async(request_type=dict) - - -def test_list_answer_records_field_headers(): - 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. - with mock.patch.object( - 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. - 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_answer_records_field_headers_async(): - 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. - with mock.patch.object( - type(client.transport.list_answer_records), - '__call__') as call: - 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. - 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_answer_records_flattened(): - client = AnswerRecordsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_answer_records), - '__call__') 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', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - arg = args[0].parent - mock_val = 'parent_value' - assert arg == mock_val - - -def test_list_answer_records_flattened_error(): - client = AnswerRecordsClient( - 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_answer_records( - answer_record.ListAnswerRecordsRequest(), - parent='parent_value', - ) - -@pytest.mark.asyncio -async def test_list_answer_records_flattened_async(): - client = AnswerRecordsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_answer_records), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = answer_record.ListAnswerRecordsResponse() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(answer_record.ListAnswerRecordsResponse()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.list_answer_records( - 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] - arg = args[0].parent - mock_val = 'parent_value' - assert arg == mock_val - -@pytest.mark.asyncio -async def test_list_answer_records_flattened_error_async(): - client = AnswerRecordsAsyncClient( - 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_answer_records( - answer_record.ListAnswerRecordsRequest(), - parent='parent_value', - ) - - -def test_list_answer_records_pager(transport_name: str = "grpc"): - client = AnswerRecordsClient( - credentials=ga_credentials.AnonymousCredentials, - transport=transport_name, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_answer_records), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - answer_record.ListAnswerRecordsResponse( - answer_records=[ - answer_record.AnswerRecord(), - answer_record.AnswerRecord(), - answer_record.AnswerRecord(), - ], - next_page_token='abc', - ), - answer_record.ListAnswerRecordsResponse( - answer_records=[], - next_page_token='def', - ), - answer_record.ListAnswerRecordsResponse( - answer_records=[ - answer_record.AnswerRecord(), - ], - next_page_token='ghi', - ), - answer_record.ListAnswerRecordsResponse( - answer_records=[ - answer_record.AnswerRecord(), - answer_record.AnswerRecord(), - ], - ), - RuntimeError, - ) - - metadata = () - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ('parent', ''), - )), - ) - pager = client.list_answer_records(request={}) - - assert pager._metadata == metadata - - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, answer_record.AnswerRecord) - for i in results) -def test_list_answer_records_pages(transport_name: str = "grpc"): - client = AnswerRecordsClient( - credentials=ga_credentials.AnonymousCredentials, - transport=transport_name, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_answer_records), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - answer_record.ListAnswerRecordsResponse( - answer_records=[ - answer_record.AnswerRecord(), - answer_record.AnswerRecord(), - answer_record.AnswerRecord(), - ], - next_page_token='abc', - ), - answer_record.ListAnswerRecordsResponse( - answer_records=[], - next_page_token='def', - ), - answer_record.ListAnswerRecordsResponse( - answer_records=[ - answer_record.AnswerRecord(), - ], - next_page_token='ghi', - ), - answer_record.ListAnswerRecordsResponse( - answer_records=[ - answer_record.AnswerRecord(), - answer_record.AnswerRecord(), - ], - ), - RuntimeError, - ) - pages = list(client.list_answer_records(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_answer_records_async_pager(): - client = AnswerRecordsAsyncClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_answer_records), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - answer_record.ListAnswerRecordsResponse( - answer_records=[ - answer_record.AnswerRecord(), - answer_record.AnswerRecord(), - answer_record.AnswerRecord(), - ], - next_page_token='abc', - ), - answer_record.ListAnswerRecordsResponse( - answer_records=[], - next_page_token='def', - ), - answer_record.ListAnswerRecordsResponse( - answer_records=[ - answer_record.AnswerRecord(), - ], - next_page_token='ghi', - ), - answer_record.ListAnswerRecordsResponse( - answer_records=[ - answer_record.AnswerRecord(), - answer_record.AnswerRecord(), - ], - ), - RuntimeError, - ) - async_pager = await client.list_answer_records(request={},) - assert async_pager.next_page_token == 'abc' - responses = [] - async for response in async_pager: # pragma: no branch - responses.append(response) - - assert len(responses) == 6 - assert all(isinstance(i, answer_record.AnswerRecord) - for i in responses) - - -@pytest.mark.asyncio -async def test_list_answer_records_async_pages(): - client = AnswerRecordsAsyncClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_answer_records), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - answer_record.ListAnswerRecordsResponse( - answer_records=[ - answer_record.AnswerRecord(), - answer_record.AnswerRecord(), - answer_record.AnswerRecord(), - ], - next_page_token='abc', - ), - answer_record.ListAnswerRecordsResponse( - answer_records=[], - next_page_token='def', - ), - answer_record.ListAnswerRecordsResponse( - answer_records=[ - answer_record.AnswerRecord(), - ], - next_page_token='ghi', - ), - answer_record.ListAnswerRecordsResponse( - answer_records=[ - answer_record.AnswerRecord(), - answer_record.AnswerRecord(), - ], - ), - RuntimeError, - ) - pages = [] - async for page_ in (await client.list_answer_records(request={})).pages: # pragma: no branch - pages.append(page_) - for page_, token in zip(pages, ['abc','def','ghi', '']): - assert page_.raw_page.next_page_token == token - -@pytest.mark.parametrize("request_type", [ - gcd_answer_record.UpdateAnswerRecordRequest, - dict, -]) -def test_update_answer_record(request_type, transport: str = 'grpc'): - client = AnswerRecordsClient( - 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_answer_record), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcd_answer_record.AnswerRecord( - name='name_value', - agent_assistant_record=gcd_answer_record.AgentAssistantRecord(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' - - -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=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_answer_record), - '__call__') as call: - client.update_answer_record() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == gcd_answer_record.UpdateAnswerRecordRequest() - -@pytest.mark.asyncio -async def test_update_answer_record_async(transport: str = 'grpc_asyncio', request_type=gcd_answer_record.UpdateAnswerRecordRequest): - client = AnswerRecordsAsyncClient( - 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_answer_record), - '__call__') as call: - # Designate an appropriate return value for the call. - 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' - - -@pytest.mark.asyncio -async def test_update_answer_record_async_from_dict(): - await test_update_answer_record_async(request_type=dict) - - -def test_update_answer_record_field_headers(): - 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 = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - 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. - 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', - 'answer_record.name=name_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_update_answer_record_field_headers_async(): - 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 = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_answer_record), - '__call__') as call: - 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. - 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', - 'answer_record.name=name_value', - ) in kw['metadata'] - - -def test_update_answer_record_flattened(): - client = AnswerRecordsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_answer_record), - '__call__') 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_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] - arg = args[0].answer_record - mock_val = gcd_answer_record.AnswerRecord(name='name_value') - assert arg == mock_val - arg = args[0].update_mask - mock_val = field_mask_pb2.FieldMask(paths=['paths_value']) - assert arg == mock_val - - -def test_update_answer_record_flattened_error(): - client = AnswerRecordsClient( - 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_answer_record( - gcd_answer_record.UpdateAnswerRecordRequest(), - answer_record=gcd_answer_record.AnswerRecord(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - -@pytest.mark.asyncio -async def test_update_answer_record_flattened_async(): - client = AnswerRecordsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_answer_record), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcd_answer_record.AnswerRecord() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcd_answer_record.AnswerRecord()) - # Call the method with a truthy value for each flattened field, - # 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_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] - arg = args[0].answer_record - mock_val = gcd_answer_record.AnswerRecord(name='name_value') - assert arg == mock_val - arg = args[0].update_mask - mock_val = field_mask_pb2.FieldMask(paths=['paths_value']) - assert arg == mock_val - -@pytest.mark.asyncio -async def test_update_answer_record_flattened_error_async(): - client = AnswerRecordsAsyncClient( - 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_answer_record( - gcd_answer_record.UpdateAnswerRecordRequest(), - answer_record=gcd_answer_record.AnswerRecord(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - - -@pytest.mark.parametrize("request_type", [ - answer_record.GetAnswerRecordRequest, - dict, -]) -def test_get_answer_record_rest(request_type): - client = AnswerRecordsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/answerRecords/sample2'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = answer_record.AnswerRecord( - name='name_value', - agent_assistant_record=answer_record.AgentAssistantRecord(article_suggestion_answer=participant.ArticleAnswer(title='title_value')), - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - pb_return_value = answer_record.AnswerRecord.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.get_answer_record(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, answer_record.AnswerRecord) - assert response.name == 'name_value' - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_get_answer_record_rest_interceptors(null_interceptor): - transport = transports.AnswerRecordsRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.AnswerRecordsRestInterceptor(), - ) - client = AnswerRecordsClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.AnswerRecordsRestInterceptor, "post_get_answer_record") as post, \ - mock.patch.object(transports.AnswerRecordsRestInterceptor, "pre_get_answer_record") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = answer_record.GetAnswerRecordRequest.pb(answer_record.GetAnswerRecordRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = answer_record.AnswerRecord.to_json(answer_record.AnswerRecord()) - - request = answer_record.GetAnswerRecordRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = answer_record.AnswerRecord() - - client.get_answer_record(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_get_answer_record_rest_bad_request(transport: str = 'rest', request_type=answer_record.GetAnswerRecordRequest): - client = AnswerRecordsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/answerRecords/sample2'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.get_answer_record(request) - - -def test_get_answer_record_rest_error(): - client = AnswerRecordsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - answer_record.ListAnswerRecordsRequest, - dict, -]) -def test_list_answer_records_rest(request_type): - client = AnswerRecordsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = answer_record.ListAnswerRecordsResponse( - next_page_token='next_page_token_value', - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - pb_return_value = answer_record.ListAnswerRecordsResponse.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.list_answer_records(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListAnswerRecordsPager) - assert response.next_page_token == 'next_page_token_value' - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_list_answer_records_rest_interceptors(null_interceptor): - transport = transports.AnswerRecordsRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.AnswerRecordsRestInterceptor(), - ) - client = AnswerRecordsClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.AnswerRecordsRestInterceptor, "post_list_answer_records") as post, \ - mock.patch.object(transports.AnswerRecordsRestInterceptor, "pre_list_answer_records") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = answer_record.ListAnswerRecordsRequest.pb(answer_record.ListAnswerRecordsRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = answer_record.ListAnswerRecordsResponse.to_json(answer_record.ListAnswerRecordsResponse()) - - request = answer_record.ListAnswerRecordsRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = answer_record.ListAnswerRecordsResponse() - - client.list_answer_records(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_list_answer_records_rest_bad_request(transport: str = 'rest', request_type=answer_record.ListAnswerRecordsRequest): - client = AnswerRecordsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.list_answer_records(request) - - -def test_list_answer_records_rest_flattened(): - client = AnswerRecordsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = answer_record.ListAnswerRecordsResponse() - - # get arguments that satisfy an http rule for this method - sample_request = {'parent': 'projects/sample1'} - - # get truthy value for each flattened field - mock_args = dict( - parent='parent_value', - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - pb_return_value = answer_record.ListAnswerRecordsResponse.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.list_answer_records(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v2beta1/{parent=projects/*}/answerRecords" % client.transport._host, args[1]) - - -def test_list_answer_records_rest_flattened_error(transport: str = 'rest'): - client = AnswerRecordsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.list_answer_records( - answer_record.ListAnswerRecordsRequest(), - parent='parent_value', - ) - - -def test_list_answer_records_rest_pager(transport: str = 'rest'): - client = AnswerRecordsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # TODO(kbandes): remove this mock unless there's a good reason for it. - #with mock.patch.object(path_template, 'transcode') as transcode: - # Set the response as a series of pages - response = ( - answer_record.ListAnswerRecordsResponse( - answer_records=[ - answer_record.AnswerRecord(), - answer_record.AnswerRecord(), - answer_record.AnswerRecord(), - ], - next_page_token='abc', - ), - answer_record.ListAnswerRecordsResponse( - answer_records=[], - next_page_token='def', - ), - answer_record.ListAnswerRecordsResponse( - answer_records=[ - answer_record.AnswerRecord(), - ], - next_page_token='ghi', - ), - answer_record.ListAnswerRecordsResponse( - answer_records=[ - answer_record.AnswerRecord(), - answer_record.AnswerRecord(), - ], - ), - ) - # Two responses for two calls - response = response + response - - # Wrap the values into proper Response objs - response = tuple(answer_record.ListAnswerRecordsResponse.to_json(x) for x in response) - return_values = tuple(Response() for i in response) - for return_val, response_val in zip(return_values, response): - return_val._content = response_val.encode('UTF-8') - return_val.status_code = 200 - req.side_effect = return_values - - sample_request = {'parent': 'projects/sample1'} - - pager = client.list_answer_records(request=sample_request) - - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, answer_record.AnswerRecord) - for i in results) - - pages = list(client.list_answer_records(request=sample_request).pages) - for page_, token in zip(pages, ['abc','def','ghi', '']): - assert page_.raw_page.next_page_token == token - - -@pytest.mark.parametrize("request_type", [ - gcd_answer_record.UpdateAnswerRecordRequest, - dict, -]) -def test_update_answer_record_rest(request_type): - client = AnswerRecordsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'answer_record': {'name': 'projects/sample1/answerRecords/sample2'}} - request_init["answer_record"] = {'name': 'projects/sample1/answerRecords/sample2', 'answer_feedback': {'correctness_level': 1, 'agent_assistant_detail_feedback': {'answer_relevance': 1, 'document_correctness': 1, 'document_efficiency': 1, 'summarization_feedback': {'start_timestamp': {'seconds': 751, 'nanos': 543}, 'submit_timestamp': {}, 'summary_text': 'summary_text_value'}}, 'clicked': True, 'click_time': {}, 'displayed': True, 'display_time': {}}, 'agent_assistant_record': {'article_suggestion_answer': {'title': 'title_value', 'uri': 'uri_value', 'snippets': ['snippets_value1', 'snippets_value2'], 'metadata': {}, 'answer_record': 'answer_record_value'}, 'faq_answer': {'answer': 'answer_value', 'confidence': 0.1038, 'question': 'question_value', 'source': 'source_value', 'metadata': {}, 'answer_record': 'answer_record_value'}}} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = gcd_answer_record.AnswerRecord( - name='name_value', - agent_assistant_record=gcd_answer_record.AgentAssistantRecord(article_suggestion_answer=participant.ArticleAnswer(title='title_value')), - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - pb_return_value = gcd_answer_record.AnswerRecord.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.update_answer_record(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, gcd_answer_record.AnswerRecord) - assert response.name == 'name_value' - - -def test_update_answer_record_rest_required_fields(request_type=gcd_answer_record.UpdateAnswerRecordRequest): - transport_class = transports.AnswerRecordsRestTransport - - request_init = {} - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - including_default_value_fields=False, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).update_answer_record._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).update_answer_record._get_unset_required_fields(jsonified_request) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("update_mask", )) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - - client = AnswerRecordsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = gcd_answer_record.AnswerRecord() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "patch", - 'query_params': pb_request, - } - transcode_result['body'] = pb_request - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - - pb_return_value = gcd_answer_record.AnswerRecord.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.update_answer_record(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_update_answer_record_rest_unset_required_fields(): - transport = transports.AnswerRecordsRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.update_answer_record._get_unset_required_fields({}) - assert set(unset_fields) == (set(("updateMask", )) & set(("answerRecord", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_update_answer_record_rest_interceptors(null_interceptor): - transport = transports.AnswerRecordsRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.AnswerRecordsRestInterceptor(), - ) - client = AnswerRecordsClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.AnswerRecordsRestInterceptor, "post_update_answer_record") as post, \ - mock.patch.object(transports.AnswerRecordsRestInterceptor, "pre_update_answer_record") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = gcd_answer_record.UpdateAnswerRecordRequest.pb(gcd_answer_record.UpdateAnswerRecordRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = gcd_answer_record.AnswerRecord.to_json(gcd_answer_record.AnswerRecord()) - - request = gcd_answer_record.UpdateAnswerRecordRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = gcd_answer_record.AnswerRecord() - - client.update_answer_record(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_update_answer_record_rest_bad_request(transport: str = 'rest', request_type=gcd_answer_record.UpdateAnswerRecordRequest): - client = AnswerRecordsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'answer_record': {'name': 'projects/sample1/answerRecords/sample2'}} - request_init["answer_record"] = {'name': 'projects/sample1/answerRecords/sample2', 'answer_feedback': {'correctness_level': 1, 'agent_assistant_detail_feedback': {'answer_relevance': 1, 'document_correctness': 1, 'document_efficiency': 1, 'summarization_feedback': {'start_timestamp': {'seconds': 751, 'nanos': 543}, 'submit_timestamp': {}, 'summary_text': 'summary_text_value'}}, 'clicked': True, 'click_time': {}, 'displayed': True, 'display_time': {}}, 'agent_assistant_record': {'article_suggestion_answer': {'title': 'title_value', 'uri': 'uri_value', 'snippets': ['snippets_value1', 'snippets_value2'], 'metadata': {}, 'answer_record': 'answer_record_value'}, 'faq_answer': {'answer': 'answer_value', 'confidence': 0.1038, 'question': 'question_value', 'source': 'source_value', 'metadata': {}, 'answer_record': 'answer_record_value'}}} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.update_answer_record(request) - - -def test_update_answer_record_rest_flattened(): - client = AnswerRecordsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = gcd_answer_record.AnswerRecord() - - # get arguments that satisfy an http rule for this method - sample_request = {'answer_record': {'name': 'projects/sample1/answerRecords/sample2'}} - - # get truthy value for each flattened field - mock_args = dict( - answer_record=gcd_answer_record.AnswerRecord(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - pb_return_value = gcd_answer_record.AnswerRecord.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.update_answer_record(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v2beta1/{answer_record.name=projects/*/answerRecords/*}" % client.transport._host, args[1]) - - -def test_update_answer_record_rest_flattened_error(transport: str = 'rest'): - client = AnswerRecordsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.update_answer_record( - gcd_answer_record.UpdateAnswerRecordRequest(), - answer_record=gcd_answer_record.AnswerRecord(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - - -def test_update_answer_record_rest_error(): - client = AnswerRecordsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -def test_credentials_transport_error(): - # It is an error to provide credentials and a transport instance. - transport = transports.AnswerRecordsGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = AnswerRecordsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # It is an error to provide a credentials file and a transport instance. - transport = transports.AnswerRecordsGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = AnswerRecordsClient( - client_options={"credentials_file": "credentials.json"}, - transport=transport, - ) - - # It is an error to provide an api_key and a transport instance. - transport = transports.AnswerRecordsGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - options = client_options.ClientOptions() - options.api_key = "api_key" - with pytest.raises(ValueError): - client = AnswerRecordsClient( - client_options=options, - transport=transport, - ) - - # It is an error to provide an api_key and a credential. - options = mock.Mock() - options.api_key = "api_key" - with pytest.raises(ValueError): - client = AnswerRecordsClient( - client_options=options, - credentials=ga_credentials.AnonymousCredentials() - ) - - # It is an error to provide scopes and a transport instance. - transport = transports.AnswerRecordsGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = AnswerRecordsClient( - client_options={"scopes": ["1", "2"]}, - transport=transport, - ) - - -def test_transport_instance(): - # A client may be instantiated with a custom transport instance. - transport = transports.AnswerRecordsGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - client = AnswerRecordsClient(transport=transport) - assert client.transport is transport - -def test_transport_get_channel(): - # A client may be instantiated with a custom transport instance. - transport = transports.AnswerRecordsGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - - transport = transports.AnswerRecordsGrpcAsyncIOTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - -@pytest.mark.parametrize("transport_class", [ - transports.AnswerRecordsGrpcTransport, - transports.AnswerRecordsGrpcAsyncIOTransport, - transports.AnswerRecordsRestTransport, -]) -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() - -@pytest.mark.parametrize("transport_name", [ - "grpc", - "rest", -]) -def test_transport_kind(transport_name): - transport = AnswerRecordsClient.get_transport_class(transport_name)( - credentials=ga_credentials.AnonymousCredentials(), - ) - assert transport.kind == transport_name - -def test_transport_grpc_default(): - # A client should use the gRPC transport by default. - 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(core_exceptions.DuplicateCredentialArgs): - transport = transports.AnswerRecordsTransport( - credentials=ga_credentials.AnonymousCredentials(), - credentials_file="credentials.json" - ) - - -def test_answer_records_base_transport(): - # Instantiate the base transport. - with mock.patch('google.cloud.dialogflow_v2beta1.services.answer_records.transports.AnswerRecordsTransport.__init__') as Transport: - Transport.return_value = None - transport = transports.AnswerRecordsTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Every method on the transport should just blindly - # raise NotImplementedError. - methods = ( - 'get_answer_record', - 'list_answer_records', - 'update_answer_record', - 'get_location', - 'list_locations', - 'get_operation', - 'cancel_operation', - 'list_operations', - ) - for method in methods: - with pytest.raises(NotImplementedError): - getattr(transport, method)(request=object()) - - with pytest.raises(NotImplementedError): - transport.close() - - # Catch all for all remaining methods and properties - remainder = [ - 'kind', - ] - for r in remainder: - with pytest.raises(NotImplementedError): - getattr(transport, r)() - - -def test_answer_records_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.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", - ) - - -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(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 = (ga_credentials.AnonymousCredentials(), None) - transport = transports.AnswerRecordsTransport() - adc.assert_called_once() - - -def test_answer_records_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) - 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, - ) - - -@pytest.mark.parametrize( - "transport_class", - [ - transports.AnswerRecordsGrpcTransport, - transports.AnswerRecordsGrpcAsyncIOTransport, - ], -) -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(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, - transports.AnswerRecordsRestTransport, - ], -) -def test_answer_records_transport_auth_gdch_credentials(transport_class): - host = 'https://language.com' - api_audience_tests = [None, 'https://language2.com'] - api_audience_expect = [host, 'https://language2.com'] - for t, e in zip(api_audience_tests, api_audience_expect): - with mock.patch.object(google.auth, 'default', autospec=True) as adc: - gdch_mock = mock.MagicMock() - type(gdch_mock).with_gdch_audience = mock.PropertyMock(return_value=gdch_mock) - adc.return_value = (gdch_mock, None) - transport_class(host=host, api_audience=t) - gdch_mock.with_gdch_audience.assert_called_once_with( - e - ) - - -@pytest.mark.parametrize( - "transport_class,grpc_helpers", - [ - (transports.AnswerRecordsGrpcTransport, grpc_helpers), - (transports.AnswerRecordsGrpcAsyncIOTransport, grpc_helpers_async) - ], -) -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", [transports.AnswerRecordsGrpcTransport, transports.AnswerRecordsGrpcAsyncIOTransport]) -def test_answer_records_grpc_transport_client_cert_source_for_mtls( - transport_class -): - cred = ga_credentials.AnonymousCredentials() - - # Check ssl_channel_credentials is used if provided. - with mock.patch.object(transport_class, "create_channel") as mock_create_channel: - mock_ssl_channel_creds = mock.Mock() - transport_class( - host="squid.clam.whelk", - credentials=cred, - ssl_channel_credentials=mock_ssl_channel_creds - ) - mock_create_channel.assert_called_once_with( - "squid.clam.whelk:443", - credentials=cred, - credentials_file=None, - scopes=None, - ssl_credentials=mock_ssl_channel_creds, - quota_project_id=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - # Check if ssl_channel_credentials is not provided, then client_cert_source_for_mtls - # is used. - with mock.patch.object(transport_class, "create_channel", return_value=mock.Mock()): - with mock.patch("grpc.ssl_channel_credentials") as mock_ssl_cred: - transport_class( - credentials=cred, - client_cert_source_for_mtls=client_cert_source_callback - ) - expected_cert, expected_key = client_cert_source_callback() - mock_ssl_cred.assert_called_once_with( - certificate_chain=expected_cert, - private_key=expected_key - ) - -def test_answer_records_http_transport_client_cert_source_for_mtls(): - cred = ga_credentials.AnonymousCredentials() - with mock.patch("google.auth.transport.requests.AuthorizedSession.configure_mtls_channel") as mock_configure_mtls_channel: - transports.AnswerRecordsRestTransport ( - credentials=cred, - client_cert_source_for_mtls=client_cert_source_callback - ) - mock_configure_mtls_channel.assert_called_once_with(client_cert_source_callback) - - -@pytest.mark.parametrize("transport_name", [ - "grpc", - "grpc_asyncio", - "rest", -]) -def test_answer_records_host_no_port(transport_name): - client = AnswerRecordsClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='dialogflow.googleapis.com'), - transport=transport_name, - ) - assert client.transport._host == ( - 'dialogflow.googleapis.com:443' - if transport_name in ['grpc', 'grpc_asyncio'] - else 'https://dialogflow.googleapis.com' - ) - -@pytest.mark.parametrize("transport_name", [ - "grpc", - "grpc_asyncio", - "rest", -]) -def test_answer_records_host_with_port(transport_name): - client = AnswerRecordsClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='dialogflow.googleapis.com:8000'), - transport=transport_name, - ) - assert client.transport._host == ( - 'dialogflow.googleapis.com:8000' - if transport_name in ['grpc', 'grpc_asyncio'] - else 'https://dialogflow.googleapis.com:8000' - ) - -@pytest.mark.parametrize("transport_name", [ - "rest", -]) -def test_answer_records_client_transport_session_collision(transport_name): - creds1 = ga_credentials.AnonymousCredentials() - creds2 = ga_credentials.AnonymousCredentials() - client1 = AnswerRecordsClient( - credentials=creds1, - transport=transport_name, - ) - client2 = AnswerRecordsClient( - credentials=creds2, - transport=transport_name, - ) - session1 = client1.transport.get_answer_record._session - session2 = client2.transport.get_answer_record._session - assert session1 != session2 - session1 = client1.transport.list_answer_records._session - session2 = client2.transport.list_answer_records._session - assert session1 != session2 - session1 = client1.transport.update_answer_record._session - session2 = client2.transport.update_answer_record._session - assert session1 != session2 -def test_answer_records_grpc_transport_channel(): - channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.AnswerRecordsGrpcTransport( - 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_answer_records_grpc_asyncio_transport_channel(): - channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.AnswerRecordsGrpcAsyncIOTransport( - 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.AnswerRecordsGrpcTransport, transports.AnswerRecordsGrpcAsyncIOTransport]) -def test_answer_records_transport_channel_mtls_with_client_cert_source( - transport_class -): - with mock.patch("grpc.ssl_channel_credentials", autospec=True) as grpc_ssl_channel_cred: - with mock.patch.object(transport_class, "create_channel") as grpc_create_channel: - mock_ssl_cred = mock.Mock() - grpc_ssl_channel_cred.return_value = mock_ssl_cred - - mock_grpc_channel = mock.Mock() - grpc_create_channel.return_value = mock_grpc_channel - - cred = ga_credentials.AnonymousCredentials() - with pytest.warns(DeprecationWarning): - with mock.patch.object(google.auth, 'default') as adc: - adc.return_value = (cred, None) - transport = transport_class( - host="squid.clam.whelk", - api_mtls_endpoint="mtls.squid.clam.whelk", - client_cert_source=client_cert_source_callback, - ) - adc.assert_called_once() - - grpc_ssl_channel_cred.assert_called_once_with( - certificate_chain=b"cert bytes", private_key=b"key bytes" - ) - grpc_create_channel.assert_called_once_with( - "mtls.squid.clam.whelk:443", - credentials=cred, - credentials_file=None, - scopes=None, - ssl_credentials=mock_ssl_cred, - quota_project_id=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - assert transport.grpc_channel == mock_grpc_channel - assert transport._ssl_channel_credentials == mock_ssl_cred - - -# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are -# removed from grpc/grpc_asyncio transport constructor. -@pytest.mark.parametrize("transport_class", [transports.AnswerRecordsGrpcTransport, transports.AnswerRecordsGrpcAsyncIOTransport]) -def test_answer_records_transport_channel_mtls_with_adc( - transport_class -): - mock_ssl_cred = mock.Mock() - with mock.patch.multiple( - "google.auth.transport.grpc.SslCredentials", - __init__=mock.Mock(return_value=None), - ssl_credentials=mock.PropertyMock(return_value=mock_ssl_cred), - ): - with mock.patch.object(transport_class, "create_channel") as grpc_create_channel: - mock_grpc_channel = mock.Mock() - grpc_create_channel.return_value = mock_grpc_channel - mock_cred = mock.Mock() - - with pytest.warns(DeprecationWarning): - transport = transport_class( - host="squid.clam.whelk", - credentials=mock_cred, - api_mtls_endpoint="mtls.squid.clam.whelk", - client_cert_source=None, - ) - - grpc_create_channel.assert_called_once_with( - "mtls.squid.clam.whelk:443", - credentials=mock_cred, - credentials_file=None, - scopes=None, - ssl_credentials=mock_ssl_cred, - quota_project_id=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - assert transport.grpc_channel == mock_grpc_channel - - -def test_answer_record_path(): - project = "squid" - answer_record = "clam" - expected = "projects/{project}/answerRecords/{answer_record}".format(project=project, answer_record=answer_record, ) - actual = AnswerRecordsClient.answer_record_path(project, answer_record) - assert expected == actual - - -def test_parse_answer_record_path(): - expected = { - "project": "whelk", - "answer_record": "octopus", - } - path = AnswerRecordsClient.answer_record_path(**expected) - - # Check that the path construction is reversible. - actual = AnswerRecordsClient.parse_answer_record_path(path) - assert expected == actual - -def test_common_billing_account_path(): - billing_account = "oyster" - expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) - actual = AnswerRecordsClient.common_billing_account_path(billing_account) - assert expected == actual - - -def test_parse_common_billing_account_path(): - expected = { - "billing_account": "nudibranch", - } - path = AnswerRecordsClient.common_billing_account_path(**expected) - - # Check that the path construction is reversible. - actual = AnswerRecordsClient.parse_common_billing_account_path(path) - assert expected == actual - -def test_common_folder_path(): - folder = "cuttlefish" - expected = "folders/{folder}".format(folder=folder, ) - actual = AnswerRecordsClient.common_folder_path(folder) - assert expected == actual - - -def test_parse_common_folder_path(): - expected = { - "folder": "mussel", - } - path = AnswerRecordsClient.common_folder_path(**expected) - - # Check that the path construction is reversible. - actual = AnswerRecordsClient.parse_common_folder_path(path) - assert expected == actual - -def test_common_organization_path(): - organization = "winkle" - expected = "organizations/{organization}".format(organization=organization, ) - actual = AnswerRecordsClient.common_organization_path(organization) - assert expected == actual - - -def test_parse_common_organization_path(): - expected = { - "organization": "nautilus", - } - path = AnswerRecordsClient.common_organization_path(**expected) - - # Check that the path construction is reversible. - actual = AnswerRecordsClient.parse_common_organization_path(path) - assert expected == actual - -def test_common_project_path(): - project = "scallop" - expected = "projects/{project}".format(project=project, ) - actual = AnswerRecordsClient.common_project_path(project) - assert expected == actual - - -def test_parse_common_project_path(): - expected = { - "project": "abalone", - } - path = AnswerRecordsClient.common_project_path(**expected) - - # Check that the path construction is reversible. - actual = AnswerRecordsClient.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 = AnswerRecordsClient.common_location_path(project, location) - assert expected == actual - - -def test_parse_common_location_path(): - expected = { - "project": "whelk", - "location": "octopus", - } - path = AnswerRecordsClient.common_location_path(**expected) - - # Check that the path construction is reversible. - actual = AnswerRecordsClient.parse_common_location_path(path) - assert expected == actual - - -def test_client_with_default_client_info(): - client_info = gapic_v1.client_info.ClientInfo() - - with mock.patch.object(transports.AnswerRecordsTransport, '_prep_wrapped_messages') as prep: - client = AnswerRecordsClient( - credentials=ga_credentials.AnonymousCredentials(), - client_info=client_info, - ) - prep.assert_called_once_with(client_info) - - with mock.patch.object(transports.AnswerRecordsTransport, '_prep_wrapped_messages') as prep: - transport_class = AnswerRecordsClient.get_transport_class() - transport = transport_class( - credentials=ga_credentials.AnonymousCredentials(), - client_info=client_info, - ) - prep.assert_called_once_with(client_info) - -@pytest.mark.asyncio -async def test_transport_close_async(): - client = AnswerRecordsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - with mock.patch.object(type(getattr(client.transport, "grpc_channel")), "close") as close: - async with client: - close.assert_not_called() - close.assert_called_once() - - -def test_get_location_rest_bad_request(transport: str = 'rest', request_type=locations_pb2.GetLocationRequest): - client = AnswerRecordsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - request = request_type() - request = json_format.ParseDict({'name': 'projects/sample1/locations/sample2'}, request) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.get_location(request) - -@pytest.mark.parametrize("request_type", [ - locations_pb2.GetLocationRequest, - dict, -]) -def test_get_location_rest(request_type): - client = AnswerRecordsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request_init = {'name': 'projects/sample1/locations/sample2'} - request = request_type(**request_init) - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = locations_pb2.Location() - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.get_location(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, locations_pb2.Location) - -def test_list_locations_rest_bad_request(transport: str = 'rest', request_type=locations_pb2.ListLocationsRequest): - client = AnswerRecordsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - request = request_type() - request = json_format.ParseDict({'name': 'projects/sample1'}, request) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.list_locations(request) - -@pytest.mark.parametrize("request_type", [ - locations_pb2.ListLocationsRequest, - dict, -]) -def test_list_locations_rest(request_type): - client = AnswerRecordsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request_init = {'name': 'projects/sample1'} - request = request_type(**request_init) - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = locations_pb2.ListLocationsResponse() - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.list_locations(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, locations_pb2.ListLocationsResponse) - -def test_cancel_operation_rest_bad_request(transport: str = 'rest', request_type=operations_pb2.CancelOperationRequest): - client = AnswerRecordsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - request = request_type() - request = json_format.ParseDict({'name': 'projects/sample1/operations/sample2'}, request) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.cancel_operation(request) - -@pytest.mark.parametrize("request_type", [ - operations_pb2.CancelOperationRequest, - dict, -]) -def test_cancel_operation_rest(request_type): - client = AnswerRecordsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request_init = {'name': 'projects/sample1/operations/sample2'} - request = request_type(**request_init) - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = None - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = '{}' - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.cancel_operation(request) - - # Establish that the response is the type that we expect. - assert response is None - -def test_get_operation_rest_bad_request(transport: str = 'rest', request_type=operations_pb2.GetOperationRequest): - client = AnswerRecordsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - request = request_type() - request = json_format.ParseDict({'name': 'projects/sample1/operations/sample2'}, request) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.get_operation(request) - -@pytest.mark.parametrize("request_type", [ - operations_pb2.GetOperationRequest, - dict, -]) -def test_get_operation_rest(request_type): - client = AnswerRecordsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request_init = {'name': 'projects/sample1/operations/sample2'} - request = request_type(**request_init) - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation() - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.get_operation(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, operations_pb2.Operation) - -def test_list_operations_rest_bad_request(transport: str = 'rest', request_type=operations_pb2.ListOperationsRequest): - client = AnswerRecordsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - request = request_type() - request = json_format.ParseDict({'name': 'projects/sample1'}, request) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.list_operations(request) - -@pytest.mark.parametrize("request_type", [ - operations_pb2.ListOperationsRequest, - dict, -]) -def test_list_operations_rest(request_type): - client = AnswerRecordsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request_init = {'name': 'projects/sample1'} - request = request_type(**request_init) - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = operations_pb2.ListOperationsResponse() - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.list_operations(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, operations_pb2.ListOperationsResponse) - - -def test_cancel_operation(transport: str = "grpc"): - client = AnswerRecordsClient( - 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 = operations_pb2.CancelOperationRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = None - response = client.cancel_operation(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 response is the type that we expect. - assert response is None -@pytest.mark.asyncio -async def test_cancel_operation_async(transport: str = "grpc"): - client = AnswerRecordsAsyncClient( - 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 = operations_pb2.CancelOperationRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - None - ) - response = await client.cancel_operation(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 response is the type that we expect. - assert response is None - -def test_cancel_operation_field_headers(): - 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 = operations_pb2.CancelOperationRequest() - request.name = "locations" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call: - call.return_value = None - - client.cancel_operation(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=locations",) in kw["metadata"] -@pytest.mark.asyncio -async def test_cancel_operation_field_headers_async(): - 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 = operations_pb2.CancelOperationRequest() - request.name = "locations" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - None - ) - await client.cancel_operation(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=locations",) in kw["metadata"] - -def test_cancel_operation_from_dict(): - client = AnswerRecordsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = None - - response = client.cancel_operation( - request={ - "name": "locations", - } - ) - call.assert_called() -@pytest.mark.asyncio -async def test_cancel_operation_from_dict_async(): - client = AnswerRecordsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - None - ) - response = await client.cancel_operation( - request={ - "name": "locations", - } - ) - call.assert_called() - - -def test_get_operation(transport: str = "grpc"): - client = AnswerRecordsClient( - 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 = operations_pb2.GetOperationRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_operation), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation() - response = client.get_operation(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 response is the type that we expect. - assert isinstance(response, operations_pb2.Operation) -@pytest.mark.asyncio -async def test_get_operation_async(transport: str = "grpc"): - client = AnswerRecordsAsyncClient( - 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 = operations_pb2.GetOperationRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_operation), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation() - ) - response = await client.get_operation(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 response is the type that we expect. - assert isinstance(response, operations_pb2.Operation) - -def test_get_operation_field_headers(): - 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 = operations_pb2.GetOperationRequest() - request.name = "locations" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_operation), "__call__") as call: - call.return_value = operations_pb2.Operation() - - client.get_operation(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=locations",) in kw["metadata"] -@pytest.mark.asyncio -async def test_get_operation_field_headers_async(): - 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 = operations_pb2.GetOperationRequest() - request.name = "locations" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_operation), "__call__") as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation() - ) - await client.get_operation(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=locations",) in kw["metadata"] - -def test_get_operation_from_dict(): - client = AnswerRecordsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_operation), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation() - - response = client.get_operation( - request={ - "name": "locations", - } - ) - call.assert_called() -@pytest.mark.asyncio -async def test_get_operation_from_dict_async(): - client = AnswerRecordsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_operation), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation() - ) - response = await client.get_operation( - request={ - "name": "locations", - } - ) - call.assert_called() - - -def test_list_operations(transport: str = "grpc"): - client = AnswerRecordsClient( - 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 = operations_pb2.ListOperationsRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_operations), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.ListOperationsResponse() - response = client.list_operations(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 response is the type that we expect. - assert isinstance(response, operations_pb2.ListOperationsResponse) -@pytest.mark.asyncio -async def test_list_operations_async(transport: str = "grpc"): - client = AnswerRecordsAsyncClient( - 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 = operations_pb2.ListOperationsRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_operations), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.ListOperationsResponse() - ) - response = await client.list_operations(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 response is the type that we expect. - assert isinstance(response, operations_pb2.ListOperationsResponse) - -def test_list_operations_field_headers(): - 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 = operations_pb2.ListOperationsRequest() - request.name = "locations" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_operations), "__call__") as call: - call.return_value = operations_pb2.ListOperationsResponse() - - client.list_operations(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=locations",) in kw["metadata"] -@pytest.mark.asyncio -async def test_list_operations_field_headers_async(): - 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 = operations_pb2.ListOperationsRequest() - request.name = "locations" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_operations), "__call__") as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.ListOperationsResponse() - ) - await client.list_operations(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=locations",) in kw["metadata"] - -def test_list_operations_from_dict(): - client = AnswerRecordsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_operations), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.ListOperationsResponse() - - response = client.list_operations( - request={ - "name": "locations", - } - ) - call.assert_called() -@pytest.mark.asyncio -async def test_list_operations_from_dict_async(): - client = AnswerRecordsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_operations), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.ListOperationsResponse() - ) - response = await client.list_operations( - request={ - "name": "locations", - } - ) - call.assert_called() - - -def test_list_locations(transport: str = "grpc"): - client = AnswerRecordsClient( - 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 = locations_pb2.ListLocationsRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_locations), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = locations_pb2.ListLocationsResponse() - response = client.list_locations(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 response is the type that we expect. - assert isinstance(response, locations_pb2.ListLocationsResponse) -@pytest.mark.asyncio -async def test_list_locations_async(transport: str = "grpc"): - client = AnswerRecordsAsyncClient( - 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 = locations_pb2.ListLocationsRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_locations), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - locations_pb2.ListLocationsResponse() - ) - response = await client.list_locations(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 response is the type that we expect. - assert isinstance(response, locations_pb2.ListLocationsResponse) - -def test_list_locations_field_headers(): - 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 = locations_pb2.ListLocationsRequest() - request.name = "locations" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_locations), "__call__") as call: - call.return_value = locations_pb2.ListLocationsResponse() - - client.list_locations(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=locations",) in kw["metadata"] -@pytest.mark.asyncio -async def test_list_locations_field_headers_async(): - 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 = locations_pb2.ListLocationsRequest() - request.name = "locations" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_locations), "__call__") as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - locations_pb2.ListLocationsResponse() - ) - await client.list_locations(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=locations",) in kw["metadata"] - -def test_list_locations_from_dict(): - client = AnswerRecordsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_locations), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = locations_pb2.ListLocationsResponse() - - response = client.list_locations( - request={ - "name": "locations", - } - ) - call.assert_called() -@pytest.mark.asyncio -async def test_list_locations_from_dict_async(): - client = AnswerRecordsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_locations), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - locations_pb2.ListLocationsResponse() - ) - response = await client.list_locations( - request={ - "name": "locations", - } - ) - call.assert_called() - - -def test_get_location(transport: str = "grpc"): - client = AnswerRecordsClient( - 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 = locations_pb2.GetLocationRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_location), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = locations_pb2.Location() - response = client.get_location(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 response is the type that we expect. - assert isinstance(response, locations_pb2.Location) -@pytest.mark.asyncio -async def test_get_location_async(transport: str = "grpc_asyncio"): - client = AnswerRecordsAsyncClient( - 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 = locations_pb2.GetLocationRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_location), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - locations_pb2.Location() - ) - response = await client.get_location(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 response is the type that we expect. - assert isinstance(response, locations_pb2.Location) - -def test_get_location_field_headers(): - 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 = locations_pb2.GetLocationRequest() - request.name = "locations/abc" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_location), "__call__") as call: - call.return_value = locations_pb2.Location() - - client.get_location(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=locations/abc",) in kw["metadata"] -@pytest.mark.asyncio -async def test_get_location_field_headers_async(): - 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 = locations_pb2.GetLocationRequest() - request.name = "locations/abc" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_location), "__call__") as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - locations_pb2.Location() - ) - await client.get_location(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=locations/abc",) in kw["metadata"] - -def test_get_location_from_dict(): - client = AnswerRecordsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_locations), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = locations_pb2.Location() - - response = client.get_location( - request={ - "name": "locations/abc", - } - ) - call.assert_called() -@pytest.mark.asyncio -async def test_get_location_from_dict_async(): - client = AnswerRecordsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_locations), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - locations_pb2.Location() - ) - response = await client.get_location( - request={ - "name": "locations", - } - ) - call.assert_called() - - -def test_transport_close(): - transports = { - "rest": "_session", - "grpc": "_grpc_channel", - } - - for transport, close_name in transports.items(): - client = AnswerRecordsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport - ) - with mock.patch.object(type(getattr(client.transport, close_name)), "close") as close: - with client: - close.assert_not_called() - close.assert_called_once() - -def test_client_ctx(): - transports = [ - 'rest', - 'grpc', - ] - for transport in transports: - client = AnswerRecordsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport - ) - # Test client calls underlying transport. - with mock.patch.object(type(client.transport), "close") as close: - close.assert_not_called() - with client: - pass - close.assert_called() - -@pytest.mark.parametrize("client_class,transport_class", [ - (AnswerRecordsClient, transports.AnswerRecordsGrpcTransport), - (AnswerRecordsAsyncClient, transports.AnswerRecordsGrpcAsyncIOTransport), -]) -def test_api_key_credentials(client_class, transport_class): - with mock.patch.object( - google.auth._default, "get_api_key_credentials", create=True - ) as get_api_key_credentials: - mock_cred = mock.Mock() - get_api_key_credentials.return_value = mock_cred - options = client_options.ClientOptions() - options.api_key = "api_key" - 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=mock_cred, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) diff --git a/owl-bot-staging/v2beta1/tests/unit/gapic/dialogflow_v2beta1/test_contexts.py b/owl-bot-staging/v2beta1/tests/unit/gapic/dialogflow_v2beta1/test_contexts.py deleted file mode 100644 index c3e69f8a5..000000000 --- a/owl-bot-staging/v2beta1/tests/unit/gapic/dialogflow_v2beta1/test_contexts.py +++ /dev/null @@ -1,5176 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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 -# try/except added for compatibility with python < 3.8 -try: - from unittest import mock - from unittest.mock import AsyncMock # pragma: NO COVER -except ImportError: # pragma: NO COVER - import mock - -import grpc -from grpc.experimental import aio -from collections.abc import Iterable -from google.protobuf import json_format -import json -import math -import pytest -from proto.marshal.rules.dates import DurationRule, TimestampRule -from proto.marshal.rules import wrappers -from requests import Response -from requests import Request, PreparedRequest -from requests.sessions import Session -from google.protobuf import json_format - -from google.api_core import client_options -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import grpc_helpers -from google.api_core import grpc_helpers_async -from google.api_core import path_template -from google.auth import credentials as ga_credentials -from google.auth.exceptions import MutualTLSChannelError -from google.cloud.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.types import context -from google.cloud.dialogflow_v2beta1.types import context as gcd_context -from google.cloud.location import locations_pb2 -from google.longrunning import operations_pb2 -from google.oauth2 import service_account -from google.protobuf import field_mask_pb2 # type: ignore -from google.protobuf import struct_pb2 # type: ignore -import google.auth - - -def client_cert_source_callback(): - return b"cert bytes", b"key bytes" - - -# If default endpoint is localhost, then default mtls endpoint will be the same. -# This method modifies the default endpoint so the client can produce a different -# mtls endpoint for endpoint testing purposes. -def modify_default_endpoint(client): - return "foo.googleapis.com" if ("localhost" in client.DEFAULT_ENDPOINT) else client.DEFAULT_ENDPOINT - - -def test__get_default_mtls_endpoint(): - api_endpoint = "example.googleapis.com" - api_mtls_endpoint = "example.mtls.googleapis.com" - sandbox_endpoint = "example.sandbox.googleapis.com" - sandbox_mtls_endpoint = "example.mtls.sandbox.googleapis.com" - non_googleapi = "api.example.com" - - assert ContextsClient._get_default_mtls_endpoint(None) is None - assert ContextsClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint - assert ContextsClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint - assert ContextsClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint - assert ContextsClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint - assert ContextsClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi - - -@pytest.mark.parametrize("client_class,transport_name", [ - (ContextsClient, "grpc"), - (ContextsAsyncClient, "grpc_asyncio"), - (ContextsClient, "rest"), -]) -def test_contexts_client_from_service_account_info(client_class, transport_name): - 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, transport=transport_name) - assert client.transport._credentials == creds - assert isinstance(client, client_class) - - assert client.transport._host == ( - 'dialogflow.googleapis.com:443' - if transport_name in ['grpc', 'grpc_asyncio'] - else - 'https://dialogflow.googleapis.com' - ) - - -@pytest.mark.parametrize("transport_class,transport_name", [ - (transports.ContextsGrpcTransport, "grpc"), - (transports.ContextsGrpcAsyncIOTransport, "grpc_asyncio"), - (transports.ContextsRestTransport, "rest"), -]) -def test_contexts_client_service_account_always_use_jwt(transport_class, transport_name): - with mock.patch.object(service_account.Credentials, 'with_always_use_jwt_access', create=True) as use_jwt: - creds = service_account.Credentials(None, None, None) - transport = transport_class(credentials=creds, always_use_jwt_access=True) - use_jwt.assert_called_once_with(True) - - with mock.patch.object(service_account.Credentials, 'with_always_use_jwt_access', create=True) as use_jwt: - creds = service_account.Credentials(None, None, None) - transport = transport_class(credentials=creds, always_use_jwt_access=False) - use_jwt.assert_not_called() - - -@pytest.mark.parametrize("client_class,transport_name", [ - (ContextsClient, "grpc"), - (ContextsAsyncClient, "grpc_asyncio"), - (ContextsClient, "rest"), -]) -def test_contexts_client_from_service_account_file(client_class, transport_name): - 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", transport=transport_name) - assert client.transport._credentials == creds - assert isinstance(client, client_class) - - client = client_class.from_service_account_json("dummy/file/path.json", transport=transport_name) - assert client.transport._credentials == creds - assert isinstance(client, client_class) - - assert client.transport._host == ( - 'dialogflow.googleapis.com:443' - if transport_name in ['grpc', 'grpc_asyncio'] - else - 'https://dialogflow.googleapis.com' - ) - - -def test_contexts_client_get_transport_class(): - transport = ContextsClient.get_transport_class() - available_transports = [ - transports.ContextsGrpcTransport, - transports.ContextsRestTransport, - ] - assert transport in available_transports - - transport = ContextsClient.get_transport_class("grpc") - assert transport == transports.ContextsGrpcTransport - - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (ContextsClient, transports.ContextsGrpcTransport, "grpc"), - (ContextsAsyncClient, transports.ContextsGrpcAsyncIOTransport, "grpc_asyncio"), - (ContextsClient, transports.ContextsRestTransport, "rest"), -]) -@mock.patch.object(ContextsClient, "DEFAULT_ENDPOINT", modify_default_endpoint(ContextsClient)) -@mock.patch.object(ContextsAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(ContextsAsyncClient)) -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=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(ContextsClient, 'get_transport_class') as gtc: - client = client_class(transport=transport_name) - gtc.assert_called() - - # Check the case api_endpoint is provided. - options = client_options.ClientOptions(api_endpoint="squid.clam.whelk") - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(transport=transport_name, client_options=options) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host="squid.clam.whelk", - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is - # "never". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is - # "always". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_MTLS_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # 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(transport=transport_name) - - # 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(transport=transport_name) - - # 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, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id="octopus", - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - # Check the case api_endpoint is provided - options = client_options.ClientOptions(api_audience="https://language.googleapis.com") - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience="https://language.googleapis.com" - ) - -@pytest.mark.parametrize("client_class,transport_class,transport_name,use_client_cert_env", [ - (ContextsClient, transports.ContextsGrpcTransport, "grpc", "true"), - (ContextsAsyncClient, transports.ContextsGrpcAsyncIOTransport, "grpc_asyncio", "true"), - (ContextsClient, transports.ContextsGrpcTransport, "grpc", "false"), - (ContextsAsyncClient, transports.ContextsGrpcAsyncIOTransport, "grpc_asyncio", "false"), - (ContextsClient, transports.ContextsRestTransport, "rest", "true"), - (ContextsClient, transports.ContextsRestTransport, "rest", "false"), -]) -@mock.patch.object(ContextsClient, "DEFAULT_ENDPOINT", modify_default_endpoint(ContextsClient)) -@mock.patch.object(ContextsAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(ContextsAsyncClient)) -@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) -def test_contexts_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, transport=transport_name) - - if use_client_cert_env == "false": - expected_client_cert_source = None - expected_host = client.DEFAULT_ENDPOINT - else: - expected_client_cert_source = client_cert_source_callback - expected_host = client.DEFAULT_MTLS_ENDPOINT - - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=expected_host, - scopes=None, - client_cert_source_for_mtls=expected_client_cert_source, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case ADC client cert is provided. Whether client cert is used depends on - # GOOGLE_API_USE_CLIENT_CERTIFICATE value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): - with mock.patch.object(transport_class, '__init__') as patched: - with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): - with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=client_cert_source_callback): - if use_client_cert_env == "false": - expected_host = client.DEFAULT_ENDPOINT - expected_client_cert_source = None - else: - expected_host = client.DEFAULT_MTLS_ENDPOINT - expected_client_cert_source = client_cert_source_callback - - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=expected_host, - scopes=None, - client_cert_source_for_mtls=expected_client_cert_source, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case client_cert_source and ADC client cert are not provided. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): - with mock.patch.object(transport_class, '__init__') as patched: - with mock.patch("google.auth.transport.mtls.has_default_client_cert_source", return_value=False): - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - -@pytest.mark.parametrize("client_class", [ - ContextsClient, ContextsAsyncClient -]) -@mock.patch.object(ContextsClient, "DEFAULT_ENDPOINT", modify_default_endpoint(ContextsClient)) -@mock.patch.object(ContextsAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(ContextsAsyncClient)) -def test_contexts_client_get_mtls_endpoint_and_cert_source(client_class): - mock_client_cert_source = mock.Mock() - - # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "true". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - mock_api_endpoint = "foo" - options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) - assert api_endpoint == mock_api_endpoint - assert cert_source == mock_client_cert_source - - # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "false". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): - mock_client_cert_source = mock.Mock() - mock_api_endpoint = "foo" - options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) - assert api_endpoint == mock_api_endpoint - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "never". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_ENDPOINT - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "always". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert doesn't exist. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=False): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_ENDPOINT - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert exists. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - 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=mock_client_cert_source): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT - assert cert_source == mock_client_cert_source - - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (ContextsClient, transports.ContextsGrpcTransport, "grpc"), - (ContextsAsyncClient, transports.ContextsGrpcAsyncIOTransport, "grpc_asyncio"), - (ContextsClient, transports.ContextsRestTransport, "rest"), -]) -def test_contexts_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, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=["1", "2"], - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - -@pytest.mark.parametrize("client_class,transport_class,transport_name,grpc_helpers", [ - (ContextsClient, transports.ContextsGrpcTransport, "grpc", grpc_helpers), - (ContextsAsyncClient, transports.ContextsGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), - (ContextsClient, transports.ContextsRestTransport, "rest", None), -]) -def test_contexts_client_client_options_credentials_file(client_class, transport_class, transport_name, grpc_helpers): - # 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, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file="credentials.json", - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - -def test_contexts_client_client_options_from_dict(): - with mock.patch('google.cloud.dialogflow_v2beta1.services.contexts.transports.ContextsGrpcTransport.__init__') as grpc_transport: - grpc_transport.return_value = None - client = ContextsClient( - client_options={'api_endpoint': 'squid.clam.whelk'} - ) - grpc_transport.assert_called_once_with( - credentials=None, - credentials_file=None, - host="squid.clam.whelk", - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - -@pytest.mark.parametrize("client_class,transport_class,transport_name,grpc_helpers", [ - (ContextsClient, transports.ContextsGrpcTransport, "grpc", grpc_helpers), - (ContextsAsyncClient, transports.ContextsGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), -]) -def test_contexts_client_create_channel_credentials_file(client_class, transport_class, transport_name, grpc_helpers): - # 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, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file="credentials.json", - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # test that the credentials from file are saved and used as the credentials. - with mock.patch.object( - google.auth, "load_credentials_from_file", autospec=True - ) as load_creds, mock.patch.object( - google.auth, "default", autospec=True - ) as adc, mock.patch.object( - grpc_helpers, "create_channel" - ) as create_channel: - creds = ga_credentials.AnonymousCredentials() - file_creds = ga_credentials.AnonymousCredentials() - load_creds.return_value = (file_creds, None) - adc.return_value = (creds, None) - client = client_class(client_options=options, transport=transport_name) - create_channel.assert_called_with( - "dialogflow.googleapis.com:443", - credentials=file_creds, - credentials_file=None, - quota_project_id=None, - default_scopes=( - 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/dialogflow', -), - scopes=None, - default_host="dialogflow.googleapis.com", - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - -@pytest.mark.parametrize("request_type", [ - context.ListContextsRequest, - dict, -]) -def test_list_contexts(request_type, transport: str = 'grpc'): - client = ContextsClient( - 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_contexts), - '__call__') as call: - # Designate an appropriate return value for the call. - 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' - - -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=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_contexts), - '__call__') as call: - client.list_contexts() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == context.ListContextsRequest() - -@pytest.mark.asyncio -async def test_list_contexts_async(transport: str = 'grpc_asyncio', request_type=context.ListContextsRequest): - client = ContextsAsyncClient( - 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_contexts), - '__call__') as call: - # Designate an appropriate return value for the call. - 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' - - -@pytest.mark.asyncio -async def test_list_contexts_async_from_dict(): - await test_list_contexts_async(request_type=dict) - - -def test_list_contexts_field_headers(): - 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. - 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_contexts_field_headers_async(): - 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. - with mock.patch.object( - type(client.transport.list_contexts), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(context.ListContextsResponse()) - 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] == 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_contexts_flattened(): - 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', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - arg = args[0].parent - mock_val = 'parent_value' - assert arg == mock_val - - -def test_list_contexts_flattened_error(): - client = ContextsClient( - 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_contexts( - context.ListContextsRequest(), - parent='parent_value', - ) - -@pytest.mark.asyncio -async def test_list_contexts_flattened_async(): - 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: - # Designate an appropriate return value for the call. - call.return_value = context.ListContextsResponse() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(context.ListContextsResponse()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.list_contexts( - 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] - arg = args[0].parent - mock_val = 'parent_value' - assert arg == mock_val - -@pytest.mark.asyncio -async def test_list_contexts_flattened_error_async(): - client = ContextsAsyncClient( - 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_contexts( - context.ListContextsRequest(), - parent='parent_value', - ) - - -def test_list_contexts_pager(transport_name: str = "grpc"): - client = ContextsClient( - credentials=ga_credentials.AnonymousCredentials, - transport=transport_name, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_contexts), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - context.ListContextsResponse( - contexts=[ - context.Context(), - context.Context(), - context.Context(), - ], - next_page_token='abc', - ), - context.ListContextsResponse( - contexts=[], - next_page_token='def', - ), - context.ListContextsResponse( - contexts=[ - context.Context(), - ], - next_page_token='ghi', - ), - context.ListContextsResponse( - contexts=[ - context.Context(), - context.Context(), - ], - ), - RuntimeError, - ) - - metadata = () - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ('parent', ''), - )), - ) - pager = client.list_contexts(request={}) - - assert pager._metadata == metadata - - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, context.Context) - for i in results) -def test_list_contexts_pages(transport_name: str = "grpc"): - client = ContextsClient( - credentials=ga_credentials.AnonymousCredentials, - transport=transport_name, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_contexts), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - context.ListContextsResponse( - contexts=[ - context.Context(), - context.Context(), - context.Context(), - ], - next_page_token='abc', - ), - context.ListContextsResponse( - contexts=[], - next_page_token='def', - ), - context.ListContextsResponse( - contexts=[ - context.Context(), - ], - next_page_token='ghi', - ), - context.ListContextsResponse( - contexts=[ - context.Context(), - context.Context(), - ], - ), - RuntimeError, - ) - pages = list(client.list_contexts(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_contexts_async_pager(): - 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__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - context.ListContextsResponse( - contexts=[ - context.Context(), - context.Context(), - context.Context(), - ], - next_page_token='abc', - ), - context.ListContextsResponse( - contexts=[], - next_page_token='def', - ), - context.ListContextsResponse( - contexts=[ - context.Context(), - ], - next_page_token='ghi', - ), - context.ListContextsResponse( - contexts=[ - context.Context(), - context.Context(), - ], - ), - RuntimeError, - ) - async_pager = await client.list_contexts(request={},) - assert async_pager.next_page_token == 'abc' - responses = [] - async for response in async_pager: # pragma: no branch - responses.append(response) - - assert len(responses) == 6 - assert all(isinstance(i, context.Context) - for i in responses) - - -@pytest.mark.asyncio -async def test_list_contexts_async_pages(): - 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__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - context.ListContextsResponse( - contexts=[ - context.Context(), - context.Context(), - context.Context(), - ], - next_page_token='abc', - ), - context.ListContextsResponse( - contexts=[], - next_page_token='def', - ), - context.ListContextsResponse( - contexts=[ - context.Context(), - ], - next_page_token='ghi', - ), - context.ListContextsResponse( - contexts=[ - context.Context(), - context.Context(), - ], - ), - RuntimeError, - ) - pages = [] - async for page_ in (await client.list_contexts(request={})).pages: # pragma: no branch - pages.append(page_) - for page_, token in zip(pages, ['abc','def','ghi', '']): - assert page_.raw_page.next_page_token == token - -@pytest.mark.parametrize("request_type", [ - context.GetContextRequest, - dict, -]) -def test_get_context(request_type, transport: str = 'grpc'): - client = ContextsClient( - 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_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 - - -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=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_context), - '__call__') as call: - client.get_context() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == context.GetContextRequest() - -@pytest.mark.asyncio -async def test_get_context_async(transport: str = 'grpc_asyncio', request_type=context.GetContextRequest): - client = ContextsAsyncClient( - 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_context), - '__call__') as call: - # Designate an appropriate return value for the call. - 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 - - -@pytest.mark.asyncio -async def test_get_context_async_from_dict(): - await test_get_context_async(request_type=dict) - - -def test_get_context_field_headers(): - 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. - 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_context_field_headers_async(): - 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. - 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_context_flattened(): - 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', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - arg = args[0].name - mock_val = 'name_value' - assert arg == mock_val - - -def test_get_context_flattened_error(): - client = ContextsClient( - 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_context( - context.GetContextRequest(), - name='name_value', - ) - -@pytest.mark.asyncio -async def test_get_context_flattened_async(): - 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: - # Designate an appropriate return value for the call. - call.return_value = context.Context() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(context.Context()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.get_context( - 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] - arg = args[0].name - mock_val = 'name_value' - assert arg == mock_val - -@pytest.mark.asyncio -async def test_get_context_flattened_error_async(): - client = ContextsAsyncClient( - 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_context( - context.GetContextRequest(), - name='name_value', - ) - - -@pytest.mark.parametrize("request_type", [ - gcd_context.CreateContextRequest, - dict, -]) -def test_create_context(request_type, transport: str = 'grpc'): - client = ContextsClient( - 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_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 - - -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=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_context), - '__call__') as call: - client.create_context() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == gcd_context.CreateContextRequest() - -@pytest.mark.asyncio -async def test_create_context_async(transport: str = 'grpc_asyncio', request_type=gcd_context.CreateContextRequest): - client = ContextsAsyncClient( - 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_context), - '__call__') as call: - # Designate an appropriate return value for the call. - 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 - - -@pytest.mark.asyncio -async def test_create_context_async_from_dict(): - await test_create_context_async(request_type=dict) - - -def test_create_context_field_headers(): - 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. - 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_context_field_headers_async(): - 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. - 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_context_flattened(): - 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( - parent='parent_value', - context=gcd_context.Context(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] - arg = args[0].parent - mock_val = 'parent_value' - assert arg == mock_val - arg = args[0].context - mock_val = gcd_context.Context(name='name_value') - assert arg == mock_val - - -def test_create_context_flattened_error(): - client = ContextsClient( - 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_context( - gcd_context.CreateContextRequest(), - parent='parent_value', - context=gcd_context.Context(name='name_value'), - ) - -@pytest.mark.asyncio -async def test_create_context_flattened_async(): - 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: - # Designate an appropriate return value for the call. - call.return_value = gcd_context.Context() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcd_context.Context()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.create_context( - parent='parent_value', - context=gcd_context.Context(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] - arg = args[0].parent - mock_val = 'parent_value' - assert arg == mock_val - arg = args[0].context - mock_val = gcd_context.Context(name='name_value') - assert arg == mock_val - -@pytest.mark.asyncio -async def test_create_context_flattened_error_async(): - client = ContextsAsyncClient( - 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_context( - gcd_context.CreateContextRequest(), - parent='parent_value', - context=gcd_context.Context(name='name_value'), - ) - - -@pytest.mark.parametrize("request_type", [ - gcd_context.UpdateContextRequest, - dict, -]) -def test_update_context(request_type, transport: str = 'grpc'): - client = ContextsClient( - 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_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 - - -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=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_context), - '__call__') as call: - client.update_context() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == gcd_context.UpdateContextRequest() - -@pytest.mark.asyncio -async def test_update_context_async(transport: str = 'grpc_asyncio', request_type=gcd_context.UpdateContextRequest): - client = ContextsAsyncClient( - 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_context), - '__call__') as call: - # Designate an appropriate return value for the call. - 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 - - -@pytest.mark.asyncio -async def test_update_context_async_from_dict(): - await test_update_context_async(request_type=dict) - - -def test_update_context_field_headers(): - 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 = '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. - 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', - 'context.name=name_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_update_context_field_headers_async(): - 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 = '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. - 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', - 'context.name=name_value', - ) in kw['metadata'] - - -def test_update_context_flattened(): - 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_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] - arg = args[0].context - mock_val = gcd_context.Context(name='name_value') - assert arg == mock_val - arg = args[0].update_mask - mock_val = field_mask_pb2.FieldMask(paths=['paths_value']) - assert arg == mock_val - - -def test_update_context_flattened_error(): - client = ContextsClient( - 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_context( - gcd_context.UpdateContextRequest(), - context=gcd_context.Context(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - -@pytest.mark.asyncio -async def test_update_context_flattened_async(): - 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: - # Designate an appropriate return value for the call. - call.return_value = gcd_context.Context() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcd_context.Context()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.update_context( - context=gcd_context.Context(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] - arg = args[0].context - mock_val = gcd_context.Context(name='name_value') - assert arg == mock_val - arg = args[0].update_mask - mock_val = field_mask_pb2.FieldMask(paths=['paths_value']) - assert arg == mock_val - -@pytest.mark.asyncio -async def test_update_context_flattened_error_async(): - client = ContextsAsyncClient( - 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_context( - gcd_context.UpdateContextRequest(), - context=gcd_context.Context(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - - -@pytest.mark.parametrize("request_type", [ - context.DeleteContextRequest, - dict, -]) -def test_delete_context(request_type, transport: str = 'grpc'): - client = ContextsClient( - 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_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. - assert response is None - - -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=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_context), - '__call__') as call: - client.delete_context() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == context.DeleteContextRequest() - -@pytest.mark.asyncio -async def test_delete_context_async(transport: str = 'grpc_asyncio', request_type=context.DeleteContextRequest): - client = ContextsAsyncClient( - 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_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. - assert response is None - - -@pytest.mark.asyncio -async def test_delete_context_async_from_dict(): - await test_delete_context_async(request_type=dict) - - -def test_delete_context_field_headers(): - 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. - 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_context_field_headers_async(): - 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. - 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_context_flattened(): - 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', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - arg = args[0].name - mock_val = 'name_value' - assert arg == mock_val - - -def test_delete_context_flattened_error(): - client = ContextsClient( - 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_context( - context.DeleteContextRequest(), - name='name_value', - ) - -@pytest.mark.asyncio -async def test_delete_context_flattened_async(): - 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: - # 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_context( - 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] - arg = args[0].name - mock_val = 'name_value' - assert arg == mock_val - -@pytest.mark.asyncio -async def test_delete_context_flattened_error_async(): - client = ContextsAsyncClient( - 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_context( - context.DeleteContextRequest(), - name='name_value', - ) - - -@pytest.mark.parametrize("request_type", [ - context.DeleteAllContextsRequest, - dict, -]) -def test_delete_all_contexts(request_type, transport: str = 'grpc'): - client = ContextsClient( - 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_all_contexts), - '__call__') 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. - assert response is None - - -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=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_all_contexts), - '__call__') as call: - client.delete_all_contexts() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == context.DeleteAllContextsRequest() - -@pytest.mark.asyncio -async def test_delete_all_contexts_async(transport: str = 'grpc_asyncio', request_type=context.DeleteAllContextsRequest): - client = ContextsAsyncClient( - 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_all_contexts), - '__call__') 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. - assert response is None - - -@pytest.mark.asyncio -async def test_delete_all_contexts_async_from_dict(): - await test_delete_all_contexts_async(request_type=dict) - - -def test_delete_all_contexts_field_headers(): - 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. - with mock.patch.object( - 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. - 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_delete_all_contexts_field_headers_async(): - 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. - with mock.patch.object( - 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. - 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_delete_all_contexts_flattened(): - 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_all_contexts), - '__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_all_contexts( - 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] - arg = args[0].parent - mock_val = 'parent_value' - assert arg == mock_val - - -def test_delete_all_contexts_flattened_error(): - client = ContextsClient( - 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_all_contexts( - context.DeleteAllContextsRequest(), - parent='parent_value', - ) - -@pytest.mark.asyncio -async def test_delete_all_contexts_flattened_async(): - 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_all_contexts), - '__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_all_contexts( - 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] - arg = args[0].parent - mock_val = 'parent_value' - assert arg == mock_val - -@pytest.mark.asyncio -async def test_delete_all_contexts_flattened_error_async(): - client = ContextsAsyncClient( - 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_all_contexts( - context.DeleteAllContextsRequest(), - parent='parent_value', - ) - - -@pytest.mark.parametrize("request_type", [ - context.ListContextsRequest, - dict, -]) -def test_list_contexts_rest(request_type): - client = ContextsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1/agent/sessions/sample2'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = context.ListContextsResponse( - next_page_token='next_page_token_value', - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - pb_return_value = context.ListContextsResponse.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.list_contexts(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListContextsPager) - assert response.next_page_token == 'next_page_token_value' - - -def test_list_contexts_rest_required_fields(request_type=context.ListContextsRequest): - transport_class = transports.ContextsRestTransport - - request_init = {} - request_init["parent"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - including_default_value_fields=False, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).list_contexts._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["parent"] = 'parent_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).list_contexts._get_unset_required_fields(jsonified_request) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("page_size", "page_token", )) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "parent" in jsonified_request - assert jsonified_request["parent"] == 'parent_value' - - client = ContextsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = context.ListContextsResponse() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "get", - 'query_params': pb_request, - } - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - - pb_return_value = context.ListContextsResponse.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.list_contexts(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_list_contexts_rest_unset_required_fields(): - transport = transports.ContextsRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.list_contexts._get_unset_required_fields({}) - assert set(unset_fields) == (set(("pageSize", "pageToken", )) & set(("parent", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_list_contexts_rest_interceptors(null_interceptor): - transport = transports.ContextsRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.ContextsRestInterceptor(), - ) - client = ContextsClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.ContextsRestInterceptor, "post_list_contexts") as post, \ - mock.patch.object(transports.ContextsRestInterceptor, "pre_list_contexts") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = context.ListContextsRequest.pb(context.ListContextsRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = context.ListContextsResponse.to_json(context.ListContextsResponse()) - - request = context.ListContextsRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = context.ListContextsResponse() - - client.list_contexts(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_list_contexts_rest_bad_request(transport: str = 'rest', request_type=context.ListContextsRequest): - client = ContextsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1/agent/sessions/sample2'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.list_contexts(request) - - -def test_list_contexts_rest_flattened(): - client = ContextsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = context.ListContextsResponse() - - # get arguments that satisfy an http rule for this method - sample_request = {'parent': 'projects/sample1/agent/sessions/sample2'} - - # get truthy value for each flattened field - mock_args = dict( - parent='parent_value', - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - pb_return_value = context.ListContextsResponse.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.list_contexts(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v2beta1/{parent=projects/*/agent/sessions/*}/contexts" % client.transport._host, args[1]) - - -def test_list_contexts_rest_flattened_error(transport: str = 'rest'): - client = ContextsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.list_contexts( - context.ListContextsRequest(), - parent='parent_value', - ) - - -def test_list_contexts_rest_pager(transport: str = 'rest'): - client = ContextsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # TODO(kbandes): remove this mock unless there's a good reason for it. - #with mock.patch.object(path_template, 'transcode') as transcode: - # Set the response as a series of pages - response = ( - context.ListContextsResponse( - contexts=[ - context.Context(), - context.Context(), - context.Context(), - ], - next_page_token='abc', - ), - context.ListContextsResponse( - contexts=[], - next_page_token='def', - ), - context.ListContextsResponse( - contexts=[ - context.Context(), - ], - next_page_token='ghi', - ), - context.ListContextsResponse( - contexts=[ - context.Context(), - context.Context(), - ], - ), - ) - # Two responses for two calls - response = response + response - - # Wrap the values into proper Response objs - response = tuple(context.ListContextsResponse.to_json(x) for x in response) - return_values = tuple(Response() for i in response) - for return_val, response_val in zip(return_values, response): - return_val._content = response_val.encode('UTF-8') - return_val.status_code = 200 - req.side_effect = return_values - - sample_request = {'parent': 'projects/sample1/agent/sessions/sample2'} - - pager = client.list_contexts(request=sample_request) - - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, context.Context) - for i in results) - - pages = list(client.list_contexts(request=sample_request).pages) - for page_, token in zip(pages, ['abc','def','ghi', '']): - assert page_.raw_page.next_page_token == token - - -@pytest.mark.parametrize("request_type", [ - context.GetContextRequest, - dict, -]) -def test_get_context_rest(request_type): - client = ContextsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/agent/sessions/sample2/contexts/sample3'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = context.Context( - name='name_value', - lifespan_count=1498, - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - pb_return_value = context.Context.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.get_context(request) - - # 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 - - -def test_get_context_rest_required_fields(request_type=context.GetContextRequest): - transport_class = transports.ContextsRestTransport - - request_init = {} - request_init["name"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - including_default_value_fields=False, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_context._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["name"] = 'name_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_context._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "name" in jsonified_request - assert jsonified_request["name"] == 'name_value' - - client = ContextsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = context.Context() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "get", - 'query_params': pb_request, - } - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - - pb_return_value = context.Context.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.get_context(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_get_context_rest_unset_required_fields(): - transport = transports.ContextsRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.get_context._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_get_context_rest_interceptors(null_interceptor): - transport = transports.ContextsRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.ContextsRestInterceptor(), - ) - client = ContextsClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.ContextsRestInterceptor, "post_get_context") as post, \ - mock.patch.object(transports.ContextsRestInterceptor, "pre_get_context") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = context.GetContextRequest.pb(context.GetContextRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = context.Context.to_json(context.Context()) - - request = context.GetContextRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = context.Context() - - client.get_context(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_get_context_rest_bad_request(transport: str = 'rest', request_type=context.GetContextRequest): - client = ContextsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/agent/sessions/sample2/contexts/sample3'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.get_context(request) - - -def test_get_context_rest_flattened(): - client = ContextsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = context.Context() - - # get arguments that satisfy an http rule for this method - sample_request = {'name': 'projects/sample1/agent/sessions/sample2/contexts/sample3'} - - # get truthy value for each flattened field - mock_args = dict( - name='name_value', - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - pb_return_value = context.Context.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.get_context(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v2beta1/{name=projects/*/agent/sessions/*/contexts/*}" % client.transport._host, args[1]) - - -def test_get_context_rest_flattened_error(transport: str = 'rest'): - client = ContextsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.get_context( - context.GetContextRequest(), - name='name_value', - ) - - -def test_get_context_rest_error(): - client = ContextsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - gcd_context.CreateContextRequest, - dict, -]) -def test_create_context_rest(request_type): - client = ContextsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1/agent/sessions/sample2'} - request_init["context"] = {'name': 'name_value', 'lifespan_count': 1498, 'parameters': {'fields': {}}} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = gcd_context.Context( - name='name_value', - lifespan_count=1498, - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - pb_return_value = gcd_context.Context.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.create_context(request) - - # 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 - - -def test_create_context_rest_required_fields(request_type=gcd_context.CreateContextRequest): - transport_class = transports.ContextsRestTransport - - request_init = {} - request_init["parent"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - including_default_value_fields=False, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_context._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["parent"] = 'parent_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_context._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "parent" in jsonified_request - assert jsonified_request["parent"] == 'parent_value' - - client = ContextsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = gcd_context.Context() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "post", - 'query_params': pb_request, - } - transcode_result['body'] = pb_request - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - - pb_return_value = gcd_context.Context.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.create_context(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_create_context_rest_unset_required_fields(): - transport = transports.ContextsRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.create_context._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("parent", "context", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_create_context_rest_interceptors(null_interceptor): - transport = transports.ContextsRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.ContextsRestInterceptor(), - ) - client = ContextsClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.ContextsRestInterceptor, "post_create_context") as post, \ - mock.patch.object(transports.ContextsRestInterceptor, "pre_create_context") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = gcd_context.CreateContextRequest.pb(gcd_context.CreateContextRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = gcd_context.Context.to_json(gcd_context.Context()) - - request = gcd_context.CreateContextRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = gcd_context.Context() - - client.create_context(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_create_context_rest_bad_request(transport: str = 'rest', request_type=gcd_context.CreateContextRequest): - client = ContextsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1/agent/sessions/sample2'} - request_init["context"] = {'name': 'name_value', 'lifespan_count': 1498, 'parameters': {'fields': {}}} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.create_context(request) - - -def test_create_context_rest_flattened(): - client = ContextsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = gcd_context.Context() - - # get arguments that satisfy an http rule for this method - sample_request = {'parent': 'projects/sample1/agent/sessions/sample2'} - - # get truthy value for each flattened field - mock_args = dict( - parent='parent_value', - context=gcd_context.Context(name='name_value'), - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - pb_return_value = gcd_context.Context.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.create_context(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v2beta1/{parent=projects/*/agent/sessions/*}/contexts" % client.transport._host, args[1]) - - -def test_create_context_rest_flattened_error(transport: str = 'rest'): - client = ContextsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.create_context( - gcd_context.CreateContextRequest(), - parent='parent_value', - context=gcd_context.Context(name='name_value'), - ) - - -def test_create_context_rest_error(): - client = ContextsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - gcd_context.UpdateContextRequest, - dict, -]) -def test_update_context_rest(request_type): - client = ContextsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'context': {'name': 'projects/sample1/agent/sessions/sample2/contexts/sample3'}} - request_init["context"] = {'name': 'projects/sample1/agent/sessions/sample2/contexts/sample3', 'lifespan_count': 1498, 'parameters': {'fields': {}}} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = gcd_context.Context( - name='name_value', - lifespan_count=1498, - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - pb_return_value = gcd_context.Context.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.update_context(request) - - # 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 - - -def test_update_context_rest_required_fields(request_type=gcd_context.UpdateContextRequest): - transport_class = transports.ContextsRestTransport - - request_init = {} - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - including_default_value_fields=False, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).update_context._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).update_context._get_unset_required_fields(jsonified_request) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("update_mask", )) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - - client = ContextsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = gcd_context.Context() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "patch", - 'query_params': pb_request, - } - transcode_result['body'] = pb_request - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - - pb_return_value = gcd_context.Context.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.update_context(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_update_context_rest_unset_required_fields(): - transport = transports.ContextsRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.update_context._get_unset_required_fields({}) - assert set(unset_fields) == (set(("updateMask", )) & set(("context", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_update_context_rest_interceptors(null_interceptor): - transport = transports.ContextsRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.ContextsRestInterceptor(), - ) - client = ContextsClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.ContextsRestInterceptor, "post_update_context") as post, \ - mock.patch.object(transports.ContextsRestInterceptor, "pre_update_context") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = gcd_context.UpdateContextRequest.pb(gcd_context.UpdateContextRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = gcd_context.Context.to_json(gcd_context.Context()) - - request = gcd_context.UpdateContextRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = gcd_context.Context() - - client.update_context(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_update_context_rest_bad_request(transport: str = 'rest', request_type=gcd_context.UpdateContextRequest): - client = ContextsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'context': {'name': 'projects/sample1/agent/sessions/sample2/contexts/sample3'}} - request_init["context"] = {'name': 'projects/sample1/agent/sessions/sample2/contexts/sample3', 'lifespan_count': 1498, 'parameters': {'fields': {}}} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.update_context(request) - - -def test_update_context_rest_flattened(): - client = ContextsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = gcd_context.Context() - - # get arguments that satisfy an http rule for this method - sample_request = {'context': {'name': 'projects/sample1/agent/sessions/sample2/contexts/sample3'}} - - # get truthy value for each flattened field - mock_args = dict( - context=gcd_context.Context(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - pb_return_value = gcd_context.Context.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.update_context(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v2beta1/{context.name=projects/*/agent/sessions/*/contexts/*}" % client.transport._host, args[1]) - - -def test_update_context_rest_flattened_error(transport: str = 'rest'): - client = ContextsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.update_context( - gcd_context.UpdateContextRequest(), - context=gcd_context.Context(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - - -def test_update_context_rest_error(): - client = ContextsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - context.DeleteContextRequest, - dict, -]) -def test_delete_context_rest(request_type): - client = ContextsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/agent/sessions/sample2/contexts/sample3'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = None - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = '' - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.delete_context(request) - - # Establish that the response is the type that we expect. - assert response is None - - -def test_delete_context_rest_required_fields(request_type=context.DeleteContextRequest): - transport_class = transports.ContextsRestTransport - - request_init = {} - request_init["name"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - including_default_value_fields=False, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).delete_context._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["name"] = 'name_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).delete_context._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "name" in jsonified_request - assert jsonified_request["name"] == 'name_value' - - client = ContextsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = None - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "delete", - 'query_params': pb_request, - } - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - json_return_value = '' - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.delete_context(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_delete_context_rest_unset_required_fields(): - transport = transports.ContextsRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.delete_context._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_delete_context_rest_interceptors(null_interceptor): - transport = transports.ContextsRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.ContextsRestInterceptor(), - ) - client = ContextsClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.ContextsRestInterceptor, "pre_delete_context") as pre: - pre.assert_not_called() - pb_message = context.DeleteContextRequest.pb(context.DeleteContextRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - - request = context.DeleteContextRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - - client.delete_context(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - - -def test_delete_context_rest_bad_request(transport: str = 'rest', request_type=context.DeleteContextRequest): - client = ContextsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/agent/sessions/sample2/contexts/sample3'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.delete_context(request) - - -def test_delete_context_rest_flattened(): - client = ContextsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = None - - # get arguments that satisfy an http rule for this method - sample_request = {'name': 'projects/sample1/agent/sessions/sample2/contexts/sample3'} - - # get truthy value for each flattened field - mock_args = dict( - name='name_value', - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = '' - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.delete_context(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v2beta1/{name=projects/*/agent/sessions/*/contexts/*}" % client.transport._host, args[1]) - - -def test_delete_context_rest_flattened_error(transport: str = 'rest'): - client = ContextsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.delete_context( - context.DeleteContextRequest(), - name='name_value', - ) - - -def test_delete_context_rest_error(): - client = ContextsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - context.DeleteAllContextsRequest, - dict, -]) -def test_delete_all_contexts_rest(request_type): - client = ContextsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1/agent/sessions/sample2'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = None - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = '' - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.delete_all_contexts(request) - - # Establish that the response is the type that we expect. - assert response is None - - -def test_delete_all_contexts_rest_required_fields(request_type=context.DeleteAllContextsRequest): - transport_class = transports.ContextsRestTransport - - request_init = {} - request_init["parent"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - including_default_value_fields=False, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).delete_all_contexts._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["parent"] = 'parent_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).delete_all_contexts._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "parent" in jsonified_request - assert jsonified_request["parent"] == 'parent_value' - - client = ContextsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = None - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "delete", - 'query_params': pb_request, - } - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - json_return_value = '' - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.delete_all_contexts(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_delete_all_contexts_rest_unset_required_fields(): - transport = transports.ContextsRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.delete_all_contexts._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("parent", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_delete_all_contexts_rest_interceptors(null_interceptor): - transport = transports.ContextsRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.ContextsRestInterceptor(), - ) - client = ContextsClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.ContextsRestInterceptor, "pre_delete_all_contexts") as pre: - pre.assert_not_called() - pb_message = context.DeleteAllContextsRequest.pb(context.DeleteAllContextsRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - - request = context.DeleteAllContextsRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - - client.delete_all_contexts(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - - -def test_delete_all_contexts_rest_bad_request(transport: str = 'rest', request_type=context.DeleteAllContextsRequest): - client = ContextsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1/agent/sessions/sample2'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.delete_all_contexts(request) - - -def test_delete_all_contexts_rest_flattened(): - client = ContextsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = None - - # get arguments that satisfy an http rule for this method - sample_request = {'parent': 'projects/sample1/agent/sessions/sample2'} - - # get truthy value for each flattened field - mock_args = dict( - parent='parent_value', - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = '' - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.delete_all_contexts(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v2beta1/{parent=projects/*/agent/sessions/*}/contexts" % client.transport._host, args[1]) - - -def test_delete_all_contexts_rest_flattened_error(transport: str = 'rest'): - client = ContextsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.delete_all_contexts( - context.DeleteAllContextsRequest(), - parent='parent_value', - ) - - -def test_delete_all_contexts_rest_error(): - client = ContextsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -def test_credentials_transport_error(): - # It is an error to provide credentials and a transport instance. - transport = transports.ContextsGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = ContextsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # It is an error to provide a credentials file and a transport instance. - transport = transports.ContextsGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = ContextsClient( - client_options={"credentials_file": "credentials.json"}, - transport=transport, - ) - - # It is an error to provide an api_key and a transport instance. - transport = transports.ContextsGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - options = client_options.ClientOptions() - options.api_key = "api_key" - with pytest.raises(ValueError): - client = ContextsClient( - client_options=options, - transport=transport, - ) - - # It is an error to provide an api_key and a credential. - options = mock.Mock() - options.api_key = "api_key" - with pytest.raises(ValueError): - client = ContextsClient( - client_options=options, - credentials=ga_credentials.AnonymousCredentials() - ) - - # It is an error to provide scopes and a transport instance. - transport = transports.ContextsGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = ContextsClient( - client_options={"scopes": ["1", "2"]}, - transport=transport, - ) - - -def test_transport_instance(): - # A client may be instantiated with a custom transport instance. - transport = transports.ContextsGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - client = ContextsClient(transport=transport) - assert client.transport is transport - -def test_transport_get_channel(): - # A client may be instantiated with a custom transport instance. - transport = transports.ContextsGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - - transport = transports.ContextsGrpcAsyncIOTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - -@pytest.mark.parametrize("transport_class", [ - transports.ContextsGrpcTransport, - transports.ContextsGrpcAsyncIOTransport, - transports.ContextsRestTransport, -]) -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() - -@pytest.mark.parametrize("transport_name", [ - "grpc", - "rest", -]) -def test_transport_kind(transport_name): - transport = ContextsClient.get_transport_class(transport_name)( - credentials=ga_credentials.AnonymousCredentials(), - ) - assert transport.kind == transport_name - -def test_transport_grpc_default(): - # A client should use the gRPC transport by default. - 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(core_exceptions.DuplicateCredentialArgs): - transport = transports.ContextsTransport( - credentials=ga_credentials.AnonymousCredentials(), - credentials_file="credentials.json" - ) - - -def test_contexts_base_transport(): - # Instantiate the base transport. - with mock.patch('google.cloud.dialogflow_v2beta1.services.contexts.transports.ContextsTransport.__init__') as Transport: - Transport.return_value = None - transport = transports.ContextsTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Every method on the transport should just blindly - # raise NotImplementedError. - methods = ( - 'list_contexts', - 'get_context', - 'create_context', - 'update_context', - 'delete_context', - 'delete_all_contexts', - 'get_location', - 'list_locations', - 'get_operation', - 'cancel_operation', - 'list_operations', - ) - for method in methods: - with pytest.raises(NotImplementedError): - getattr(transport, method)(request=object()) - - with pytest.raises(NotImplementedError): - transport.close() - - # Catch all for all remaining methods and properties - remainder = [ - 'kind', - ] - for r in remainder: - with pytest.raises(NotImplementedError): - getattr(transport, r)() - - -def test_contexts_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.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", - ) - - -def test_contexts_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.contexts.transports.ContextsTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.ContextsTransport() - adc.assert_called_once() - - -def test_contexts_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) - 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, - ) - - -@pytest.mark.parametrize( - "transport_class", - [ - transports.ContextsGrpcTransport, - transports.ContextsGrpcAsyncIOTransport, - ], -) -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(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, - transports.ContextsRestTransport, - ], -) -def test_contexts_transport_auth_gdch_credentials(transport_class): - host = 'https://language.com' - api_audience_tests = [None, 'https://language2.com'] - api_audience_expect = [host, 'https://language2.com'] - for t, e in zip(api_audience_tests, api_audience_expect): - with mock.patch.object(google.auth, 'default', autospec=True) as adc: - gdch_mock = mock.MagicMock() - type(gdch_mock).with_gdch_audience = mock.PropertyMock(return_value=gdch_mock) - adc.return_value = (gdch_mock, None) - transport_class(host=host, api_audience=t) - gdch_mock.with_gdch_audience.assert_called_once_with( - e - ) - - -@pytest.mark.parametrize( - "transport_class,grpc_helpers", - [ - (transports.ContextsGrpcTransport, grpc_helpers), - (transports.ContextsGrpcAsyncIOTransport, grpc_helpers_async) - ], -) -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", [transports.ContextsGrpcTransport, transports.ContextsGrpcAsyncIOTransport]) -def test_contexts_grpc_transport_client_cert_source_for_mtls( - transport_class -): - cred = ga_credentials.AnonymousCredentials() - - # Check ssl_channel_credentials is used if provided. - with mock.patch.object(transport_class, "create_channel") as mock_create_channel: - mock_ssl_channel_creds = mock.Mock() - transport_class( - host="squid.clam.whelk", - credentials=cred, - ssl_channel_credentials=mock_ssl_channel_creds - ) - mock_create_channel.assert_called_once_with( - "squid.clam.whelk:443", - credentials=cred, - credentials_file=None, - scopes=None, - ssl_credentials=mock_ssl_channel_creds, - quota_project_id=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - # Check if ssl_channel_credentials is not provided, then client_cert_source_for_mtls - # is used. - with mock.patch.object(transport_class, "create_channel", return_value=mock.Mock()): - with mock.patch("grpc.ssl_channel_credentials") as mock_ssl_cred: - transport_class( - credentials=cred, - client_cert_source_for_mtls=client_cert_source_callback - ) - expected_cert, expected_key = client_cert_source_callback() - mock_ssl_cred.assert_called_once_with( - certificate_chain=expected_cert, - private_key=expected_key - ) - -def test_contexts_http_transport_client_cert_source_for_mtls(): - cred = ga_credentials.AnonymousCredentials() - with mock.patch("google.auth.transport.requests.AuthorizedSession.configure_mtls_channel") as mock_configure_mtls_channel: - transports.ContextsRestTransport ( - credentials=cred, - client_cert_source_for_mtls=client_cert_source_callback - ) - mock_configure_mtls_channel.assert_called_once_with(client_cert_source_callback) - - -@pytest.mark.parametrize("transport_name", [ - "grpc", - "grpc_asyncio", - "rest", -]) -def test_contexts_host_no_port(transport_name): - client = ContextsClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='dialogflow.googleapis.com'), - transport=transport_name, - ) - assert client.transport._host == ( - 'dialogflow.googleapis.com:443' - if transport_name in ['grpc', 'grpc_asyncio'] - else 'https://dialogflow.googleapis.com' - ) - -@pytest.mark.parametrize("transport_name", [ - "grpc", - "grpc_asyncio", - "rest", -]) -def test_contexts_host_with_port(transport_name): - client = ContextsClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='dialogflow.googleapis.com:8000'), - transport=transport_name, - ) - assert client.transport._host == ( - 'dialogflow.googleapis.com:8000' - if transport_name in ['grpc', 'grpc_asyncio'] - else 'https://dialogflow.googleapis.com:8000' - ) - -@pytest.mark.parametrize("transport_name", [ - "rest", -]) -def test_contexts_client_transport_session_collision(transport_name): - creds1 = ga_credentials.AnonymousCredentials() - creds2 = ga_credentials.AnonymousCredentials() - client1 = ContextsClient( - credentials=creds1, - transport=transport_name, - ) - client2 = ContextsClient( - credentials=creds2, - transport=transport_name, - ) - session1 = client1.transport.list_contexts._session - session2 = client2.transport.list_contexts._session - assert session1 != session2 - session1 = client1.transport.get_context._session - session2 = client2.transport.get_context._session - assert session1 != session2 - session1 = client1.transport.create_context._session - session2 = client2.transport.create_context._session - assert session1 != session2 - session1 = client1.transport.update_context._session - session2 = client2.transport.update_context._session - assert session1 != session2 - session1 = client1.transport.delete_context._session - session2 = client2.transport.delete_context._session - assert session1 != session2 - session1 = client1.transport.delete_all_contexts._session - session2 = client2.transport.delete_all_contexts._session - assert session1 != session2 -def test_contexts_grpc_transport_channel(): - channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.ContextsGrpcTransport( - 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_contexts_grpc_asyncio_transport_channel(): - channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.ContextsGrpcAsyncIOTransport( - 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.ContextsGrpcTransport, transports.ContextsGrpcAsyncIOTransport]) -def test_contexts_transport_channel_mtls_with_client_cert_source( - transport_class -): - with mock.patch("grpc.ssl_channel_credentials", autospec=True) as grpc_ssl_channel_cred: - with mock.patch.object(transport_class, "create_channel") as grpc_create_channel: - mock_ssl_cred = mock.Mock() - grpc_ssl_channel_cred.return_value = mock_ssl_cred - - mock_grpc_channel = mock.Mock() - grpc_create_channel.return_value = mock_grpc_channel - - cred = ga_credentials.AnonymousCredentials() - with pytest.warns(DeprecationWarning): - with mock.patch.object(google.auth, 'default') as adc: - adc.return_value = (cred, None) - transport = transport_class( - host="squid.clam.whelk", - api_mtls_endpoint="mtls.squid.clam.whelk", - client_cert_source=client_cert_source_callback, - ) - adc.assert_called_once() - - grpc_ssl_channel_cred.assert_called_once_with( - certificate_chain=b"cert bytes", private_key=b"key bytes" - ) - grpc_create_channel.assert_called_once_with( - "mtls.squid.clam.whelk:443", - credentials=cred, - credentials_file=None, - scopes=None, - ssl_credentials=mock_ssl_cred, - quota_project_id=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - assert transport.grpc_channel == mock_grpc_channel - assert transport._ssl_channel_credentials == mock_ssl_cred - - -# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are -# removed from grpc/grpc_asyncio transport constructor. -@pytest.mark.parametrize("transport_class", [transports.ContextsGrpcTransport, transports.ContextsGrpcAsyncIOTransport]) -def test_contexts_transport_channel_mtls_with_adc( - transport_class -): - mock_ssl_cred = mock.Mock() - with mock.patch.multiple( - "google.auth.transport.grpc.SslCredentials", - __init__=mock.Mock(return_value=None), - ssl_credentials=mock.PropertyMock(return_value=mock_ssl_cred), - ): - with mock.patch.object(transport_class, "create_channel") as grpc_create_channel: - mock_grpc_channel = mock.Mock() - grpc_create_channel.return_value = mock_grpc_channel - mock_cred = mock.Mock() - - with pytest.warns(DeprecationWarning): - transport = transport_class( - host="squid.clam.whelk", - credentials=mock_cred, - api_mtls_endpoint="mtls.squid.clam.whelk", - client_cert_source=None, - ) - - grpc_create_channel.assert_called_once_with( - "mtls.squid.clam.whelk:443", - credentials=mock_cred, - credentials_file=None, - scopes=None, - ssl_credentials=mock_ssl_cred, - quota_project_id=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - assert transport.grpc_channel == mock_grpc_channel - - -def test_context_path(): - project = "squid" - session = "clam" - context = "whelk" - expected = "projects/{project}/agent/sessions/{session}/contexts/{context}".format(project=project, session=session, context=context, ) - actual = ContextsClient.context_path(project, session, context) - assert expected == actual - - -def test_parse_context_path(): - expected = { - "project": "octopus", - "session": "oyster", - "context": "nudibranch", - } - path = ContextsClient.context_path(**expected) - - # Check that the path construction is reversible. - actual = ContextsClient.parse_context_path(path) - assert expected == actual - -def test_common_billing_account_path(): - billing_account = "cuttlefish" - expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) - actual = ContextsClient.common_billing_account_path(billing_account) - assert expected == actual - - -def test_parse_common_billing_account_path(): - expected = { - "billing_account": "mussel", - } - path = ContextsClient.common_billing_account_path(**expected) - - # Check that the path construction is reversible. - actual = ContextsClient.parse_common_billing_account_path(path) - assert expected == actual - -def test_common_folder_path(): - folder = "winkle" - expected = "folders/{folder}".format(folder=folder, ) - actual = ContextsClient.common_folder_path(folder) - assert expected == actual - - -def test_parse_common_folder_path(): - expected = { - "folder": "nautilus", - } - path = ContextsClient.common_folder_path(**expected) - - # Check that the path construction is reversible. - actual = ContextsClient.parse_common_folder_path(path) - assert expected == actual - -def test_common_organization_path(): - organization = "scallop" - expected = "organizations/{organization}".format(organization=organization, ) - actual = ContextsClient.common_organization_path(organization) - assert expected == actual - - -def test_parse_common_organization_path(): - expected = { - "organization": "abalone", - } - path = ContextsClient.common_organization_path(**expected) - - # Check that the path construction is reversible. - actual = ContextsClient.parse_common_organization_path(path) - assert expected == actual - -def test_common_project_path(): - project = "squid" - expected = "projects/{project}".format(project=project, ) - actual = ContextsClient.common_project_path(project) - assert expected == actual - - -def test_parse_common_project_path(): - expected = { - "project": "clam", - } - path = ContextsClient.common_project_path(**expected) - - # Check that the path construction is reversible. - actual = ContextsClient.parse_common_project_path(path) - assert expected == actual - -def test_common_location_path(): - project = "whelk" - location = "octopus" - expected = "projects/{project}/locations/{location}".format(project=project, location=location, ) - actual = ContextsClient.common_location_path(project, location) - assert expected == actual - - -def test_parse_common_location_path(): - expected = { - "project": "oyster", - "location": "nudibranch", - } - path = ContextsClient.common_location_path(**expected) - - # Check that the path construction is reversible. - actual = ContextsClient.parse_common_location_path(path) - assert expected == actual - - -def test_client_with_default_client_info(): - client_info = gapic_v1.client_info.ClientInfo() - - with mock.patch.object(transports.ContextsTransport, '_prep_wrapped_messages') as prep: - client = ContextsClient( - credentials=ga_credentials.AnonymousCredentials(), - client_info=client_info, - ) - prep.assert_called_once_with(client_info) - - with mock.patch.object(transports.ContextsTransport, '_prep_wrapped_messages') as prep: - transport_class = ContextsClient.get_transport_class() - transport = transport_class( - credentials=ga_credentials.AnonymousCredentials(), - client_info=client_info, - ) - prep.assert_called_once_with(client_info) - -@pytest.mark.asyncio -async def test_transport_close_async(): - client = ContextsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - with mock.patch.object(type(getattr(client.transport, "grpc_channel")), "close") as close: - async with client: - close.assert_not_called() - close.assert_called_once() - - -def test_get_location_rest_bad_request(transport: str = 'rest', request_type=locations_pb2.GetLocationRequest): - client = ContextsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - request = request_type() - request = json_format.ParseDict({'name': 'projects/sample1/locations/sample2'}, request) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.get_location(request) - -@pytest.mark.parametrize("request_type", [ - locations_pb2.GetLocationRequest, - dict, -]) -def test_get_location_rest(request_type): - client = ContextsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request_init = {'name': 'projects/sample1/locations/sample2'} - request = request_type(**request_init) - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = locations_pb2.Location() - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.get_location(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, locations_pb2.Location) - -def test_list_locations_rest_bad_request(transport: str = 'rest', request_type=locations_pb2.ListLocationsRequest): - client = ContextsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - request = request_type() - request = json_format.ParseDict({'name': 'projects/sample1'}, request) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.list_locations(request) - -@pytest.mark.parametrize("request_type", [ - locations_pb2.ListLocationsRequest, - dict, -]) -def test_list_locations_rest(request_type): - client = ContextsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request_init = {'name': 'projects/sample1'} - request = request_type(**request_init) - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = locations_pb2.ListLocationsResponse() - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.list_locations(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, locations_pb2.ListLocationsResponse) - -def test_cancel_operation_rest_bad_request(transport: str = 'rest', request_type=operations_pb2.CancelOperationRequest): - client = ContextsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - request = request_type() - request = json_format.ParseDict({'name': 'projects/sample1/operations/sample2'}, request) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.cancel_operation(request) - -@pytest.mark.parametrize("request_type", [ - operations_pb2.CancelOperationRequest, - dict, -]) -def test_cancel_operation_rest(request_type): - client = ContextsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request_init = {'name': 'projects/sample1/operations/sample2'} - request = request_type(**request_init) - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = None - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = '{}' - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.cancel_operation(request) - - # Establish that the response is the type that we expect. - assert response is None - -def test_get_operation_rest_bad_request(transport: str = 'rest', request_type=operations_pb2.GetOperationRequest): - client = ContextsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - request = request_type() - request = json_format.ParseDict({'name': 'projects/sample1/operations/sample2'}, request) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.get_operation(request) - -@pytest.mark.parametrize("request_type", [ - operations_pb2.GetOperationRequest, - dict, -]) -def test_get_operation_rest(request_type): - client = ContextsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request_init = {'name': 'projects/sample1/operations/sample2'} - request = request_type(**request_init) - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation() - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.get_operation(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, operations_pb2.Operation) - -def test_list_operations_rest_bad_request(transport: str = 'rest', request_type=operations_pb2.ListOperationsRequest): - client = ContextsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - request = request_type() - request = json_format.ParseDict({'name': 'projects/sample1'}, request) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.list_operations(request) - -@pytest.mark.parametrize("request_type", [ - operations_pb2.ListOperationsRequest, - dict, -]) -def test_list_operations_rest(request_type): - client = ContextsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request_init = {'name': 'projects/sample1'} - request = request_type(**request_init) - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = operations_pb2.ListOperationsResponse() - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.list_operations(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, operations_pb2.ListOperationsResponse) - - -def test_cancel_operation(transport: str = "grpc"): - client = ContextsClient( - 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 = operations_pb2.CancelOperationRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = None - response = client.cancel_operation(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 response is the type that we expect. - assert response is None -@pytest.mark.asyncio -async def test_cancel_operation_async(transport: str = "grpc"): - client = ContextsAsyncClient( - 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 = operations_pb2.CancelOperationRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - None - ) - response = await client.cancel_operation(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 response is the type that we expect. - assert response is None - -def test_cancel_operation_field_headers(): - 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 = operations_pb2.CancelOperationRequest() - request.name = "locations" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call: - call.return_value = None - - client.cancel_operation(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=locations",) in kw["metadata"] -@pytest.mark.asyncio -async def test_cancel_operation_field_headers_async(): - 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 = operations_pb2.CancelOperationRequest() - request.name = "locations" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - None - ) - await client.cancel_operation(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=locations",) in kw["metadata"] - -def test_cancel_operation_from_dict(): - 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.cancel_operation), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = None - - response = client.cancel_operation( - request={ - "name": "locations", - } - ) - call.assert_called() -@pytest.mark.asyncio -async def test_cancel_operation_from_dict_async(): - 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.cancel_operation), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - None - ) - response = await client.cancel_operation( - request={ - "name": "locations", - } - ) - call.assert_called() - - -def test_get_operation(transport: str = "grpc"): - client = ContextsClient( - 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 = operations_pb2.GetOperationRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_operation), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation() - response = client.get_operation(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 response is the type that we expect. - assert isinstance(response, operations_pb2.Operation) -@pytest.mark.asyncio -async def test_get_operation_async(transport: str = "grpc"): - client = ContextsAsyncClient( - 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 = operations_pb2.GetOperationRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_operation), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation() - ) - response = await client.get_operation(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 response is the type that we expect. - assert isinstance(response, operations_pb2.Operation) - -def test_get_operation_field_headers(): - 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 = operations_pb2.GetOperationRequest() - request.name = "locations" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_operation), "__call__") as call: - call.return_value = operations_pb2.Operation() - - client.get_operation(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=locations",) in kw["metadata"] -@pytest.mark.asyncio -async def test_get_operation_field_headers_async(): - 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 = operations_pb2.GetOperationRequest() - request.name = "locations" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_operation), "__call__") as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation() - ) - await client.get_operation(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=locations",) in kw["metadata"] - -def test_get_operation_from_dict(): - 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_operation), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation() - - response = client.get_operation( - request={ - "name": "locations", - } - ) - call.assert_called() -@pytest.mark.asyncio -async def test_get_operation_from_dict_async(): - 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_operation), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation() - ) - response = await client.get_operation( - request={ - "name": "locations", - } - ) - call.assert_called() - - -def test_list_operations(transport: str = "grpc"): - client = ContextsClient( - 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 = operations_pb2.ListOperationsRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_operations), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.ListOperationsResponse() - response = client.list_operations(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 response is the type that we expect. - assert isinstance(response, operations_pb2.ListOperationsResponse) -@pytest.mark.asyncio -async def test_list_operations_async(transport: str = "grpc"): - client = ContextsAsyncClient( - 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 = operations_pb2.ListOperationsRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_operations), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.ListOperationsResponse() - ) - response = await client.list_operations(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 response is the type that we expect. - assert isinstance(response, operations_pb2.ListOperationsResponse) - -def test_list_operations_field_headers(): - 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 = operations_pb2.ListOperationsRequest() - request.name = "locations" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_operations), "__call__") as call: - call.return_value = operations_pb2.ListOperationsResponse() - - client.list_operations(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=locations",) in kw["metadata"] -@pytest.mark.asyncio -async def test_list_operations_field_headers_async(): - 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 = operations_pb2.ListOperationsRequest() - request.name = "locations" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_operations), "__call__") as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.ListOperationsResponse() - ) - await client.list_operations(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=locations",) in kw["metadata"] - -def test_list_operations_from_dict(): - 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_operations), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.ListOperationsResponse() - - response = client.list_operations( - request={ - "name": "locations", - } - ) - call.assert_called() -@pytest.mark.asyncio -async def test_list_operations_from_dict_async(): - 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_operations), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.ListOperationsResponse() - ) - response = await client.list_operations( - request={ - "name": "locations", - } - ) - call.assert_called() - - -def test_list_locations(transport: str = "grpc"): - client = ContextsClient( - 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 = locations_pb2.ListLocationsRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_locations), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = locations_pb2.ListLocationsResponse() - response = client.list_locations(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 response is the type that we expect. - assert isinstance(response, locations_pb2.ListLocationsResponse) -@pytest.mark.asyncio -async def test_list_locations_async(transport: str = "grpc"): - client = ContextsAsyncClient( - 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 = locations_pb2.ListLocationsRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_locations), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - locations_pb2.ListLocationsResponse() - ) - response = await client.list_locations(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 response is the type that we expect. - assert isinstance(response, locations_pb2.ListLocationsResponse) - -def test_list_locations_field_headers(): - 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 = locations_pb2.ListLocationsRequest() - request.name = "locations" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_locations), "__call__") as call: - call.return_value = locations_pb2.ListLocationsResponse() - - client.list_locations(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=locations",) in kw["metadata"] -@pytest.mark.asyncio -async def test_list_locations_field_headers_async(): - 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 = locations_pb2.ListLocationsRequest() - request.name = "locations" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_locations), "__call__") as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - locations_pb2.ListLocationsResponse() - ) - await client.list_locations(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=locations",) in kw["metadata"] - -def test_list_locations_from_dict(): - 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_locations), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = locations_pb2.ListLocationsResponse() - - response = client.list_locations( - request={ - "name": "locations", - } - ) - call.assert_called() -@pytest.mark.asyncio -async def test_list_locations_from_dict_async(): - 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_locations), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - locations_pb2.ListLocationsResponse() - ) - response = await client.list_locations( - request={ - "name": "locations", - } - ) - call.assert_called() - - -def test_get_location(transport: str = "grpc"): - client = ContextsClient( - 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 = locations_pb2.GetLocationRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_location), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = locations_pb2.Location() - response = client.get_location(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 response is the type that we expect. - assert isinstance(response, locations_pb2.Location) -@pytest.mark.asyncio -async def test_get_location_async(transport: str = "grpc_asyncio"): - client = ContextsAsyncClient( - 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 = locations_pb2.GetLocationRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_location), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - locations_pb2.Location() - ) - response = await client.get_location(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 response is the type that we expect. - assert isinstance(response, locations_pb2.Location) - -def test_get_location_field_headers(): - 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 = locations_pb2.GetLocationRequest() - request.name = "locations/abc" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_location), "__call__") as call: - call.return_value = locations_pb2.Location() - - client.get_location(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=locations/abc",) in kw["metadata"] -@pytest.mark.asyncio -async def test_get_location_field_headers_async(): - 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 = locations_pb2.GetLocationRequest() - request.name = "locations/abc" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_location), "__call__") as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - locations_pb2.Location() - ) - await client.get_location(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=locations/abc",) in kw["metadata"] - -def test_get_location_from_dict(): - 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_locations), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = locations_pb2.Location() - - response = client.get_location( - request={ - "name": "locations/abc", - } - ) - call.assert_called() -@pytest.mark.asyncio -async def test_get_location_from_dict_async(): - 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_locations), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - locations_pb2.Location() - ) - response = await client.get_location( - request={ - "name": "locations", - } - ) - call.assert_called() - - -def test_transport_close(): - transports = { - "rest": "_session", - "grpc": "_grpc_channel", - } - - for transport, close_name in transports.items(): - client = ContextsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport - ) - with mock.patch.object(type(getattr(client.transport, close_name)), "close") as close: - with client: - close.assert_not_called() - close.assert_called_once() - -def test_client_ctx(): - transports = [ - 'rest', - 'grpc', - ] - for transport in transports: - client = ContextsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport - ) - # Test client calls underlying transport. - with mock.patch.object(type(client.transport), "close") as close: - close.assert_not_called() - with client: - pass - close.assert_called() - -@pytest.mark.parametrize("client_class,transport_class", [ - (ContextsClient, transports.ContextsGrpcTransport), - (ContextsAsyncClient, transports.ContextsGrpcAsyncIOTransport), -]) -def test_api_key_credentials(client_class, transport_class): - with mock.patch.object( - google.auth._default, "get_api_key_credentials", create=True - ) as get_api_key_credentials: - mock_cred = mock.Mock() - get_api_key_credentials.return_value = mock_cred - options = client_options.ClientOptions() - options.api_key = "api_key" - 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=mock_cred, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) diff --git a/owl-bot-staging/v2beta1/tests/unit/gapic/dialogflow_v2beta1/test_conversation_profiles.py b/owl-bot-staging/v2beta1/tests/unit/gapic/dialogflow_v2beta1/test_conversation_profiles.py deleted file mode 100644 index f9855b63f..000000000 --- a/owl-bot-staging/v2beta1/tests/unit/gapic/dialogflow_v2beta1/test_conversation_profiles.py +++ /dev/null @@ -1,5910 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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 -# try/except added for compatibility with python < 3.8 -try: - from unittest import mock - from unittest.mock import AsyncMock # pragma: NO COVER -except ImportError: # pragma: NO COVER - import mock - -import grpc -from grpc.experimental import aio -from collections.abc import Iterable -from google.protobuf import json_format -import json -import math -import pytest -from proto.marshal.rules.dates import DurationRule, TimestampRule -from proto.marshal.rules import wrappers -from requests import Response -from requests import Request, PreparedRequest -from requests.sessions import Session -from google.protobuf import json_format - -from google.api_core import client_options -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 -from google.api_core import operation_async # type: ignore -from google.api_core import operations_v1 -from google.api_core import path_template -from google.auth import credentials as ga_credentials -from google.auth.exceptions import MutualTLSChannelError -from google.cloud.dialogflow_v2beta1.services.conversation_profiles import ConversationProfilesAsyncClient -from google.cloud.dialogflow_v2beta1.services.conversation_profiles import ConversationProfilesClient -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.types import audio_config -from google.cloud.dialogflow_v2beta1.types import conversation_profile -from google.cloud.dialogflow_v2beta1.types import conversation_profile as gcd_conversation_profile -from google.cloud.dialogflow_v2beta1.types import participant -from google.cloud.location import locations_pb2 -from google.longrunning import operations_pb2 -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 - - -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 ConversationProfilesClient._get_default_mtls_endpoint(None) is None - assert ConversationProfilesClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint - assert ConversationProfilesClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint - assert ConversationProfilesClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint - assert ConversationProfilesClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint - assert ConversationProfilesClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi - - -@pytest.mark.parametrize("client_class,transport_name", [ - (ConversationProfilesClient, "grpc"), - (ConversationProfilesAsyncClient, "grpc_asyncio"), - (ConversationProfilesClient, "rest"), -]) -def test_conversation_profiles_client_from_service_account_info(client_class, transport_name): - 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, transport=transport_name) - assert client.transport._credentials == creds - assert isinstance(client, client_class) - - assert client.transport._host == ( - 'dialogflow.googleapis.com:443' - if transport_name in ['grpc', 'grpc_asyncio'] - else - 'https://dialogflow.googleapis.com' - ) - - -@pytest.mark.parametrize("transport_class,transport_name", [ - (transports.ConversationProfilesGrpcTransport, "grpc"), - (transports.ConversationProfilesGrpcAsyncIOTransport, "grpc_asyncio"), - (transports.ConversationProfilesRestTransport, "rest"), -]) -def test_conversation_profiles_client_service_account_always_use_jwt(transport_class, transport_name): - with mock.patch.object(service_account.Credentials, 'with_always_use_jwt_access', create=True) as use_jwt: - creds = service_account.Credentials(None, None, None) - transport = transport_class(credentials=creds, always_use_jwt_access=True) - use_jwt.assert_called_once_with(True) - - with mock.patch.object(service_account.Credentials, 'with_always_use_jwt_access', create=True) as use_jwt: - creds = service_account.Credentials(None, None, None) - transport = transport_class(credentials=creds, always_use_jwt_access=False) - use_jwt.assert_not_called() - - -@pytest.mark.parametrize("client_class,transport_name", [ - (ConversationProfilesClient, "grpc"), - (ConversationProfilesAsyncClient, "grpc_asyncio"), - (ConversationProfilesClient, "rest"), -]) -def test_conversation_profiles_client_from_service_account_file(client_class, transport_name): - 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", transport=transport_name) - assert client.transport._credentials == creds - assert isinstance(client, client_class) - - client = client_class.from_service_account_json("dummy/file/path.json", transport=transport_name) - assert client.transport._credentials == creds - assert isinstance(client, client_class) - - assert client.transport._host == ( - 'dialogflow.googleapis.com:443' - if transport_name in ['grpc', 'grpc_asyncio'] - else - 'https://dialogflow.googleapis.com' - ) - - -def test_conversation_profiles_client_get_transport_class(): - transport = ConversationProfilesClient.get_transport_class() - available_transports = [ - transports.ConversationProfilesGrpcTransport, - transports.ConversationProfilesRestTransport, - ] - assert transport in available_transports - - transport = ConversationProfilesClient.get_transport_class("grpc") - assert transport == transports.ConversationProfilesGrpcTransport - - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (ConversationProfilesClient, transports.ConversationProfilesGrpcTransport, "grpc"), - (ConversationProfilesAsyncClient, transports.ConversationProfilesGrpcAsyncIOTransport, "grpc_asyncio"), - (ConversationProfilesClient, transports.ConversationProfilesRestTransport, "rest"), -]) -@mock.patch.object(ConversationProfilesClient, "DEFAULT_ENDPOINT", modify_default_endpoint(ConversationProfilesClient)) -@mock.patch.object(ConversationProfilesAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(ConversationProfilesAsyncClient)) -def test_conversation_profiles_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(ConversationProfilesClient, '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(ConversationProfilesClient, 'get_transport_class') as gtc: - client = client_class(transport=transport_name) - gtc.assert_called() - - # Check the case api_endpoint is provided. - options = client_options.ClientOptions(api_endpoint="squid.clam.whelk") - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(transport=transport_name, client_options=options) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host="squid.clam.whelk", - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is - # "never". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is - # "always". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_MTLS_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # 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(transport=transport_name) - - # 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(transport=transport_name) - - # 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, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id="octopus", - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - # Check the case api_endpoint is provided - options = client_options.ClientOptions(api_audience="https://language.googleapis.com") - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience="https://language.googleapis.com" - ) - -@pytest.mark.parametrize("client_class,transport_class,transport_name,use_client_cert_env", [ - (ConversationProfilesClient, transports.ConversationProfilesGrpcTransport, "grpc", "true"), - (ConversationProfilesAsyncClient, transports.ConversationProfilesGrpcAsyncIOTransport, "grpc_asyncio", "true"), - (ConversationProfilesClient, transports.ConversationProfilesGrpcTransport, "grpc", "false"), - (ConversationProfilesAsyncClient, transports.ConversationProfilesGrpcAsyncIOTransport, "grpc_asyncio", "false"), - (ConversationProfilesClient, transports.ConversationProfilesRestTransport, "rest", "true"), - (ConversationProfilesClient, transports.ConversationProfilesRestTransport, "rest", "false"), -]) -@mock.patch.object(ConversationProfilesClient, "DEFAULT_ENDPOINT", modify_default_endpoint(ConversationProfilesClient)) -@mock.patch.object(ConversationProfilesAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(ConversationProfilesAsyncClient)) -@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) -def test_conversation_profiles_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, transport=transport_name) - - if use_client_cert_env == "false": - expected_client_cert_source = None - expected_host = client.DEFAULT_ENDPOINT - else: - expected_client_cert_source = client_cert_source_callback - expected_host = client.DEFAULT_MTLS_ENDPOINT - - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=expected_host, - scopes=None, - client_cert_source_for_mtls=expected_client_cert_source, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case ADC client cert is provided. Whether client cert is used depends on - # GOOGLE_API_USE_CLIENT_CERTIFICATE value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): - with mock.patch.object(transport_class, '__init__') as patched: - with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): - with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=client_cert_source_callback): - if use_client_cert_env == "false": - expected_host = client.DEFAULT_ENDPOINT - expected_client_cert_source = None - else: - expected_host = client.DEFAULT_MTLS_ENDPOINT - expected_client_cert_source = client_cert_source_callback - - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=expected_host, - scopes=None, - client_cert_source_for_mtls=expected_client_cert_source, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case client_cert_source and ADC client cert are not provided. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): - with mock.patch.object(transport_class, '__init__') as patched: - with mock.patch("google.auth.transport.mtls.has_default_client_cert_source", return_value=False): - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - -@pytest.mark.parametrize("client_class", [ - ConversationProfilesClient, ConversationProfilesAsyncClient -]) -@mock.patch.object(ConversationProfilesClient, "DEFAULT_ENDPOINT", modify_default_endpoint(ConversationProfilesClient)) -@mock.patch.object(ConversationProfilesAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(ConversationProfilesAsyncClient)) -def test_conversation_profiles_client_get_mtls_endpoint_and_cert_source(client_class): - mock_client_cert_source = mock.Mock() - - # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "true". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - mock_api_endpoint = "foo" - options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) - assert api_endpoint == mock_api_endpoint - assert cert_source == mock_client_cert_source - - # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "false". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): - mock_client_cert_source = mock.Mock() - mock_api_endpoint = "foo" - options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) - assert api_endpoint == mock_api_endpoint - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "never". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_ENDPOINT - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "always". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert doesn't exist. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=False): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_ENDPOINT - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert exists. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - 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=mock_client_cert_source): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT - assert cert_source == mock_client_cert_source - - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (ConversationProfilesClient, transports.ConversationProfilesGrpcTransport, "grpc"), - (ConversationProfilesAsyncClient, transports.ConversationProfilesGrpcAsyncIOTransport, "grpc_asyncio"), - (ConversationProfilesClient, transports.ConversationProfilesRestTransport, "rest"), -]) -def test_conversation_profiles_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, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=["1", "2"], - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - -@pytest.mark.parametrize("client_class,transport_class,transport_name,grpc_helpers", [ - (ConversationProfilesClient, transports.ConversationProfilesGrpcTransport, "grpc", grpc_helpers), - (ConversationProfilesAsyncClient, transports.ConversationProfilesGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), - (ConversationProfilesClient, transports.ConversationProfilesRestTransport, "rest", None), -]) -def test_conversation_profiles_client_client_options_credentials_file(client_class, transport_class, transport_name, grpc_helpers): - # 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, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file="credentials.json", - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - -def test_conversation_profiles_client_client_options_from_dict(): - with mock.patch('google.cloud.dialogflow_v2beta1.services.conversation_profiles.transports.ConversationProfilesGrpcTransport.__init__') as grpc_transport: - grpc_transport.return_value = None - client = ConversationProfilesClient( - client_options={'api_endpoint': 'squid.clam.whelk'} - ) - grpc_transport.assert_called_once_with( - credentials=None, - credentials_file=None, - host="squid.clam.whelk", - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - -@pytest.mark.parametrize("client_class,transport_class,transport_name,grpc_helpers", [ - (ConversationProfilesClient, transports.ConversationProfilesGrpcTransport, "grpc", grpc_helpers), - (ConversationProfilesAsyncClient, transports.ConversationProfilesGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), -]) -def test_conversation_profiles_client_create_channel_credentials_file(client_class, transport_class, transport_name, grpc_helpers): - # 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, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file="credentials.json", - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # test that the credentials from file are saved and used as the credentials. - with mock.patch.object( - google.auth, "load_credentials_from_file", autospec=True - ) as load_creds, mock.patch.object( - google.auth, "default", autospec=True - ) as adc, mock.patch.object( - grpc_helpers, "create_channel" - ) as create_channel: - creds = ga_credentials.AnonymousCredentials() - file_creds = ga_credentials.AnonymousCredentials() - load_creds.return_value = (file_creds, None) - adc.return_value = (creds, None) - client = client_class(client_options=options, transport=transport_name) - create_channel.assert_called_with( - "dialogflow.googleapis.com:443", - credentials=file_creds, - credentials_file=None, - quota_project_id=None, - default_scopes=( - 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/dialogflow', -), - scopes=None, - default_host="dialogflow.googleapis.com", - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - -@pytest.mark.parametrize("request_type", [ - conversation_profile.ListConversationProfilesRequest, - dict, -]) -def test_list_conversation_profiles(request_type, transport: str = 'grpc'): - client = ConversationProfilesClient( - 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_conversation_profiles), - '__call__') as call: - # Designate an appropriate return value for the call. - 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' - - -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=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_conversation_profiles), - '__call__') as call: - client.list_conversation_profiles() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == conversation_profile.ListConversationProfilesRequest() - -@pytest.mark.asyncio -async def test_list_conversation_profiles_async(transport: str = 'grpc_asyncio', request_type=conversation_profile.ListConversationProfilesRequest): - client = ConversationProfilesAsyncClient( - 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_conversation_profiles), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(conversation_profile.ListConversationProfilesResponse( - 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' - - -@pytest.mark.asyncio -async def test_list_conversation_profiles_async_from_dict(): - await test_list_conversation_profiles_async(request_type=dict) - - -def test_list_conversation_profiles_field_headers(): - 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. - with mock.patch.object( - 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. - 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_conversation_profiles_field_headers_async(): - client = ConversationProfilesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value 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. - with mock.patch.object( - type(client.transport.list_conversation_profiles), - '__call__') as call: - 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. - 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_conversation_profiles_flattened(): - client = ConversationProfilesClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_conversation_profiles), - '__call__') 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', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - arg = args[0].parent - mock_val = 'parent_value' - assert arg == mock_val - - -def test_list_conversation_profiles_flattened_error(): - client = ConversationProfilesClient( - 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_conversation_profiles( - conversation_profile.ListConversationProfilesRequest(), - parent='parent_value', - ) - -@pytest.mark.asyncio -async def test_list_conversation_profiles_flattened_async(): - client = ConversationProfilesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_conversation_profiles), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = conversation_profile.ListConversationProfilesResponse() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(conversation_profile.ListConversationProfilesResponse()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.list_conversation_profiles( - 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] - arg = args[0].parent - mock_val = 'parent_value' - assert arg == mock_val - -@pytest.mark.asyncio -async def test_list_conversation_profiles_flattened_error_async(): - client = ConversationProfilesAsyncClient( - 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_conversation_profiles( - conversation_profile.ListConversationProfilesRequest(), - parent='parent_value', - ) - - -def test_list_conversation_profiles_pager(transport_name: str = "grpc"): - client = ConversationProfilesClient( - credentials=ga_credentials.AnonymousCredentials, - transport=transport_name, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_conversation_profiles), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - conversation_profile.ListConversationProfilesResponse( - conversation_profiles=[ - conversation_profile.ConversationProfile(), - conversation_profile.ConversationProfile(), - conversation_profile.ConversationProfile(), - ], - next_page_token='abc', - ), - conversation_profile.ListConversationProfilesResponse( - conversation_profiles=[], - next_page_token='def', - ), - conversation_profile.ListConversationProfilesResponse( - conversation_profiles=[ - conversation_profile.ConversationProfile(), - ], - next_page_token='ghi', - ), - conversation_profile.ListConversationProfilesResponse( - conversation_profiles=[ - conversation_profile.ConversationProfile(), - conversation_profile.ConversationProfile(), - ], - ), - RuntimeError, - ) - - metadata = () - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ('parent', ''), - )), - ) - pager = client.list_conversation_profiles(request={}) - - assert pager._metadata == metadata - - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, conversation_profile.ConversationProfile) - for i in results) -def test_list_conversation_profiles_pages(transport_name: str = "grpc"): - client = ConversationProfilesClient( - credentials=ga_credentials.AnonymousCredentials, - transport=transport_name, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_conversation_profiles), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - conversation_profile.ListConversationProfilesResponse( - conversation_profiles=[ - conversation_profile.ConversationProfile(), - conversation_profile.ConversationProfile(), - conversation_profile.ConversationProfile(), - ], - next_page_token='abc', - ), - conversation_profile.ListConversationProfilesResponse( - conversation_profiles=[], - next_page_token='def', - ), - conversation_profile.ListConversationProfilesResponse( - conversation_profiles=[ - conversation_profile.ConversationProfile(), - ], - next_page_token='ghi', - ), - conversation_profile.ListConversationProfilesResponse( - conversation_profiles=[ - conversation_profile.ConversationProfile(), - conversation_profile.ConversationProfile(), - ], - ), - RuntimeError, - ) - pages = list(client.list_conversation_profiles(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_conversation_profiles_async_pager(): - client = ConversationProfilesAsyncClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_conversation_profiles), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - conversation_profile.ListConversationProfilesResponse( - conversation_profiles=[ - conversation_profile.ConversationProfile(), - conversation_profile.ConversationProfile(), - conversation_profile.ConversationProfile(), - ], - next_page_token='abc', - ), - conversation_profile.ListConversationProfilesResponse( - conversation_profiles=[], - next_page_token='def', - ), - conversation_profile.ListConversationProfilesResponse( - conversation_profiles=[ - conversation_profile.ConversationProfile(), - ], - next_page_token='ghi', - ), - conversation_profile.ListConversationProfilesResponse( - conversation_profiles=[ - conversation_profile.ConversationProfile(), - conversation_profile.ConversationProfile(), - ], - ), - RuntimeError, - ) - async_pager = await client.list_conversation_profiles(request={},) - assert async_pager.next_page_token == 'abc' - responses = [] - async for response in async_pager: # pragma: no branch - responses.append(response) - - assert len(responses) == 6 - assert all(isinstance(i, conversation_profile.ConversationProfile) - for i in responses) - - -@pytest.mark.asyncio -async def test_list_conversation_profiles_async_pages(): - client = ConversationProfilesAsyncClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_conversation_profiles), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - conversation_profile.ListConversationProfilesResponse( - conversation_profiles=[ - conversation_profile.ConversationProfile(), - conversation_profile.ConversationProfile(), - conversation_profile.ConversationProfile(), - ], - next_page_token='abc', - ), - conversation_profile.ListConversationProfilesResponse( - conversation_profiles=[], - next_page_token='def', - ), - conversation_profile.ListConversationProfilesResponse( - conversation_profiles=[ - conversation_profile.ConversationProfile(), - ], - next_page_token='ghi', - ), - conversation_profile.ListConversationProfilesResponse( - conversation_profiles=[ - conversation_profile.ConversationProfile(), - conversation_profile.ConversationProfile(), - ], - ), - RuntimeError, - ) - pages = [] - async for page_ in (await client.list_conversation_profiles(request={})).pages: # pragma: no branch - pages.append(page_) - for page_, token in zip(pages, ['abc','def','ghi', '']): - assert page_.raw_page.next_page_token == token - -@pytest.mark.parametrize("request_type", [ - conversation_profile.GetConversationProfileRequest, - dict, -]) -def test_get_conversation_profile(request_type, transport: str = 'grpc'): - client = ConversationProfilesClient( - 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_conversation_profile), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = conversation_profile.ConversationProfile( - name='name_value', - display_name='display_name_value', - language_code='language_code_value', - time_zone='time_zone_value', - security_settings='security_settings_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' - assert response.time_zone == 'time_zone_value' - assert response.security_settings == 'security_settings_value' - - -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=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_conversation_profile), - '__call__') as call: - client.get_conversation_profile() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == conversation_profile.GetConversationProfileRequest() - -@pytest.mark.asyncio -async def test_get_conversation_profile_async(transport: str = 'grpc_asyncio', request_type=conversation_profile.GetConversationProfileRequest): - client = ConversationProfilesAsyncClient( - 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_conversation_profile), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(conversation_profile.ConversationProfile( - name='name_value', - display_name='display_name_value', - language_code='language_code_value', - time_zone='time_zone_value', - security_settings='security_settings_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' - assert response.time_zone == 'time_zone_value' - assert response.security_settings == 'security_settings_value' - - -@pytest.mark.asyncio -async def test_get_conversation_profile_async_from_dict(): - await test_get_conversation_profile_async(request_type=dict) - - -def test_get_conversation_profile_field_headers(): - 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. - with mock.patch.object( - 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. - 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_conversation_profile_field_headers_async(): - client = ConversationProfilesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value 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. - with mock.patch.object( - type(client.transport.get_conversation_profile), - '__call__') as call: - 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. - 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_conversation_profile_flattened(): - client = ConversationProfilesClient( - 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_profile), - '__call__') 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', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - arg = args[0].name - mock_val = 'name_value' - assert arg == mock_val - - -def test_get_conversation_profile_flattened_error(): - client = ConversationProfilesClient( - 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_conversation_profile( - conversation_profile.GetConversationProfileRequest(), - name='name_value', - ) - -@pytest.mark.asyncio -async def test_get_conversation_profile_flattened_async(): - client = ConversationProfilesAsyncClient( - 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_profile), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = conversation_profile.ConversationProfile() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(conversation_profile.ConversationProfile()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.get_conversation_profile( - 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] - arg = args[0].name - mock_val = 'name_value' - assert arg == mock_val - -@pytest.mark.asyncio -async def test_get_conversation_profile_flattened_error_async(): - client = ConversationProfilesAsyncClient( - 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_conversation_profile( - conversation_profile.GetConversationProfileRequest(), - name='name_value', - ) - - -@pytest.mark.parametrize("request_type", [ - gcd_conversation_profile.CreateConversationProfileRequest, - dict, -]) -def test_create_conversation_profile(request_type, transport: str = 'grpc'): - client = ConversationProfilesClient( - 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_conversation_profile), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcd_conversation_profile.ConversationProfile( - name='name_value', - display_name='display_name_value', - language_code='language_code_value', - time_zone='time_zone_value', - security_settings='security_settings_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' - assert response.time_zone == 'time_zone_value' - assert response.security_settings == 'security_settings_value' - - -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=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_conversation_profile), - '__call__') as call: - client.create_conversation_profile() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == gcd_conversation_profile.CreateConversationProfileRequest() - -@pytest.mark.asyncio -async def test_create_conversation_profile_async(transport: str = 'grpc_asyncio', request_type=gcd_conversation_profile.CreateConversationProfileRequest): - client = ConversationProfilesAsyncClient( - 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_conversation_profile), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gcd_conversation_profile.ConversationProfile( - name='name_value', - display_name='display_name_value', - language_code='language_code_value', - time_zone='time_zone_value', - security_settings='security_settings_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' - assert response.time_zone == 'time_zone_value' - assert response.security_settings == 'security_settings_value' - - -@pytest.mark.asyncio -async def test_create_conversation_profile_async_from_dict(): - await test_create_conversation_profile_async(request_type=dict) - - -def test_create_conversation_profile_field_headers(): - 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. - with mock.patch.object( - 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. - 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_conversation_profile_field_headers_async(): - client = ConversationProfilesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value 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. - with mock.patch.object( - type(client.transport.create_conversation_profile), - '__call__') as call: - 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. - 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_conversation_profile_flattened(): - client = ConversationProfilesClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_conversation_profile), - '__call__') 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( - parent='parent_value', - conversation_profile=gcd_conversation_profile.ConversationProfile(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] - arg = args[0].parent - mock_val = 'parent_value' - assert arg == mock_val - arg = args[0].conversation_profile - mock_val = gcd_conversation_profile.ConversationProfile(name='name_value') - assert arg == mock_val - - -def test_create_conversation_profile_flattened_error(): - client = ConversationProfilesClient( - 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_conversation_profile( - gcd_conversation_profile.CreateConversationProfileRequest(), - parent='parent_value', - conversation_profile=gcd_conversation_profile.ConversationProfile(name='name_value'), - ) - -@pytest.mark.asyncio -async def test_create_conversation_profile_flattened_async(): - client = ConversationProfilesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_conversation_profile), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcd_conversation_profile.ConversationProfile() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcd_conversation_profile.ConversationProfile()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.create_conversation_profile( - parent='parent_value', - conversation_profile=gcd_conversation_profile.ConversationProfile(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] - arg = args[0].parent - mock_val = 'parent_value' - assert arg == mock_val - arg = args[0].conversation_profile - mock_val = gcd_conversation_profile.ConversationProfile(name='name_value') - assert arg == mock_val - -@pytest.mark.asyncio -async def test_create_conversation_profile_flattened_error_async(): - client = ConversationProfilesAsyncClient( - 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_conversation_profile( - gcd_conversation_profile.CreateConversationProfileRequest(), - parent='parent_value', - conversation_profile=gcd_conversation_profile.ConversationProfile(name='name_value'), - ) - - -@pytest.mark.parametrize("request_type", [ - gcd_conversation_profile.UpdateConversationProfileRequest, - dict, -]) -def test_update_conversation_profile(request_type, transport: str = 'grpc'): - client = ConversationProfilesClient( - 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_conversation_profile), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcd_conversation_profile.ConversationProfile( - name='name_value', - display_name='display_name_value', - language_code='language_code_value', - time_zone='time_zone_value', - security_settings='security_settings_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' - assert response.time_zone == 'time_zone_value' - assert response.security_settings == 'security_settings_value' - - -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=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_conversation_profile), - '__call__') as call: - client.update_conversation_profile() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == gcd_conversation_profile.UpdateConversationProfileRequest() - -@pytest.mark.asyncio -async def test_update_conversation_profile_async(transport: str = 'grpc_asyncio', request_type=gcd_conversation_profile.UpdateConversationProfileRequest): - client = ConversationProfilesAsyncClient( - 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_conversation_profile), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gcd_conversation_profile.ConversationProfile( - name='name_value', - display_name='display_name_value', - language_code='language_code_value', - time_zone='time_zone_value', - security_settings='security_settings_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' - assert response.time_zone == 'time_zone_value' - assert response.security_settings == 'security_settings_value' - - -@pytest.mark.asyncio -async def test_update_conversation_profile_async_from_dict(): - await test_update_conversation_profile_async(request_type=dict) - - -def test_update_conversation_profile_field_headers(): - 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 = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - 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. - 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', - 'conversation_profile.name=name_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_update_conversation_profile_field_headers_async(): - client = ConversationProfilesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value 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 = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_conversation_profile), - '__call__') as call: - 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. - 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', - 'conversation_profile.name=name_value', - ) in kw['metadata'] - - -def test_update_conversation_profile_flattened(): - client = ConversationProfilesClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_conversation_profile), - '__call__') 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_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] - arg = args[0].conversation_profile - mock_val = gcd_conversation_profile.ConversationProfile(name='name_value') - assert arg == mock_val - arg = args[0].update_mask - mock_val = field_mask_pb2.FieldMask(paths=['paths_value']) - assert arg == mock_val - - -def test_update_conversation_profile_flattened_error(): - client = ConversationProfilesClient( - 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_conversation_profile( - gcd_conversation_profile.UpdateConversationProfileRequest(), - conversation_profile=gcd_conversation_profile.ConversationProfile(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - -@pytest.mark.asyncio -async def test_update_conversation_profile_flattened_async(): - client = ConversationProfilesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_conversation_profile), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcd_conversation_profile.ConversationProfile() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcd_conversation_profile.ConversationProfile()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.update_conversation_profile( - conversation_profile=gcd_conversation_profile.ConversationProfile(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] - arg = args[0].conversation_profile - mock_val = gcd_conversation_profile.ConversationProfile(name='name_value') - assert arg == mock_val - arg = args[0].update_mask - mock_val = field_mask_pb2.FieldMask(paths=['paths_value']) - assert arg == mock_val - -@pytest.mark.asyncio -async def test_update_conversation_profile_flattened_error_async(): - client = ConversationProfilesAsyncClient( - 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_conversation_profile( - gcd_conversation_profile.UpdateConversationProfileRequest(), - conversation_profile=gcd_conversation_profile.ConversationProfile(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - - -@pytest.mark.parametrize("request_type", [ - conversation_profile.DeleteConversationProfileRequest, - dict, -]) -def test_delete_conversation_profile(request_type, transport: str = 'grpc'): - client = ConversationProfilesClient( - 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_conversation_profile), - '__call__') 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. - assert response is None - - -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=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_conversation_profile), - '__call__') as call: - client.delete_conversation_profile() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == conversation_profile.DeleteConversationProfileRequest() - -@pytest.mark.asyncio -async def test_delete_conversation_profile_async(transport: str = 'grpc_asyncio', request_type=conversation_profile.DeleteConversationProfileRequest): - client = ConversationProfilesAsyncClient( - 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_conversation_profile), - '__call__') 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. - assert response is None - - -@pytest.mark.asyncio -async def test_delete_conversation_profile_async_from_dict(): - await test_delete_conversation_profile_async(request_type=dict) - - -def test_delete_conversation_profile_field_headers(): - 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. - with mock.patch.object( - 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. - 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_conversation_profile_field_headers_async(): - client = ConversationProfilesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value 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. - with mock.patch.object( - 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. - 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_conversation_profile_flattened(): - client = ConversationProfilesClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_conversation_profile), - '__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_conversation_profile( - 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] - arg = args[0].name - mock_val = 'name_value' - assert arg == mock_val - - -def test_delete_conversation_profile_flattened_error(): - client = ConversationProfilesClient( - 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_conversation_profile( - conversation_profile.DeleteConversationProfileRequest(), - name='name_value', - ) - -@pytest.mark.asyncio -async def test_delete_conversation_profile_flattened_async(): - client = ConversationProfilesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_conversation_profile), - '__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_conversation_profile( - 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] - arg = args[0].name - mock_val = 'name_value' - assert arg == mock_val - -@pytest.mark.asyncio -async def test_delete_conversation_profile_flattened_error_async(): - client = ConversationProfilesAsyncClient( - 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_conversation_profile( - conversation_profile.DeleteConversationProfileRequest(), - name='name_value', - ) - - -@pytest.mark.parametrize("request_type", [ - gcd_conversation_profile.SetSuggestionFeatureConfigRequest, - dict, -]) -def test_set_suggestion_feature_config(request_type, transport: str = 'grpc'): - client = ConversationProfilesClient( - 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.set_suggestion_feature_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/spam') - response = client.set_suggestion_feature_config(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.SetSuggestionFeatureConfigRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -def test_set_suggestion_feature_config_empty_call(): - # 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=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.set_suggestion_feature_config), - '__call__') as call: - client.set_suggestion_feature_config() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == gcd_conversation_profile.SetSuggestionFeatureConfigRequest() - -@pytest.mark.asyncio -async def test_set_suggestion_feature_config_async(transport: str = 'grpc_asyncio', request_type=gcd_conversation_profile.SetSuggestionFeatureConfigRequest): - client = ConversationProfilesAsyncClient( - 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.set_suggestion_feature_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name='operations/spam') - ) - response = await client.set_suggestion_feature_config(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.SetSuggestionFeatureConfigRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -@pytest.mark.asyncio -async def test_set_suggestion_feature_config_async_from_dict(): - await test_set_suggestion_feature_config_async(request_type=dict) - - -def test_set_suggestion_feature_config_field_headers(): - 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.SetSuggestionFeatureConfigRequest() - - request.conversation_profile = 'conversation_profile_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.set_suggestion_feature_config), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') - client.set_suggestion_feature_config(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', - 'conversation_profile=conversation_profile_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_set_suggestion_feature_config_field_headers_async(): - client = ConversationProfilesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value 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.SetSuggestionFeatureConfigRequest() - - request.conversation_profile = 'conversation_profile_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.set_suggestion_feature_config), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) - await client.set_suggestion_feature_config(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', - 'conversation_profile=conversation_profile_value', - ) in kw['metadata'] - - -def test_set_suggestion_feature_config_flattened(): - client = ConversationProfilesClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.set_suggestion_feature_config), - '__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.set_suggestion_feature_config( - conversation_profile='conversation_profile_value', - participant_role=participant.Participant.Role.HUMAN_AGENT, - suggestion_feature_config=gcd_conversation_profile.HumanAgentAssistantConfig.SuggestionFeatureConfig(suggestion_feature=participant.SuggestionFeature(type_=participant.SuggestionFeature.Type.ARTICLE_SUGGESTION)), - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - arg = args[0].conversation_profile - mock_val = 'conversation_profile_value' - assert arg == mock_val - arg = args[0].participant_role - mock_val = participant.Participant.Role.HUMAN_AGENT - assert arg == mock_val - arg = args[0].suggestion_feature_config - mock_val = gcd_conversation_profile.HumanAgentAssistantConfig.SuggestionFeatureConfig(suggestion_feature=participant.SuggestionFeature(type_=participant.SuggestionFeature.Type.ARTICLE_SUGGESTION)) - assert arg == mock_val - - -def test_set_suggestion_feature_config_flattened_error(): - client = ConversationProfilesClient( - 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.set_suggestion_feature_config( - gcd_conversation_profile.SetSuggestionFeatureConfigRequest(), - conversation_profile='conversation_profile_value', - participant_role=participant.Participant.Role.HUMAN_AGENT, - suggestion_feature_config=gcd_conversation_profile.HumanAgentAssistantConfig.SuggestionFeatureConfig(suggestion_feature=participant.SuggestionFeature(type_=participant.SuggestionFeature.Type.ARTICLE_SUGGESTION)), - ) - -@pytest.mark.asyncio -async def test_set_suggestion_feature_config_flattened_async(): - client = ConversationProfilesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.set_suggestion_feature_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/op') - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name='operations/spam') - ) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.set_suggestion_feature_config( - conversation_profile='conversation_profile_value', - participant_role=participant.Participant.Role.HUMAN_AGENT, - suggestion_feature_config=gcd_conversation_profile.HumanAgentAssistantConfig.SuggestionFeatureConfig(suggestion_feature=participant.SuggestionFeature(type_=participant.SuggestionFeature.Type.ARTICLE_SUGGESTION)), - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - arg = args[0].conversation_profile - mock_val = 'conversation_profile_value' - assert arg == mock_val - arg = args[0].participant_role - mock_val = participant.Participant.Role.HUMAN_AGENT - assert arg == mock_val - arg = args[0].suggestion_feature_config - mock_val = gcd_conversation_profile.HumanAgentAssistantConfig.SuggestionFeatureConfig(suggestion_feature=participant.SuggestionFeature(type_=participant.SuggestionFeature.Type.ARTICLE_SUGGESTION)) - assert arg == mock_val - -@pytest.mark.asyncio -async def test_set_suggestion_feature_config_flattened_error_async(): - client = ConversationProfilesAsyncClient( - 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.set_suggestion_feature_config( - gcd_conversation_profile.SetSuggestionFeatureConfigRequest(), - conversation_profile='conversation_profile_value', - participant_role=participant.Participant.Role.HUMAN_AGENT, - suggestion_feature_config=gcd_conversation_profile.HumanAgentAssistantConfig.SuggestionFeatureConfig(suggestion_feature=participant.SuggestionFeature(type_=participant.SuggestionFeature.Type.ARTICLE_SUGGESTION)), - ) - - -@pytest.mark.parametrize("request_type", [ - gcd_conversation_profile.ClearSuggestionFeatureConfigRequest, - dict, -]) -def test_clear_suggestion_feature_config(request_type, transport: str = 'grpc'): - client = ConversationProfilesClient( - 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.clear_suggestion_feature_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/spam') - response = client.clear_suggestion_feature_config(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.ClearSuggestionFeatureConfigRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -def test_clear_suggestion_feature_config_empty_call(): - # 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=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.clear_suggestion_feature_config), - '__call__') as call: - client.clear_suggestion_feature_config() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == gcd_conversation_profile.ClearSuggestionFeatureConfigRequest() - -@pytest.mark.asyncio -async def test_clear_suggestion_feature_config_async(transport: str = 'grpc_asyncio', request_type=gcd_conversation_profile.ClearSuggestionFeatureConfigRequest): - client = ConversationProfilesAsyncClient( - 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.clear_suggestion_feature_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name='operations/spam') - ) - response = await client.clear_suggestion_feature_config(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.ClearSuggestionFeatureConfigRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -@pytest.mark.asyncio -async def test_clear_suggestion_feature_config_async_from_dict(): - await test_clear_suggestion_feature_config_async(request_type=dict) - - -def test_clear_suggestion_feature_config_field_headers(): - 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.ClearSuggestionFeatureConfigRequest() - - request.conversation_profile = 'conversation_profile_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.clear_suggestion_feature_config), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') - client.clear_suggestion_feature_config(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', - 'conversation_profile=conversation_profile_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_clear_suggestion_feature_config_field_headers_async(): - client = ConversationProfilesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value 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.ClearSuggestionFeatureConfigRequest() - - request.conversation_profile = 'conversation_profile_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.clear_suggestion_feature_config), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) - await client.clear_suggestion_feature_config(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', - 'conversation_profile=conversation_profile_value', - ) in kw['metadata'] - - -def test_clear_suggestion_feature_config_flattened(): - client = ConversationProfilesClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.clear_suggestion_feature_config), - '__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.clear_suggestion_feature_config( - conversation_profile='conversation_profile_value', - participant_role=participant.Participant.Role.HUMAN_AGENT, - suggestion_feature_type=participant.SuggestionFeature.Type.ARTICLE_SUGGESTION, - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - arg = args[0].conversation_profile - mock_val = 'conversation_profile_value' - assert arg == mock_val - arg = args[0].participant_role - mock_val = participant.Participant.Role.HUMAN_AGENT - assert arg == mock_val - arg = args[0].suggestion_feature_type - mock_val = participant.SuggestionFeature.Type.ARTICLE_SUGGESTION - assert arg == mock_val - - -def test_clear_suggestion_feature_config_flattened_error(): - client = ConversationProfilesClient( - 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.clear_suggestion_feature_config( - gcd_conversation_profile.ClearSuggestionFeatureConfigRequest(), - conversation_profile='conversation_profile_value', - participant_role=participant.Participant.Role.HUMAN_AGENT, - suggestion_feature_type=participant.SuggestionFeature.Type.ARTICLE_SUGGESTION, - ) - -@pytest.mark.asyncio -async def test_clear_suggestion_feature_config_flattened_async(): - client = ConversationProfilesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.clear_suggestion_feature_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/op') - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name='operations/spam') - ) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.clear_suggestion_feature_config( - conversation_profile='conversation_profile_value', - participant_role=participant.Participant.Role.HUMAN_AGENT, - suggestion_feature_type=participant.SuggestionFeature.Type.ARTICLE_SUGGESTION, - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - arg = args[0].conversation_profile - mock_val = 'conversation_profile_value' - assert arg == mock_val - arg = args[0].participant_role - mock_val = participant.Participant.Role.HUMAN_AGENT - assert arg == mock_val - arg = args[0].suggestion_feature_type - mock_val = participant.SuggestionFeature.Type.ARTICLE_SUGGESTION - assert arg == mock_val - -@pytest.mark.asyncio -async def test_clear_suggestion_feature_config_flattened_error_async(): - client = ConversationProfilesAsyncClient( - 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.clear_suggestion_feature_config( - gcd_conversation_profile.ClearSuggestionFeatureConfigRequest(), - conversation_profile='conversation_profile_value', - participant_role=participant.Participant.Role.HUMAN_AGENT, - suggestion_feature_type=participant.SuggestionFeature.Type.ARTICLE_SUGGESTION, - ) - - -@pytest.mark.parametrize("request_type", [ - conversation_profile.ListConversationProfilesRequest, - dict, -]) -def test_list_conversation_profiles_rest(request_type): - client = ConversationProfilesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = conversation_profile.ListConversationProfilesResponse( - next_page_token='next_page_token_value', - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - pb_return_value = conversation_profile.ListConversationProfilesResponse.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.list_conversation_profiles(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListConversationProfilesPager) - assert response.next_page_token == 'next_page_token_value' - - -def test_list_conversation_profiles_rest_required_fields(request_type=conversation_profile.ListConversationProfilesRequest): - transport_class = transports.ConversationProfilesRestTransport - - request_init = {} - request_init["parent"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - including_default_value_fields=False, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).list_conversation_profiles._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["parent"] = 'parent_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).list_conversation_profiles._get_unset_required_fields(jsonified_request) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("page_size", "page_token", )) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "parent" in jsonified_request - assert jsonified_request["parent"] == 'parent_value' - - client = ConversationProfilesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = conversation_profile.ListConversationProfilesResponse() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "get", - 'query_params': pb_request, - } - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - - pb_return_value = conversation_profile.ListConversationProfilesResponse.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.list_conversation_profiles(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_list_conversation_profiles_rest_unset_required_fields(): - transport = transports.ConversationProfilesRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.list_conversation_profiles._get_unset_required_fields({}) - assert set(unset_fields) == (set(("pageSize", "pageToken", )) & set(("parent", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_list_conversation_profiles_rest_interceptors(null_interceptor): - transport = transports.ConversationProfilesRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.ConversationProfilesRestInterceptor(), - ) - client = ConversationProfilesClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.ConversationProfilesRestInterceptor, "post_list_conversation_profiles") as post, \ - mock.patch.object(transports.ConversationProfilesRestInterceptor, "pre_list_conversation_profiles") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = conversation_profile.ListConversationProfilesRequest.pb(conversation_profile.ListConversationProfilesRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = conversation_profile.ListConversationProfilesResponse.to_json(conversation_profile.ListConversationProfilesResponse()) - - request = conversation_profile.ListConversationProfilesRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = conversation_profile.ListConversationProfilesResponse() - - client.list_conversation_profiles(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_list_conversation_profiles_rest_bad_request(transport: str = 'rest', request_type=conversation_profile.ListConversationProfilesRequest): - client = ConversationProfilesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.list_conversation_profiles(request) - - -def test_list_conversation_profiles_rest_flattened(): - client = ConversationProfilesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = conversation_profile.ListConversationProfilesResponse() - - # get arguments that satisfy an http rule for this method - sample_request = {'parent': 'projects/sample1'} - - # get truthy value for each flattened field - mock_args = dict( - parent='parent_value', - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - pb_return_value = conversation_profile.ListConversationProfilesResponse.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.list_conversation_profiles(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v2beta1/{parent=projects/*}/conversationProfiles" % client.transport._host, args[1]) - - -def test_list_conversation_profiles_rest_flattened_error(transport: str = 'rest'): - client = ConversationProfilesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.list_conversation_profiles( - conversation_profile.ListConversationProfilesRequest(), - parent='parent_value', - ) - - -def test_list_conversation_profiles_rest_pager(transport: str = 'rest'): - client = ConversationProfilesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # TODO(kbandes): remove this mock unless there's a good reason for it. - #with mock.patch.object(path_template, 'transcode') as transcode: - # Set the response as a series of pages - response = ( - conversation_profile.ListConversationProfilesResponse( - conversation_profiles=[ - conversation_profile.ConversationProfile(), - conversation_profile.ConversationProfile(), - conversation_profile.ConversationProfile(), - ], - next_page_token='abc', - ), - conversation_profile.ListConversationProfilesResponse( - conversation_profiles=[], - next_page_token='def', - ), - conversation_profile.ListConversationProfilesResponse( - conversation_profiles=[ - conversation_profile.ConversationProfile(), - ], - next_page_token='ghi', - ), - conversation_profile.ListConversationProfilesResponse( - conversation_profiles=[ - conversation_profile.ConversationProfile(), - conversation_profile.ConversationProfile(), - ], - ), - ) - # Two responses for two calls - response = response + response - - # Wrap the values into proper Response objs - response = tuple(conversation_profile.ListConversationProfilesResponse.to_json(x) for x in response) - return_values = tuple(Response() for i in response) - for return_val, response_val in zip(return_values, response): - return_val._content = response_val.encode('UTF-8') - return_val.status_code = 200 - req.side_effect = return_values - - sample_request = {'parent': 'projects/sample1'} - - pager = client.list_conversation_profiles(request=sample_request) - - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, conversation_profile.ConversationProfile) - for i in results) - - pages = list(client.list_conversation_profiles(request=sample_request).pages) - for page_, token in zip(pages, ['abc','def','ghi', '']): - assert page_.raw_page.next_page_token == token - - -@pytest.mark.parametrize("request_type", [ - conversation_profile.GetConversationProfileRequest, - dict, -]) -def test_get_conversation_profile_rest(request_type): - client = ConversationProfilesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/conversationProfiles/sample2'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = conversation_profile.ConversationProfile( - name='name_value', - display_name='display_name_value', - language_code='language_code_value', - time_zone='time_zone_value', - security_settings='security_settings_value', - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - pb_return_value = conversation_profile.ConversationProfile.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.get_conversation_profile(request) - - # 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' - assert response.time_zone == 'time_zone_value' - assert response.security_settings == 'security_settings_value' - - -def test_get_conversation_profile_rest_required_fields(request_type=conversation_profile.GetConversationProfileRequest): - transport_class = transports.ConversationProfilesRestTransport - - request_init = {} - request_init["name"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - including_default_value_fields=False, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_conversation_profile._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["name"] = 'name_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_conversation_profile._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "name" in jsonified_request - assert jsonified_request["name"] == 'name_value' - - client = ConversationProfilesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = conversation_profile.ConversationProfile() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "get", - 'query_params': pb_request, - } - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - - pb_return_value = conversation_profile.ConversationProfile.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.get_conversation_profile(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_get_conversation_profile_rest_unset_required_fields(): - transport = transports.ConversationProfilesRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.get_conversation_profile._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_get_conversation_profile_rest_interceptors(null_interceptor): - transport = transports.ConversationProfilesRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.ConversationProfilesRestInterceptor(), - ) - client = ConversationProfilesClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.ConversationProfilesRestInterceptor, "post_get_conversation_profile") as post, \ - mock.patch.object(transports.ConversationProfilesRestInterceptor, "pre_get_conversation_profile") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = conversation_profile.GetConversationProfileRequest.pb(conversation_profile.GetConversationProfileRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = conversation_profile.ConversationProfile.to_json(conversation_profile.ConversationProfile()) - - request = conversation_profile.GetConversationProfileRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = conversation_profile.ConversationProfile() - - client.get_conversation_profile(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_get_conversation_profile_rest_bad_request(transport: str = 'rest', request_type=conversation_profile.GetConversationProfileRequest): - client = ConversationProfilesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/conversationProfiles/sample2'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.get_conversation_profile(request) - - -def test_get_conversation_profile_rest_flattened(): - client = ConversationProfilesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = conversation_profile.ConversationProfile() - - # get arguments that satisfy an http rule for this method - sample_request = {'name': 'projects/sample1/conversationProfiles/sample2'} - - # get truthy value for each flattened field - mock_args = dict( - name='name_value', - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - pb_return_value = conversation_profile.ConversationProfile.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.get_conversation_profile(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v2beta1/{name=projects/*/conversationProfiles/*}" % client.transport._host, args[1]) - - -def test_get_conversation_profile_rest_flattened_error(transport: str = 'rest'): - client = ConversationProfilesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.get_conversation_profile( - conversation_profile.GetConversationProfileRequest(), - name='name_value', - ) - - -def test_get_conversation_profile_rest_error(): - client = ConversationProfilesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - gcd_conversation_profile.CreateConversationProfileRequest, - dict, -]) -def test_create_conversation_profile_rest(request_type): - client = ConversationProfilesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1'} - request_init["conversation_profile"] = {'name': 'name_value', 'display_name': 'display_name_value', 'create_time': {'seconds': 751, 'nanos': 543}, 'update_time': {}, 'automated_agent_config': {'agent': 'agent_value'}, 'human_agent_assistant_config': {'notification_config': {'topic': 'topic_value', 'message_format': 1}, 'human_agent_suggestion_config': {'feature_configs': [{'suggestion_feature': {'type_': 1}, 'enable_event_based_suggestion': True, 'suggestion_trigger_settings': {'no_small_talk': True, 'only_end_user': True}, 'query_config': {'knowledge_base_query_source': {'knowledge_bases': ['knowledge_bases_value1', 'knowledge_bases_value2']}, 'document_query_source': {'documents': ['documents_value1', 'documents_value2']}, 'dialogflow_query_source': {'agent': 'agent_value'}, 'max_results': 1207, 'confidence_threshold': 0.2106, 'context_filter_settings': {'drop_handoff_messages': True, 'drop_virtual_agent_messages': True, 'drop_ivr_messages': True}}, 'conversation_model_config': {'model': 'model_value'}, 'conversation_process_config': {'recent_sentences_count': 2352}}], 'group_suggestion_responses': True}, 'end_user_suggestion_config': {}, 'message_analysis_config': {'enable_entity_extraction': True, 'enable_sentiment_analysis': True}}, 'human_agent_handoff_config': {'live_person_config': {'account_number': 'account_number_value'}, 'salesforce_live_agent_config': {'organization_id': 'organization_id_value', 'deployment_id': 'deployment_id_value', 'button_id': 'button_id_value', 'endpoint_domain': 'endpoint_domain_value'}}, 'notification_config': {}, 'logging_config': {'enable_stackdriver_logging': True}, 'new_message_event_notification_config': {}, 'stt_config': {'speech_model_variant': 1, 'model': 'model_value'}, 'language_code': 'language_code_value', 'time_zone': 'time_zone_value', 'security_settings': 'security_settings_value', 'tts_config': {'speaking_rate': 0.1373, 'pitch': 0.536, 'volume_gain_db': 0.1467, 'effects_profile_id': ['effects_profile_id_value1', 'effects_profile_id_value2'], 'voice': {'name': 'name_value', 'ssml_gender': 1}}} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = gcd_conversation_profile.ConversationProfile( - name='name_value', - display_name='display_name_value', - language_code='language_code_value', - time_zone='time_zone_value', - security_settings='security_settings_value', - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - pb_return_value = gcd_conversation_profile.ConversationProfile.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.create_conversation_profile(request) - - # 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' - assert response.time_zone == 'time_zone_value' - assert response.security_settings == 'security_settings_value' - - -def test_create_conversation_profile_rest_required_fields(request_type=gcd_conversation_profile.CreateConversationProfileRequest): - transport_class = transports.ConversationProfilesRestTransport - - request_init = {} - request_init["parent"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - including_default_value_fields=False, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_conversation_profile._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["parent"] = 'parent_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_conversation_profile._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "parent" in jsonified_request - assert jsonified_request["parent"] == 'parent_value' - - client = ConversationProfilesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = gcd_conversation_profile.ConversationProfile() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "post", - 'query_params': pb_request, - } - transcode_result['body'] = pb_request - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - - pb_return_value = gcd_conversation_profile.ConversationProfile.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.create_conversation_profile(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_create_conversation_profile_rest_unset_required_fields(): - transport = transports.ConversationProfilesRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.create_conversation_profile._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("parent", "conversationProfile", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_create_conversation_profile_rest_interceptors(null_interceptor): - transport = transports.ConversationProfilesRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.ConversationProfilesRestInterceptor(), - ) - client = ConversationProfilesClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.ConversationProfilesRestInterceptor, "post_create_conversation_profile") as post, \ - mock.patch.object(transports.ConversationProfilesRestInterceptor, "pre_create_conversation_profile") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = gcd_conversation_profile.CreateConversationProfileRequest.pb(gcd_conversation_profile.CreateConversationProfileRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = gcd_conversation_profile.ConversationProfile.to_json(gcd_conversation_profile.ConversationProfile()) - - request = gcd_conversation_profile.CreateConversationProfileRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = gcd_conversation_profile.ConversationProfile() - - client.create_conversation_profile(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_create_conversation_profile_rest_bad_request(transport: str = 'rest', request_type=gcd_conversation_profile.CreateConversationProfileRequest): - client = ConversationProfilesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1'} - request_init["conversation_profile"] = {'name': 'name_value', 'display_name': 'display_name_value', 'create_time': {'seconds': 751, 'nanos': 543}, 'update_time': {}, 'automated_agent_config': {'agent': 'agent_value'}, 'human_agent_assistant_config': {'notification_config': {'topic': 'topic_value', 'message_format': 1}, 'human_agent_suggestion_config': {'feature_configs': [{'suggestion_feature': {'type_': 1}, 'enable_event_based_suggestion': True, 'suggestion_trigger_settings': {'no_small_talk': True, 'only_end_user': True}, 'query_config': {'knowledge_base_query_source': {'knowledge_bases': ['knowledge_bases_value1', 'knowledge_bases_value2']}, 'document_query_source': {'documents': ['documents_value1', 'documents_value2']}, 'dialogflow_query_source': {'agent': 'agent_value'}, 'max_results': 1207, 'confidence_threshold': 0.2106, 'context_filter_settings': {'drop_handoff_messages': True, 'drop_virtual_agent_messages': True, 'drop_ivr_messages': True}}, 'conversation_model_config': {'model': 'model_value'}, 'conversation_process_config': {'recent_sentences_count': 2352}}], 'group_suggestion_responses': True}, 'end_user_suggestion_config': {}, 'message_analysis_config': {'enable_entity_extraction': True, 'enable_sentiment_analysis': True}}, 'human_agent_handoff_config': {'live_person_config': {'account_number': 'account_number_value'}, 'salesforce_live_agent_config': {'organization_id': 'organization_id_value', 'deployment_id': 'deployment_id_value', 'button_id': 'button_id_value', 'endpoint_domain': 'endpoint_domain_value'}}, 'notification_config': {}, 'logging_config': {'enable_stackdriver_logging': True}, 'new_message_event_notification_config': {}, 'stt_config': {'speech_model_variant': 1, 'model': 'model_value'}, 'language_code': 'language_code_value', 'time_zone': 'time_zone_value', 'security_settings': 'security_settings_value', 'tts_config': {'speaking_rate': 0.1373, 'pitch': 0.536, 'volume_gain_db': 0.1467, 'effects_profile_id': ['effects_profile_id_value1', 'effects_profile_id_value2'], 'voice': {'name': 'name_value', 'ssml_gender': 1}}} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.create_conversation_profile(request) - - -def test_create_conversation_profile_rest_flattened(): - client = ConversationProfilesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = gcd_conversation_profile.ConversationProfile() - - # get arguments that satisfy an http rule for this method - sample_request = {'parent': 'projects/sample1'} - - # get truthy value for each flattened field - mock_args = dict( - parent='parent_value', - conversation_profile=gcd_conversation_profile.ConversationProfile(name='name_value'), - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - pb_return_value = gcd_conversation_profile.ConversationProfile.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.create_conversation_profile(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v2beta1/{parent=projects/*}/conversationProfiles" % client.transport._host, args[1]) - - -def test_create_conversation_profile_rest_flattened_error(transport: str = 'rest'): - client = ConversationProfilesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.create_conversation_profile( - gcd_conversation_profile.CreateConversationProfileRequest(), - parent='parent_value', - conversation_profile=gcd_conversation_profile.ConversationProfile(name='name_value'), - ) - - -def test_create_conversation_profile_rest_error(): - client = ConversationProfilesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - gcd_conversation_profile.UpdateConversationProfileRequest, - dict, -]) -def test_update_conversation_profile_rest(request_type): - client = ConversationProfilesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'conversation_profile': {'name': 'projects/sample1/conversationProfiles/sample2'}} - request_init["conversation_profile"] = {'name': 'projects/sample1/conversationProfiles/sample2', 'display_name': 'display_name_value', 'create_time': {'seconds': 751, 'nanos': 543}, 'update_time': {}, 'automated_agent_config': {'agent': 'agent_value'}, 'human_agent_assistant_config': {'notification_config': {'topic': 'topic_value', 'message_format': 1}, 'human_agent_suggestion_config': {'feature_configs': [{'suggestion_feature': {'type_': 1}, 'enable_event_based_suggestion': True, 'suggestion_trigger_settings': {'no_small_talk': True, 'only_end_user': True}, 'query_config': {'knowledge_base_query_source': {'knowledge_bases': ['knowledge_bases_value1', 'knowledge_bases_value2']}, 'document_query_source': {'documents': ['documents_value1', 'documents_value2']}, 'dialogflow_query_source': {'agent': 'agent_value'}, 'max_results': 1207, 'confidence_threshold': 0.2106, 'context_filter_settings': {'drop_handoff_messages': True, 'drop_virtual_agent_messages': True, 'drop_ivr_messages': True}}, 'conversation_model_config': {'model': 'model_value'}, 'conversation_process_config': {'recent_sentences_count': 2352}}], 'group_suggestion_responses': True}, 'end_user_suggestion_config': {}, 'message_analysis_config': {'enable_entity_extraction': True, 'enable_sentiment_analysis': True}}, 'human_agent_handoff_config': {'live_person_config': {'account_number': 'account_number_value'}, 'salesforce_live_agent_config': {'organization_id': 'organization_id_value', 'deployment_id': 'deployment_id_value', 'button_id': 'button_id_value', 'endpoint_domain': 'endpoint_domain_value'}}, 'notification_config': {}, 'logging_config': {'enable_stackdriver_logging': True}, 'new_message_event_notification_config': {}, 'stt_config': {'speech_model_variant': 1, 'model': 'model_value'}, 'language_code': 'language_code_value', 'time_zone': 'time_zone_value', 'security_settings': 'security_settings_value', 'tts_config': {'speaking_rate': 0.1373, 'pitch': 0.536, 'volume_gain_db': 0.1467, 'effects_profile_id': ['effects_profile_id_value1', 'effects_profile_id_value2'], 'voice': {'name': 'name_value', 'ssml_gender': 1}}} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = gcd_conversation_profile.ConversationProfile( - name='name_value', - display_name='display_name_value', - language_code='language_code_value', - time_zone='time_zone_value', - security_settings='security_settings_value', - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - pb_return_value = gcd_conversation_profile.ConversationProfile.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.update_conversation_profile(request) - - # 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' - assert response.time_zone == 'time_zone_value' - assert response.security_settings == 'security_settings_value' - - -def test_update_conversation_profile_rest_required_fields(request_type=gcd_conversation_profile.UpdateConversationProfileRequest): - transport_class = transports.ConversationProfilesRestTransport - - request_init = {} - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - including_default_value_fields=False, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).update_conversation_profile._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).update_conversation_profile._get_unset_required_fields(jsonified_request) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("update_mask", )) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - - client = ConversationProfilesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = gcd_conversation_profile.ConversationProfile() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "patch", - 'query_params': pb_request, - } - transcode_result['body'] = pb_request - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - - pb_return_value = gcd_conversation_profile.ConversationProfile.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.update_conversation_profile(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_update_conversation_profile_rest_unset_required_fields(): - transport = transports.ConversationProfilesRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.update_conversation_profile._get_unset_required_fields({}) - assert set(unset_fields) == (set(("updateMask", )) & set(("conversationProfile", "updateMask", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_update_conversation_profile_rest_interceptors(null_interceptor): - transport = transports.ConversationProfilesRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.ConversationProfilesRestInterceptor(), - ) - client = ConversationProfilesClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.ConversationProfilesRestInterceptor, "post_update_conversation_profile") as post, \ - mock.patch.object(transports.ConversationProfilesRestInterceptor, "pre_update_conversation_profile") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = gcd_conversation_profile.UpdateConversationProfileRequest.pb(gcd_conversation_profile.UpdateConversationProfileRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = gcd_conversation_profile.ConversationProfile.to_json(gcd_conversation_profile.ConversationProfile()) - - request = gcd_conversation_profile.UpdateConversationProfileRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = gcd_conversation_profile.ConversationProfile() - - client.update_conversation_profile(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_update_conversation_profile_rest_bad_request(transport: str = 'rest', request_type=gcd_conversation_profile.UpdateConversationProfileRequest): - client = ConversationProfilesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'conversation_profile': {'name': 'projects/sample1/conversationProfiles/sample2'}} - request_init["conversation_profile"] = {'name': 'projects/sample1/conversationProfiles/sample2', 'display_name': 'display_name_value', 'create_time': {'seconds': 751, 'nanos': 543}, 'update_time': {}, 'automated_agent_config': {'agent': 'agent_value'}, 'human_agent_assistant_config': {'notification_config': {'topic': 'topic_value', 'message_format': 1}, 'human_agent_suggestion_config': {'feature_configs': [{'suggestion_feature': {'type_': 1}, 'enable_event_based_suggestion': True, 'suggestion_trigger_settings': {'no_small_talk': True, 'only_end_user': True}, 'query_config': {'knowledge_base_query_source': {'knowledge_bases': ['knowledge_bases_value1', 'knowledge_bases_value2']}, 'document_query_source': {'documents': ['documents_value1', 'documents_value2']}, 'dialogflow_query_source': {'agent': 'agent_value'}, 'max_results': 1207, 'confidence_threshold': 0.2106, 'context_filter_settings': {'drop_handoff_messages': True, 'drop_virtual_agent_messages': True, 'drop_ivr_messages': True}}, 'conversation_model_config': {'model': 'model_value'}, 'conversation_process_config': {'recent_sentences_count': 2352}}], 'group_suggestion_responses': True}, 'end_user_suggestion_config': {}, 'message_analysis_config': {'enable_entity_extraction': True, 'enable_sentiment_analysis': True}}, 'human_agent_handoff_config': {'live_person_config': {'account_number': 'account_number_value'}, 'salesforce_live_agent_config': {'organization_id': 'organization_id_value', 'deployment_id': 'deployment_id_value', 'button_id': 'button_id_value', 'endpoint_domain': 'endpoint_domain_value'}}, 'notification_config': {}, 'logging_config': {'enable_stackdriver_logging': True}, 'new_message_event_notification_config': {}, 'stt_config': {'speech_model_variant': 1, 'model': 'model_value'}, 'language_code': 'language_code_value', 'time_zone': 'time_zone_value', 'security_settings': 'security_settings_value', 'tts_config': {'speaking_rate': 0.1373, 'pitch': 0.536, 'volume_gain_db': 0.1467, 'effects_profile_id': ['effects_profile_id_value1', 'effects_profile_id_value2'], 'voice': {'name': 'name_value', 'ssml_gender': 1}}} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.update_conversation_profile(request) - - -def test_update_conversation_profile_rest_flattened(): - client = ConversationProfilesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = gcd_conversation_profile.ConversationProfile() - - # get arguments that satisfy an http rule for this method - sample_request = {'conversation_profile': {'name': 'projects/sample1/conversationProfiles/sample2'}} - - # get truthy value for each flattened field - mock_args = dict( - conversation_profile=gcd_conversation_profile.ConversationProfile(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - pb_return_value = gcd_conversation_profile.ConversationProfile.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.update_conversation_profile(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v2beta1/{conversation_profile.name=projects/*/conversationProfiles/*}" % client.transport._host, args[1]) - - -def test_update_conversation_profile_rest_flattened_error(transport: str = 'rest'): - client = ConversationProfilesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.update_conversation_profile( - gcd_conversation_profile.UpdateConversationProfileRequest(), - conversation_profile=gcd_conversation_profile.ConversationProfile(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - - -def test_update_conversation_profile_rest_error(): - client = ConversationProfilesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - conversation_profile.DeleteConversationProfileRequest, - dict, -]) -def test_delete_conversation_profile_rest(request_type): - client = ConversationProfilesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/conversationProfiles/sample2'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = None - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = '' - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.delete_conversation_profile(request) - - # Establish that the response is the type that we expect. - assert response is None - - -def test_delete_conversation_profile_rest_required_fields(request_type=conversation_profile.DeleteConversationProfileRequest): - transport_class = transports.ConversationProfilesRestTransport - - request_init = {} - request_init["name"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - including_default_value_fields=False, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).delete_conversation_profile._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["name"] = 'name_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).delete_conversation_profile._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "name" in jsonified_request - assert jsonified_request["name"] == 'name_value' - - client = ConversationProfilesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = None - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "delete", - 'query_params': pb_request, - } - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - json_return_value = '' - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.delete_conversation_profile(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_delete_conversation_profile_rest_unset_required_fields(): - transport = transports.ConversationProfilesRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.delete_conversation_profile._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_delete_conversation_profile_rest_interceptors(null_interceptor): - transport = transports.ConversationProfilesRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.ConversationProfilesRestInterceptor(), - ) - client = ConversationProfilesClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.ConversationProfilesRestInterceptor, "pre_delete_conversation_profile") as pre: - pre.assert_not_called() - pb_message = conversation_profile.DeleteConversationProfileRequest.pb(conversation_profile.DeleteConversationProfileRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - - request = conversation_profile.DeleteConversationProfileRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - - client.delete_conversation_profile(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - - -def test_delete_conversation_profile_rest_bad_request(transport: str = 'rest', request_type=conversation_profile.DeleteConversationProfileRequest): - client = ConversationProfilesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/conversationProfiles/sample2'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.delete_conversation_profile(request) - - -def test_delete_conversation_profile_rest_flattened(): - client = ConversationProfilesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = None - - # get arguments that satisfy an http rule for this method - sample_request = {'name': 'projects/sample1/conversationProfiles/sample2'} - - # get truthy value for each flattened field - mock_args = dict( - name='name_value', - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = '' - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.delete_conversation_profile(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v2beta1/{name=projects/*/conversationProfiles/*}" % client.transport._host, args[1]) - - -def test_delete_conversation_profile_rest_flattened_error(transport: str = 'rest'): - client = ConversationProfilesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.delete_conversation_profile( - conversation_profile.DeleteConversationProfileRequest(), - name='name_value', - ) - - -def test_delete_conversation_profile_rest_error(): - client = ConversationProfilesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - gcd_conversation_profile.SetSuggestionFeatureConfigRequest, - dict, -]) -def test_set_suggestion_feature_config_rest(request_type): - client = ConversationProfilesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'conversation_profile': 'projects/sample1/conversationProfiles/sample2'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name='operations/spam') - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.set_suggestion_feature_config(request) - - # Establish that the response is the type that we expect. - assert response.operation.name == "operations/spam" - - -def test_set_suggestion_feature_config_rest_required_fields(request_type=gcd_conversation_profile.SetSuggestionFeatureConfigRequest): - transport_class = transports.ConversationProfilesRestTransport - - request_init = {} - request_init["conversation_profile"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - including_default_value_fields=False, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).set_suggestion_feature_config._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["conversationProfile"] = 'conversation_profile_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).set_suggestion_feature_config._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "conversationProfile" in jsonified_request - assert jsonified_request["conversationProfile"] == 'conversation_profile_value' - - client = ConversationProfilesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name='operations/spam') - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "post", - 'query_params': pb_request, - } - transcode_result['body'] = pb_request - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.set_suggestion_feature_config(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_set_suggestion_feature_config_rest_unset_required_fields(): - transport = transports.ConversationProfilesRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.set_suggestion_feature_config._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("conversationProfile", "participantRole", "suggestionFeatureConfig", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_set_suggestion_feature_config_rest_interceptors(null_interceptor): - transport = transports.ConversationProfilesRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.ConversationProfilesRestInterceptor(), - ) - client = ConversationProfilesClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(operation.Operation, "_set_result_from_operation"), \ - mock.patch.object(transports.ConversationProfilesRestInterceptor, "post_set_suggestion_feature_config") as post, \ - mock.patch.object(transports.ConversationProfilesRestInterceptor, "pre_set_suggestion_feature_config") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = gcd_conversation_profile.SetSuggestionFeatureConfigRequest.pb(gcd_conversation_profile.SetSuggestionFeatureConfigRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = json_format.MessageToJson(operations_pb2.Operation()) - - request = gcd_conversation_profile.SetSuggestionFeatureConfigRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = operations_pb2.Operation() - - client.set_suggestion_feature_config(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_set_suggestion_feature_config_rest_bad_request(transport: str = 'rest', request_type=gcd_conversation_profile.SetSuggestionFeatureConfigRequest): - client = ConversationProfilesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'conversation_profile': 'projects/sample1/conversationProfiles/sample2'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.set_suggestion_feature_config(request) - - -def test_set_suggestion_feature_config_rest_flattened(): - client = ConversationProfilesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name='operations/spam') - - # get arguments that satisfy an http rule for this method - sample_request = {'conversation_profile': 'projects/sample1/conversationProfiles/sample2'} - - # get truthy value for each flattened field - mock_args = dict( - conversation_profile='conversation_profile_value', - participant_role=participant.Participant.Role.HUMAN_AGENT, - suggestion_feature_config=gcd_conversation_profile.HumanAgentAssistantConfig.SuggestionFeatureConfig(suggestion_feature=participant.SuggestionFeature(type_=participant.SuggestionFeature.Type.ARTICLE_SUGGESTION)), - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.set_suggestion_feature_config(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v2beta1/{conversation_profile=projects/*/conversationProfiles/*}:setSuggestionFeatureConfig" % client.transport._host, args[1]) - - -def test_set_suggestion_feature_config_rest_flattened_error(transport: str = 'rest'): - client = ConversationProfilesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.set_suggestion_feature_config( - gcd_conversation_profile.SetSuggestionFeatureConfigRequest(), - conversation_profile='conversation_profile_value', - participant_role=participant.Participant.Role.HUMAN_AGENT, - suggestion_feature_config=gcd_conversation_profile.HumanAgentAssistantConfig.SuggestionFeatureConfig(suggestion_feature=participant.SuggestionFeature(type_=participant.SuggestionFeature.Type.ARTICLE_SUGGESTION)), - ) - - -def test_set_suggestion_feature_config_rest_error(): - client = ConversationProfilesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - gcd_conversation_profile.ClearSuggestionFeatureConfigRequest, - dict, -]) -def test_clear_suggestion_feature_config_rest(request_type): - client = ConversationProfilesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'conversation_profile': 'projects/sample1/conversationProfiles/sample2'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name='operations/spam') - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.clear_suggestion_feature_config(request) - - # Establish that the response is the type that we expect. - assert response.operation.name == "operations/spam" - - -def test_clear_suggestion_feature_config_rest_required_fields(request_type=gcd_conversation_profile.ClearSuggestionFeatureConfigRequest): - transport_class = transports.ConversationProfilesRestTransport - - request_init = {} - request_init["conversation_profile"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - including_default_value_fields=False, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).clear_suggestion_feature_config._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["conversationProfile"] = 'conversation_profile_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).clear_suggestion_feature_config._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "conversationProfile" in jsonified_request - assert jsonified_request["conversationProfile"] == 'conversation_profile_value' - - client = ConversationProfilesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name='operations/spam') - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "post", - 'query_params': pb_request, - } - transcode_result['body'] = pb_request - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.clear_suggestion_feature_config(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_clear_suggestion_feature_config_rest_unset_required_fields(): - transport = transports.ConversationProfilesRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.clear_suggestion_feature_config._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("conversationProfile", "participantRole", "suggestionFeatureType", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_clear_suggestion_feature_config_rest_interceptors(null_interceptor): - transport = transports.ConversationProfilesRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.ConversationProfilesRestInterceptor(), - ) - client = ConversationProfilesClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(operation.Operation, "_set_result_from_operation"), \ - mock.patch.object(transports.ConversationProfilesRestInterceptor, "post_clear_suggestion_feature_config") as post, \ - mock.patch.object(transports.ConversationProfilesRestInterceptor, "pre_clear_suggestion_feature_config") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = gcd_conversation_profile.ClearSuggestionFeatureConfigRequest.pb(gcd_conversation_profile.ClearSuggestionFeatureConfigRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = json_format.MessageToJson(operations_pb2.Operation()) - - request = gcd_conversation_profile.ClearSuggestionFeatureConfigRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = operations_pb2.Operation() - - client.clear_suggestion_feature_config(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_clear_suggestion_feature_config_rest_bad_request(transport: str = 'rest', request_type=gcd_conversation_profile.ClearSuggestionFeatureConfigRequest): - client = ConversationProfilesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'conversation_profile': 'projects/sample1/conversationProfiles/sample2'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.clear_suggestion_feature_config(request) - - -def test_clear_suggestion_feature_config_rest_flattened(): - client = ConversationProfilesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name='operations/spam') - - # get arguments that satisfy an http rule for this method - sample_request = {'conversation_profile': 'projects/sample1/conversationProfiles/sample2'} - - # get truthy value for each flattened field - mock_args = dict( - conversation_profile='conversation_profile_value', - participant_role=participant.Participant.Role.HUMAN_AGENT, - suggestion_feature_type=participant.SuggestionFeature.Type.ARTICLE_SUGGESTION, - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.clear_suggestion_feature_config(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v2beta1/{conversation_profile=projects/*/conversationProfiles/*}:clearSuggestionFeatureConfig" % client.transport._host, args[1]) - - -def test_clear_suggestion_feature_config_rest_flattened_error(transport: str = 'rest'): - client = ConversationProfilesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.clear_suggestion_feature_config( - gcd_conversation_profile.ClearSuggestionFeatureConfigRequest(), - conversation_profile='conversation_profile_value', - participant_role=participant.Participant.Role.HUMAN_AGENT, - suggestion_feature_type=participant.SuggestionFeature.Type.ARTICLE_SUGGESTION, - ) - - -def test_clear_suggestion_feature_config_rest_error(): - client = ConversationProfilesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -def test_credentials_transport_error(): - # It is an error to provide credentials and a transport instance. - transport = transports.ConversationProfilesGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = ConversationProfilesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # It is an error to provide a credentials file and a transport instance. - transport = transports.ConversationProfilesGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = ConversationProfilesClient( - client_options={"credentials_file": "credentials.json"}, - transport=transport, - ) - - # It is an error to provide an api_key and a transport instance. - transport = transports.ConversationProfilesGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - options = client_options.ClientOptions() - options.api_key = "api_key" - with pytest.raises(ValueError): - client = ConversationProfilesClient( - client_options=options, - transport=transport, - ) - - # It is an error to provide an api_key and a credential. - options = mock.Mock() - options.api_key = "api_key" - with pytest.raises(ValueError): - client = ConversationProfilesClient( - client_options=options, - credentials=ga_credentials.AnonymousCredentials() - ) - - # It is an error to provide scopes and a transport instance. - transport = transports.ConversationProfilesGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = ConversationProfilesClient( - client_options={"scopes": ["1", "2"]}, - transport=transport, - ) - - -def test_transport_instance(): - # A client may be instantiated with a custom transport instance. - transport = transports.ConversationProfilesGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - client = ConversationProfilesClient(transport=transport) - assert client.transport is transport - -def test_transport_get_channel(): - # A client may be instantiated with a custom transport instance. - transport = transports.ConversationProfilesGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - - transport = transports.ConversationProfilesGrpcAsyncIOTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - -@pytest.mark.parametrize("transport_class", [ - transports.ConversationProfilesGrpcTransport, - transports.ConversationProfilesGrpcAsyncIOTransport, - transports.ConversationProfilesRestTransport, -]) -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() - -@pytest.mark.parametrize("transport_name", [ - "grpc", - "rest", -]) -def test_transport_kind(transport_name): - transport = ConversationProfilesClient.get_transport_class(transport_name)( - credentials=ga_credentials.AnonymousCredentials(), - ) - assert transport.kind == transport_name - -def test_transport_grpc_default(): - # A client should use the gRPC transport by default. - 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(core_exceptions.DuplicateCredentialArgs): - transport = transports.ConversationProfilesTransport( - credentials=ga_credentials.AnonymousCredentials(), - credentials_file="credentials.json" - ) - - -def test_conversation_profiles_base_transport(): - # Instantiate the base transport. - with mock.patch('google.cloud.dialogflow_v2beta1.services.conversation_profiles.transports.ConversationProfilesTransport.__init__') as Transport: - Transport.return_value = None - transport = transports.ConversationProfilesTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Every method on the transport should just blindly - # raise NotImplementedError. - methods = ( - 'list_conversation_profiles', - 'get_conversation_profile', - 'create_conversation_profile', - 'update_conversation_profile', - 'delete_conversation_profile', - 'set_suggestion_feature_config', - 'clear_suggestion_feature_config', - 'get_location', - 'list_locations', - 'get_operation', - 'cancel_operation', - 'list_operations', - ) - for method in methods: - with pytest.raises(NotImplementedError): - getattr(transport, method)(request=object()) - - with pytest.raises(NotImplementedError): - transport.close() - - # Additionally, the LRO client (a property) should - # also raise NotImplementedError - with pytest.raises(NotImplementedError): - transport.operations_client - - # Catch all for all remaining methods and properties - remainder = [ - 'kind', - ] - for r in remainder: - with pytest.raises(NotImplementedError): - getattr(transport, r)() - - -def test_conversation_profiles_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.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", - ) - load_creds.assert_called_once_with("credentials.json", - scopes=None, - default_scopes=( - 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/dialogflow', -), - quota_project_id="octopus", - ) - - -def test_conversation_profiles_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.conversation_profiles.transports.ConversationProfilesTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.ConversationProfilesTransport() - adc.assert_called_once() - - -def test_conversation_profiles_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) - 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, - ) - - -@pytest.mark.parametrize( - "transport_class", - [ - transports.ConversationProfilesGrpcTransport, - transports.ConversationProfilesGrpcAsyncIOTransport, - ], -) -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(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, - transports.ConversationProfilesRestTransport, - ], -) -def test_conversation_profiles_transport_auth_gdch_credentials(transport_class): - host = 'https://language.com' - api_audience_tests = [None, 'https://language2.com'] - api_audience_expect = [host, 'https://language2.com'] - for t, e in zip(api_audience_tests, api_audience_expect): - with mock.patch.object(google.auth, 'default', autospec=True) as adc: - gdch_mock = mock.MagicMock() - type(gdch_mock).with_gdch_audience = mock.PropertyMock(return_value=gdch_mock) - adc.return_value = (gdch_mock, None) - transport_class(host=host, api_audience=t) - gdch_mock.with_gdch_audience.assert_called_once_with( - e - ) - - -@pytest.mark.parametrize( - "transport_class,grpc_helpers", - [ - (transports.ConversationProfilesGrpcTransport, grpc_helpers), - (transports.ConversationProfilesGrpcAsyncIOTransport, grpc_helpers_async) - ], -) -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", [transports.ConversationProfilesGrpcTransport, transports.ConversationProfilesGrpcAsyncIOTransport]) -def test_conversation_profiles_grpc_transport_client_cert_source_for_mtls( - transport_class -): - cred = ga_credentials.AnonymousCredentials() - - # Check ssl_channel_credentials is used if provided. - with mock.patch.object(transport_class, "create_channel") as mock_create_channel: - mock_ssl_channel_creds = mock.Mock() - transport_class( - host="squid.clam.whelk", - credentials=cred, - ssl_channel_credentials=mock_ssl_channel_creds - ) - mock_create_channel.assert_called_once_with( - "squid.clam.whelk:443", - credentials=cred, - credentials_file=None, - scopes=None, - ssl_credentials=mock_ssl_channel_creds, - quota_project_id=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - # Check if ssl_channel_credentials is not provided, then client_cert_source_for_mtls - # is used. - with mock.patch.object(transport_class, "create_channel", return_value=mock.Mock()): - with mock.patch("grpc.ssl_channel_credentials") as mock_ssl_cred: - transport_class( - credentials=cred, - client_cert_source_for_mtls=client_cert_source_callback - ) - expected_cert, expected_key = client_cert_source_callback() - mock_ssl_cred.assert_called_once_with( - certificate_chain=expected_cert, - private_key=expected_key - ) - -def test_conversation_profiles_http_transport_client_cert_source_for_mtls(): - cred = ga_credentials.AnonymousCredentials() - with mock.patch("google.auth.transport.requests.AuthorizedSession.configure_mtls_channel") as mock_configure_mtls_channel: - transports.ConversationProfilesRestTransport ( - credentials=cred, - client_cert_source_for_mtls=client_cert_source_callback - ) - mock_configure_mtls_channel.assert_called_once_with(client_cert_source_callback) - - -def test_conversation_profiles_rest_lro_client(): - client = ConversationProfilesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - transport = client.transport - - # Ensure that we have a api-core operations client. - assert isinstance( - transport.operations_client, - operations_v1.AbstractOperationsClient, - ) - - # Ensure that subsequent calls to the property send the exact same object. - assert transport.operations_client is transport.operations_client - - -@pytest.mark.parametrize("transport_name", [ - "grpc", - "grpc_asyncio", - "rest", -]) -def test_conversation_profiles_host_no_port(transport_name): - client = ConversationProfilesClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='dialogflow.googleapis.com'), - transport=transport_name, - ) - assert client.transport._host == ( - 'dialogflow.googleapis.com:443' - if transport_name in ['grpc', 'grpc_asyncio'] - else 'https://dialogflow.googleapis.com' - ) - -@pytest.mark.parametrize("transport_name", [ - "grpc", - "grpc_asyncio", - "rest", -]) -def test_conversation_profiles_host_with_port(transport_name): - client = ConversationProfilesClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='dialogflow.googleapis.com:8000'), - transport=transport_name, - ) - assert client.transport._host == ( - 'dialogflow.googleapis.com:8000' - if transport_name in ['grpc', 'grpc_asyncio'] - else 'https://dialogflow.googleapis.com:8000' - ) - -@pytest.mark.parametrize("transport_name", [ - "rest", -]) -def test_conversation_profiles_client_transport_session_collision(transport_name): - creds1 = ga_credentials.AnonymousCredentials() - creds2 = ga_credentials.AnonymousCredentials() - client1 = ConversationProfilesClient( - credentials=creds1, - transport=transport_name, - ) - client2 = ConversationProfilesClient( - credentials=creds2, - transport=transport_name, - ) - session1 = client1.transport.list_conversation_profiles._session - session2 = client2.transport.list_conversation_profiles._session - assert session1 != session2 - session1 = client1.transport.get_conversation_profile._session - session2 = client2.transport.get_conversation_profile._session - assert session1 != session2 - session1 = client1.transport.create_conversation_profile._session - session2 = client2.transport.create_conversation_profile._session - assert session1 != session2 - session1 = client1.transport.update_conversation_profile._session - session2 = client2.transport.update_conversation_profile._session - assert session1 != session2 - session1 = client1.transport.delete_conversation_profile._session - session2 = client2.transport.delete_conversation_profile._session - assert session1 != session2 - session1 = client1.transport.set_suggestion_feature_config._session - session2 = client2.transport.set_suggestion_feature_config._session - assert session1 != session2 - session1 = client1.transport.clear_suggestion_feature_config._session - session2 = client2.transport.clear_suggestion_feature_config._session - assert session1 != session2 -def test_conversation_profiles_grpc_transport_channel(): - channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.ConversationProfilesGrpcTransport( - 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_conversation_profiles_grpc_asyncio_transport_channel(): - channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.ConversationProfilesGrpcAsyncIOTransport( - 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.ConversationProfilesGrpcTransport, transports.ConversationProfilesGrpcAsyncIOTransport]) -def test_conversation_profiles_transport_channel_mtls_with_client_cert_source( - transport_class -): - with mock.patch("grpc.ssl_channel_credentials", autospec=True) as grpc_ssl_channel_cred: - with mock.patch.object(transport_class, "create_channel") as grpc_create_channel: - mock_ssl_cred = mock.Mock() - grpc_ssl_channel_cred.return_value = mock_ssl_cred - - mock_grpc_channel = mock.Mock() - grpc_create_channel.return_value = mock_grpc_channel - - cred = ga_credentials.AnonymousCredentials() - with pytest.warns(DeprecationWarning): - with mock.patch.object(google.auth, 'default') as adc: - adc.return_value = (cred, None) - transport = transport_class( - host="squid.clam.whelk", - api_mtls_endpoint="mtls.squid.clam.whelk", - client_cert_source=client_cert_source_callback, - ) - adc.assert_called_once() - - grpc_ssl_channel_cred.assert_called_once_with( - certificate_chain=b"cert bytes", private_key=b"key bytes" - ) - grpc_create_channel.assert_called_once_with( - "mtls.squid.clam.whelk:443", - credentials=cred, - credentials_file=None, - scopes=None, - ssl_credentials=mock_ssl_cred, - quota_project_id=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - assert transport.grpc_channel == mock_grpc_channel - assert transport._ssl_channel_credentials == mock_ssl_cred - - -# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are -# removed from grpc/grpc_asyncio transport constructor. -@pytest.mark.parametrize("transport_class", [transports.ConversationProfilesGrpcTransport, transports.ConversationProfilesGrpcAsyncIOTransport]) -def test_conversation_profiles_transport_channel_mtls_with_adc( - transport_class -): - mock_ssl_cred = mock.Mock() - with mock.patch.multiple( - "google.auth.transport.grpc.SslCredentials", - __init__=mock.Mock(return_value=None), - ssl_credentials=mock.PropertyMock(return_value=mock_ssl_cred), - ): - with mock.patch.object(transport_class, "create_channel") as grpc_create_channel: - mock_grpc_channel = mock.Mock() - grpc_create_channel.return_value = mock_grpc_channel - mock_cred = mock.Mock() - - with pytest.warns(DeprecationWarning): - transport = transport_class( - host="squid.clam.whelk", - credentials=mock_cred, - api_mtls_endpoint="mtls.squid.clam.whelk", - client_cert_source=None, - ) - - grpc_create_channel.assert_called_once_with( - "mtls.squid.clam.whelk:443", - credentials=mock_cred, - credentials_file=None, - scopes=None, - ssl_credentials=mock_ssl_cred, - quota_project_id=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - assert transport.grpc_channel == mock_grpc_channel - - -def test_conversation_profiles_grpc_lro_client(): - client = ConversationProfilesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - transport = client.transport - - # Ensure that we have a api-core operations client. - assert isinstance( - transport.operations_client, - operations_v1.OperationsClient, - ) - - # Ensure that subsequent calls to the property send the exact same object. - assert transport.operations_client is transport.operations_client - - -def test_conversation_profiles_grpc_lro_async_client(): - client = ConversationProfilesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc_asyncio', - ) - transport = client.transport - - # Ensure that we have a api-core operations client. - assert isinstance( - transport.operations_client, - operations_v1.OperationsAsyncClient, - ) - - # Ensure that subsequent calls to the property send the exact same object. - assert transport.operations_client is transport.operations_client - - -def test_agent_path(): - project = "squid" - expected = "projects/{project}/agent".format(project=project, ) - actual = ConversationProfilesClient.agent_path(project) - assert expected == actual - - -def test_parse_agent_path(): - expected = { - "project": "clam", - } - path = ConversationProfilesClient.agent_path(**expected) - - # Check that the path construction is reversible. - actual = ConversationProfilesClient.parse_agent_path(path) - assert expected == actual - -def test_conversation_model_path(): - project = "whelk" - 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, ) - actual = ConversationProfilesClient.conversation_profile_path(project, conversation_profile) - assert expected == actual - - -def test_parse_conversation_profile_path(): - expected = { - "project": "scallop", - "conversation_profile": "abalone", - } - path = ConversationProfilesClient.conversation_profile_path(**expected) - - # Check that the path construction is reversible. - actual = ConversationProfilesClient.parse_conversation_profile_path(path) - assert expected == actual - -def test_cx_security_settings_path(): - project = "squid" - location = "clam" - security_settings = "whelk" - expected = "projects/{project}/locations/{location}/securitySettings/{security_settings}".format(project=project, location=location, security_settings=security_settings, ) - actual = ConversationProfilesClient.cx_security_settings_path(project, location, security_settings) - assert expected == actual - - -def test_parse_cx_security_settings_path(): - expected = { - "project": "octopus", - "location": "oyster", - "security_settings": "nudibranch", - } - path = ConversationProfilesClient.cx_security_settings_path(**expected) - - # Check that the path construction is reversible. - actual = ConversationProfilesClient.parse_cx_security_settings_path(path) - assert expected == actual - -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, ) - actual = ConversationProfilesClient.document_path(project, knowledge_base, document) - assert expected == actual - - -def test_parse_document_path(): - expected = { - "project": "nautilus", - "knowledge_base": "scallop", - "document": "abalone", - } - path = ConversationProfilesClient.document_path(**expected) - - # Check that the path construction is reversible. - actual = ConversationProfilesClient.parse_document_path(path) - assert expected == actual - -def test_knowledge_base_path(): - project = "squid" - knowledge_base = "clam" - expected = "projects/{project}/knowledgeBases/{knowledge_base}".format(project=project, knowledge_base=knowledge_base, ) - actual = ConversationProfilesClient.knowledge_base_path(project, knowledge_base) - assert expected == actual - - -def test_parse_knowledge_base_path(): - expected = { - "project": "whelk", - "knowledge_base": "octopus", - } - path = ConversationProfilesClient.knowledge_base_path(**expected) - - # Check that the path construction is reversible. - actual = ConversationProfilesClient.parse_knowledge_base_path(path) - assert expected == actual - -def test_common_billing_account_path(): - billing_account = "oyster" - expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) - actual = ConversationProfilesClient.common_billing_account_path(billing_account) - assert expected == actual - - -def test_parse_common_billing_account_path(): - expected = { - "billing_account": "nudibranch", - } - path = ConversationProfilesClient.common_billing_account_path(**expected) - - # Check that the path construction is reversible. - actual = ConversationProfilesClient.parse_common_billing_account_path(path) - assert expected == actual - -def test_common_folder_path(): - folder = "cuttlefish" - expected = "folders/{folder}".format(folder=folder, ) - actual = ConversationProfilesClient.common_folder_path(folder) - assert expected == actual - - -def test_parse_common_folder_path(): - expected = { - "folder": "mussel", - } - path = ConversationProfilesClient.common_folder_path(**expected) - - # Check that the path construction is reversible. - actual = ConversationProfilesClient.parse_common_folder_path(path) - assert expected == actual - -def test_common_organization_path(): - organization = "winkle" - expected = "organizations/{organization}".format(organization=organization, ) - actual = ConversationProfilesClient.common_organization_path(organization) - assert expected == actual - - -def test_parse_common_organization_path(): - expected = { - "organization": "nautilus", - } - path = ConversationProfilesClient.common_organization_path(**expected) - - # Check that the path construction is reversible. - actual = ConversationProfilesClient.parse_common_organization_path(path) - assert expected == actual - -def test_common_project_path(): - project = "scallop" - expected = "projects/{project}".format(project=project, ) - actual = ConversationProfilesClient.common_project_path(project) - assert expected == actual - - -def test_parse_common_project_path(): - expected = { - "project": "abalone", - } - path = ConversationProfilesClient.common_project_path(**expected) - - # Check that the path construction is reversible. - actual = ConversationProfilesClient.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 = ConversationProfilesClient.common_location_path(project, location) - assert expected == actual - - -def test_parse_common_location_path(): - expected = { - "project": "whelk", - "location": "octopus", - } - path = ConversationProfilesClient.common_location_path(**expected) - - # Check that the path construction is reversible. - actual = ConversationProfilesClient.parse_common_location_path(path) - assert expected == actual - - -def test_client_with_default_client_info(): - client_info = gapic_v1.client_info.ClientInfo() - - with mock.patch.object(transports.ConversationProfilesTransport, '_prep_wrapped_messages') as prep: - client = ConversationProfilesClient( - credentials=ga_credentials.AnonymousCredentials(), - client_info=client_info, - ) - prep.assert_called_once_with(client_info) - - with mock.patch.object(transports.ConversationProfilesTransport, '_prep_wrapped_messages') as prep: - transport_class = ConversationProfilesClient.get_transport_class() - transport = transport_class( - credentials=ga_credentials.AnonymousCredentials(), - client_info=client_info, - ) - prep.assert_called_once_with(client_info) - -@pytest.mark.asyncio -async def test_transport_close_async(): - client = ConversationProfilesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - with mock.patch.object(type(getattr(client.transport, "grpc_channel")), "close") as close: - async with client: - close.assert_not_called() - close.assert_called_once() - - -def test_get_location_rest_bad_request(transport: str = 'rest', request_type=locations_pb2.GetLocationRequest): - client = ConversationProfilesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - request = request_type() - request = json_format.ParseDict({'name': 'projects/sample1/locations/sample2'}, request) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.get_location(request) - -@pytest.mark.parametrize("request_type", [ - locations_pb2.GetLocationRequest, - dict, -]) -def test_get_location_rest(request_type): - client = ConversationProfilesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request_init = {'name': 'projects/sample1/locations/sample2'} - request = request_type(**request_init) - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = locations_pb2.Location() - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.get_location(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, locations_pb2.Location) - -def test_list_locations_rest_bad_request(transport: str = 'rest', request_type=locations_pb2.ListLocationsRequest): - client = ConversationProfilesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - request = request_type() - request = json_format.ParseDict({'name': 'projects/sample1'}, request) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.list_locations(request) - -@pytest.mark.parametrize("request_type", [ - locations_pb2.ListLocationsRequest, - dict, -]) -def test_list_locations_rest(request_type): - client = ConversationProfilesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request_init = {'name': 'projects/sample1'} - request = request_type(**request_init) - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = locations_pb2.ListLocationsResponse() - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.list_locations(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, locations_pb2.ListLocationsResponse) - -def test_cancel_operation_rest_bad_request(transport: str = 'rest', request_type=operations_pb2.CancelOperationRequest): - client = ConversationProfilesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - request = request_type() - request = json_format.ParseDict({'name': 'projects/sample1/operations/sample2'}, request) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.cancel_operation(request) - -@pytest.mark.parametrize("request_type", [ - operations_pb2.CancelOperationRequest, - dict, -]) -def test_cancel_operation_rest(request_type): - client = ConversationProfilesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request_init = {'name': 'projects/sample1/operations/sample2'} - request = request_type(**request_init) - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = None - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = '{}' - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.cancel_operation(request) - - # Establish that the response is the type that we expect. - assert response is None - -def test_get_operation_rest_bad_request(transport: str = 'rest', request_type=operations_pb2.GetOperationRequest): - client = ConversationProfilesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - request = request_type() - request = json_format.ParseDict({'name': 'projects/sample1/operations/sample2'}, request) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.get_operation(request) - -@pytest.mark.parametrize("request_type", [ - operations_pb2.GetOperationRequest, - dict, -]) -def test_get_operation_rest(request_type): - client = ConversationProfilesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request_init = {'name': 'projects/sample1/operations/sample2'} - request = request_type(**request_init) - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation() - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.get_operation(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, operations_pb2.Operation) - -def test_list_operations_rest_bad_request(transport: str = 'rest', request_type=operations_pb2.ListOperationsRequest): - client = ConversationProfilesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - request = request_type() - request = json_format.ParseDict({'name': 'projects/sample1'}, request) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.list_operations(request) - -@pytest.mark.parametrize("request_type", [ - operations_pb2.ListOperationsRequest, - dict, -]) -def test_list_operations_rest(request_type): - client = ConversationProfilesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request_init = {'name': 'projects/sample1'} - request = request_type(**request_init) - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = operations_pb2.ListOperationsResponse() - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.list_operations(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, operations_pb2.ListOperationsResponse) - - -def test_cancel_operation(transport: str = "grpc"): - client = ConversationProfilesClient( - 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 = operations_pb2.CancelOperationRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = None - response = client.cancel_operation(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 response is the type that we expect. - assert response is None -@pytest.mark.asyncio -async def test_cancel_operation_async(transport: str = "grpc"): - client = ConversationProfilesAsyncClient( - 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 = operations_pb2.CancelOperationRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - None - ) - response = await client.cancel_operation(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 response is the type that we expect. - assert response is None - -def test_cancel_operation_field_headers(): - 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 = operations_pb2.CancelOperationRequest() - request.name = "locations" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call: - call.return_value = None - - client.cancel_operation(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=locations",) in kw["metadata"] -@pytest.mark.asyncio -async def test_cancel_operation_field_headers_async(): - client = ConversationProfilesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = operations_pb2.CancelOperationRequest() - request.name = "locations" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - None - ) - await client.cancel_operation(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=locations",) in kw["metadata"] - -def test_cancel_operation_from_dict(): - client = ConversationProfilesClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = None - - response = client.cancel_operation( - request={ - "name": "locations", - } - ) - call.assert_called() -@pytest.mark.asyncio -async def test_cancel_operation_from_dict_async(): - client = ConversationProfilesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - None - ) - response = await client.cancel_operation( - request={ - "name": "locations", - } - ) - call.assert_called() - - -def test_get_operation(transport: str = "grpc"): - client = ConversationProfilesClient( - 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 = operations_pb2.GetOperationRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_operation), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation() - response = client.get_operation(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 response is the type that we expect. - assert isinstance(response, operations_pb2.Operation) -@pytest.mark.asyncio -async def test_get_operation_async(transport: str = "grpc"): - client = ConversationProfilesAsyncClient( - 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 = operations_pb2.GetOperationRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_operation), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation() - ) - response = await client.get_operation(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 response is the type that we expect. - assert isinstance(response, operations_pb2.Operation) - -def test_get_operation_field_headers(): - 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 = operations_pb2.GetOperationRequest() - request.name = "locations" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_operation), "__call__") as call: - call.return_value = operations_pb2.Operation() - - client.get_operation(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=locations",) in kw["metadata"] -@pytest.mark.asyncio -async def test_get_operation_field_headers_async(): - client = ConversationProfilesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = operations_pb2.GetOperationRequest() - request.name = "locations" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_operation), "__call__") as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation() - ) - await client.get_operation(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=locations",) in kw["metadata"] - -def test_get_operation_from_dict(): - client = ConversationProfilesClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_operation), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation() - - response = client.get_operation( - request={ - "name": "locations", - } - ) - call.assert_called() -@pytest.mark.asyncio -async def test_get_operation_from_dict_async(): - client = ConversationProfilesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_operation), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation() - ) - response = await client.get_operation( - request={ - "name": "locations", - } - ) - call.assert_called() - - -def test_list_operations(transport: str = "grpc"): - client = ConversationProfilesClient( - 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 = operations_pb2.ListOperationsRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_operations), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.ListOperationsResponse() - response = client.list_operations(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 response is the type that we expect. - assert isinstance(response, operations_pb2.ListOperationsResponse) -@pytest.mark.asyncio -async def test_list_operations_async(transport: str = "grpc"): - client = ConversationProfilesAsyncClient( - 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 = operations_pb2.ListOperationsRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_operations), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.ListOperationsResponse() - ) - response = await client.list_operations(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 response is the type that we expect. - assert isinstance(response, operations_pb2.ListOperationsResponse) - -def test_list_operations_field_headers(): - 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 = operations_pb2.ListOperationsRequest() - request.name = "locations" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_operations), "__call__") as call: - call.return_value = operations_pb2.ListOperationsResponse() - - client.list_operations(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=locations",) in kw["metadata"] -@pytest.mark.asyncio -async def test_list_operations_field_headers_async(): - client = ConversationProfilesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = operations_pb2.ListOperationsRequest() - request.name = "locations" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_operations), "__call__") as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.ListOperationsResponse() - ) - await client.list_operations(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=locations",) in kw["metadata"] - -def test_list_operations_from_dict(): - client = ConversationProfilesClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_operations), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.ListOperationsResponse() - - response = client.list_operations( - request={ - "name": "locations", - } - ) - call.assert_called() -@pytest.mark.asyncio -async def test_list_operations_from_dict_async(): - client = ConversationProfilesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_operations), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.ListOperationsResponse() - ) - response = await client.list_operations( - request={ - "name": "locations", - } - ) - call.assert_called() - - -def test_list_locations(transport: str = "grpc"): - client = ConversationProfilesClient( - 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 = locations_pb2.ListLocationsRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_locations), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = locations_pb2.ListLocationsResponse() - response = client.list_locations(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 response is the type that we expect. - assert isinstance(response, locations_pb2.ListLocationsResponse) -@pytest.mark.asyncio -async def test_list_locations_async(transport: str = "grpc"): - client = ConversationProfilesAsyncClient( - 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 = locations_pb2.ListLocationsRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_locations), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - locations_pb2.ListLocationsResponse() - ) - response = await client.list_locations(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 response is the type that we expect. - assert isinstance(response, locations_pb2.ListLocationsResponse) - -def test_list_locations_field_headers(): - 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 = locations_pb2.ListLocationsRequest() - request.name = "locations" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_locations), "__call__") as call: - call.return_value = locations_pb2.ListLocationsResponse() - - client.list_locations(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=locations",) in kw["metadata"] -@pytest.mark.asyncio -async def test_list_locations_field_headers_async(): - client = ConversationProfilesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = locations_pb2.ListLocationsRequest() - request.name = "locations" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_locations), "__call__") as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - locations_pb2.ListLocationsResponse() - ) - await client.list_locations(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=locations",) in kw["metadata"] - -def test_list_locations_from_dict(): - client = ConversationProfilesClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_locations), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = locations_pb2.ListLocationsResponse() - - response = client.list_locations( - request={ - "name": "locations", - } - ) - call.assert_called() -@pytest.mark.asyncio -async def test_list_locations_from_dict_async(): - client = ConversationProfilesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_locations), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - locations_pb2.ListLocationsResponse() - ) - response = await client.list_locations( - request={ - "name": "locations", - } - ) - call.assert_called() - - -def test_get_location(transport: str = "grpc"): - client = ConversationProfilesClient( - 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 = locations_pb2.GetLocationRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_location), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = locations_pb2.Location() - response = client.get_location(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 response is the type that we expect. - assert isinstance(response, locations_pb2.Location) -@pytest.mark.asyncio -async def test_get_location_async(transport: str = "grpc_asyncio"): - client = ConversationProfilesAsyncClient( - 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 = locations_pb2.GetLocationRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_location), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - locations_pb2.Location() - ) - response = await client.get_location(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 response is the type that we expect. - assert isinstance(response, locations_pb2.Location) - -def test_get_location_field_headers(): - 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 = locations_pb2.GetLocationRequest() - request.name = "locations/abc" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_location), "__call__") as call: - call.return_value = locations_pb2.Location() - - client.get_location(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=locations/abc",) in kw["metadata"] -@pytest.mark.asyncio -async def test_get_location_field_headers_async(): - client = ConversationProfilesAsyncClient( - credentials=ga_credentials.AnonymousCredentials() - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = locations_pb2.GetLocationRequest() - request.name = "locations/abc" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_location), "__call__") as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - locations_pb2.Location() - ) - await client.get_location(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=locations/abc",) in kw["metadata"] - -def test_get_location_from_dict(): - client = ConversationProfilesClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_locations), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = locations_pb2.Location() - - response = client.get_location( - request={ - "name": "locations/abc", - } - ) - call.assert_called() -@pytest.mark.asyncio -async def test_get_location_from_dict_async(): - client = ConversationProfilesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_locations), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - locations_pb2.Location() - ) - response = await client.get_location( - request={ - "name": "locations", - } - ) - call.assert_called() - - -def test_transport_close(): - transports = { - "rest": "_session", - "grpc": "_grpc_channel", - } - - for transport, close_name in transports.items(): - client = ConversationProfilesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport - ) - with mock.patch.object(type(getattr(client.transport, close_name)), "close") as close: - with client: - close.assert_not_called() - close.assert_called_once() - -def test_client_ctx(): - transports = [ - 'rest', - 'grpc', - ] - for transport in transports: - client = ConversationProfilesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport - ) - # Test client calls underlying transport. - with mock.patch.object(type(client.transport), "close") as close: - close.assert_not_called() - with client: - pass - close.assert_called() - -@pytest.mark.parametrize("client_class,transport_class", [ - (ConversationProfilesClient, transports.ConversationProfilesGrpcTransport), - (ConversationProfilesAsyncClient, transports.ConversationProfilesGrpcAsyncIOTransport), -]) -def test_api_key_credentials(client_class, transport_class): - with mock.patch.object( - google.auth._default, "get_api_key_credentials", create=True - ) as get_api_key_credentials: - mock_cred = mock.Mock() - get_api_key_credentials.return_value = mock_cred - options = client_options.ClientOptions() - options.api_key = "api_key" - 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=mock_cred, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) diff --git a/owl-bot-staging/v2beta1/tests/unit/gapic/dialogflow_v2beta1/test_conversations.py b/owl-bot-staging/v2beta1/tests/unit/gapic/dialogflow_v2beta1/test_conversations.py deleted file mode 100644 index b7a6833d1..000000000 --- a/owl-bot-staging/v2beta1/tests/unit/gapic/dialogflow_v2beta1/test_conversations.py +++ /dev/null @@ -1,6014 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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 -# try/except added for compatibility with python < 3.8 -try: - from unittest import mock - from unittest.mock import AsyncMock # pragma: NO COVER -except ImportError: # pragma: NO COVER - import mock - -import grpc -from grpc.experimental import aio -from collections.abc import Iterable -from google.protobuf import json_format -import json -import math -import pytest -from proto.marshal.rules.dates import DurationRule, TimestampRule -from proto.marshal.rules import wrappers -from requests import Response -from requests import Request, PreparedRequest -from requests.sessions import Session -from google.protobuf import json_format - -from google.api_core import client_options -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import grpc_helpers -from google.api_core import grpc_helpers_async -from google.api_core import path_template -from google.auth import credentials as ga_credentials -from google.auth.exceptions import MutualTLSChannelError -from google.cloud.dialogflow_v2beta1.services.conversations import ConversationsAsyncClient -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.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.cloud.location import locations_pb2 -from google.longrunning import operations_pb2 -from google.oauth2 import service_account -from google.protobuf import struct_pb2 # type: ignore -from google.protobuf import timestamp_pb2 # type: ignore -import google.auth - - -def client_cert_source_callback(): - return b"cert bytes", b"key bytes" - - -# If default endpoint is localhost, then default mtls endpoint will be the same. -# This method modifies the default endpoint so the client can produce a different -# mtls endpoint for endpoint testing purposes. -def modify_default_endpoint(client): - return "foo.googleapis.com" if ("localhost" in client.DEFAULT_ENDPOINT) else client.DEFAULT_ENDPOINT - - -def test__get_default_mtls_endpoint(): - api_endpoint = "example.googleapis.com" - api_mtls_endpoint = "example.mtls.googleapis.com" - sandbox_endpoint = "example.sandbox.googleapis.com" - sandbox_mtls_endpoint = "example.mtls.sandbox.googleapis.com" - non_googleapi = "api.example.com" - - assert ConversationsClient._get_default_mtls_endpoint(None) is None - assert ConversationsClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint - assert ConversationsClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint - assert ConversationsClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint - assert ConversationsClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint - assert ConversationsClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi - - -@pytest.mark.parametrize("client_class,transport_name", [ - (ConversationsClient, "grpc"), - (ConversationsAsyncClient, "grpc_asyncio"), - (ConversationsClient, "rest"), -]) -def test_conversations_client_from_service_account_info(client_class, transport_name): - 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, transport=transport_name) - assert client.transport._credentials == creds - assert isinstance(client, client_class) - - assert client.transport._host == ( - 'dialogflow.googleapis.com:443' - if transport_name in ['grpc', 'grpc_asyncio'] - else - 'https://dialogflow.googleapis.com' - ) - - -@pytest.mark.parametrize("transport_class,transport_name", [ - (transports.ConversationsGrpcTransport, "grpc"), - (transports.ConversationsGrpcAsyncIOTransport, "grpc_asyncio"), - (transports.ConversationsRestTransport, "rest"), -]) -def test_conversations_client_service_account_always_use_jwt(transport_class, transport_name): - with mock.patch.object(service_account.Credentials, 'with_always_use_jwt_access', create=True) as use_jwt: - creds = service_account.Credentials(None, None, None) - transport = transport_class(credentials=creds, always_use_jwt_access=True) - use_jwt.assert_called_once_with(True) - - with mock.patch.object(service_account.Credentials, 'with_always_use_jwt_access', create=True) as use_jwt: - creds = service_account.Credentials(None, None, None) - transport = transport_class(credentials=creds, always_use_jwt_access=False) - use_jwt.assert_not_called() - - -@pytest.mark.parametrize("client_class,transport_name", [ - (ConversationsClient, "grpc"), - (ConversationsAsyncClient, "grpc_asyncio"), - (ConversationsClient, "rest"), -]) -def test_conversations_client_from_service_account_file(client_class, transport_name): - 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", transport=transport_name) - assert client.transport._credentials == creds - assert isinstance(client, client_class) - - client = client_class.from_service_account_json("dummy/file/path.json", transport=transport_name) - assert client.transport._credentials == creds - assert isinstance(client, client_class) - - assert client.transport._host == ( - 'dialogflow.googleapis.com:443' - if transport_name in ['grpc', 'grpc_asyncio'] - else - 'https://dialogflow.googleapis.com' - ) - - -def test_conversations_client_get_transport_class(): - transport = ConversationsClient.get_transport_class() - available_transports = [ - transports.ConversationsGrpcTransport, - transports.ConversationsRestTransport, - ] - assert transport in available_transports - - transport = ConversationsClient.get_transport_class("grpc") - assert transport == transports.ConversationsGrpcTransport - - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (ConversationsClient, transports.ConversationsGrpcTransport, "grpc"), - (ConversationsAsyncClient, transports.ConversationsGrpcAsyncIOTransport, "grpc_asyncio"), - (ConversationsClient, transports.ConversationsRestTransport, "rest"), -]) -@mock.patch.object(ConversationsClient, "DEFAULT_ENDPOINT", modify_default_endpoint(ConversationsClient)) -@mock.patch.object(ConversationsAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(ConversationsAsyncClient)) -def test_conversations_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(ConversationsClient, '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(ConversationsClient, 'get_transport_class') as gtc: - client = client_class(transport=transport_name) - gtc.assert_called() - - # Check the case api_endpoint is provided. - options = client_options.ClientOptions(api_endpoint="squid.clam.whelk") - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(transport=transport_name, client_options=options) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host="squid.clam.whelk", - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is - # "never". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is - # "always". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_MTLS_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # 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(transport=transport_name) - - # 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(transport=transport_name) - - # 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, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id="octopus", - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - # Check the case api_endpoint is provided - options = client_options.ClientOptions(api_audience="https://language.googleapis.com") - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience="https://language.googleapis.com" - ) - -@pytest.mark.parametrize("client_class,transport_class,transport_name,use_client_cert_env", [ - (ConversationsClient, transports.ConversationsGrpcTransport, "grpc", "true"), - (ConversationsAsyncClient, transports.ConversationsGrpcAsyncIOTransport, "grpc_asyncio", "true"), - (ConversationsClient, transports.ConversationsGrpcTransport, "grpc", "false"), - (ConversationsAsyncClient, transports.ConversationsGrpcAsyncIOTransport, "grpc_asyncio", "false"), - (ConversationsClient, transports.ConversationsRestTransport, "rest", "true"), - (ConversationsClient, transports.ConversationsRestTransport, "rest", "false"), -]) -@mock.patch.object(ConversationsClient, "DEFAULT_ENDPOINT", modify_default_endpoint(ConversationsClient)) -@mock.patch.object(ConversationsAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(ConversationsAsyncClient)) -@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) -def test_conversations_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, transport=transport_name) - - if use_client_cert_env == "false": - expected_client_cert_source = None - expected_host = client.DEFAULT_ENDPOINT - else: - expected_client_cert_source = client_cert_source_callback - expected_host = client.DEFAULT_MTLS_ENDPOINT - - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=expected_host, - scopes=None, - client_cert_source_for_mtls=expected_client_cert_source, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case ADC client cert is provided. Whether client cert is used depends on - # GOOGLE_API_USE_CLIENT_CERTIFICATE value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): - with mock.patch.object(transport_class, '__init__') as patched: - with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): - with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=client_cert_source_callback): - if use_client_cert_env == "false": - expected_host = client.DEFAULT_ENDPOINT - expected_client_cert_source = None - else: - expected_host = client.DEFAULT_MTLS_ENDPOINT - expected_client_cert_source = client_cert_source_callback - - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=expected_host, - scopes=None, - client_cert_source_for_mtls=expected_client_cert_source, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case client_cert_source and ADC client cert are not provided. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): - with mock.patch.object(transport_class, '__init__') as patched: - with mock.patch("google.auth.transport.mtls.has_default_client_cert_source", return_value=False): - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - -@pytest.mark.parametrize("client_class", [ - ConversationsClient, ConversationsAsyncClient -]) -@mock.patch.object(ConversationsClient, "DEFAULT_ENDPOINT", modify_default_endpoint(ConversationsClient)) -@mock.patch.object(ConversationsAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(ConversationsAsyncClient)) -def test_conversations_client_get_mtls_endpoint_and_cert_source(client_class): - mock_client_cert_source = mock.Mock() - - # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "true". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - mock_api_endpoint = "foo" - options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) - assert api_endpoint == mock_api_endpoint - assert cert_source == mock_client_cert_source - - # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "false". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): - mock_client_cert_source = mock.Mock() - mock_api_endpoint = "foo" - options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) - assert api_endpoint == mock_api_endpoint - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "never". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_ENDPOINT - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "always". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert doesn't exist. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=False): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_ENDPOINT - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert exists. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - 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=mock_client_cert_source): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT - assert cert_source == mock_client_cert_source - - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (ConversationsClient, transports.ConversationsGrpcTransport, "grpc"), - (ConversationsAsyncClient, transports.ConversationsGrpcAsyncIOTransport, "grpc_asyncio"), - (ConversationsClient, transports.ConversationsRestTransport, "rest"), -]) -def test_conversations_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, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=["1", "2"], - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - -@pytest.mark.parametrize("client_class,transport_class,transport_name,grpc_helpers", [ - (ConversationsClient, transports.ConversationsGrpcTransport, "grpc", grpc_helpers), - (ConversationsAsyncClient, transports.ConversationsGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), - (ConversationsClient, transports.ConversationsRestTransport, "rest", None), -]) -def test_conversations_client_client_options_credentials_file(client_class, transport_class, transport_name, grpc_helpers): - # 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, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file="credentials.json", - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - -def test_conversations_client_client_options_from_dict(): - with mock.patch('google.cloud.dialogflow_v2beta1.services.conversations.transports.ConversationsGrpcTransport.__init__') as grpc_transport: - grpc_transport.return_value = None - client = ConversationsClient( - client_options={'api_endpoint': 'squid.clam.whelk'} - ) - grpc_transport.assert_called_once_with( - credentials=None, - credentials_file=None, - host="squid.clam.whelk", - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - -@pytest.mark.parametrize("client_class,transport_class,transport_name,grpc_helpers", [ - (ConversationsClient, transports.ConversationsGrpcTransport, "grpc", grpc_helpers), - (ConversationsAsyncClient, transports.ConversationsGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), -]) -def test_conversations_client_create_channel_credentials_file(client_class, transport_class, transport_name, grpc_helpers): - # 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, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file="credentials.json", - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # test that the credentials from file are saved and used as the credentials. - with mock.patch.object( - google.auth, "load_credentials_from_file", autospec=True - ) as load_creds, mock.patch.object( - google.auth, "default", autospec=True - ) as adc, mock.patch.object( - grpc_helpers, "create_channel" - ) as create_channel: - creds = ga_credentials.AnonymousCredentials() - file_creds = ga_credentials.AnonymousCredentials() - load_creds.return_value = (file_creds, None) - adc.return_value = (creds, None) - client = client_class(client_options=options, transport=transport_name) - create_channel.assert_called_with( - "dialogflow.googleapis.com:443", - credentials=file_creds, - credentials_file=None, - quota_project_id=None, - default_scopes=( - 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/dialogflow', -), - scopes=None, - default_host="dialogflow.googleapis.com", - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - -@pytest.mark.parametrize("request_type", [ - gcd_conversation.CreateConversationRequest, - dict, -]) -def test_create_conversation(request_type, transport: str = 'grpc'): - client = ConversationsClient( - 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_conversation), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcd_conversation.Conversation( - name='name_value', - lifecycle_state=gcd_conversation.Conversation.LifecycleState.IN_PROGRESS, - 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 - - -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=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_conversation), - '__call__') as call: - client.create_conversation() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == gcd_conversation.CreateConversationRequest() - -@pytest.mark.asyncio -async def test_create_conversation_async(transport: str = 'grpc_asyncio', request_type=gcd_conversation.CreateConversationRequest): - client = ConversationsAsyncClient( - 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_conversation), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gcd_conversation.Conversation( - name='name_value', - lifecycle_state=gcd_conversation.Conversation.LifecycleState.IN_PROGRESS, - conversation_profile='conversation_profile_value', - 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 - - -@pytest.mark.asyncio -async def test_create_conversation_async_from_dict(): - await test_create_conversation_async(request_type=dict) - - -def test_create_conversation_field_headers(): - 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. - with mock.patch.object( - 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. - 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_conversation_field_headers_async(): - 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. - with mock.patch.object( - type(client.transport.create_conversation), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcd_conversation.Conversation()) - 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] == 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_conversation_flattened(): - 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.create_conversation), - '__call__') 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( - parent='parent_value', - conversation=gcd_conversation.Conversation(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] - arg = args[0].parent - mock_val = 'parent_value' - assert arg == mock_val - arg = args[0].conversation - mock_val = gcd_conversation.Conversation(name='name_value') - assert arg == mock_val - - -def test_create_conversation_flattened_error(): - client = ConversationsClient( - 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_conversation( - gcd_conversation.CreateConversationRequest(), - parent='parent_value', - conversation=gcd_conversation.Conversation(name='name_value'), - ) - -@pytest.mark.asyncio -async def test_create_conversation_flattened_async(): - 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.create_conversation), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcd_conversation.Conversation() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcd_conversation.Conversation()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.create_conversation( - parent='parent_value', - conversation=gcd_conversation.Conversation(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] - arg = args[0].parent - mock_val = 'parent_value' - assert arg == mock_val - arg = args[0].conversation - mock_val = gcd_conversation.Conversation(name='name_value') - assert arg == mock_val - -@pytest.mark.asyncio -async def test_create_conversation_flattened_error_async(): - client = ConversationsAsyncClient( - 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_conversation( - gcd_conversation.CreateConversationRequest(), - parent='parent_value', - conversation=gcd_conversation.Conversation(name='name_value'), - ) - - -@pytest.mark.parametrize("request_type", [ - conversation.ListConversationsRequest, - dict, -]) -def test_list_conversations(request_type, transport: str = 'grpc'): - client = ConversationsClient( - 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_conversations), - '__call__') as call: - # Designate an appropriate return value for the call. - 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' - - -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=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_conversations), - '__call__') as call: - client.list_conversations() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == conversation.ListConversationsRequest() - -@pytest.mark.asyncio -async def test_list_conversations_async(transport: str = 'grpc_asyncio', request_type=conversation.ListConversationsRequest): - client = ConversationsAsyncClient( - 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_conversations), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(conversation.ListConversationsResponse( - 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' - - -@pytest.mark.asyncio -async def test_list_conversations_async_from_dict(): - await test_list_conversations_async(request_type=dict) - - -def test_list_conversations_field_headers(): - 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. - with mock.patch.object( - 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. - 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_conversations_field_headers_async(): - 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. - with mock.patch.object( - type(client.transport.list_conversations), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(conversation.ListConversationsResponse()) - 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] == 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_conversations_flattened(): - 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_conversations), - '__call__') 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', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - arg = args[0].parent - mock_val = 'parent_value' - assert arg == mock_val - - -def test_list_conversations_flattened_error(): - client = ConversationsClient( - 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_conversations( - conversation.ListConversationsRequest(), - parent='parent_value', - ) - -@pytest.mark.asyncio -async def test_list_conversations_flattened_async(): - 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_conversations), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = conversation.ListConversationsResponse() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(conversation.ListConversationsResponse()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.list_conversations( - 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] - arg = args[0].parent - mock_val = 'parent_value' - assert arg == mock_val - -@pytest.mark.asyncio -async def test_list_conversations_flattened_error_async(): - client = ConversationsAsyncClient( - 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_conversations( - conversation.ListConversationsRequest(), - parent='parent_value', - ) - - -def test_list_conversations_pager(transport_name: str = "grpc"): - client = ConversationsClient( - credentials=ga_credentials.AnonymousCredentials, - transport=transport_name, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_conversations), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - conversation.ListConversationsResponse( - conversations=[ - conversation.Conversation(), - conversation.Conversation(), - conversation.Conversation(), - ], - next_page_token='abc', - ), - conversation.ListConversationsResponse( - conversations=[], - next_page_token='def', - ), - conversation.ListConversationsResponse( - conversations=[ - conversation.Conversation(), - ], - next_page_token='ghi', - ), - conversation.ListConversationsResponse( - conversations=[ - conversation.Conversation(), - conversation.Conversation(), - ], - ), - RuntimeError, - ) - - metadata = () - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ('parent', ''), - )), - ) - pager = client.list_conversations(request={}) - - assert pager._metadata == metadata - - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, conversation.Conversation) - for i in results) -def test_list_conversations_pages(transport_name: str = "grpc"): - client = ConversationsClient( - credentials=ga_credentials.AnonymousCredentials, - transport=transport_name, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_conversations), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - conversation.ListConversationsResponse( - conversations=[ - conversation.Conversation(), - conversation.Conversation(), - conversation.Conversation(), - ], - next_page_token='abc', - ), - conversation.ListConversationsResponse( - conversations=[], - next_page_token='def', - ), - conversation.ListConversationsResponse( - conversations=[ - conversation.Conversation(), - ], - next_page_token='ghi', - ), - conversation.ListConversationsResponse( - conversations=[ - conversation.Conversation(), - conversation.Conversation(), - ], - ), - RuntimeError, - ) - pages = list(client.list_conversations(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_conversations_async_pager(): - 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_conversations), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - conversation.ListConversationsResponse( - conversations=[ - conversation.Conversation(), - conversation.Conversation(), - conversation.Conversation(), - ], - next_page_token='abc', - ), - conversation.ListConversationsResponse( - conversations=[], - next_page_token='def', - ), - conversation.ListConversationsResponse( - conversations=[ - conversation.Conversation(), - ], - next_page_token='ghi', - ), - conversation.ListConversationsResponse( - conversations=[ - conversation.Conversation(), - conversation.Conversation(), - ], - ), - RuntimeError, - ) - async_pager = await client.list_conversations(request={},) - assert async_pager.next_page_token == 'abc' - responses = [] - async for response in async_pager: # pragma: no branch - responses.append(response) - - assert len(responses) == 6 - assert all(isinstance(i, conversation.Conversation) - for i in responses) - - -@pytest.mark.asyncio -async def test_list_conversations_async_pages(): - 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_conversations), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - conversation.ListConversationsResponse( - conversations=[ - conversation.Conversation(), - conversation.Conversation(), - conversation.Conversation(), - ], - next_page_token='abc', - ), - conversation.ListConversationsResponse( - conversations=[], - next_page_token='def', - ), - conversation.ListConversationsResponse( - conversations=[ - conversation.Conversation(), - ], - next_page_token='ghi', - ), - conversation.ListConversationsResponse( - conversations=[ - conversation.Conversation(), - conversation.Conversation(), - ], - ), - RuntimeError, - ) - pages = [] - async for page_ in (await client.list_conversations(request={})).pages: # pragma: no branch - pages.append(page_) - for page_, token in zip(pages, ['abc','def','ghi', '']): - assert page_.raw_page.next_page_token == token - -@pytest.mark.parametrize("request_type", [ - conversation.GetConversationRequest, - dict, -]) -def test_get_conversation(request_type, transport: str = 'grpc'): - client = ConversationsClient( - 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_conversation), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = conversation.Conversation( - name='name_value', - lifecycle_state=conversation.Conversation.LifecycleState.IN_PROGRESS, - 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 - - -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=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_conversation), - '__call__') as call: - client.get_conversation() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == conversation.GetConversationRequest() - -@pytest.mark.asyncio -async def test_get_conversation_async(transport: str = 'grpc_asyncio', request_type=conversation.GetConversationRequest): - client = ConversationsAsyncClient( - 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_conversation), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(conversation.Conversation( - name='name_value', - lifecycle_state=conversation.Conversation.LifecycleState.IN_PROGRESS, - conversation_profile='conversation_profile_value', - 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 - - -@pytest.mark.asyncio -async def test_get_conversation_async_from_dict(): - await test_get_conversation_async(request_type=dict) - - -def test_get_conversation_field_headers(): - 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. - 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_conversation_field_headers_async(): - 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. - with mock.patch.object( - type(client.transport.get_conversation), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(conversation.Conversation()) - 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] == 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_conversation_flattened(): - 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', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - arg = args[0].name - mock_val = 'name_value' - assert arg == mock_val - - -def test_get_conversation_flattened_error(): - client = ConversationsClient( - 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_conversation( - conversation.GetConversationRequest(), - name='name_value', - ) - -@pytest.mark.asyncio -async def test_get_conversation_flattened_async(): - 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: - # Designate an appropriate return value for the call. - call.return_value = conversation.Conversation() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(conversation.Conversation()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.get_conversation( - 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] - arg = args[0].name - mock_val = 'name_value' - assert arg == mock_val - -@pytest.mark.asyncio -async def test_get_conversation_flattened_error_async(): - client = ConversationsAsyncClient( - 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_conversation( - conversation.GetConversationRequest(), - name='name_value', - ) - - -@pytest.mark.parametrize("request_type", [ - conversation.CompleteConversationRequest, - dict, -]) -def test_complete_conversation(request_type, transport: str = 'grpc'): - client = ConversationsClient( - 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.complete_conversation), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = conversation.Conversation( - name='name_value', - lifecycle_state=conversation.Conversation.LifecycleState.IN_PROGRESS, - 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 - - -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=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.complete_conversation), - '__call__') as call: - client.complete_conversation() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == conversation.CompleteConversationRequest() - -@pytest.mark.asyncio -async def test_complete_conversation_async(transport: str = 'grpc_asyncio', request_type=conversation.CompleteConversationRequest): - client = ConversationsAsyncClient( - 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.complete_conversation), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(conversation.Conversation( - name='name_value', - lifecycle_state=conversation.Conversation.LifecycleState.IN_PROGRESS, - conversation_profile='conversation_profile_value', - 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 - - -@pytest.mark.asyncio -async def test_complete_conversation_async_from_dict(): - await test_complete_conversation_async(request_type=dict) - - -def test_complete_conversation_field_headers(): - 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. - with mock.patch.object( - 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. - 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_complete_conversation_field_headers_async(): - 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. - with mock.patch.object( - type(client.transport.complete_conversation), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(conversation.Conversation()) - 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] == 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_complete_conversation_flattened(): - 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.complete_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.complete_conversation( - 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] - arg = args[0].name - mock_val = 'name_value' - assert arg == mock_val - - -def test_complete_conversation_flattened_error(): - client = ConversationsClient( - 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.complete_conversation( - conversation.CompleteConversationRequest(), - name='name_value', - ) - -@pytest.mark.asyncio -async def test_complete_conversation_flattened_async(): - 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.complete_conversation), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = conversation.Conversation() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(conversation.Conversation()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.complete_conversation( - 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] - arg = args[0].name - mock_val = 'name_value' - assert arg == mock_val - -@pytest.mark.asyncio -async def test_complete_conversation_flattened_error_async(): - client = ConversationsAsyncClient( - 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.complete_conversation( - conversation.CompleteConversationRequest(), - name='name_value', - ) - - -@pytest.mark.parametrize("request_type", [ - conversation.BatchCreateMessagesRequest, - dict, -]) -def test_batch_create_messages(request_type, transport: str = 'grpc'): - client = ConversationsClient( - 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.batch_create_messages), - '__call__') 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) - - -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=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.batch_create_messages), - '__call__') as call: - client.batch_create_messages() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == conversation.BatchCreateMessagesRequest() - -@pytest.mark.asyncio -async def test_batch_create_messages_async(transport: str = 'grpc_asyncio', request_type=conversation.BatchCreateMessagesRequest): - client = ConversationsAsyncClient( - 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.batch_create_messages), - '__call__') as call: - # Designate an appropriate return value for the call. - 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. - assert isinstance(response, conversation.BatchCreateMessagesResponse) - - -@pytest.mark.asyncio -async def test_batch_create_messages_async_from_dict(): - await test_batch_create_messages_async(request_type=dict) - - -def test_batch_create_messages_field_headers(): - 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. - with mock.patch.object( - 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. - 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_batch_create_messages_field_headers_async(): - 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. - with mock.patch.object( - type(client.transport.batch_create_messages), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(conversation.BatchCreateMessagesResponse()) - 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] == 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_batch_create_messages_flattened(): - 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.batch_create_messages), - '__call__') 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', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - arg = args[0].parent - mock_val = 'parent_value' - assert arg == mock_val - - -def test_batch_create_messages_flattened_error(): - client = ConversationsClient( - 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.batch_create_messages( - conversation.BatchCreateMessagesRequest(), - parent='parent_value', - ) - -@pytest.mark.asyncio -async def test_batch_create_messages_flattened_async(): - 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.batch_create_messages), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = conversation.BatchCreateMessagesResponse() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(conversation.BatchCreateMessagesResponse()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.batch_create_messages( - 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] - arg = args[0].parent - mock_val = 'parent_value' - assert arg == mock_val - -@pytest.mark.asyncio -async def test_batch_create_messages_flattened_error_async(): - client = ConversationsAsyncClient( - 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.batch_create_messages( - conversation.BatchCreateMessagesRequest(), - parent='parent_value', - ) - - -@pytest.mark.parametrize("request_type", [ - conversation.ListMessagesRequest, - dict, -]) -def test_list_messages(request_type, transport: str = 'grpc'): - client = ConversationsClient( - 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_messages), - '__call__') as call: - # Designate an appropriate return value for the call. - 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' - - -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=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_messages), - '__call__') as call: - client.list_messages() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == conversation.ListMessagesRequest() - -@pytest.mark.asyncio -async def test_list_messages_async(transport: str = 'grpc_asyncio', request_type=conversation.ListMessagesRequest): - client = ConversationsAsyncClient( - 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_messages), - '__call__') as call: - # Designate an appropriate return value for the call. - 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' - - -@pytest.mark.asyncio -async def test_list_messages_async_from_dict(): - await test_list_messages_async(request_type=dict) - - -def test_list_messages_field_headers(): - 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. - 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_messages_field_headers_async(): - 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. - with mock.patch.object( - type(client.transport.list_messages), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(conversation.ListMessagesResponse()) - 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] == 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_messages_flattened(): - 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', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - arg = args[0].parent - mock_val = 'parent_value' - assert arg == mock_val - - -def test_list_messages_flattened_error(): - client = ConversationsClient( - 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_messages( - conversation.ListMessagesRequest(), - parent='parent_value', - ) - -@pytest.mark.asyncio -async def test_list_messages_flattened_async(): - 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: - # Designate an appropriate return value for the call. - call.return_value = conversation.ListMessagesResponse() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(conversation.ListMessagesResponse()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.list_messages( - 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] - arg = args[0].parent - mock_val = 'parent_value' - assert arg == mock_val - -@pytest.mark.asyncio -async def test_list_messages_flattened_error_async(): - client = ConversationsAsyncClient( - 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_messages( - conversation.ListMessagesRequest(), - parent='parent_value', - ) - - -def test_list_messages_pager(transport_name: str = "grpc"): - client = ConversationsClient( - credentials=ga_credentials.AnonymousCredentials, - transport=transport_name, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_messages), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - conversation.ListMessagesResponse( - messages=[ - participant.Message(), - participant.Message(), - participant.Message(), - ], - next_page_token='abc', - ), - conversation.ListMessagesResponse( - messages=[], - next_page_token='def', - ), - conversation.ListMessagesResponse( - messages=[ - participant.Message(), - ], - next_page_token='ghi', - ), - conversation.ListMessagesResponse( - messages=[ - participant.Message(), - participant.Message(), - ], - ), - RuntimeError, - ) - - metadata = () - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ('parent', ''), - )), - ) - pager = client.list_messages(request={}) - - assert pager._metadata == metadata - - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, participant.Message) - for i in results) -def test_list_messages_pages(transport_name: str = "grpc"): - client = ConversationsClient( - credentials=ga_credentials.AnonymousCredentials, - transport=transport_name, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_messages), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - conversation.ListMessagesResponse( - messages=[ - participant.Message(), - participant.Message(), - participant.Message(), - ], - next_page_token='abc', - ), - conversation.ListMessagesResponse( - messages=[], - next_page_token='def', - ), - conversation.ListMessagesResponse( - messages=[ - participant.Message(), - ], - next_page_token='ghi', - ), - conversation.ListMessagesResponse( - messages=[ - participant.Message(), - participant.Message(), - ], - ), - RuntimeError, - ) - pages = list(client.list_messages(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_messages_async_pager(): - 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__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - conversation.ListMessagesResponse( - messages=[ - participant.Message(), - participant.Message(), - participant.Message(), - ], - next_page_token='abc', - ), - conversation.ListMessagesResponse( - messages=[], - next_page_token='def', - ), - conversation.ListMessagesResponse( - messages=[ - participant.Message(), - ], - next_page_token='ghi', - ), - conversation.ListMessagesResponse( - messages=[ - participant.Message(), - participant.Message(), - ], - ), - RuntimeError, - ) - async_pager = await client.list_messages(request={},) - assert async_pager.next_page_token == 'abc' - responses = [] - async for response in async_pager: # pragma: no branch - responses.append(response) - - assert len(responses) == 6 - assert all(isinstance(i, participant.Message) - for i in responses) - - -@pytest.mark.asyncio -async def test_list_messages_async_pages(): - 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__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - conversation.ListMessagesResponse( - messages=[ - participant.Message(), - participant.Message(), - participant.Message(), - ], - next_page_token='abc', - ), - conversation.ListMessagesResponse( - messages=[], - next_page_token='def', - ), - conversation.ListMessagesResponse( - messages=[ - participant.Message(), - ], - next_page_token='ghi', - ), - conversation.ListMessagesResponse( - messages=[ - participant.Message(), - participant.Message(), - ], - ), - RuntimeError, - ) - pages = [] - async for page_ in (await client.list_messages(request={})).pages: # pragma: no branch - pages.append(page_) - for page_, token in zip(pages, ['abc','def','ghi', '']): - assert page_.raw_page.next_page_token == token - -@pytest.mark.parametrize("request_type", [ - gcd_conversation.SuggestConversationSummaryRequest, - dict, -]) -def test_suggest_conversation_summary(request_type, transport: str = 'grpc'): - client = ConversationsClient( - 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.suggest_conversation_summary), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcd_conversation.SuggestConversationSummaryResponse( - latest_message='latest_message_value', - context_size=1311, - ) - response = client.suggest_conversation_summary(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.SuggestConversationSummaryRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, gcd_conversation.SuggestConversationSummaryResponse) - assert response.latest_message == 'latest_message_value' - assert response.context_size == 1311 - - -def test_suggest_conversation_summary_empty_call(): - # 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=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.suggest_conversation_summary), - '__call__') as call: - client.suggest_conversation_summary() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == gcd_conversation.SuggestConversationSummaryRequest() - -@pytest.mark.asyncio -async def test_suggest_conversation_summary_async(transport: str = 'grpc_asyncio', request_type=gcd_conversation.SuggestConversationSummaryRequest): - client = ConversationsAsyncClient( - 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.suggest_conversation_summary), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gcd_conversation.SuggestConversationSummaryResponse( - latest_message='latest_message_value', - context_size=1311, - )) - response = await client.suggest_conversation_summary(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.SuggestConversationSummaryRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, gcd_conversation.SuggestConversationSummaryResponse) - assert response.latest_message == 'latest_message_value' - assert response.context_size == 1311 - - -@pytest.mark.asyncio -async def test_suggest_conversation_summary_async_from_dict(): - await test_suggest_conversation_summary_async(request_type=dict) - - -def test_suggest_conversation_summary_field_headers(): - 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.SuggestConversationSummaryRequest() - - request.conversation = 'conversation_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.suggest_conversation_summary), - '__call__') as call: - call.return_value = gcd_conversation.SuggestConversationSummaryResponse() - client.suggest_conversation_summary(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', - 'conversation=conversation_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_suggest_conversation_summary_field_headers_async(): - 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.SuggestConversationSummaryRequest() - - request.conversation = 'conversation_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.suggest_conversation_summary), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcd_conversation.SuggestConversationSummaryResponse()) - await client.suggest_conversation_summary(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', - 'conversation=conversation_value', - ) in kw['metadata'] - - -def test_suggest_conversation_summary_flattened(): - 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.suggest_conversation_summary), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcd_conversation.SuggestConversationSummaryResponse() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.suggest_conversation_summary( - conversation='conversation_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] - arg = args[0].conversation - mock_val = 'conversation_value' - assert arg == mock_val - - -def test_suggest_conversation_summary_flattened_error(): - client = ConversationsClient( - 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.suggest_conversation_summary( - gcd_conversation.SuggestConversationSummaryRequest(), - conversation='conversation_value', - ) - -@pytest.mark.asyncio -async def test_suggest_conversation_summary_flattened_async(): - 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.suggest_conversation_summary), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcd_conversation.SuggestConversationSummaryResponse() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcd_conversation.SuggestConversationSummaryResponse()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.suggest_conversation_summary( - conversation='conversation_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - arg = args[0].conversation - mock_val = 'conversation_value' - assert arg == mock_val - -@pytest.mark.asyncio -async def test_suggest_conversation_summary_flattened_error_async(): - client = ConversationsAsyncClient( - 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.suggest_conversation_summary( - gcd_conversation.SuggestConversationSummaryRequest(), - conversation='conversation_value', - ) - - -@pytest.mark.parametrize("request_type", [ - gcd_conversation.CreateConversationRequest, - dict, -]) -def test_create_conversation_rest(request_type): - client = ConversationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1'} - request_init["conversation"] = {'name': 'name_value', 'lifecycle_state': 1, 'conversation_profile': 'conversation_profile_value', 'phone_number': {'phone_number': 'phone_number_value'}, 'conversation_stage': 1, 'start_time': {'seconds': 751, 'nanos': 543}, 'end_time': {}} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = gcd_conversation.Conversation( - name='name_value', - lifecycle_state=gcd_conversation.Conversation.LifecycleState.IN_PROGRESS, - conversation_profile='conversation_profile_value', - conversation_stage=gcd_conversation.Conversation.ConversationStage.VIRTUAL_AGENT_STAGE, - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - pb_return_value = gcd_conversation.Conversation.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.create_conversation(request) - - # 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 - - -def test_create_conversation_rest_required_fields(request_type=gcd_conversation.CreateConversationRequest): - transport_class = transports.ConversationsRestTransport - - request_init = {} - request_init["parent"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - including_default_value_fields=False, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_conversation._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["parent"] = 'parent_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_conversation._get_unset_required_fields(jsonified_request) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("conversation_id", )) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "parent" in jsonified_request - assert jsonified_request["parent"] == 'parent_value' - - client = ConversationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = gcd_conversation.Conversation() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "post", - 'query_params': pb_request, - } - transcode_result['body'] = pb_request - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - - pb_return_value = gcd_conversation.Conversation.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.create_conversation(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_create_conversation_rest_unset_required_fields(): - transport = transports.ConversationsRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.create_conversation._get_unset_required_fields({}) - assert set(unset_fields) == (set(("conversationId", )) & set(("parent", "conversation", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_create_conversation_rest_interceptors(null_interceptor): - transport = transports.ConversationsRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.ConversationsRestInterceptor(), - ) - client = ConversationsClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.ConversationsRestInterceptor, "post_create_conversation") as post, \ - mock.patch.object(transports.ConversationsRestInterceptor, "pre_create_conversation") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = gcd_conversation.CreateConversationRequest.pb(gcd_conversation.CreateConversationRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = gcd_conversation.Conversation.to_json(gcd_conversation.Conversation()) - - request = gcd_conversation.CreateConversationRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = gcd_conversation.Conversation() - - client.create_conversation(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_create_conversation_rest_bad_request(transport: str = 'rest', request_type=gcd_conversation.CreateConversationRequest): - client = ConversationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1'} - request_init["conversation"] = {'name': 'name_value', 'lifecycle_state': 1, 'conversation_profile': 'conversation_profile_value', 'phone_number': {'phone_number': 'phone_number_value'}, 'conversation_stage': 1, 'start_time': {'seconds': 751, 'nanos': 543}, 'end_time': {}} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.create_conversation(request) - - -def test_create_conversation_rest_flattened(): - client = ConversationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = gcd_conversation.Conversation() - - # get arguments that satisfy an http rule for this method - sample_request = {'parent': 'projects/sample1'} - - # get truthy value for each flattened field - mock_args = dict( - parent='parent_value', - conversation=gcd_conversation.Conversation(name='name_value'), - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - pb_return_value = gcd_conversation.Conversation.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.create_conversation(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v2beta1/{parent=projects/*}/conversations" % client.transport._host, args[1]) - - -def test_create_conversation_rest_flattened_error(transport: str = 'rest'): - client = ConversationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.create_conversation( - gcd_conversation.CreateConversationRequest(), - parent='parent_value', - conversation=gcd_conversation.Conversation(name='name_value'), - ) - - -def test_create_conversation_rest_error(): - client = ConversationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - conversation.ListConversationsRequest, - dict, -]) -def test_list_conversations_rest(request_type): - client = ConversationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = conversation.ListConversationsResponse( - next_page_token='next_page_token_value', - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - pb_return_value = conversation.ListConversationsResponse.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.list_conversations(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListConversationsPager) - assert response.next_page_token == 'next_page_token_value' - - -def test_list_conversations_rest_required_fields(request_type=conversation.ListConversationsRequest): - transport_class = transports.ConversationsRestTransport - - request_init = {} - request_init["parent"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - including_default_value_fields=False, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).list_conversations._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["parent"] = 'parent_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).list_conversations._get_unset_required_fields(jsonified_request) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("filter", "page_size", "page_token", )) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "parent" in jsonified_request - assert jsonified_request["parent"] == 'parent_value' - - client = ConversationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = conversation.ListConversationsResponse() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "get", - 'query_params': pb_request, - } - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - - pb_return_value = conversation.ListConversationsResponse.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.list_conversations(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_list_conversations_rest_unset_required_fields(): - transport = transports.ConversationsRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.list_conversations._get_unset_required_fields({}) - assert set(unset_fields) == (set(("filter", "pageSize", "pageToken", )) & set(("parent", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_list_conversations_rest_interceptors(null_interceptor): - transport = transports.ConversationsRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.ConversationsRestInterceptor(), - ) - client = ConversationsClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.ConversationsRestInterceptor, "post_list_conversations") as post, \ - mock.patch.object(transports.ConversationsRestInterceptor, "pre_list_conversations") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = conversation.ListConversationsRequest.pb(conversation.ListConversationsRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = conversation.ListConversationsResponse.to_json(conversation.ListConversationsResponse()) - - request = conversation.ListConversationsRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = conversation.ListConversationsResponse() - - client.list_conversations(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_list_conversations_rest_bad_request(transport: str = 'rest', request_type=conversation.ListConversationsRequest): - client = ConversationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.list_conversations(request) - - -def test_list_conversations_rest_flattened(): - client = ConversationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = conversation.ListConversationsResponse() - - # get arguments that satisfy an http rule for this method - sample_request = {'parent': 'projects/sample1'} - - # get truthy value for each flattened field - mock_args = dict( - parent='parent_value', - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - pb_return_value = conversation.ListConversationsResponse.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.list_conversations(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v2beta1/{parent=projects/*}/conversations" % client.transport._host, args[1]) - - -def test_list_conversations_rest_flattened_error(transport: str = 'rest'): - client = ConversationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.list_conversations( - conversation.ListConversationsRequest(), - parent='parent_value', - ) - - -def test_list_conversations_rest_pager(transport: str = 'rest'): - client = ConversationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # TODO(kbandes): remove this mock unless there's a good reason for it. - #with mock.patch.object(path_template, 'transcode') as transcode: - # Set the response as a series of pages - response = ( - conversation.ListConversationsResponse( - conversations=[ - conversation.Conversation(), - conversation.Conversation(), - conversation.Conversation(), - ], - next_page_token='abc', - ), - conversation.ListConversationsResponse( - conversations=[], - next_page_token='def', - ), - conversation.ListConversationsResponse( - conversations=[ - conversation.Conversation(), - ], - next_page_token='ghi', - ), - conversation.ListConversationsResponse( - conversations=[ - conversation.Conversation(), - conversation.Conversation(), - ], - ), - ) - # Two responses for two calls - response = response + response - - # Wrap the values into proper Response objs - response = tuple(conversation.ListConversationsResponse.to_json(x) for x in response) - return_values = tuple(Response() for i in response) - for return_val, response_val in zip(return_values, response): - return_val._content = response_val.encode('UTF-8') - return_val.status_code = 200 - req.side_effect = return_values - - sample_request = {'parent': 'projects/sample1'} - - pager = client.list_conversations(request=sample_request) - - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, conversation.Conversation) - for i in results) - - pages = list(client.list_conversations(request=sample_request).pages) - for page_, token in zip(pages, ['abc','def','ghi', '']): - assert page_.raw_page.next_page_token == token - - -@pytest.mark.parametrize("request_type", [ - conversation.GetConversationRequest, - dict, -]) -def test_get_conversation_rest(request_type): - client = ConversationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/conversations/sample2'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = conversation.Conversation( - name='name_value', - lifecycle_state=conversation.Conversation.LifecycleState.IN_PROGRESS, - conversation_profile='conversation_profile_value', - conversation_stage=conversation.Conversation.ConversationStage.VIRTUAL_AGENT_STAGE, - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - pb_return_value = conversation.Conversation.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.get_conversation(request) - - # 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 - - -def test_get_conversation_rest_required_fields(request_type=conversation.GetConversationRequest): - transport_class = transports.ConversationsRestTransport - - request_init = {} - request_init["name"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - including_default_value_fields=False, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_conversation._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["name"] = 'name_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_conversation._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "name" in jsonified_request - assert jsonified_request["name"] == 'name_value' - - client = ConversationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = conversation.Conversation() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "get", - 'query_params': pb_request, - } - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - - pb_return_value = conversation.Conversation.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.get_conversation(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_get_conversation_rest_unset_required_fields(): - transport = transports.ConversationsRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.get_conversation._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_get_conversation_rest_interceptors(null_interceptor): - transport = transports.ConversationsRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.ConversationsRestInterceptor(), - ) - client = ConversationsClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.ConversationsRestInterceptor, "post_get_conversation") as post, \ - mock.patch.object(transports.ConversationsRestInterceptor, "pre_get_conversation") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = conversation.GetConversationRequest.pb(conversation.GetConversationRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = conversation.Conversation.to_json(conversation.Conversation()) - - request = conversation.GetConversationRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = conversation.Conversation() - - client.get_conversation(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_get_conversation_rest_bad_request(transport: str = 'rest', request_type=conversation.GetConversationRequest): - client = ConversationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/conversations/sample2'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.get_conversation(request) - - -def test_get_conversation_rest_flattened(): - client = ConversationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = conversation.Conversation() - - # get arguments that satisfy an http rule for this method - sample_request = {'name': 'projects/sample1/conversations/sample2'} - - # get truthy value for each flattened field - mock_args = dict( - name='name_value', - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - pb_return_value = conversation.Conversation.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.get_conversation(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v2beta1/{name=projects/*/conversations/*}" % client.transport._host, args[1]) - - -def test_get_conversation_rest_flattened_error(transport: str = 'rest'): - client = ConversationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.get_conversation( - conversation.GetConversationRequest(), - name='name_value', - ) - - -def test_get_conversation_rest_error(): - client = ConversationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - conversation.CompleteConversationRequest, - dict, -]) -def test_complete_conversation_rest(request_type): - client = ConversationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/conversations/sample2'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = conversation.Conversation( - name='name_value', - lifecycle_state=conversation.Conversation.LifecycleState.IN_PROGRESS, - conversation_profile='conversation_profile_value', - conversation_stage=conversation.Conversation.ConversationStage.VIRTUAL_AGENT_STAGE, - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - pb_return_value = conversation.Conversation.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.complete_conversation(request) - - # 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 - - -def test_complete_conversation_rest_required_fields(request_type=conversation.CompleteConversationRequest): - transport_class = transports.ConversationsRestTransport - - request_init = {} - request_init["name"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - including_default_value_fields=False, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).complete_conversation._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["name"] = 'name_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).complete_conversation._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "name" in jsonified_request - assert jsonified_request["name"] == 'name_value' - - client = ConversationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = conversation.Conversation() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "post", - 'query_params': pb_request, - } - transcode_result['body'] = pb_request - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - - pb_return_value = conversation.Conversation.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.complete_conversation(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_complete_conversation_rest_unset_required_fields(): - transport = transports.ConversationsRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.complete_conversation._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_complete_conversation_rest_interceptors(null_interceptor): - transport = transports.ConversationsRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.ConversationsRestInterceptor(), - ) - client = ConversationsClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.ConversationsRestInterceptor, "post_complete_conversation") as post, \ - mock.patch.object(transports.ConversationsRestInterceptor, "pre_complete_conversation") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = conversation.CompleteConversationRequest.pb(conversation.CompleteConversationRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = conversation.Conversation.to_json(conversation.Conversation()) - - request = conversation.CompleteConversationRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = conversation.Conversation() - - client.complete_conversation(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_complete_conversation_rest_bad_request(transport: str = 'rest', request_type=conversation.CompleteConversationRequest): - client = ConversationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/conversations/sample2'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.complete_conversation(request) - - -def test_complete_conversation_rest_flattened(): - client = ConversationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = conversation.Conversation() - - # get arguments that satisfy an http rule for this method - sample_request = {'name': 'projects/sample1/conversations/sample2'} - - # get truthy value for each flattened field - mock_args = dict( - name='name_value', - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - pb_return_value = conversation.Conversation.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.complete_conversation(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v2beta1/{name=projects/*/conversations/*}:complete" % client.transport._host, args[1]) - - -def test_complete_conversation_rest_flattened_error(transport: str = 'rest'): - client = ConversationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.complete_conversation( - conversation.CompleteConversationRequest(), - name='name_value', - ) - - -def test_complete_conversation_rest_error(): - client = ConversationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - conversation.BatchCreateMessagesRequest, - dict, -]) -def test_batch_create_messages_rest(request_type): - client = ConversationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1/conversations/sample2'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = conversation.BatchCreateMessagesResponse( - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - pb_return_value = conversation.BatchCreateMessagesResponse.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.batch_create_messages(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, conversation.BatchCreateMessagesResponse) - - -def test_batch_create_messages_rest_required_fields(request_type=conversation.BatchCreateMessagesRequest): - transport_class = transports.ConversationsRestTransport - - request_init = {} - request_init["parent"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - including_default_value_fields=False, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).batch_create_messages._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["parent"] = 'parent_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).batch_create_messages._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "parent" in jsonified_request - assert jsonified_request["parent"] == 'parent_value' - - client = ConversationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = conversation.BatchCreateMessagesResponse() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "post", - 'query_params': pb_request, - } - transcode_result['body'] = pb_request - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - - pb_return_value = conversation.BatchCreateMessagesResponse.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.batch_create_messages(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_batch_create_messages_rest_unset_required_fields(): - transport = transports.ConversationsRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.batch_create_messages._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("parent", "requests", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_batch_create_messages_rest_interceptors(null_interceptor): - transport = transports.ConversationsRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.ConversationsRestInterceptor(), - ) - client = ConversationsClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.ConversationsRestInterceptor, "post_batch_create_messages") as post, \ - mock.patch.object(transports.ConversationsRestInterceptor, "pre_batch_create_messages") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = conversation.BatchCreateMessagesRequest.pb(conversation.BatchCreateMessagesRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = conversation.BatchCreateMessagesResponse.to_json(conversation.BatchCreateMessagesResponse()) - - request = conversation.BatchCreateMessagesRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = conversation.BatchCreateMessagesResponse() - - client.batch_create_messages(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_batch_create_messages_rest_bad_request(transport: str = 'rest', request_type=conversation.BatchCreateMessagesRequest): - client = ConversationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1/conversations/sample2'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.batch_create_messages(request) - - -def test_batch_create_messages_rest_flattened(): - client = ConversationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = conversation.BatchCreateMessagesResponse() - - # get arguments that satisfy an http rule for this method - sample_request = {'parent': 'projects/sample1/conversations/sample2'} - - # get truthy value for each flattened field - mock_args = dict( - parent='parent_value', - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - pb_return_value = conversation.BatchCreateMessagesResponse.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.batch_create_messages(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v2beta1/{parent=projects/*/conversations/*}/messages:batchCreate" % client.transport._host, args[1]) - - -def test_batch_create_messages_rest_flattened_error(transport: str = 'rest'): - client = ConversationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.batch_create_messages( - conversation.BatchCreateMessagesRequest(), - parent='parent_value', - ) - - -def test_batch_create_messages_rest_error(): - client = ConversationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - conversation.ListMessagesRequest, - dict, -]) -def test_list_messages_rest(request_type): - client = ConversationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1/conversations/sample2'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = conversation.ListMessagesResponse( - next_page_token='next_page_token_value', - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - pb_return_value = conversation.ListMessagesResponse.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.list_messages(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListMessagesPager) - assert response.next_page_token == 'next_page_token_value' - - -def test_list_messages_rest_required_fields(request_type=conversation.ListMessagesRequest): - transport_class = transports.ConversationsRestTransport - - request_init = {} - request_init["parent"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - including_default_value_fields=False, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).list_messages._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["parent"] = 'parent_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).list_messages._get_unset_required_fields(jsonified_request) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("filter", "page_size", "page_token", )) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "parent" in jsonified_request - assert jsonified_request["parent"] == 'parent_value' - - client = ConversationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = conversation.ListMessagesResponse() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "get", - 'query_params': pb_request, - } - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - - pb_return_value = conversation.ListMessagesResponse.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.list_messages(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_list_messages_rest_unset_required_fields(): - transport = transports.ConversationsRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.list_messages._get_unset_required_fields({}) - assert set(unset_fields) == (set(("filter", "pageSize", "pageToken", )) & set(("parent", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_list_messages_rest_interceptors(null_interceptor): - transport = transports.ConversationsRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.ConversationsRestInterceptor(), - ) - client = ConversationsClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.ConversationsRestInterceptor, "post_list_messages") as post, \ - mock.patch.object(transports.ConversationsRestInterceptor, "pre_list_messages") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = conversation.ListMessagesRequest.pb(conversation.ListMessagesRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = conversation.ListMessagesResponse.to_json(conversation.ListMessagesResponse()) - - request = conversation.ListMessagesRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = conversation.ListMessagesResponse() - - client.list_messages(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_list_messages_rest_bad_request(transport: str = 'rest', request_type=conversation.ListMessagesRequest): - client = ConversationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1/conversations/sample2'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.list_messages(request) - - -def test_list_messages_rest_flattened(): - client = ConversationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = conversation.ListMessagesResponse() - - # get arguments that satisfy an http rule for this method - sample_request = {'parent': 'projects/sample1/conversations/sample2'} - - # get truthy value for each flattened field - mock_args = dict( - parent='parent_value', - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - pb_return_value = conversation.ListMessagesResponse.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.list_messages(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v2beta1/{parent=projects/*/conversations/*}/messages" % client.transport._host, args[1]) - - -def test_list_messages_rest_flattened_error(transport: str = 'rest'): - client = ConversationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.list_messages( - conversation.ListMessagesRequest(), - parent='parent_value', - ) - - -def test_list_messages_rest_pager(transport: str = 'rest'): - client = ConversationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # TODO(kbandes): remove this mock unless there's a good reason for it. - #with mock.patch.object(path_template, 'transcode') as transcode: - # Set the response as a series of pages - response = ( - conversation.ListMessagesResponse( - messages=[ - participant.Message(), - participant.Message(), - participant.Message(), - ], - next_page_token='abc', - ), - conversation.ListMessagesResponse( - messages=[], - next_page_token='def', - ), - conversation.ListMessagesResponse( - messages=[ - participant.Message(), - ], - next_page_token='ghi', - ), - conversation.ListMessagesResponse( - messages=[ - participant.Message(), - participant.Message(), - ], - ), - ) - # Two responses for two calls - response = response + response - - # Wrap the values into proper Response objs - response = tuple(conversation.ListMessagesResponse.to_json(x) for x in response) - return_values = tuple(Response() for i in response) - for return_val, response_val in zip(return_values, response): - return_val._content = response_val.encode('UTF-8') - return_val.status_code = 200 - req.side_effect = return_values - - sample_request = {'parent': 'projects/sample1/conversations/sample2'} - - pager = client.list_messages(request=sample_request) - - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, participant.Message) - for i in results) - - pages = list(client.list_messages(request=sample_request).pages) - for page_, token in zip(pages, ['abc','def','ghi', '']): - assert page_.raw_page.next_page_token == token - - -@pytest.mark.parametrize("request_type", [ - gcd_conversation.SuggestConversationSummaryRequest, - dict, -]) -def test_suggest_conversation_summary_rest(request_type): - client = ConversationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'conversation': 'projects/sample1/conversations/sample2'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = gcd_conversation.SuggestConversationSummaryResponse( - latest_message='latest_message_value', - context_size=1311, - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - pb_return_value = gcd_conversation.SuggestConversationSummaryResponse.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.suggest_conversation_summary(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, gcd_conversation.SuggestConversationSummaryResponse) - assert response.latest_message == 'latest_message_value' - assert response.context_size == 1311 - - -def test_suggest_conversation_summary_rest_required_fields(request_type=gcd_conversation.SuggestConversationSummaryRequest): - transport_class = transports.ConversationsRestTransport - - request_init = {} - request_init["conversation"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - including_default_value_fields=False, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).suggest_conversation_summary._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["conversation"] = 'conversation_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).suggest_conversation_summary._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "conversation" in jsonified_request - assert jsonified_request["conversation"] == 'conversation_value' - - client = ConversationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = gcd_conversation.SuggestConversationSummaryResponse() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "post", - 'query_params': pb_request, - } - transcode_result['body'] = pb_request - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - - pb_return_value = gcd_conversation.SuggestConversationSummaryResponse.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.suggest_conversation_summary(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_suggest_conversation_summary_rest_unset_required_fields(): - transport = transports.ConversationsRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.suggest_conversation_summary._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("conversation", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_suggest_conversation_summary_rest_interceptors(null_interceptor): - transport = transports.ConversationsRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.ConversationsRestInterceptor(), - ) - client = ConversationsClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.ConversationsRestInterceptor, "post_suggest_conversation_summary") as post, \ - mock.patch.object(transports.ConversationsRestInterceptor, "pre_suggest_conversation_summary") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = gcd_conversation.SuggestConversationSummaryRequest.pb(gcd_conversation.SuggestConversationSummaryRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = gcd_conversation.SuggestConversationSummaryResponse.to_json(gcd_conversation.SuggestConversationSummaryResponse()) - - request = gcd_conversation.SuggestConversationSummaryRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = gcd_conversation.SuggestConversationSummaryResponse() - - client.suggest_conversation_summary(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_suggest_conversation_summary_rest_bad_request(transport: str = 'rest', request_type=gcd_conversation.SuggestConversationSummaryRequest): - client = ConversationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'conversation': 'projects/sample1/conversations/sample2'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.suggest_conversation_summary(request) - - -def test_suggest_conversation_summary_rest_flattened(): - client = ConversationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = gcd_conversation.SuggestConversationSummaryResponse() - - # get arguments that satisfy an http rule for this method - sample_request = {'conversation': 'projects/sample1/conversations/sample2'} - - # get truthy value for each flattened field - mock_args = dict( - conversation='conversation_value', - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - pb_return_value = gcd_conversation.SuggestConversationSummaryResponse.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.suggest_conversation_summary(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v2beta1/{conversation=projects/*/conversations/*}/suggestions:suggestConversationSummary" % client.transport._host, args[1]) - - -def test_suggest_conversation_summary_rest_flattened_error(transport: str = 'rest'): - client = ConversationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.suggest_conversation_summary( - gcd_conversation.SuggestConversationSummaryRequest(), - conversation='conversation_value', - ) - - -def test_suggest_conversation_summary_rest_error(): - client = ConversationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -def test_credentials_transport_error(): - # It is an error to provide credentials and a transport instance. - transport = transports.ConversationsGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = ConversationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # It is an error to provide a credentials file and a transport instance. - transport = transports.ConversationsGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = ConversationsClient( - client_options={"credentials_file": "credentials.json"}, - transport=transport, - ) - - # It is an error to provide an api_key and a transport instance. - transport = transports.ConversationsGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - options = client_options.ClientOptions() - options.api_key = "api_key" - with pytest.raises(ValueError): - client = ConversationsClient( - client_options=options, - transport=transport, - ) - - # It is an error to provide an api_key and a credential. - options = mock.Mock() - options.api_key = "api_key" - with pytest.raises(ValueError): - client = ConversationsClient( - client_options=options, - credentials=ga_credentials.AnonymousCredentials() - ) - - # It is an error to provide scopes and a transport instance. - transport = transports.ConversationsGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = ConversationsClient( - client_options={"scopes": ["1", "2"]}, - transport=transport, - ) - - -def test_transport_instance(): - # A client may be instantiated with a custom transport instance. - transport = transports.ConversationsGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - client = ConversationsClient(transport=transport) - assert client.transport is transport - -def test_transport_get_channel(): - # A client may be instantiated with a custom transport instance. - transport = transports.ConversationsGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - - transport = transports.ConversationsGrpcAsyncIOTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - -@pytest.mark.parametrize("transport_class", [ - transports.ConversationsGrpcTransport, - transports.ConversationsGrpcAsyncIOTransport, - transports.ConversationsRestTransport, -]) -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() - -@pytest.mark.parametrize("transport_name", [ - "grpc", - "rest", -]) -def test_transport_kind(transport_name): - transport = ConversationsClient.get_transport_class(transport_name)( - credentials=ga_credentials.AnonymousCredentials(), - ) - assert transport.kind == transport_name - -def test_transport_grpc_default(): - # A client should use the gRPC transport by default. - 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(core_exceptions.DuplicateCredentialArgs): - transport = transports.ConversationsTransport( - credentials=ga_credentials.AnonymousCredentials(), - credentials_file="credentials.json" - ) - - -def test_conversations_base_transport(): - # Instantiate the base transport. - with mock.patch('google.cloud.dialogflow_v2beta1.services.conversations.transports.ConversationsTransport.__init__') as Transport: - Transport.return_value = None - transport = transports.ConversationsTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Every method on the transport should just blindly - # raise NotImplementedError. - methods = ( - 'create_conversation', - 'list_conversations', - 'get_conversation', - 'complete_conversation', - 'batch_create_messages', - 'list_messages', - 'suggest_conversation_summary', - 'get_location', - 'list_locations', - 'get_operation', - 'cancel_operation', - 'list_operations', - ) - for method in methods: - with pytest.raises(NotImplementedError): - getattr(transport, method)(request=object()) - - with pytest.raises(NotImplementedError): - transport.close() - - # Catch all for all remaining methods and properties - remainder = [ - 'kind', - ] - for r in remainder: - with pytest.raises(NotImplementedError): - getattr(transport, r)() - - -def test_conversations_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.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", - ) - - -def test_conversations_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.conversations.transports.ConversationsTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.ConversationsTransport() - adc.assert_called_once() - - -def test_conversations_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) - 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, - ) - - -@pytest.mark.parametrize( - "transport_class", - [ - transports.ConversationsGrpcTransport, - transports.ConversationsGrpcAsyncIOTransport, - ], -) -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(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, - transports.ConversationsRestTransport, - ], -) -def test_conversations_transport_auth_gdch_credentials(transport_class): - host = 'https://language.com' - api_audience_tests = [None, 'https://language2.com'] - api_audience_expect = [host, 'https://language2.com'] - for t, e in zip(api_audience_tests, api_audience_expect): - with mock.patch.object(google.auth, 'default', autospec=True) as adc: - gdch_mock = mock.MagicMock() - type(gdch_mock).with_gdch_audience = mock.PropertyMock(return_value=gdch_mock) - adc.return_value = (gdch_mock, None) - transport_class(host=host, api_audience=t) - gdch_mock.with_gdch_audience.assert_called_once_with( - e - ) - - -@pytest.mark.parametrize( - "transport_class,grpc_helpers", - [ - (transports.ConversationsGrpcTransport, grpc_helpers), - (transports.ConversationsGrpcAsyncIOTransport, grpc_helpers_async) - ], -) -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", [transports.ConversationsGrpcTransport, transports.ConversationsGrpcAsyncIOTransport]) -def test_conversations_grpc_transport_client_cert_source_for_mtls( - transport_class -): - cred = ga_credentials.AnonymousCredentials() - - # Check ssl_channel_credentials is used if provided. - with mock.patch.object(transport_class, "create_channel") as mock_create_channel: - mock_ssl_channel_creds = mock.Mock() - transport_class( - host="squid.clam.whelk", - credentials=cred, - ssl_channel_credentials=mock_ssl_channel_creds - ) - mock_create_channel.assert_called_once_with( - "squid.clam.whelk:443", - credentials=cred, - credentials_file=None, - scopes=None, - ssl_credentials=mock_ssl_channel_creds, - quota_project_id=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - # Check if ssl_channel_credentials is not provided, then client_cert_source_for_mtls - # is used. - with mock.patch.object(transport_class, "create_channel", return_value=mock.Mock()): - with mock.patch("grpc.ssl_channel_credentials") as mock_ssl_cred: - transport_class( - credentials=cred, - client_cert_source_for_mtls=client_cert_source_callback - ) - expected_cert, expected_key = client_cert_source_callback() - mock_ssl_cred.assert_called_once_with( - certificate_chain=expected_cert, - private_key=expected_key - ) - -def test_conversations_http_transport_client_cert_source_for_mtls(): - cred = ga_credentials.AnonymousCredentials() - with mock.patch("google.auth.transport.requests.AuthorizedSession.configure_mtls_channel") as mock_configure_mtls_channel: - transports.ConversationsRestTransport ( - credentials=cred, - client_cert_source_for_mtls=client_cert_source_callback - ) - mock_configure_mtls_channel.assert_called_once_with(client_cert_source_callback) - - -@pytest.mark.parametrize("transport_name", [ - "grpc", - "grpc_asyncio", - "rest", -]) -def test_conversations_host_no_port(transport_name): - client = ConversationsClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='dialogflow.googleapis.com'), - transport=transport_name, - ) - assert client.transport._host == ( - 'dialogflow.googleapis.com:443' - if transport_name in ['grpc', 'grpc_asyncio'] - else 'https://dialogflow.googleapis.com' - ) - -@pytest.mark.parametrize("transport_name", [ - "grpc", - "grpc_asyncio", - "rest", -]) -def test_conversations_host_with_port(transport_name): - client = ConversationsClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='dialogflow.googleapis.com:8000'), - transport=transport_name, - ) - assert client.transport._host == ( - 'dialogflow.googleapis.com:8000' - if transport_name in ['grpc', 'grpc_asyncio'] - else 'https://dialogflow.googleapis.com:8000' - ) - -@pytest.mark.parametrize("transport_name", [ - "rest", -]) -def test_conversations_client_transport_session_collision(transport_name): - creds1 = ga_credentials.AnonymousCredentials() - creds2 = ga_credentials.AnonymousCredentials() - client1 = ConversationsClient( - credentials=creds1, - transport=transport_name, - ) - client2 = ConversationsClient( - credentials=creds2, - transport=transport_name, - ) - session1 = client1.transport.create_conversation._session - session2 = client2.transport.create_conversation._session - assert session1 != session2 - session1 = client1.transport.list_conversations._session - session2 = client2.transport.list_conversations._session - assert session1 != session2 - session1 = client1.transport.get_conversation._session - session2 = client2.transport.get_conversation._session - assert session1 != session2 - session1 = client1.transport.complete_conversation._session - session2 = client2.transport.complete_conversation._session - assert session1 != session2 - session1 = client1.transport.batch_create_messages._session - session2 = client2.transport.batch_create_messages._session - assert session1 != session2 - session1 = client1.transport.list_messages._session - session2 = client2.transport.list_messages._session - assert session1 != session2 - session1 = client1.transport.suggest_conversation_summary._session - session2 = client2.transport.suggest_conversation_summary._session - assert session1 != session2 -def test_conversations_grpc_transport_channel(): - channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.ConversationsGrpcTransport( - 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_conversations_grpc_asyncio_transport_channel(): - channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.ConversationsGrpcAsyncIOTransport( - 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.ConversationsGrpcTransport, transports.ConversationsGrpcAsyncIOTransport]) -def test_conversations_transport_channel_mtls_with_client_cert_source( - transport_class -): - with mock.patch("grpc.ssl_channel_credentials", autospec=True) as grpc_ssl_channel_cred: - with mock.patch.object(transport_class, "create_channel") as grpc_create_channel: - mock_ssl_cred = mock.Mock() - grpc_ssl_channel_cred.return_value = mock_ssl_cred - - mock_grpc_channel = mock.Mock() - grpc_create_channel.return_value = mock_grpc_channel - - cred = ga_credentials.AnonymousCredentials() - with pytest.warns(DeprecationWarning): - with mock.patch.object(google.auth, 'default') as adc: - adc.return_value = (cred, None) - transport = transport_class( - host="squid.clam.whelk", - api_mtls_endpoint="mtls.squid.clam.whelk", - client_cert_source=client_cert_source_callback, - ) - adc.assert_called_once() - - grpc_ssl_channel_cred.assert_called_once_with( - certificate_chain=b"cert bytes", private_key=b"key bytes" - ) - grpc_create_channel.assert_called_once_with( - "mtls.squid.clam.whelk:443", - credentials=cred, - credentials_file=None, - scopes=None, - ssl_credentials=mock_ssl_cred, - quota_project_id=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - assert transport.grpc_channel == mock_grpc_channel - assert transport._ssl_channel_credentials == mock_ssl_cred - - -# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are -# removed from grpc/grpc_asyncio transport constructor. -@pytest.mark.parametrize("transport_class", [transports.ConversationsGrpcTransport, transports.ConversationsGrpcAsyncIOTransport]) -def test_conversations_transport_channel_mtls_with_adc( - transport_class -): - mock_ssl_cred = mock.Mock() - with mock.patch.multiple( - "google.auth.transport.grpc.SslCredentials", - __init__=mock.Mock(return_value=None), - ssl_credentials=mock.PropertyMock(return_value=mock_ssl_cred), - ): - with mock.patch.object(transport_class, "create_channel") as grpc_create_channel: - mock_grpc_channel = mock.Mock() - grpc_create_channel.return_value = mock_grpc_channel - mock_cred = mock.Mock() - - with pytest.warns(DeprecationWarning): - transport = transport_class( - host="squid.clam.whelk", - credentials=mock_cred, - api_mtls_endpoint="mtls.squid.clam.whelk", - client_cert_source=None, - ) - - grpc_create_channel.assert_called_once_with( - "mtls.squid.clam.whelk:443", - credentials=mock_cred, - credentials_file=None, - scopes=None, - ssl_credentials=mock_ssl_cred, - quota_project_id=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - assert transport.grpc_channel == mock_grpc_channel - - -def test_answer_record_path(): - project = "squid" - answer_record = "clam" - expected = "projects/{project}/answerRecords/{answer_record}".format(project=project, answer_record=answer_record, ) - actual = ConversationsClient.answer_record_path(project, answer_record) - assert expected == actual - - -def test_parse_answer_record_path(): - expected = { - "project": "whelk", - "answer_record": "octopus", - } - path = ConversationsClient.answer_record_path(**expected) - - # Check that the path construction is reversible. - actual = ConversationsClient.parse_answer_record_path(path) - assert expected == actual - -def test_conversation_path(): - project = "oyster" - conversation = "nudibranch" - expected = "projects/{project}/conversations/{conversation}".format(project=project, conversation=conversation, ) - actual = ConversationsClient.conversation_path(project, conversation) - assert expected == actual - - -def test_parse_conversation_path(): - expected = { - "project": "cuttlefish", - "conversation": "mussel", - } - path = ConversationsClient.conversation_path(**expected) - - # Check that the path construction is reversible. - actual = ConversationsClient.parse_conversation_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, ) - actual = ConversationsClient.conversation_profile_path(project, conversation_profile) - assert expected == actual - - -def test_parse_conversation_profile_path(): - expected = { - "project": "scallop", - "conversation_profile": "abalone", - } - path = ConversationsClient.conversation_profile_path(**expected) - - # Check that the path construction is reversible. - actual = ConversationsClient.parse_conversation_profile_path(path) - assert expected == actual - -def test_message_path(): - project = "squid" - conversation = "clam" - message = "whelk" - expected = "projects/{project}/conversations/{conversation}/messages/{message}".format(project=project, conversation=conversation, message=message, ) - actual = ConversationsClient.message_path(project, conversation, message) - assert expected == actual - - -def test_parse_message_path(): - expected = { - "project": "octopus", - "conversation": "oyster", - "message": "nudibranch", - } - path = ConversationsClient.message_path(**expected) - - # Check that the path construction is reversible. - actual = ConversationsClient.parse_message_path(path) - assert expected == actual - -def test_common_billing_account_path(): - billing_account = "cuttlefish" - expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) - actual = ConversationsClient.common_billing_account_path(billing_account) - assert expected == actual - - -def test_parse_common_billing_account_path(): - expected = { - "billing_account": "mussel", - } - path = ConversationsClient.common_billing_account_path(**expected) - - # Check that the path construction is reversible. - actual = ConversationsClient.parse_common_billing_account_path(path) - assert expected == actual - -def test_common_folder_path(): - folder = "winkle" - expected = "folders/{folder}".format(folder=folder, ) - actual = ConversationsClient.common_folder_path(folder) - assert expected == actual - - -def test_parse_common_folder_path(): - expected = { - "folder": "nautilus", - } - path = ConversationsClient.common_folder_path(**expected) - - # Check that the path construction is reversible. - actual = ConversationsClient.parse_common_folder_path(path) - assert expected == actual - -def test_common_organization_path(): - organization = "scallop" - expected = "organizations/{organization}".format(organization=organization, ) - actual = ConversationsClient.common_organization_path(organization) - assert expected == actual - - -def test_parse_common_organization_path(): - expected = { - "organization": "abalone", - } - path = ConversationsClient.common_organization_path(**expected) - - # Check that the path construction is reversible. - actual = ConversationsClient.parse_common_organization_path(path) - assert expected == actual - -def test_common_project_path(): - project = "squid" - expected = "projects/{project}".format(project=project, ) - actual = ConversationsClient.common_project_path(project) - assert expected == actual - - -def test_parse_common_project_path(): - expected = { - "project": "clam", - } - path = ConversationsClient.common_project_path(**expected) - - # Check that the path construction is reversible. - actual = ConversationsClient.parse_common_project_path(path) - assert expected == actual - -def test_common_location_path(): - project = "whelk" - location = "octopus" - expected = "projects/{project}/locations/{location}".format(project=project, location=location, ) - actual = ConversationsClient.common_location_path(project, location) - assert expected == actual - - -def test_parse_common_location_path(): - expected = { - "project": "oyster", - "location": "nudibranch", - } - path = ConversationsClient.common_location_path(**expected) - - # Check that the path construction is reversible. - actual = ConversationsClient.parse_common_location_path(path) - assert expected == actual - - -def test_client_with_default_client_info(): - client_info = gapic_v1.client_info.ClientInfo() - - with mock.patch.object(transports.ConversationsTransport, '_prep_wrapped_messages') as prep: - client = ConversationsClient( - credentials=ga_credentials.AnonymousCredentials(), - client_info=client_info, - ) - prep.assert_called_once_with(client_info) - - with mock.patch.object(transports.ConversationsTransport, '_prep_wrapped_messages') as prep: - transport_class = ConversationsClient.get_transport_class() - transport = transport_class( - credentials=ga_credentials.AnonymousCredentials(), - client_info=client_info, - ) - prep.assert_called_once_with(client_info) - -@pytest.mark.asyncio -async def test_transport_close_async(): - client = ConversationsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - with mock.patch.object(type(getattr(client.transport, "grpc_channel")), "close") as close: - async with client: - close.assert_not_called() - close.assert_called_once() - - -def test_get_location_rest_bad_request(transport: str = 'rest', request_type=locations_pb2.GetLocationRequest): - client = ConversationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - request = request_type() - request = json_format.ParseDict({'name': 'projects/sample1/locations/sample2'}, request) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.get_location(request) - -@pytest.mark.parametrize("request_type", [ - locations_pb2.GetLocationRequest, - dict, -]) -def test_get_location_rest(request_type): - client = ConversationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request_init = {'name': 'projects/sample1/locations/sample2'} - request = request_type(**request_init) - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = locations_pb2.Location() - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.get_location(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, locations_pb2.Location) - -def test_list_locations_rest_bad_request(transport: str = 'rest', request_type=locations_pb2.ListLocationsRequest): - client = ConversationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - request = request_type() - request = json_format.ParseDict({'name': 'projects/sample1'}, request) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.list_locations(request) - -@pytest.mark.parametrize("request_type", [ - locations_pb2.ListLocationsRequest, - dict, -]) -def test_list_locations_rest(request_type): - client = ConversationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request_init = {'name': 'projects/sample1'} - request = request_type(**request_init) - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = locations_pb2.ListLocationsResponse() - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.list_locations(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, locations_pb2.ListLocationsResponse) - -def test_cancel_operation_rest_bad_request(transport: str = 'rest', request_type=operations_pb2.CancelOperationRequest): - client = ConversationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - request = request_type() - request = json_format.ParseDict({'name': 'projects/sample1/operations/sample2'}, request) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.cancel_operation(request) - -@pytest.mark.parametrize("request_type", [ - operations_pb2.CancelOperationRequest, - dict, -]) -def test_cancel_operation_rest(request_type): - client = ConversationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request_init = {'name': 'projects/sample1/operations/sample2'} - request = request_type(**request_init) - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = None - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = '{}' - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.cancel_operation(request) - - # Establish that the response is the type that we expect. - assert response is None - -def test_get_operation_rest_bad_request(transport: str = 'rest', request_type=operations_pb2.GetOperationRequest): - client = ConversationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - request = request_type() - request = json_format.ParseDict({'name': 'projects/sample1/operations/sample2'}, request) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.get_operation(request) - -@pytest.mark.parametrize("request_type", [ - operations_pb2.GetOperationRequest, - dict, -]) -def test_get_operation_rest(request_type): - client = ConversationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request_init = {'name': 'projects/sample1/operations/sample2'} - request = request_type(**request_init) - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation() - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.get_operation(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, operations_pb2.Operation) - -def test_list_operations_rest_bad_request(transport: str = 'rest', request_type=operations_pb2.ListOperationsRequest): - client = ConversationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - request = request_type() - request = json_format.ParseDict({'name': 'projects/sample1'}, request) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.list_operations(request) - -@pytest.mark.parametrize("request_type", [ - operations_pb2.ListOperationsRequest, - dict, -]) -def test_list_operations_rest(request_type): - client = ConversationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request_init = {'name': 'projects/sample1'} - request = request_type(**request_init) - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = operations_pb2.ListOperationsResponse() - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.list_operations(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, operations_pb2.ListOperationsResponse) - - -def test_cancel_operation(transport: str = "grpc"): - client = ConversationsClient( - 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 = operations_pb2.CancelOperationRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = None - response = client.cancel_operation(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 response is the type that we expect. - assert response is None -@pytest.mark.asyncio -async def test_cancel_operation_async(transport: str = "grpc"): - client = ConversationsAsyncClient( - 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 = operations_pb2.CancelOperationRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - None - ) - response = await client.cancel_operation(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 response is the type that we expect. - assert response is None - -def test_cancel_operation_field_headers(): - 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 = operations_pb2.CancelOperationRequest() - request.name = "locations" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call: - call.return_value = None - - client.cancel_operation(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=locations",) in kw["metadata"] -@pytest.mark.asyncio -async def test_cancel_operation_field_headers_async(): - 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 = operations_pb2.CancelOperationRequest() - request.name = "locations" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - None - ) - await client.cancel_operation(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=locations",) in kw["metadata"] - -def test_cancel_operation_from_dict(): - 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.cancel_operation), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = None - - response = client.cancel_operation( - request={ - "name": "locations", - } - ) - call.assert_called() -@pytest.mark.asyncio -async def test_cancel_operation_from_dict_async(): - 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.cancel_operation), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - None - ) - response = await client.cancel_operation( - request={ - "name": "locations", - } - ) - call.assert_called() - - -def test_get_operation(transport: str = "grpc"): - client = ConversationsClient( - 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 = operations_pb2.GetOperationRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_operation), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation() - response = client.get_operation(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 response is the type that we expect. - assert isinstance(response, operations_pb2.Operation) -@pytest.mark.asyncio -async def test_get_operation_async(transport: str = "grpc"): - client = ConversationsAsyncClient( - 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 = operations_pb2.GetOperationRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_operation), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation() - ) - response = await client.get_operation(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 response is the type that we expect. - assert isinstance(response, operations_pb2.Operation) - -def test_get_operation_field_headers(): - 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 = operations_pb2.GetOperationRequest() - request.name = "locations" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_operation), "__call__") as call: - call.return_value = operations_pb2.Operation() - - client.get_operation(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=locations",) in kw["metadata"] -@pytest.mark.asyncio -async def test_get_operation_field_headers_async(): - 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 = operations_pb2.GetOperationRequest() - request.name = "locations" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_operation), "__call__") as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation() - ) - await client.get_operation(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=locations",) in kw["metadata"] - -def test_get_operation_from_dict(): - 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_operation), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation() - - response = client.get_operation( - request={ - "name": "locations", - } - ) - call.assert_called() -@pytest.mark.asyncio -async def test_get_operation_from_dict_async(): - 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_operation), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation() - ) - response = await client.get_operation( - request={ - "name": "locations", - } - ) - call.assert_called() - - -def test_list_operations(transport: str = "grpc"): - client = ConversationsClient( - 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 = operations_pb2.ListOperationsRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_operations), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.ListOperationsResponse() - response = client.list_operations(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 response is the type that we expect. - assert isinstance(response, operations_pb2.ListOperationsResponse) -@pytest.mark.asyncio -async def test_list_operations_async(transport: str = "grpc"): - client = ConversationsAsyncClient( - 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 = operations_pb2.ListOperationsRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_operations), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.ListOperationsResponse() - ) - response = await client.list_operations(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 response is the type that we expect. - assert isinstance(response, operations_pb2.ListOperationsResponse) - -def test_list_operations_field_headers(): - 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 = operations_pb2.ListOperationsRequest() - request.name = "locations" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_operations), "__call__") as call: - call.return_value = operations_pb2.ListOperationsResponse() - - client.list_operations(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=locations",) in kw["metadata"] -@pytest.mark.asyncio -async def test_list_operations_field_headers_async(): - 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 = operations_pb2.ListOperationsRequest() - request.name = "locations" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_operations), "__call__") as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.ListOperationsResponse() - ) - await client.list_operations(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=locations",) in kw["metadata"] - -def test_list_operations_from_dict(): - 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_operations), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.ListOperationsResponse() - - response = client.list_operations( - request={ - "name": "locations", - } - ) - call.assert_called() -@pytest.mark.asyncio -async def test_list_operations_from_dict_async(): - 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_operations), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.ListOperationsResponse() - ) - response = await client.list_operations( - request={ - "name": "locations", - } - ) - call.assert_called() - - -def test_list_locations(transport: str = "grpc"): - client = ConversationsClient( - 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 = locations_pb2.ListLocationsRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_locations), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = locations_pb2.ListLocationsResponse() - response = client.list_locations(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 response is the type that we expect. - assert isinstance(response, locations_pb2.ListLocationsResponse) -@pytest.mark.asyncio -async def test_list_locations_async(transport: str = "grpc"): - client = ConversationsAsyncClient( - 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 = locations_pb2.ListLocationsRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_locations), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - locations_pb2.ListLocationsResponse() - ) - response = await client.list_locations(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 response is the type that we expect. - assert isinstance(response, locations_pb2.ListLocationsResponse) - -def test_list_locations_field_headers(): - 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 = locations_pb2.ListLocationsRequest() - request.name = "locations" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_locations), "__call__") as call: - call.return_value = locations_pb2.ListLocationsResponse() - - client.list_locations(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=locations",) in kw["metadata"] -@pytest.mark.asyncio -async def test_list_locations_field_headers_async(): - 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 = locations_pb2.ListLocationsRequest() - request.name = "locations" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_locations), "__call__") as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - locations_pb2.ListLocationsResponse() - ) - await client.list_locations(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=locations",) in kw["metadata"] - -def test_list_locations_from_dict(): - 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_locations), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = locations_pb2.ListLocationsResponse() - - response = client.list_locations( - request={ - "name": "locations", - } - ) - call.assert_called() -@pytest.mark.asyncio -async def test_list_locations_from_dict_async(): - 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_locations), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - locations_pb2.ListLocationsResponse() - ) - response = await client.list_locations( - request={ - "name": "locations", - } - ) - call.assert_called() - - -def test_get_location(transport: str = "grpc"): - client = ConversationsClient( - 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 = locations_pb2.GetLocationRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_location), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = locations_pb2.Location() - response = client.get_location(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 response is the type that we expect. - assert isinstance(response, locations_pb2.Location) -@pytest.mark.asyncio -async def test_get_location_async(transport: str = "grpc_asyncio"): - client = ConversationsAsyncClient( - 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 = locations_pb2.GetLocationRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_location), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - locations_pb2.Location() - ) - response = await client.get_location(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 response is the type that we expect. - assert isinstance(response, locations_pb2.Location) - -def test_get_location_field_headers(): - 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 = locations_pb2.GetLocationRequest() - request.name = "locations/abc" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_location), "__call__") as call: - call.return_value = locations_pb2.Location() - - client.get_location(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=locations/abc",) in kw["metadata"] -@pytest.mark.asyncio -async def test_get_location_field_headers_async(): - 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 = locations_pb2.GetLocationRequest() - request.name = "locations/abc" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_location), "__call__") as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - locations_pb2.Location() - ) - await client.get_location(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=locations/abc",) in kw["metadata"] - -def test_get_location_from_dict(): - 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_locations), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = locations_pb2.Location() - - response = client.get_location( - request={ - "name": "locations/abc", - } - ) - call.assert_called() -@pytest.mark.asyncio -async def test_get_location_from_dict_async(): - 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_locations), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - locations_pb2.Location() - ) - response = await client.get_location( - request={ - "name": "locations", - } - ) - call.assert_called() - - -def test_transport_close(): - transports = { - "rest": "_session", - "grpc": "_grpc_channel", - } - - for transport, close_name in transports.items(): - client = ConversationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport - ) - with mock.patch.object(type(getattr(client.transport, close_name)), "close") as close: - with client: - close.assert_not_called() - close.assert_called_once() - -def test_client_ctx(): - transports = [ - 'rest', - 'grpc', - ] - for transport in transports: - client = ConversationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport - ) - # Test client calls underlying transport. - with mock.patch.object(type(client.transport), "close") as close: - close.assert_not_called() - with client: - pass - close.assert_called() - -@pytest.mark.parametrize("client_class,transport_class", [ - (ConversationsClient, transports.ConversationsGrpcTransport), - (ConversationsAsyncClient, transports.ConversationsGrpcAsyncIOTransport), -]) -def test_api_key_credentials(client_class, transport_class): - with mock.patch.object( - google.auth._default, "get_api_key_credentials", create=True - ) as get_api_key_credentials: - mock_cred = mock.Mock() - get_api_key_credentials.return_value = mock_cred - options = client_options.ClientOptions() - options.api_key = "api_key" - 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=mock_cred, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) diff --git a/owl-bot-staging/v2beta1/tests/unit/gapic/dialogflow_v2beta1/test_documents.py b/owl-bot-staging/v2beta1/tests/unit/gapic/dialogflow_v2beta1/test_documents.py deleted file mode 100644 index f531c7646..000000000 --- a/owl-bot-staging/v2beta1/tests/unit/gapic/dialogflow_v2beta1/test_documents.py +++ /dev/null @@ -1,5595 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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 -# try/except added for compatibility with python < 3.8 -try: - from unittest import mock - from unittest.mock import AsyncMock # pragma: NO COVER -except ImportError: # pragma: NO COVER - import mock - -import grpc -from grpc.experimental import aio -from collections.abc import Iterable -from google.protobuf import json_format -import json -import math -import pytest -from proto.marshal.rules.dates import DurationRule, TimestampRule -from proto.marshal.rules import wrappers -from requests import Response -from requests import Request, PreparedRequest -from requests.sessions import Session -from google.protobuf import json_format - -from google.api_core import client_options -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 -from google.api_core import operation_async # type: ignore -from google.api_core import operations_v1 -from google.api_core import path_template -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.types import document -from google.cloud.dialogflow_v2beta1.types import document as gcd_document -from google.cloud.dialogflow_v2beta1.types import gcs -from google.cloud.location import locations_pb2 -from google.longrunning import operations_pb2 -from google.oauth2 import service_account -from google.protobuf import any_pb2 # type: ignore -from google.protobuf import empty_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 - - -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 DocumentsClient._get_default_mtls_endpoint(None) is None - assert DocumentsClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint - assert DocumentsClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint - assert DocumentsClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint - assert DocumentsClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint - assert DocumentsClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi - - -@pytest.mark.parametrize("client_class,transport_name", [ - (DocumentsClient, "grpc"), - (DocumentsAsyncClient, "grpc_asyncio"), - (DocumentsClient, "rest"), -]) -def test_documents_client_from_service_account_info(client_class, transport_name): - 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, transport=transport_name) - assert client.transport._credentials == creds - assert isinstance(client, client_class) - - assert client.transport._host == ( - 'dialogflow.googleapis.com:443' - if transport_name in ['grpc', 'grpc_asyncio'] - else - 'https://dialogflow.googleapis.com' - ) - - -@pytest.mark.parametrize("transport_class,transport_name", [ - (transports.DocumentsGrpcTransport, "grpc"), - (transports.DocumentsGrpcAsyncIOTransport, "grpc_asyncio"), - (transports.DocumentsRestTransport, "rest"), -]) -def test_documents_client_service_account_always_use_jwt(transport_class, transport_name): - with mock.patch.object(service_account.Credentials, 'with_always_use_jwt_access', create=True) as use_jwt: - creds = service_account.Credentials(None, None, None) - transport = transport_class(credentials=creds, always_use_jwt_access=True) - use_jwt.assert_called_once_with(True) - - with mock.patch.object(service_account.Credentials, 'with_always_use_jwt_access', create=True) as use_jwt: - creds = service_account.Credentials(None, None, None) - transport = transport_class(credentials=creds, always_use_jwt_access=False) - use_jwt.assert_not_called() - - -@pytest.mark.parametrize("client_class,transport_name", [ - (DocumentsClient, "grpc"), - (DocumentsAsyncClient, "grpc_asyncio"), - (DocumentsClient, "rest"), -]) -def test_documents_client_from_service_account_file(client_class, transport_name): - 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", transport=transport_name) - assert client.transport._credentials == creds - assert isinstance(client, client_class) - - client = client_class.from_service_account_json("dummy/file/path.json", transport=transport_name) - assert client.transport._credentials == creds - assert isinstance(client, client_class) - - assert client.transport._host == ( - 'dialogflow.googleapis.com:443' - if transport_name in ['grpc', 'grpc_asyncio'] - else - 'https://dialogflow.googleapis.com' - ) - - -def test_documents_client_get_transport_class(): - transport = DocumentsClient.get_transport_class() - available_transports = [ - transports.DocumentsGrpcTransport, - transports.DocumentsRestTransport, - ] - assert transport in available_transports - - transport = DocumentsClient.get_transport_class("grpc") - assert transport == transports.DocumentsGrpcTransport - - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (DocumentsClient, transports.DocumentsGrpcTransport, "grpc"), - (DocumentsAsyncClient, transports.DocumentsGrpcAsyncIOTransport, "grpc_asyncio"), - (DocumentsClient, transports.DocumentsRestTransport, "rest"), -]) -@mock.patch.object(DocumentsClient, "DEFAULT_ENDPOINT", modify_default_endpoint(DocumentsClient)) -@mock.patch.object(DocumentsAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(DocumentsAsyncClient)) -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=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(DocumentsClient, 'get_transport_class') as gtc: - client = client_class(transport=transport_name) - gtc.assert_called() - - # Check the case api_endpoint is provided. - options = client_options.ClientOptions(api_endpoint="squid.clam.whelk") - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(transport=transport_name, client_options=options) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host="squid.clam.whelk", - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is - # "never". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is - # "always". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_MTLS_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # 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(transport=transport_name) - - # 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(transport=transport_name) - - # 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, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id="octopus", - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - # Check the case api_endpoint is provided - options = client_options.ClientOptions(api_audience="https://language.googleapis.com") - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience="https://language.googleapis.com" - ) - -@pytest.mark.parametrize("client_class,transport_class,transport_name,use_client_cert_env", [ - (DocumentsClient, transports.DocumentsGrpcTransport, "grpc", "true"), - (DocumentsAsyncClient, transports.DocumentsGrpcAsyncIOTransport, "grpc_asyncio", "true"), - (DocumentsClient, transports.DocumentsGrpcTransport, "grpc", "false"), - (DocumentsAsyncClient, transports.DocumentsGrpcAsyncIOTransport, "grpc_asyncio", "false"), - (DocumentsClient, transports.DocumentsRestTransport, "rest", "true"), - (DocumentsClient, transports.DocumentsRestTransport, "rest", "false"), -]) -@mock.patch.object(DocumentsClient, "DEFAULT_ENDPOINT", modify_default_endpoint(DocumentsClient)) -@mock.patch.object(DocumentsAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(DocumentsAsyncClient)) -@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) -def test_documents_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, transport=transport_name) - - if use_client_cert_env == "false": - expected_client_cert_source = None - expected_host = client.DEFAULT_ENDPOINT - else: - expected_client_cert_source = client_cert_source_callback - expected_host = client.DEFAULT_MTLS_ENDPOINT - - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=expected_host, - scopes=None, - client_cert_source_for_mtls=expected_client_cert_source, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case ADC client cert is provided. Whether client cert is used depends on - # GOOGLE_API_USE_CLIENT_CERTIFICATE value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): - with mock.patch.object(transport_class, '__init__') as patched: - with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): - with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=client_cert_source_callback): - if use_client_cert_env == "false": - expected_host = client.DEFAULT_ENDPOINT - expected_client_cert_source = None - else: - expected_host = client.DEFAULT_MTLS_ENDPOINT - expected_client_cert_source = client_cert_source_callback - - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=expected_host, - scopes=None, - client_cert_source_for_mtls=expected_client_cert_source, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case client_cert_source and ADC client cert are not provided. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): - with mock.patch.object(transport_class, '__init__') as patched: - with mock.patch("google.auth.transport.mtls.has_default_client_cert_source", return_value=False): - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - -@pytest.mark.parametrize("client_class", [ - DocumentsClient, DocumentsAsyncClient -]) -@mock.patch.object(DocumentsClient, "DEFAULT_ENDPOINT", modify_default_endpoint(DocumentsClient)) -@mock.patch.object(DocumentsAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(DocumentsAsyncClient)) -def test_documents_client_get_mtls_endpoint_and_cert_source(client_class): - mock_client_cert_source = mock.Mock() - - # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "true". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - mock_api_endpoint = "foo" - options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) - assert api_endpoint == mock_api_endpoint - assert cert_source == mock_client_cert_source - - # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "false". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): - mock_client_cert_source = mock.Mock() - mock_api_endpoint = "foo" - options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) - assert api_endpoint == mock_api_endpoint - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "never". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_ENDPOINT - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "always". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert doesn't exist. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=False): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_ENDPOINT - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert exists. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - 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=mock_client_cert_source): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT - assert cert_source == mock_client_cert_source - - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (DocumentsClient, transports.DocumentsGrpcTransport, "grpc"), - (DocumentsAsyncClient, transports.DocumentsGrpcAsyncIOTransport, "grpc_asyncio"), - (DocumentsClient, transports.DocumentsRestTransport, "rest"), -]) -def test_documents_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, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=["1", "2"], - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - -@pytest.mark.parametrize("client_class,transport_class,transport_name,grpc_helpers", [ - (DocumentsClient, transports.DocumentsGrpcTransport, "grpc", grpc_helpers), - (DocumentsAsyncClient, transports.DocumentsGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), - (DocumentsClient, transports.DocumentsRestTransport, "rest", None), -]) -def test_documents_client_client_options_credentials_file(client_class, transport_class, transport_name, grpc_helpers): - # 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, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file="credentials.json", - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - -def test_documents_client_client_options_from_dict(): - with mock.patch('google.cloud.dialogflow_v2beta1.services.documents.transports.DocumentsGrpcTransport.__init__') as grpc_transport: - grpc_transport.return_value = None - client = DocumentsClient( - client_options={'api_endpoint': 'squid.clam.whelk'} - ) - grpc_transport.assert_called_once_with( - credentials=None, - credentials_file=None, - host="squid.clam.whelk", - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - -@pytest.mark.parametrize("client_class,transport_class,transport_name,grpc_helpers", [ - (DocumentsClient, transports.DocumentsGrpcTransport, "grpc", grpc_helpers), - (DocumentsAsyncClient, transports.DocumentsGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), -]) -def test_documents_client_create_channel_credentials_file(client_class, transport_class, transport_name, grpc_helpers): - # 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, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file="credentials.json", - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # test that the credentials from file are saved and used as the credentials. - with mock.patch.object( - google.auth, "load_credentials_from_file", autospec=True - ) as load_creds, mock.patch.object( - google.auth, "default", autospec=True - ) as adc, mock.patch.object( - grpc_helpers, "create_channel" - ) as create_channel: - creds = ga_credentials.AnonymousCredentials() - file_creds = ga_credentials.AnonymousCredentials() - load_creds.return_value = (file_creds, None) - adc.return_value = (creds, None) - client = client_class(client_options=options, transport=transport_name) - create_channel.assert_called_with( - "dialogflow.googleapis.com:443", - credentials=file_creds, - credentials_file=None, - quota_project_id=None, - default_scopes=( - 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/dialogflow', -), - scopes=None, - default_host="dialogflow.googleapis.com", - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - -@pytest.mark.parametrize("request_type", [ - document.ListDocumentsRequest, - dict, -]) -def test_list_documents(request_type, transport: str = 'grpc'): - client = DocumentsClient( - 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_documents), - '__call__') as call: - # Designate an appropriate return value for the call. - 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' - - -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=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_documents), - '__call__') as call: - client.list_documents() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == document.ListDocumentsRequest() - -@pytest.mark.asyncio -async def test_list_documents_async(transport: str = 'grpc_asyncio', request_type=document.ListDocumentsRequest): - client = DocumentsAsyncClient( - 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_documents), - '__call__') as call: - # Designate an appropriate return value for the call. - 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' - - -@pytest.mark.asyncio -async def test_list_documents_async_from_dict(): - await test_list_documents_async(request_type=dict) - - -def test_list_documents_field_headers(): - 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. - 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_documents_field_headers_async(): - 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. - with mock.patch.object( - type(client.transport.list_documents), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(document.ListDocumentsResponse()) - 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] == 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_documents_flattened(): - 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', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - arg = args[0].parent - mock_val = 'parent_value' - assert arg == mock_val - - -def test_list_documents_flattened_error(): - client = DocumentsClient( - 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_documents( - document.ListDocumentsRequest(), - parent='parent_value', - ) - -@pytest.mark.asyncio -async def test_list_documents_flattened_async(): - 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: - # Designate an appropriate return value for the call. - call.return_value = document.ListDocumentsResponse() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(document.ListDocumentsResponse()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.list_documents( - 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] - arg = args[0].parent - mock_val = 'parent_value' - assert arg == mock_val - -@pytest.mark.asyncio -async def test_list_documents_flattened_error_async(): - client = DocumentsAsyncClient( - 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_documents( - document.ListDocumentsRequest(), - parent='parent_value', - ) - - -def test_list_documents_pager(transport_name: str = "grpc"): - client = DocumentsClient( - credentials=ga_credentials.AnonymousCredentials, - transport=transport_name, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_documents), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - document.ListDocumentsResponse( - documents=[ - document.Document(), - document.Document(), - document.Document(), - ], - next_page_token='abc', - ), - document.ListDocumentsResponse( - documents=[], - next_page_token='def', - ), - document.ListDocumentsResponse( - documents=[ - document.Document(), - ], - next_page_token='ghi', - ), - document.ListDocumentsResponse( - documents=[ - document.Document(), - document.Document(), - ], - ), - RuntimeError, - ) - - metadata = () - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ('parent', ''), - )), - ) - pager = client.list_documents(request={}) - - assert pager._metadata == metadata - - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, document.Document) - for i in results) -def test_list_documents_pages(transport_name: str = "grpc"): - client = DocumentsClient( - credentials=ga_credentials.AnonymousCredentials, - transport=transport_name, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_documents), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - document.ListDocumentsResponse( - documents=[ - document.Document(), - document.Document(), - document.Document(), - ], - next_page_token='abc', - ), - document.ListDocumentsResponse( - documents=[], - next_page_token='def', - ), - document.ListDocumentsResponse( - documents=[ - document.Document(), - ], - next_page_token='ghi', - ), - document.ListDocumentsResponse( - documents=[ - document.Document(), - document.Document(), - ], - ), - RuntimeError, - ) - pages = list(client.list_documents(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_documents_async_pager(): - 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__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - document.ListDocumentsResponse( - documents=[ - document.Document(), - document.Document(), - document.Document(), - ], - next_page_token='abc', - ), - document.ListDocumentsResponse( - documents=[], - next_page_token='def', - ), - document.ListDocumentsResponse( - documents=[ - document.Document(), - ], - next_page_token='ghi', - ), - document.ListDocumentsResponse( - documents=[ - document.Document(), - document.Document(), - ], - ), - RuntimeError, - ) - async_pager = await client.list_documents(request={},) - assert async_pager.next_page_token == 'abc' - responses = [] - async for response in async_pager: # pragma: no branch - responses.append(response) - - assert len(responses) == 6 - assert all(isinstance(i, document.Document) - for i in responses) - - -@pytest.mark.asyncio -async def test_list_documents_async_pages(): - 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__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - document.ListDocumentsResponse( - documents=[ - document.Document(), - document.Document(), - document.Document(), - ], - next_page_token='abc', - ), - document.ListDocumentsResponse( - documents=[], - next_page_token='def', - ), - document.ListDocumentsResponse( - documents=[ - document.Document(), - ], - next_page_token='ghi', - ), - document.ListDocumentsResponse( - documents=[ - document.Document(), - document.Document(), - ], - ), - RuntimeError, - ) - pages = [] - async for page_ in (await client.list_documents(request={})).pages: # pragma: no branch - pages.append(page_) - for page_, token in zip(pages, ['abc','def','ghi', '']): - assert page_.raw_page.next_page_token == token - -@pytest.mark.parametrize("request_type", [ - document.GetDocumentRequest, - dict, -]) -def test_get_document(request_type, transport: str = 'grpc'): - client = DocumentsClient( - 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_document), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = document.Document( - name='name_value', - display_name='display_name_value', - mime_type='mime_type_value', - knowledge_types=[document.Document.KnowledgeType.FAQ], - enable_auto_reload=True, - state=document.Document.State.CREATING, - 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 - assert response.state == document.Document.State.CREATING - - -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=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_document), - '__call__') as call: - client.get_document() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == document.GetDocumentRequest() - -@pytest.mark.asyncio -async def test_get_document_async(transport: str = 'grpc_asyncio', request_type=document.GetDocumentRequest): - client = DocumentsAsyncClient( - 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_document), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(document.Document( - name='name_value', - display_name='display_name_value', - mime_type='mime_type_value', - knowledge_types=[document.Document.KnowledgeType.FAQ], - enable_auto_reload=True, - state=document.Document.State.CREATING, - )) - 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 - assert response.state == document.Document.State.CREATING - - -@pytest.mark.asyncio -async def test_get_document_async_from_dict(): - await test_get_document_async(request_type=dict) - - -def test_get_document_field_headers(): - 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. - 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_document_field_headers_async(): - 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. - 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_document_flattened(): - 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', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - arg = args[0].name - mock_val = 'name_value' - assert arg == mock_val - - -def test_get_document_flattened_error(): - client = DocumentsClient( - 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_document( - document.GetDocumentRequest(), - name='name_value', - ) - -@pytest.mark.asyncio -async def test_get_document_flattened_async(): - 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: - # Designate an appropriate return value for the call. - call.return_value = document.Document() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(document.Document()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.get_document( - 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] - arg = args[0].name - mock_val = 'name_value' - assert arg == mock_val - -@pytest.mark.asyncio -async def test_get_document_flattened_error_async(): - client = DocumentsAsyncClient( - 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_document( - document.GetDocumentRequest(), - name='name_value', - ) - - -@pytest.mark.parametrize("request_type", [ - gcd_document.CreateDocumentRequest, - dict, -]) -def test_create_document(request_type, transport: str = 'grpc'): - client = DocumentsClient( - 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_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. - assert isinstance(response, future.Future) - - -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=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_document), - '__call__') as call: - client.create_document() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == gcd_document.CreateDocumentRequest() - -@pytest.mark.asyncio -async def test_create_document_async(transport: str = 'grpc_asyncio', request_type=gcd_document.CreateDocumentRequest): - client = DocumentsAsyncClient( - 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_document), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name='operations/spam') - ) - response = await client.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. - assert isinstance(response, future.Future) - - -@pytest.mark.asyncio -async def test_create_document_async_from_dict(): - await test_create_document_async(request_type=dict) - - -def test_create_document_field_headers(): - 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. - 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_document_field_headers_async(): - 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. - with mock.patch.object( - type(client.transport.create_document), - '__call__') as call: - 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. - 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_document_flattened(): - 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( - parent='parent_value', - document=gcd_document.Document(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] - arg = args[0].parent - mock_val = 'parent_value' - assert arg == mock_val - arg = args[0].document - mock_val = gcd_document.Document(name='name_value') - assert arg == mock_val - - -def test_create_document_flattened_error(): - client = DocumentsClient( - 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_document( - gcd_document.CreateDocumentRequest(), - parent='parent_value', - document=gcd_document.Document(name='name_value'), - ) - -@pytest.mark.asyncio -async def test_create_document_flattened_async(): - 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: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/op') - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name='operations/spam') - ) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.create_document( - parent='parent_value', - document=gcd_document.Document(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] - arg = args[0].parent - mock_val = 'parent_value' - assert arg == mock_val - arg = args[0].document - mock_val = gcd_document.Document(name='name_value') - assert arg == mock_val - -@pytest.mark.asyncio -async def test_create_document_flattened_error_async(): - client = DocumentsAsyncClient( - 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_document( - gcd_document.CreateDocumentRequest(), - parent='parent_value', - document=gcd_document.Document(name='name_value'), - ) - - -@pytest.mark.parametrize("request_type", [ - document.ImportDocumentsRequest, - dict, -]) -def test_import_documents(request_type, transport: str = 'grpc'): - client = DocumentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.import_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. - assert isinstance(response, future.Future) - - -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=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.import_documents), - '__call__') as call: - client.import_documents() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == document.ImportDocumentsRequest() - -@pytest.mark.asyncio -async def test_import_documents_async(transport: str = 'grpc_asyncio', request_type=document.ImportDocumentsRequest): - client = DocumentsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.import_documents), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name='operations/spam') - ) - response = await client.import_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. - assert isinstance(response, future.Future) - - -@pytest.mark.asyncio -async def test_import_documents_async_from_dict(): - await test_import_documents_async(request_type=dict) - - -def test_import_documents_field_headers(): - 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. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'parent=parent_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_import_documents_field_headers_async(): - 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. - with mock.patch.object( - type(client.transport.import_documents), - '__call__') as call: - 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. - 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'] - - -@pytest.mark.parametrize("request_type", [ - document.DeleteDocumentRequest, - dict, -]) -def test_delete_document(request_type, transport: str = 'grpc'): - client = DocumentsClient( - 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_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. - assert isinstance(response, future.Future) - - -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=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_document), - '__call__') as call: - client.delete_document() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == document.DeleteDocumentRequest() - -@pytest.mark.asyncio -async def test_delete_document_async(transport: str = 'grpc_asyncio', request_type=document.DeleteDocumentRequest): - client = DocumentsAsyncClient( - 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_document), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name='operations/spam') - ) - response = await client.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. - assert isinstance(response, future.Future) - - -@pytest.mark.asyncio -async def test_delete_document_async_from_dict(): - await test_delete_document_async(request_type=dict) - - -def test_delete_document_field_headers(): - 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. - 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_document_field_headers_async(): - 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. - with mock.patch.object( - type(client.transport.delete_document), - '__call__') as call: - 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. - 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_document_flattened(): - 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', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - arg = args[0].name - mock_val = 'name_value' - assert arg == mock_val - - -def test_delete_document_flattened_error(): - client = DocumentsClient( - 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_document( - document.DeleteDocumentRequest(), - name='name_value', - ) - -@pytest.mark.asyncio -async def test_delete_document_flattened_async(): - 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: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/op') - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name='operations/spam') - ) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.delete_document( - 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] - arg = args[0].name - mock_val = 'name_value' - assert arg == mock_val - -@pytest.mark.asyncio -async def test_delete_document_flattened_error_async(): - client = DocumentsAsyncClient( - 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_document( - document.DeleteDocumentRequest(), - name='name_value', - ) - - -@pytest.mark.parametrize("request_type", [ - gcd_document.UpdateDocumentRequest, - dict, -]) -def test_update_document(request_type, transport: str = 'grpc'): - client = DocumentsClient( - 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_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. - assert isinstance(response, future.Future) - - -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=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_document), - '__call__') as call: - client.update_document() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == gcd_document.UpdateDocumentRequest() - -@pytest.mark.asyncio -async def test_update_document_async(transport: str = 'grpc_asyncio', request_type=gcd_document.UpdateDocumentRequest): - client = DocumentsAsyncClient( - 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_document), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name='operations/spam') - ) - response = await client.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. - assert isinstance(response, future.Future) - - -@pytest.mark.asyncio -async def test_update_document_async_from_dict(): - await test_update_document_async(request_type=dict) - - -def test_update_document_field_headers(): - 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 = '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. - 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', - 'document.name=name_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_update_document_field_headers_async(): - 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 = '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 = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) - 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] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'document.name=name_value', - ) in kw['metadata'] - - -def test_update_document_flattened(): - 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_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] - arg = args[0].document - mock_val = gcd_document.Document(name='name_value') - assert arg == mock_val - arg = args[0].update_mask - mock_val = field_mask_pb2.FieldMask(paths=['paths_value']) - assert arg == mock_val - - -def test_update_document_flattened_error(): - client = DocumentsClient( - 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_document( - gcd_document.UpdateDocumentRequest(), - document=gcd_document.Document(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - -@pytest.mark.asyncio -async def test_update_document_flattened_async(): - 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: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/op') - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name='operations/spam') - ) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.update_document( - document=gcd_document.Document(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] - arg = args[0].document - mock_val = gcd_document.Document(name='name_value') - assert arg == mock_val - arg = args[0].update_mask - mock_val = field_mask_pb2.FieldMask(paths=['paths_value']) - assert arg == mock_val - -@pytest.mark.asyncio -async def test_update_document_flattened_error_async(): - client = DocumentsAsyncClient( - 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_document( - gcd_document.UpdateDocumentRequest(), - document=gcd_document.Document(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - - -@pytest.mark.parametrize("request_type", [ - document.ReloadDocumentRequest, - dict, -]) -def test_reload_document(request_type, transport: str = 'grpc'): - client = DocumentsClient( - 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.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. - assert isinstance(response, future.Future) - - -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=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.reload_document), - '__call__') as call: - client.reload_document() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == document.ReloadDocumentRequest() - -@pytest.mark.asyncio -async def test_reload_document_async(transport: str = 'grpc_asyncio', request_type=document.ReloadDocumentRequest): - client = DocumentsAsyncClient( - 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.reload_document), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name='operations/spam') - ) - response = await client.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. - assert isinstance(response, future.Future) - - -@pytest.mark.asyncio -async def test_reload_document_async_from_dict(): - await test_reload_document_async(request_type=dict) - - -def test_reload_document_field_headers(): - 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. - 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_reload_document_field_headers_async(): - 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. - with mock.patch.object( - type(client.transport.reload_document), - '__call__') as call: - 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. - 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_reload_document_flattened(): - 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( - name='name_value', - gcs_source=gcs.GcsSource(uri='uri_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] - arg = args[0].name - mock_val = 'name_value' - assert arg == mock_val - assert args[0].gcs_source == gcs.GcsSource(uri='uri_value') - - -def test_reload_document_flattened_error(): - client = DocumentsClient( - 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.reload_document( - document.ReloadDocumentRequest(), - name='name_value', - gcs_source=gcs.GcsSource(uri='uri_value'), - ) - -@pytest.mark.asyncio -async def test_reload_document_flattened_async(): - 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: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/op') - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name='operations/spam') - ) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.reload_document( - name='name_value', - gcs_source=gcs.GcsSource(uri='uri_value'), - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - arg = args[0].name - mock_val = 'name_value' - assert arg == mock_val - assert args[0].gcs_source == gcs.GcsSource(uri='uri_value') - -@pytest.mark.asyncio -async def test_reload_document_flattened_error_async(): - client = DocumentsAsyncClient( - 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.reload_document( - document.ReloadDocumentRequest(), - name='name_value', - gcs_source=gcs.GcsSource(uri='uri_value'), - ) - - -@pytest.mark.parametrize("request_type", [ - document.ListDocumentsRequest, - dict, -]) -def test_list_documents_rest(request_type): - client = DocumentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1/knowledgeBases/sample2'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = document.ListDocumentsResponse( - next_page_token='next_page_token_value', - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - pb_return_value = document.ListDocumentsResponse.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.list_documents(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListDocumentsPager) - assert response.next_page_token == 'next_page_token_value' - - -def test_list_documents_rest_required_fields(request_type=document.ListDocumentsRequest): - transport_class = transports.DocumentsRestTransport - - request_init = {} - request_init["parent"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - including_default_value_fields=False, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).list_documents._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["parent"] = 'parent_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).list_documents._get_unset_required_fields(jsonified_request) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("filter", "page_size", "page_token", )) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "parent" in jsonified_request - assert jsonified_request["parent"] == 'parent_value' - - client = DocumentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = document.ListDocumentsResponse() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "get", - 'query_params': pb_request, - } - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - - pb_return_value = document.ListDocumentsResponse.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.list_documents(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_list_documents_rest_unset_required_fields(): - transport = transports.DocumentsRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.list_documents._get_unset_required_fields({}) - assert set(unset_fields) == (set(("filter", "pageSize", "pageToken", )) & set(("parent", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_list_documents_rest_interceptors(null_interceptor): - transport = transports.DocumentsRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.DocumentsRestInterceptor(), - ) - client = DocumentsClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.DocumentsRestInterceptor, "post_list_documents") as post, \ - mock.patch.object(transports.DocumentsRestInterceptor, "pre_list_documents") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = document.ListDocumentsRequest.pb(document.ListDocumentsRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = document.ListDocumentsResponse.to_json(document.ListDocumentsResponse()) - - request = document.ListDocumentsRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = document.ListDocumentsResponse() - - client.list_documents(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_list_documents_rest_bad_request(transport: str = 'rest', request_type=document.ListDocumentsRequest): - client = DocumentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1/knowledgeBases/sample2'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.list_documents(request) - - -def test_list_documents_rest_flattened(): - client = DocumentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = document.ListDocumentsResponse() - - # get arguments that satisfy an http rule for this method - sample_request = {'parent': 'projects/sample1/knowledgeBases/sample2'} - - # get truthy value for each flattened field - mock_args = dict( - parent='parent_value', - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - pb_return_value = document.ListDocumentsResponse.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.list_documents(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v2beta1/{parent=projects/*/knowledgeBases/*}/documents" % client.transport._host, args[1]) - - -def test_list_documents_rest_flattened_error(transport: str = 'rest'): - client = DocumentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.list_documents( - document.ListDocumentsRequest(), - parent='parent_value', - ) - - -def test_list_documents_rest_pager(transport: str = 'rest'): - client = DocumentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # TODO(kbandes): remove this mock unless there's a good reason for it. - #with mock.patch.object(path_template, 'transcode') as transcode: - # Set the response as a series of pages - response = ( - document.ListDocumentsResponse( - documents=[ - document.Document(), - document.Document(), - document.Document(), - ], - next_page_token='abc', - ), - document.ListDocumentsResponse( - documents=[], - next_page_token='def', - ), - document.ListDocumentsResponse( - documents=[ - document.Document(), - ], - next_page_token='ghi', - ), - document.ListDocumentsResponse( - documents=[ - document.Document(), - document.Document(), - ], - ), - ) - # Two responses for two calls - response = response + response - - # Wrap the values into proper Response objs - response = tuple(document.ListDocumentsResponse.to_json(x) for x in response) - return_values = tuple(Response() for i in response) - for return_val, response_val in zip(return_values, response): - return_val._content = response_val.encode('UTF-8') - return_val.status_code = 200 - req.side_effect = return_values - - sample_request = {'parent': 'projects/sample1/knowledgeBases/sample2'} - - pager = client.list_documents(request=sample_request) - - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, document.Document) - for i in results) - - pages = list(client.list_documents(request=sample_request).pages) - for page_, token in zip(pages, ['abc','def','ghi', '']): - assert page_.raw_page.next_page_token == token - - -@pytest.mark.parametrize("request_type", [ - document.GetDocumentRequest, - dict, -]) -def test_get_document_rest(request_type): - client = DocumentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/knowledgeBases/sample2/documents/sample3'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = document.Document( - name='name_value', - display_name='display_name_value', - mime_type='mime_type_value', - knowledge_types=[document.Document.KnowledgeType.FAQ], - enable_auto_reload=True, - state=document.Document.State.CREATING, - content_uri='content_uri_value', - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - pb_return_value = document.Document.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.get_document(request) - - # 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 - assert response.state == document.Document.State.CREATING - - -def test_get_document_rest_required_fields(request_type=document.GetDocumentRequest): - transport_class = transports.DocumentsRestTransport - - request_init = {} - request_init["name"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - including_default_value_fields=False, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_document._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["name"] = 'name_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_document._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "name" in jsonified_request - assert jsonified_request["name"] == 'name_value' - - client = DocumentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = document.Document() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "get", - 'query_params': pb_request, - } - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - - pb_return_value = document.Document.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.get_document(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_get_document_rest_unset_required_fields(): - transport = transports.DocumentsRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.get_document._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_get_document_rest_interceptors(null_interceptor): - transport = transports.DocumentsRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.DocumentsRestInterceptor(), - ) - client = DocumentsClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.DocumentsRestInterceptor, "post_get_document") as post, \ - mock.patch.object(transports.DocumentsRestInterceptor, "pre_get_document") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = document.GetDocumentRequest.pb(document.GetDocumentRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = document.Document.to_json(document.Document()) - - request = document.GetDocumentRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = document.Document() - - client.get_document(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_get_document_rest_bad_request(transport: str = 'rest', request_type=document.GetDocumentRequest): - client = DocumentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/knowledgeBases/sample2/documents/sample3'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.get_document(request) - - -def test_get_document_rest_flattened(): - client = DocumentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = document.Document() - - # get arguments that satisfy an http rule for this method - sample_request = {'name': 'projects/sample1/knowledgeBases/sample2/documents/sample3'} - - # get truthy value for each flattened field - mock_args = dict( - name='name_value', - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - pb_return_value = document.Document.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.get_document(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v2beta1/{name=projects/*/knowledgeBases/*/documents/*}" % client.transport._host, args[1]) - - -def test_get_document_rest_flattened_error(transport: str = 'rest'): - client = DocumentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.get_document( - document.GetDocumentRequest(), - name='name_value', - ) - - -def test_get_document_rest_error(): - client = DocumentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - gcd_document.CreateDocumentRequest, - dict, -]) -def test_create_document_rest(request_type): - client = DocumentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1/knowledgeBases/sample2'} - request_init["document"] = {'name': 'name_value', 'display_name': 'display_name_value', 'mime_type': 'mime_type_value', 'knowledge_types': [1], 'content_uri': 'content_uri_value', 'content': 'content_value', 'raw_content': b'raw_content_blob', 'enable_auto_reload': True, 'latest_reload_status': {'time': {'seconds': 751, 'nanos': 543}, 'status': {'code': 411, 'message': 'message_value', 'details': [{'type_url': 'type.googleapis.com/google.protobuf.Duration', 'value': b'\x08\x0c\x10\xdb\x07'}]}}, 'metadata': {}, 'state': 1} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name='operations/spam') - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.create_document(request) - - # Establish that the response is the type that we expect. - assert response.operation.name == "operations/spam" - - -def test_create_document_rest_required_fields(request_type=gcd_document.CreateDocumentRequest): - transport_class = transports.DocumentsRestTransport - - request_init = {} - request_init["parent"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - including_default_value_fields=False, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_document._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["parent"] = 'parent_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_document._get_unset_required_fields(jsonified_request) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("import_gcs_custom_metadata", )) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "parent" in jsonified_request - assert jsonified_request["parent"] == 'parent_value' - - client = DocumentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name='operations/spam') - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "post", - 'query_params': pb_request, - } - transcode_result['body'] = pb_request - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.create_document(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_create_document_rest_unset_required_fields(): - transport = transports.DocumentsRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.create_document._get_unset_required_fields({}) - assert set(unset_fields) == (set(("importGcsCustomMetadata", )) & set(("parent", "document", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_create_document_rest_interceptors(null_interceptor): - transport = transports.DocumentsRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.DocumentsRestInterceptor(), - ) - client = DocumentsClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(operation.Operation, "_set_result_from_operation"), \ - mock.patch.object(transports.DocumentsRestInterceptor, "post_create_document") as post, \ - mock.patch.object(transports.DocumentsRestInterceptor, "pre_create_document") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = gcd_document.CreateDocumentRequest.pb(gcd_document.CreateDocumentRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = json_format.MessageToJson(operations_pb2.Operation()) - - request = gcd_document.CreateDocumentRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = operations_pb2.Operation() - - client.create_document(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_create_document_rest_bad_request(transport: str = 'rest', request_type=gcd_document.CreateDocumentRequest): - client = DocumentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1/knowledgeBases/sample2'} - request_init["document"] = {'name': 'name_value', 'display_name': 'display_name_value', 'mime_type': 'mime_type_value', 'knowledge_types': [1], 'content_uri': 'content_uri_value', 'content': 'content_value', 'raw_content': b'raw_content_blob', 'enable_auto_reload': True, 'latest_reload_status': {'time': {'seconds': 751, 'nanos': 543}, 'status': {'code': 411, 'message': 'message_value', 'details': [{'type_url': 'type.googleapis.com/google.protobuf.Duration', 'value': b'\x08\x0c\x10\xdb\x07'}]}}, 'metadata': {}, 'state': 1} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.create_document(request) - - -def test_create_document_rest_flattened(): - client = DocumentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name='operations/spam') - - # get arguments that satisfy an http rule for this method - sample_request = {'parent': 'projects/sample1/knowledgeBases/sample2'} - - # get truthy value for each flattened field - mock_args = dict( - parent='parent_value', - document=gcd_document.Document(name='name_value'), - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.create_document(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v2beta1/{parent=projects/*/knowledgeBases/*}/documents" % client.transport._host, args[1]) - - -def test_create_document_rest_flattened_error(transport: str = 'rest'): - client = DocumentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.create_document( - gcd_document.CreateDocumentRequest(), - parent='parent_value', - document=gcd_document.Document(name='name_value'), - ) - - -def test_create_document_rest_error(): - client = DocumentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - document.ImportDocumentsRequest, - dict, -]) -def test_import_documents_rest(request_type): - client = DocumentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1/knowledgeBases/sample2'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name='operations/spam') - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.import_documents(request) - - # Establish that the response is the type that we expect. - assert response.operation.name == "operations/spam" - - -def test_import_documents_rest_required_fields(request_type=document.ImportDocumentsRequest): - transport_class = transports.DocumentsRestTransport - - request_init = {} - request_init["parent"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - including_default_value_fields=False, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).import_documents._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["parent"] = 'parent_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).import_documents._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "parent" in jsonified_request - assert jsonified_request["parent"] == 'parent_value' - - client = DocumentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name='operations/spam') - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "post", - 'query_params': pb_request, - } - transcode_result['body'] = pb_request - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.import_documents(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_import_documents_rest_unset_required_fields(): - transport = transports.DocumentsRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.import_documents._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("parent", "documentTemplate", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_import_documents_rest_interceptors(null_interceptor): - transport = transports.DocumentsRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.DocumentsRestInterceptor(), - ) - client = DocumentsClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(operation.Operation, "_set_result_from_operation"), \ - mock.patch.object(transports.DocumentsRestInterceptor, "post_import_documents") as post, \ - mock.patch.object(transports.DocumentsRestInterceptor, "pre_import_documents") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = document.ImportDocumentsRequest.pb(document.ImportDocumentsRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = json_format.MessageToJson(operations_pb2.Operation()) - - request = document.ImportDocumentsRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = operations_pb2.Operation() - - client.import_documents(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_import_documents_rest_bad_request(transport: str = 'rest', request_type=document.ImportDocumentsRequest): - client = DocumentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1/knowledgeBases/sample2'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.import_documents(request) - - -def test_import_documents_rest_error(): - client = DocumentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - document.DeleteDocumentRequest, - dict, -]) -def test_delete_document_rest(request_type): - client = DocumentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/knowledgeBases/sample2/documents/sample3'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name='operations/spam') - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.delete_document(request) - - # Establish that the response is the type that we expect. - assert response.operation.name == "operations/spam" - - -def test_delete_document_rest_required_fields(request_type=document.DeleteDocumentRequest): - transport_class = transports.DocumentsRestTransport - - request_init = {} - request_init["name"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - including_default_value_fields=False, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).delete_document._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["name"] = 'name_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).delete_document._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "name" in jsonified_request - assert jsonified_request["name"] == 'name_value' - - client = DocumentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name='operations/spam') - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "delete", - 'query_params': pb_request, - } - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.delete_document(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_delete_document_rest_unset_required_fields(): - transport = transports.DocumentsRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.delete_document._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_delete_document_rest_interceptors(null_interceptor): - transport = transports.DocumentsRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.DocumentsRestInterceptor(), - ) - client = DocumentsClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(operation.Operation, "_set_result_from_operation"), \ - mock.patch.object(transports.DocumentsRestInterceptor, "post_delete_document") as post, \ - mock.patch.object(transports.DocumentsRestInterceptor, "pre_delete_document") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = document.DeleteDocumentRequest.pb(document.DeleteDocumentRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = json_format.MessageToJson(operations_pb2.Operation()) - - request = document.DeleteDocumentRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = operations_pb2.Operation() - - client.delete_document(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_delete_document_rest_bad_request(transport: str = 'rest', request_type=document.DeleteDocumentRequest): - client = DocumentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/knowledgeBases/sample2/documents/sample3'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.delete_document(request) - - -def test_delete_document_rest_flattened(): - client = DocumentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name='operations/spam') - - # get arguments that satisfy an http rule for this method - sample_request = {'name': 'projects/sample1/knowledgeBases/sample2/documents/sample3'} - - # get truthy value for each flattened field - mock_args = dict( - name='name_value', - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.delete_document(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v2beta1/{name=projects/*/knowledgeBases/*/documents/*}" % client.transport._host, args[1]) - - -def test_delete_document_rest_flattened_error(transport: str = 'rest'): - client = DocumentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.delete_document( - document.DeleteDocumentRequest(), - name='name_value', - ) - - -def test_delete_document_rest_error(): - client = DocumentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - gcd_document.UpdateDocumentRequest, - dict, -]) -def test_update_document_rest(request_type): - client = DocumentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'document': {'name': 'projects/sample1/knowledgeBases/sample2/documents/sample3'}} - request_init["document"] = {'name': 'projects/sample1/knowledgeBases/sample2/documents/sample3', 'display_name': 'display_name_value', 'mime_type': 'mime_type_value', 'knowledge_types': [1], 'content_uri': 'content_uri_value', 'content': 'content_value', 'raw_content': b'raw_content_blob', 'enable_auto_reload': True, 'latest_reload_status': {'time': {'seconds': 751, 'nanos': 543}, 'status': {'code': 411, 'message': 'message_value', 'details': [{'type_url': 'type.googleapis.com/google.protobuf.Duration', 'value': b'\x08\x0c\x10\xdb\x07'}]}}, 'metadata': {}, 'state': 1} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name='operations/spam') - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.update_document(request) - - # Establish that the response is the type that we expect. - assert response.operation.name == "operations/spam" - - -def test_update_document_rest_required_fields(request_type=gcd_document.UpdateDocumentRequest): - transport_class = transports.DocumentsRestTransport - - request_init = {} - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - including_default_value_fields=False, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).update_document._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).update_document._get_unset_required_fields(jsonified_request) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("update_mask", )) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - - client = DocumentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name='operations/spam') - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "patch", - 'query_params': pb_request, - } - transcode_result['body'] = pb_request - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.update_document(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_update_document_rest_unset_required_fields(): - transport = transports.DocumentsRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.update_document._get_unset_required_fields({}) - assert set(unset_fields) == (set(("updateMask", )) & set(("document", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_update_document_rest_interceptors(null_interceptor): - transport = transports.DocumentsRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.DocumentsRestInterceptor(), - ) - client = DocumentsClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(operation.Operation, "_set_result_from_operation"), \ - mock.patch.object(transports.DocumentsRestInterceptor, "post_update_document") as post, \ - mock.patch.object(transports.DocumentsRestInterceptor, "pre_update_document") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = gcd_document.UpdateDocumentRequest.pb(gcd_document.UpdateDocumentRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = json_format.MessageToJson(operations_pb2.Operation()) - - request = gcd_document.UpdateDocumentRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = operations_pb2.Operation() - - client.update_document(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_update_document_rest_bad_request(transport: str = 'rest', request_type=gcd_document.UpdateDocumentRequest): - client = DocumentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'document': {'name': 'projects/sample1/knowledgeBases/sample2/documents/sample3'}} - request_init["document"] = {'name': 'projects/sample1/knowledgeBases/sample2/documents/sample3', 'display_name': 'display_name_value', 'mime_type': 'mime_type_value', 'knowledge_types': [1], 'content_uri': 'content_uri_value', 'content': 'content_value', 'raw_content': b'raw_content_blob', 'enable_auto_reload': True, 'latest_reload_status': {'time': {'seconds': 751, 'nanos': 543}, 'status': {'code': 411, 'message': 'message_value', 'details': [{'type_url': 'type.googleapis.com/google.protobuf.Duration', 'value': b'\x08\x0c\x10\xdb\x07'}]}}, 'metadata': {}, 'state': 1} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.update_document(request) - - -def test_update_document_rest_flattened(): - client = DocumentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name='operations/spam') - - # get arguments that satisfy an http rule for this method - sample_request = {'document': {'name': 'projects/sample1/knowledgeBases/sample2/documents/sample3'}} - - # get truthy value for each flattened field - mock_args = dict( - document=gcd_document.Document(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.update_document(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v2beta1/{document.name=projects/*/knowledgeBases/*/documents/*}" % client.transport._host, args[1]) - - -def test_update_document_rest_flattened_error(transport: str = 'rest'): - client = DocumentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.update_document( - gcd_document.UpdateDocumentRequest(), - document=gcd_document.Document(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - - -def test_update_document_rest_error(): - client = DocumentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - document.ReloadDocumentRequest, - dict, -]) -def test_reload_document_rest(request_type): - client = DocumentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/knowledgeBases/sample2/documents/sample3'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name='operations/spam') - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.reload_document(request) - - # Establish that the response is the type that we expect. - assert response.operation.name == "operations/spam" - - -def test_reload_document_rest_required_fields(request_type=document.ReloadDocumentRequest): - transport_class = transports.DocumentsRestTransport - - request_init = {} - request_init["name"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - including_default_value_fields=False, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).reload_document._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["name"] = 'name_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).reload_document._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "name" in jsonified_request - assert jsonified_request["name"] == 'name_value' - - client = DocumentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name='operations/spam') - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "post", - 'query_params': pb_request, - } - transcode_result['body'] = pb_request - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.reload_document(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_reload_document_rest_unset_required_fields(): - transport = transports.DocumentsRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.reload_document._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_reload_document_rest_interceptors(null_interceptor): - transport = transports.DocumentsRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.DocumentsRestInterceptor(), - ) - client = DocumentsClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(operation.Operation, "_set_result_from_operation"), \ - mock.patch.object(transports.DocumentsRestInterceptor, "post_reload_document") as post, \ - mock.patch.object(transports.DocumentsRestInterceptor, "pre_reload_document") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = document.ReloadDocumentRequest.pb(document.ReloadDocumentRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = json_format.MessageToJson(operations_pb2.Operation()) - - request = document.ReloadDocumentRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = operations_pb2.Operation() - - client.reload_document(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_reload_document_rest_bad_request(transport: str = 'rest', request_type=document.ReloadDocumentRequest): - client = DocumentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/knowledgeBases/sample2/documents/sample3'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.reload_document(request) - - -def test_reload_document_rest_flattened(): - client = DocumentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name='operations/spam') - - # get arguments that satisfy an http rule for this method - sample_request = {'name': 'projects/sample1/knowledgeBases/sample2/documents/sample3'} - - # get truthy value for each flattened field - mock_args = dict( - name='name_value', - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.reload_document(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v2beta1/{name=projects/*/knowledgeBases/*/documents/*}:reload" % client.transport._host, args[1]) - - -def test_reload_document_rest_flattened_error(transport: str = 'rest'): - client = DocumentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.reload_document( - document.ReloadDocumentRequest(), - name='name_value', - gcs_source=gcs.GcsSource(uri='uri_value'), - ) - - -def test_reload_document_rest_error(): - client = DocumentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -def test_credentials_transport_error(): - # It is an error to provide credentials and a transport instance. - transport = transports.DocumentsGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = DocumentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # It is an error to provide a credentials file and a transport instance. - transport = transports.DocumentsGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = DocumentsClient( - client_options={"credentials_file": "credentials.json"}, - transport=transport, - ) - - # It is an error to provide an api_key and a transport instance. - transport = transports.DocumentsGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - options = client_options.ClientOptions() - options.api_key = "api_key" - with pytest.raises(ValueError): - client = DocumentsClient( - client_options=options, - transport=transport, - ) - - # It is an error to provide an api_key and a credential. - options = mock.Mock() - options.api_key = "api_key" - with pytest.raises(ValueError): - client = DocumentsClient( - client_options=options, - credentials=ga_credentials.AnonymousCredentials() - ) - - # It is an error to provide scopes and a transport instance. - transport = transports.DocumentsGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = DocumentsClient( - client_options={"scopes": ["1", "2"]}, - transport=transport, - ) - - -def test_transport_instance(): - # A client may be instantiated with a custom transport instance. - transport = transports.DocumentsGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - client = DocumentsClient(transport=transport) - assert client.transport is transport - -def test_transport_get_channel(): - # A client may be instantiated with a custom transport instance. - transport = transports.DocumentsGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - - transport = transports.DocumentsGrpcAsyncIOTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - -@pytest.mark.parametrize("transport_class", [ - transports.DocumentsGrpcTransport, - transports.DocumentsGrpcAsyncIOTransport, - transports.DocumentsRestTransport, -]) -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() - -@pytest.mark.parametrize("transport_name", [ - "grpc", - "rest", -]) -def test_transport_kind(transport_name): - transport = DocumentsClient.get_transport_class(transport_name)( - credentials=ga_credentials.AnonymousCredentials(), - ) - assert transport.kind == transport_name - -def test_transport_grpc_default(): - # A client should use the gRPC transport by default. - 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(core_exceptions.DuplicateCredentialArgs): - transport = transports.DocumentsTransport( - credentials=ga_credentials.AnonymousCredentials(), - credentials_file="credentials.json" - ) - - -def test_documents_base_transport(): - # Instantiate the base transport. - with mock.patch('google.cloud.dialogflow_v2beta1.services.documents.transports.DocumentsTransport.__init__') as Transport: - Transport.return_value = None - transport = transports.DocumentsTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Every method on the transport should just blindly - # raise NotImplementedError. - methods = ( - 'list_documents', - 'get_document', - 'create_document', - 'import_documents', - 'delete_document', - 'update_document', - 'reload_document', - 'get_location', - 'list_locations', - 'get_operation', - 'cancel_operation', - 'list_operations', - ) - for method in methods: - with pytest.raises(NotImplementedError): - getattr(transport, method)(request=object()) - - with pytest.raises(NotImplementedError): - transport.close() - - # Additionally, the LRO client (a property) should - # also raise NotImplementedError - with pytest.raises(NotImplementedError): - transport.operations_client - - # Catch all for all remaining methods and properties - remainder = [ - 'kind', - ] - for r in remainder: - with pytest.raises(NotImplementedError): - getattr(transport, r)() - - -def test_documents_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.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", - ) - - -def test_documents_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.documents.transports.DocumentsTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.DocumentsTransport() - adc.assert_called_once() - - -def test_documents_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) - 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, - ) - - -@pytest.mark.parametrize( - "transport_class", - [ - transports.DocumentsGrpcTransport, - transports.DocumentsGrpcAsyncIOTransport, - ], -) -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(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, - transports.DocumentsRestTransport, - ], -) -def test_documents_transport_auth_gdch_credentials(transport_class): - host = 'https://language.com' - api_audience_tests = [None, 'https://language2.com'] - api_audience_expect = [host, 'https://language2.com'] - for t, e in zip(api_audience_tests, api_audience_expect): - with mock.patch.object(google.auth, 'default', autospec=True) as adc: - gdch_mock = mock.MagicMock() - type(gdch_mock).with_gdch_audience = mock.PropertyMock(return_value=gdch_mock) - adc.return_value = (gdch_mock, None) - transport_class(host=host, api_audience=t) - gdch_mock.with_gdch_audience.assert_called_once_with( - e - ) - - -@pytest.mark.parametrize( - "transport_class,grpc_helpers", - [ - (transports.DocumentsGrpcTransport, grpc_helpers), - (transports.DocumentsGrpcAsyncIOTransport, grpc_helpers_async) - ], -) -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", [transports.DocumentsGrpcTransport, transports.DocumentsGrpcAsyncIOTransport]) -def test_documents_grpc_transport_client_cert_source_for_mtls( - transport_class -): - cred = ga_credentials.AnonymousCredentials() - - # Check ssl_channel_credentials is used if provided. - with mock.patch.object(transport_class, "create_channel") as mock_create_channel: - mock_ssl_channel_creds = mock.Mock() - transport_class( - host="squid.clam.whelk", - credentials=cred, - ssl_channel_credentials=mock_ssl_channel_creds - ) - mock_create_channel.assert_called_once_with( - "squid.clam.whelk:443", - credentials=cred, - credentials_file=None, - scopes=None, - ssl_credentials=mock_ssl_channel_creds, - quota_project_id=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - # Check if ssl_channel_credentials is not provided, then client_cert_source_for_mtls - # is used. - with mock.patch.object(transport_class, "create_channel", return_value=mock.Mock()): - with mock.patch("grpc.ssl_channel_credentials") as mock_ssl_cred: - transport_class( - credentials=cred, - client_cert_source_for_mtls=client_cert_source_callback - ) - expected_cert, expected_key = client_cert_source_callback() - mock_ssl_cred.assert_called_once_with( - certificate_chain=expected_cert, - private_key=expected_key - ) - -def test_documents_http_transport_client_cert_source_for_mtls(): - cred = ga_credentials.AnonymousCredentials() - with mock.patch("google.auth.transport.requests.AuthorizedSession.configure_mtls_channel") as mock_configure_mtls_channel: - transports.DocumentsRestTransport ( - credentials=cred, - client_cert_source_for_mtls=client_cert_source_callback - ) - mock_configure_mtls_channel.assert_called_once_with(client_cert_source_callback) - - -def test_documents_rest_lro_client(): - client = DocumentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - transport = client.transport - - # Ensure that we have a api-core operations client. - assert isinstance( - transport.operations_client, - operations_v1.AbstractOperationsClient, - ) - - # Ensure that subsequent calls to the property send the exact same object. - assert transport.operations_client is transport.operations_client - - -@pytest.mark.parametrize("transport_name", [ - "grpc", - "grpc_asyncio", - "rest", -]) -def test_documents_host_no_port(transport_name): - client = DocumentsClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='dialogflow.googleapis.com'), - transport=transport_name, - ) - assert client.transport._host == ( - 'dialogflow.googleapis.com:443' - if transport_name in ['grpc', 'grpc_asyncio'] - else 'https://dialogflow.googleapis.com' - ) - -@pytest.mark.parametrize("transport_name", [ - "grpc", - "grpc_asyncio", - "rest", -]) -def test_documents_host_with_port(transport_name): - client = DocumentsClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='dialogflow.googleapis.com:8000'), - transport=transport_name, - ) - assert client.transport._host == ( - 'dialogflow.googleapis.com:8000' - if transport_name in ['grpc', 'grpc_asyncio'] - else 'https://dialogflow.googleapis.com:8000' - ) - -@pytest.mark.parametrize("transport_name", [ - "rest", -]) -def test_documents_client_transport_session_collision(transport_name): - creds1 = ga_credentials.AnonymousCredentials() - creds2 = ga_credentials.AnonymousCredentials() - client1 = DocumentsClient( - credentials=creds1, - transport=transport_name, - ) - client2 = DocumentsClient( - credentials=creds2, - transport=transport_name, - ) - session1 = client1.transport.list_documents._session - session2 = client2.transport.list_documents._session - assert session1 != session2 - session1 = client1.transport.get_document._session - session2 = client2.transport.get_document._session - assert session1 != session2 - session1 = client1.transport.create_document._session - session2 = client2.transport.create_document._session - assert session1 != session2 - session1 = client1.transport.import_documents._session - session2 = client2.transport.import_documents._session - assert session1 != session2 - session1 = client1.transport.delete_document._session - session2 = client2.transport.delete_document._session - assert session1 != session2 - session1 = client1.transport.update_document._session - session2 = client2.transport.update_document._session - assert session1 != session2 - session1 = client1.transport.reload_document._session - session2 = client2.transport.reload_document._session - assert session1 != session2 -def test_documents_grpc_transport_channel(): - channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.DocumentsGrpcTransport( - 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_documents_grpc_asyncio_transport_channel(): - channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.DocumentsGrpcAsyncIOTransport( - 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.DocumentsGrpcTransport, transports.DocumentsGrpcAsyncIOTransport]) -def test_documents_transport_channel_mtls_with_client_cert_source( - transport_class -): - with mock.patch("grpc.ssl_channel_credentials", autospec=True) as grpc_ssl_channel_cred: - with mock.patch.object(transport_class, "create_channel") as grpc_create_channel: - mock_ssl_cred = mock.Mock() - grpc_ssl_channel_cred.return_value = mock_ssl_cred - - mock_grpc_channel = mock.Mock() - grpc_create_channel.return_value = mock_grpc_channel - - cred = ga_credentials.AnonymousCredentials() - with pytest.warns(DeprecationWarning): - with mock.patch.object(google.auth, 'default') as adc: - adc.return_value = (cred, None) - transport = transport_class( - host="squid.clam.whelk", - api_mtls_endpoint="mtls.squid.clam.whelk", - client_cert_source=client_cert_source_callback, - ) - adc.assert_called_once() - - grpc_ssl_channel_cred.assert_called_once_with( - certificate_chain=b"cert bytes", private_key=b"key bytes" - ) - grpc_create_channel.assert_called_once_with( - "mtls.squid.clam.whelk:443", - credentials=cred, - credentials_file=None, - scopes=None, - ssl_credentials=mock_ssl_cred, - quota_project_id=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - assert transport.grpc_channel == mock_grpc_channel - assert transport._ssl_channel_credentials == mock_ssl_cred - - -# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are -# removed from grpc/grpc_asyncio transport constructor. -@pytest.mark.parametrize("transport_class", [transports.DocumentsGrpcTransport, transports.DocumentsGrpcAsyncIOTransport]) -def test_documents_transport_channel_mtls_with_adc( - transport_class -): - mock_ssl_cred = mock.Mock() - with mock.patch.multiple( - "google.auth.transport.grpc.SslCredentials", - __init__=mock.Mock(return_value=None), - ssl_credentials=mock.PropertyMock(return_value=mock_ssl_cred), - ): - with mock.patch.object(transport_class, "create_channel") as grpc_create_channel: - mock_grpc_channel = mock.Mock() - grpc_create_channel.return_value = mock_grpc_channel - mock_cred = mock.Mock() - - with pytest.warns(DeprecationWarning): - transport = transport_class( - host="squid.clam.whelk", - credentials=mock_cred, - api_mtls_endpoint="mtls.squid.clam.whelk", - client_cert_source=None, - ) - - grpc_create_channel.assert_called_once_with( - "mtls.squid.clam.whelk:443", - credentials=mock_cred, - credentials_file=None, - scopes=None, - ssl_credentials=mock_ssl_cred, - quota_project_id=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - assert transport.grpc_channel == mock_grpc_channel - - -def test_documents_grpc_lro_client(): - client = DocumentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - transport = client.transport - - # Ensure that we have a api-core operations client. - assert isinstance( - transport.operations_client, - operations_v1.OperationsClient, - ) - - # Ensure that subsequent calls to the property send the exact same object. - assert transport.operations_client is transport.operations_client - - -def test_documents_grpc_lro_async_client(): - client = DocumentsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc_asyncio', - ) - transport = client.transport - - # Ensure that we have a api-core operations client. - assert isinstance( - transport.operations_client, - operations_v1.OperationsAsyncClient, - ) - - # Ensure that subsequent calls to the property send the exact same object. - assert transport.operations_client is transport.operations_client - - -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, ) - actual = DocumentsClient.document_path(project, knowledge_base, document) - assert expected == actual - - -def test_parse_document_path(): - expected = { - "project": "octopus", - "knowledge_base": "oyster", - "document": "nudibranch", - } - path = DocumentsClient.document_path(**expected) - - # Check that the path construction is reversible. - actual = DocumentsClient.parse_document_path(path) - assert expected == actual - -def test_common_billing_account_path(): - billing_account = "cuttlefish" - expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) - actual = DocumentsClient.common_billing_account_path(billing_account) - assert expected == actual - - -def test_parse_common_billing_account_path(): - expected = { - "billing_account": "mussel", - } - path = DocumentsClient.common_billing_account_path(**expected) - - # Check that the path construction is reversible. - actual = DocumentsClient.parse_common_billing_account_path(path) - assert expected == actual - -def test_common_folder_path(): - folder = "winkle" - expected = "folders/{folder}".format(folder=folder, ) - actual = DocumentsClient.common_folder_path(folder) - assert expected == actual - - -def test_parse_common_folder_path(): - expected = { - "folder": "nautilus", - } - path = DocumentsClient.common_folder_path(**expected) - - # Check that the path construction is reversible. - actual = DocumentsClient.parse_common_folder_path(path) - assert expected == actual - -def test_common_organization_path(): - organization = "scallop" - expected = "organizations/{organization}".format(organization=organization, ) - actual = DocumentsClient.common_organization_path(organization) - assert expected == actual - - -def test_parse_common_organization_path(): - expected = { - "organization": "abalone", - } - path = DocumentsClient.common_organization_path(**expected) - - # Check that the path construction is reversible. - actual = DocumentsClient.parse_common_organization_path(path) - assert expected == actual - -def test_common_project_path(): - project = "squid" - expected = "projects/{project}".format(project=project, ) - actual = DocumentsClient.common_project_path(project) - assert expected == actual - - -def test_parse_common_project_path(): - expected = { - "project": "clam", - } - path = DocumentsClient.common_project_path(**expected) - - # Check that the path construction is reversible. - actual = DocumentsClient.parse_common_project_path(path) - assert expected == actual - -def test_common_location_path(): - project = "whelk" - location = "octopus" - expected = "projects/{project}/locations/{location}".format(project=project, location=location, ) - actual = DocumentsClient.common_location_path(project, location) - assert expected == actual - - -def test_parse_common_location_path(): - expected = { - "project": "oyster", - "location": "nudibranch", - } - path = DocumentsClient.common_location_path(**expected) - - # Check that the path construction is reversible. - actual = DocumentsClient.parse_common_location_path(path) - assert expected == actual - - -def test_client_with_default_client_info(): - client_info = gapic_v1.client_info.ClientInfo() - - with mock.patch.object(transports.DocumentsTransport, '_prep_wrapped_messages') as prep: - client = DocumentsClient( - credentials=ga_credentials.AnonymousCredentials(), - client_info=client_info, - ) - prep.assert_called_once_with(client_info) - - with mock.patch.object(transports.DocumentsTransport, '_prep_wrapped_messages') as prep: - transport_class = DocumentsClient.get_transport_class() - transport = transport_class( - credentials=ga_credentials.AnonymousCredentials(), - client_info=client_info, - ) - prep.assert_called_once_with(client_info) - -@pytest.mark.asyncio -async def test_transport_close_async(): - client = DocumentsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - with mock.patch.object(type(getattr(client.transport, "grpc_channel")), "close") as close: - async with client: - close.assert_not_called() - close.assert_called_once() - - -def test_get_location_rest_bad_request(transport: str = 'rest', request_type=locations_pb2.GetLocationRequest): - client = DocumentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - request = request_type() - request = json_format.ParseDict({'name': 'projects/sample1/locations/sample2'}, request) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.get_location(request) - -@pytest.mark.parametrize("request_type", [ - locations_pb2.GetLocationRequest, - dict, -]) -def test_get_location_rest(request_type): - client = DocumentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request_init = {'name': 'projects/sample1/locations/sample2'} - request = request_type(**request_init) - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = locations_pb2.Location() - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.get_location(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, locations_pb2.Location) - -def test_list_locations_rest_bad_request(transport: str = 'rest', request_type=locations_pb2.ListLocationsRequest): - client = DocumentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - request = request_type() - request = json_format.ParseDict({'name': 'projects/sample1'}, request) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.list_locations(request) - -@pytest.mark.parametrize("request_type", [ - locations_pb2.ListLocationsRequest, - dict, -]) -def test_list_locations_rest(request_type): - client = DocumentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request_init = {'name': 'projects/sample1'} - request = request_type(**request_init) - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = locations_pb2.ListLocationsResponse() - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.list_locations(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, locations_pb2.ListLocationsResponse) - -def test_cancel_operation_rest_bad_request(transport: str = 'rest', request_type=operations_pb2.CancelOperationRequest): - client = DocumentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - request = request_type() - request = json_format.ParseDict({'name': 'projects/sample1/operations/sample2'}, request) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.cancel_operation(request) - -@pytest.mark.parametrize("request_type", [ - operations_pb2.CancelOperationRequest, - dict, -]) -def test_cancel_operation_rest(request_type): - client = DocumentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request_init = {'name': 'projects/sample1/operations/sample2'} - request = request_type(**request_init) - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = None - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = '{}' - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.cancel_operation(request) - - # Establish that the response is the type that we expect. - assert response is None - -def test_get_operation_rest_bad_request(transport: str = 'rest', request_type=operations_pb2.GetOperationRequest): - client = DocumentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - request = request_type() - request = json_format.ParseDict({'name': 'projects/sample1/operations/sample2'}, request) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.get_operation(request) - -@pytest.mark.parametrize("request_type", [ - operations_pb2.GetOperationRequest, - dict, -]) -def test_get_operation_rest(request_type): - client = DocumentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request_init = {'name': 'projects/sample1/operations/sample2'} - request = request_type(**request_init) - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation() - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.get_operation(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, operations_pb2.Operation) - -def test_list_operations_rest_bad_request(transport: str = 'rest', request_type=operations_pb2.ListOperationsRequest): - client = DocumentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - request = request_type() - request = json_format.ParseDict({'name': 'projects/sample1'}, request) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.list_operations(request) - -@pytest.mark.parametrize("request_type", [ - operations_pb2.ListOperationsRequest, - dict, -]) -def test_list_operations_rest(request_type): - client = DocumentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request_init = {'name': 'projects/sample1'} - request = request_type(**request_init) - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = operations_pb2.ListOperationsResponse() - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.list_operations(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, operations_pb2.ListOperationsResponse) - - -def test_cancel_operation(transport: str = "grpc"): - client = DocumentsClient( - 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 = operations_pb2.CancelOperationRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = None - response = client.cancel_operation(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 response is the type that we expect. - assert response is None -@pytest.mark.asyncio -async def test_cancel_operation_async(transport: str = "grpc"): - client = DocumentsAsyncClient( - 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 = operations_pb2.CancelOperationRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - None - ) - response = await client.cancel_operation(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 response is the type that we expect. - assert response is None - -def test_cancel_operation_field_headers(): - 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 = operations_pb2.CancelOperationRequest() - request.name = "locations" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call: - call.return_value = None - - client.cancel_operation(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=locations",) in kw["metadata"] -@pytest.mark.asyncio -async def test_cancel_operation_field_headers_async(): - 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 = operations_pb2.CancelOperationRequest() - request.name = "locations" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - None - ) - await client.cancel_operation(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=locations",) in kw["metadata"] - -def test_cancel_operation_from_dict(): - 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.cancel_operation), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = None - - response = client.cancel_operation( - request={ - "name": "locations", - } - ) - call.assert_called() -@pytest.mark.asyncio -async def test_cancel_operation_from_dict_async(): - 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.cancel_operation), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - None - ) - response = await client.cancel_operation( - request={ - "name": "locations", - } - ) - call.assert_called() - - -def test_get_operation(transport: str = "grpc"): - client = DocumentsClient( - 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 = operations_pb2.GetOperationRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_operation), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation() - response = client.get_operation(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 response is the type that we expect. - assert isinstance(response, operations_pb2.Operation) -@pytest.mark.asyncio -async def test_get_operation_async(transport: str = "grpc"): - client = DocumentsAsyncClient( - 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 = operations_pb2.GetOperationRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_operation), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation() - ) - response = await client.get_operation(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 response is the type that we expect. - assert isinstance(response, operations_pb2.Operation) - -def test_get_operation_field_headers(): - 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 = operations_pb2.GetOperationRequest() - request.name = "locations" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_operation), "__call__") as call: - call.return_value = operations_pb2.Operation() - - client.get_operation(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=locations",) in kw["metadata"] -@pytest.mark.asyncio -async def test_get_operation_field_headers_async(): - 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 = operations_pb2.GetOperationRequest() - request.name = "locations" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_operation), "__call__") as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation() - ) - await client.get_operation(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=locations",) in kw["metadata"] - -def test_get_operation_from_dict(): - 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_operation), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation() - - response = client.get_operation( - request={ - "name": "locations", - } - ) - call.assert_called() -@pytest.mark.asyncio -async def test_get_operation_from_dict_async(): - 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_operation), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation() - ) - response = await client.get_operation( - request={ - "name": "locations", - } - ) - call.assert_called() - - -def test_list_operations(transport: str = "grpc"): - client = DocumentsClient( - 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 = operations_pb2.ListOperationsRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_operations), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.ListOperationsResponse() - response = client.list_operations(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 response is the type that we expect. - assert isinstance(response, operations_pb2.ListOperationsResponse) -@pytest.mark.asyncio -async def test_list_operations_async(transport: str = "grpc"): - client = DocumentsAsyncClient( - 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 = operations_pb2.ListOperationsRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_operations), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.ListOperationsResponse() - ) - response = await client.list_operations(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 response is the type that we expect. - assert isinstance(response, operations_pb2.ListOperationsResponse) - -def test_list_operations_field_headers(): - 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 = operations_pb2.ListOperationsRequest() - request.name = "locations" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_operations), "__call__") as call: - call.return_value = operations_pb2.ListOperationsResponse() - - client.list_operations(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=locations",) in kw["metadata"] -@pytest.mark.asyncio -async def test_list_operations_field_headers_async(): - 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 = operations_pb2.ListOperationsRequest() - request.name = "locations" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_operations), "__call__") as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.ListOperationsResponse() - ) - await client.list_operations(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=locations",) in kw["metadata"] - -def test_list_operations_from_dict(): - 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_operations), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.ListOperationsResponse() - - response = client.list_operations( - request={ - "name": "locations", - } - ) - call.assert_called() -@pytest.mark.asyncio -async def test_list_operations_from_dict_async(): - 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_operations), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.ListOperationsResponse() - ) - response = await client.list_operations( - request={ - "name": "locations", - } - ) - call.assert_called() - - -def test_list_locations(transport: str = "grpc"): - client = DocumentsClient( - 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 = locations_pb2.ListLocationsRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_locations), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = locations_pb2.ListLocationsResponse() - response = client.list_locations(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 response is the type that we expect. - assert isinstance(response, locations_pb2.ListLocationsResponse) -@pytest.mark.asyncio -async def test_list_locations_async(transport: str = "grpc"): - client = DocumentsAsyncClient( - 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 = locations_pb2.ListLocationsRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_locations), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - locations_pb2.ListLocationsResponse() - ) - response = await client.list_locations(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 response is the type that we expect. - assert isinstance(response, locations_pb2.ListLocationsResponse) - -def test_list_locations_field_headers(): - 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 = locations_pb2.ListLocationsRequest() - request.name = "locations" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_locations), "__call__") as call: - call.return_value = locations_pb2.ListLocationsResponse() - - client.list_locations(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=locations",) in kw["metadata"] -@pytest.mark.asyncio -async def test_list_locations_field_headers_async(): - 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 = locations_pb2.ListLocationsRequest() - request.name = "locations" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_locations), "__call__") as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - locations_pb2.ListLocationsResponse() - ) - await client.list_locations(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=locations",) in kw["metadata"] - -def test_list_locations_from_dict(): - 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_locations), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = locations_pb2.ListLocationsResponse() - - response = client.list_locations( - request={ - "name": "locations", - } - ) - call.assert_called() -@pytest.mark.asyncio -async def test_list_locations_from_dict_async(): - 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_locations), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - locations_pb2.ListLocationsResponse() - ) - response = await client.list_locations( - request={ - "name": "locations", - } - ) - call.assert_called() - - -def test_get_location(transport: str = "grpc"): - client = DocumentsClient( - 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 = locations_pb2.GetLocationRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_location), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = locations_pb2.Location() - response = client.get_location(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 response is the type that we expect. - assert isinstance(response, locations_pb2.Location) -@pytest.mark.asyncio -async def test_get_location_async(transport: str = "grpc_asyncio"): - client = DocumentsAsyncClient( - 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 = locations_pb2.GetLocationRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_location), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - locations_pb2.Location() - ) - response = await client.get_location(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 response is the type that we expect. - assert isinstance(response, locations_pb2.Location) - -def test_get_location_field_headers(): - 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 = locations_pb2.GetLocationRequest() - request.name = "locations/abc" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_location), "__call__") as call: - call.return_value = locations_pb2.Location() - - client.get_location(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=locations/abc",) in kw["metadata"] -@pytest.mark.asyncio -async def test_get_location_field_headers_async(): - 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 = locations_pb2.GetLocationRequest() - request.name = "locations/abc" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_location), "__call__") as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - locations_pb2.Location() - ) - await client.get_location(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=locations/abc",) in kw["metadata"] - -def test_get_location_from_dict(): - 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_locations), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = locations_pb2.Location() - - response = client.get_location( - request={ - "name": "locations/abc", - } - ) - call.assert_called() -@pytest.mark.asyncio -async def test_get_location_from_dict_async(): - 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_locations), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - locations_pb2.Location() - ) - response = await client.get_location( - request={ - "name": "locations", - } - ) - call.assert_called() - - -def test_transport_close(): - transports = { - "rest": "_session", - "grpc": "_grpc_channel", - } - - for transport, close_name in transports.items(): - client = DocumentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport - ) - with mock.patch.object(type(getattr(client.transport, close_name)), "close") as close: - with client: - close.assert_not_called() - close.assert_called_once() - -def test_client_ctx(): - transports = [ - 'rest', - 'grpc', - ] - for transport in transports: - client = DocumentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport - ) - # Test client calls underlying transport. - with mock.patch.object(type(client.transport), "close") as close: - close.assert_not_called() - with client: - pass - close.assert_called() - -@pytest.mark.parametrize("client_class,transport_class", [ - (DocumentsClient, transports.DocumentsGrpcTransport), - (DocumentsAsyncClient, transports.DocumentsGrpcAsyncIOTransport), -]) -def test_api_key_credentials(client_class, transport_class): - with mock.patch.object( - google.auth._default, "get_api_key_credentials", create=True - ) as get_api_key_credentials: - mock_cred = mock.Mock() - get_api_key_credentials.return_value = mock_cred - options = client_options.ClientOptions() - options.api_key = "api_key" - 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=mock_cred, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) diff --git a/owl-bot-staging/v2beta1/tests/unit/gapic/dialogflow_v2beta1/test_entity_types.py b/owl-bot-staging/v2beta1/tests/unit/gapic/dialogflow_v2beta1/test_entity_types.py deleted file mode 100644 index 545a00e97..000000000 --- a/owl-bot-staging/v2beta1/tests/unit/gapic/dialogflow_v2beta1/test_entity_types.py +++ /dev/null @@ -1,7157 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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 -# try/except added for compatibility with python < 3.8 -try: - from unittest import mock - from unittest.mock import AsyncMock # pragma: NO COVER -except ImportError: # pragma: NO COVER - import mock - -import grpc -from grpc.experimental import aio -from collections.abc import Iterable -from google.protobuf import json_format -import json -import math -import pytest -from proto.marshal.rules.dates import DurationRule, TimestampRule -from proto.marshal.rules import wrappers -from requests import Response -from requests import Request, PreparedRequest -from requests.sessions import Session -from google.protobuf import json_format - -from google.api_core import client_options -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 -from google.api_core import operation_async # type: ignore -from google.api_core import operations_v1 -from google.api_core import path_template -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.types import entity_type -from google.cloud.dialogflow_v2beta1.types import entity_type as gcd_entity_type -from google.cloud.location import locations_pb2 -from google.longrunning import operations_pb2 -from google.oauth2 import service_account -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 -import google.auth - - -def client_cert_source_callback(): - return b"cert bytes", b"key bytes" - - -# If default endpoint is localhost, then default mtls endpoint will be the same. -# This method modifies the default endpoint so the client can produce a different -# mtls endpoint for endpoint testing purposes. -def modify_default_endpoint(client): - return "foo.googleapis.com" if ("localhost" in client.DEFAULT_ENDPOINT) else client.DEFAULT_ENDPOINT - - -def test__get_default_mtls_endpoint(): - api_endpoint = "example.googleapis.com" - api_mtls_endpoint = "example.mtls.googleapis.com" - sandbox_endpoint = "example.sandbox.googleapis.com" - sandbox_mtls_endpoint = "example.mtls.sandbox.googleapis.com" - non_googleapi = "api.example.com" - - assert EntityTypesClient._get_default_mtls_endpoint(None) is None - assert EntityTypesClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint - assert EntityTypesClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint - assert EntityTypesClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint - assert EntityTypesClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint - assert EntityTypesClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi - - -@pytest.mark.parametrize("client_class,transport_name", [ - (EntityTypesClient, "grpc"), - (EntityTypesAsyncClient, "grpc_asyncio"), - (EntityTypesClient, "rest"), -]) -def test_entity_types_client_from_service_account_info(client_class, transport_name): - 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, transport=transport_name) - assert client.transport._credentials == creds - assert isinstance(client, client_class) - - assert client.transport._host == ( - 'dialogflow.googleapis.com:443' - if transport_name in ['grpc', 'grpc_asyncio'] - else - 'https://dialogflow.googleapis.com' - ) - - -@pytest.mark.parametrize("transport_class,transport_name", [ - (transports.EntityTypesGrpcTransport, "grpc"), - (transports.EntityTypesGrpcAsyncIOTransport, "grpc_asyncio"), - (transports.EntityTypesRestTransport, "rest"), -]) -def test_entity_types_client_service_account_always_use_jwt(transport_class, transport_name): - with mock.patch.object(service_account.Credentials, 'with_always_use_jwt_access', create=True) as use_jwt: - creds = service_account.Credentials(None, None, None) - transport = transport_class(credentials=creds, always_use_jwt_access=True) - use_jwt.assert_called_once_with(True) - - with mock.patch.object(service_account.Credentials, 'with_always_use_jwt_access', create=True) as use_jwt: - creds = service_account.Credentials(None, None, None) - transport = transport_class(credentials=creds, always_use_jwt_access=False) - use_jwt.assert_not_called() - - -@pytest.mark.parametrize("client_class,transport_name", [ - (EntityTypesClient, "grpc"), - (EntityTypesAsyncClient, "grpc_asyncio"), - (EntityTypesClient, "rest"), -]) -def test_entity_types_client_from_service_account_file(client_class, transport_name): - 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", transport=transport_name) - assert client.transport._credentials == creds - assert isinstance(client, client_class) - - client = client_class.from_service_account_json("dummy/file/path.json", transport=transport_name) - assert client.transport._credentials == creds - assert isinstance(client, client_class) - - assert client.transport._host == ( - 'dialogflow.googleapis.com:443' - if transport_name in ['grpc', 'grpc_asyncio'] - else - 'https://dialogflow.googleapis.com' - ) - - -def test_entity_types_client_get_transport_class(): - transport = EntityTypesClient.get_transport_class() - available_transports = [ - transports.EntityTypesGrpcTransport, - transports.EntityTypesRestTransport, - ] - assert transport in available_transports - - transport = EntityTypesClient.get_transport_class("grpc") - assert transport == transports.EntityTypesGrpcTransport - - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (EntityTypesClient, transports.EntityTypesGrpcTransport, "grpc"), - (EntityTypesAsyncClient, transports.EntityTypesGrpcAsyncIOTransport, "grpc_asyncio"), - (EntityTypesClient, transports.EntityTypesRestTransport, "rest"), -]) -@mock.patch.object(EntityTypesClient, "DEFAULT_ENDPOINT", modify_default_endpoint(EntityTypesClient)) -@mock.patch.object(EntityTypesAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(EntityTypesAsyncClient)) -def test_entity_types_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(EntityTypesClient, '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(EntityTypesClient, 'get_transport_class') as gtc: - client = client_class(transport=transport_name) - gtc.assert_called() - - # Check the case api_endpoint is provided. - options = client_options.ClientOptions(api_endpoint="squid.clam.whelk") - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(transport=transport_name, client_options=options) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host="squid.clam.whelk", - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is - # "never". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is - # "always". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_MTLS_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # 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(transport=transport_name) - - # 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(transport=transport_name) - - # 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, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id="octopus", - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - # Check the case api_endpoint is provided - options = client_options.ClientOptions(api_audience="https://language.googleapis.com") - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience="https://language.googleapis.com" - ) - -@pytest.mark.parametrize("client_class,transport_class,transport_name,use_client_cert_env", [ - (EntityTypesClient, transports.EntityTypesGrpcTransport, "grpc", "true"), - (EntityTypesAsyncClient, transports.EntityTypesGrpcAsyncIOTransport, "grpc_asyncio", "true"), - (EntityTypesClient, transports.EntityTypesGrpcTransport, "grpc", "false"), - (EntityTypesAsyncClient, transports.EntityTypesGrpcAsyncIOTransport, "grpc_asyncio", "false"), - (EntityTypesClient, transports.EntityTypesRestTransport, "rest", "true"), - (EntityTypesClient, transports.EntityTypesRestTransport, "rest", "false"), -]) -@mock.patch.object(EntityTypesClient, "DEFAULT_ENDPOINT", modify_default_endpoint(EntityTypesClient)) -@mock.patch.object(EntityTypesAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(EntityTypesAsyncClient)) -@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) -def test_entity_types_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, transport=transport_name) - - if use_client_cert_env == "false": - expected_client_cert_source = None - expected_host = client.DEFAULT_ENDPOINT - else: - expected_client_cert_source = client_cert_source_callback - expected_host = client.DEFAULT_MTLS_ENDPOINT - - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=expected_host, - scopes=None, - client_cert_source_for_mtls=expected_client_cert_source, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case ADC client cert is provided. Whether client cert is used depends on - # GOOGLE_API_USE_CLIENT_CERTIFICATE value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): - with mock.patch.object(transport_class, '__init__') as patched: - with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): - with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=client_cert_source_callback): - if use_client_cert_env == "false": - expected_host = client.DEFAULT_ENDPOINT - expected_client_cert_source = None - else: - expected_host = client.DEFAULT_MTLS_ENDPOINT - expected_client_cert_source = client_cert_source_callback - - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=expected_host, - scopes=None, - client_cert_source_for_mtls=expected_client_cert_source, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case client_cert_source and ADC client cert are not provided. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): - with mock.patch.object(transport_class, '__init__') as patched: - with mock.patch("google.auth.transport.mtls.has_default_client_cert_source", return_value=False): - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - -@pytest.mark.parametrize("client_class", [ - EntityTypesClient, EntityTypesAsyncClient -]) -@mock.patch.object(EntityTypesClient, "DEFAULT_ENDPOINT", modify_default_endpoint(EntityTypesClient)) -@mock.patch.object(EntityTypesAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(EntityTypesAsyncClient)) -def test_entity_types_client_get_mtls_endpoint_and_cert_source(client_class): - mock_client_cert_source = mock.Mock() - - # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "true". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - mock_api_endpoint = "foo" - options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) - assert api_endpoint == mock_api_endpoint - assert cert_source == mock_client_cert_source - - # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "false". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): - mock_client_cert_source = mock.Mock() - mock_api_endpoint = "foo" - options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) - assert api_endpoint == mock_api_endpoint - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "never". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_ENDPOINT - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "always". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert doesn't exist. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=False): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_ENDPOINT - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert exists. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - 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=mock_client_cert_source): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT - assert cert_source == mock_client_cert_source - - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (EntityTypesClient, transports.EntityTypesGrpcTransport, "grpc"), - (EntityTypesAsyncClient, transports.EntityTypesGrpcAsyncIOTransport, "grpc_asyncio"), - (EntityTypesClient, transports.EntityTypesRestTransport, "rest"), -]) -def test_entity_types_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, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=["1", "2"], - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - -@pytest.mark.parametrize("client_class,transport_class,transport_name,grpc_helpers", [ - (EntityTypesClient, transports.EntityTypesGrpcTransport, "grpc", grpc_helpers), - (EntityTypesAsyncClient, transports.EntityTypesGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), - (EntityTypesClient, transports.EntityTypesRestTransport, "rest", None), -]) -def test_entity_types_client_client_options_credentials_file(client_class, transport_class, transport_name, grpc_helpers): - # 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, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file="credentials.json", - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - -def test_entity_types_client_client_options_from_dict(): - with mock.patch('google.cloud.dialogflow_v2beta1.services.entity_types.transports.EntityTypesGrpcTransport.__init__') as grpc_transport: - grpc_transport.return_value = None - client = EntityTypesClient( - client_options={'api_endpoint': 'squid.clam.whelk'} - ) - grpc_transport.assert_called_once_with( - credentials=None, - credentials_file=None, - host="squid.clam.whelk", - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - -@pytest.mark.parametrize("client_class,transport_class,transport_name,grpc_helpers", [ - (EntityTypesClient, transports.EntityTypesGrpcTransport, "grpc", grpc_helpers), - (EntityTypesAsyncClient, transports.EntityTypesGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), -]) -def test_entity_types_client_create_channel_credentials_file(client_class, transport_class, transport_name, grpc_helpers): - # 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, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file="credentials.json", - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # test that the credentials from file are saved and used as the credentials. - with mock.patch.object( - google.auth, "load_credentials_from_file", autospec=True - ) as load_creds, mock.patch.object( - google.auth, "default", autospec=True - ) as adc, mock.patch.object( - grpc_helpers, "create_channel" - ) as create_channel: - creds = ga_credentials.AnonymousCredentials() - file_creds = ga_credentials.AnonymousCredentials() - load_creds.return_value = (file_creds, None) - adc.return_value = (creds, None) - client = client_class(client_options=options, transport=transport_name) - create_channel.assert_called_with( - "dialogflow.googleapis.com:443", - credentials=file_creds, - credentials_file=None, - quota_project_id=None, - default_scopes=( - 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/dialogflow', -), - scopes=None, - default_host="dialogflow.googleapis.com", - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - -@pytest.mark.parametrize("request_type", [ - entity_type.ListEntityTypesRequest, - dict, -]) -def test_list_entity_types(request_type, transport: str = 'grpc'): - client = EntityTypesClient( - 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_entity_types), - '__call__') as call: - # Designate an appropriate return value for the call. - 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' - - -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=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_entity_types), - '__call__') as call: - client.list_entity_types() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == entity_type.ListEntityTypesRequest() - -@pytest.mark.asyncio -async def test_list_entity_types_async(transport: str = 'grpc_asyncio', request_type=entity_type.ListEntityTypesRequest): - client = EntityTypesAsyncClient( - 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_entity_types), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(entity_type.ListEntityTypesResponse( - 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' - - -@pytest.mark.asyncio -async def test_list_entity_types_async_from_dict(): - await test_list_entity_types_async(request_type=dict) - - -def test_list_entity_types_field_headers(): - 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. - with mock.patch.object( - 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. - 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_entity_types_field_headers_async(): - 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. - with mock.patch.object( - type(client.transport.list_entity_types), - '__call__') as call: - 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. - 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_entity_types_flattened(): - 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.list_entity_types), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = entity_type.ListEntityTypesResponse() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.list_entity_types( - parent='parent_value', - language_code='language_code_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] - arg = args[0].parent - mock_val = 'parent_value' - assert arg == mock_val - arg = args[0].language_code - mock_val = 'language_code_value' - assert arg == mock_val - - -def test_list_entity_types_flattened_error(): - client = EntityTypesClient( - 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_entity_types( - entity_type.ListEntityTypesRequest(), - parent='parent_value', - language_code='language_code_value', - ) - -@pytest.mark.asyncio -async def test_list_entity_types_flattened_async(): - 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.list_entity_types), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = entity_type.ListEntityTypesResponse() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(entity_type.ListEntityTypesResponse()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.list_entity_types( - parent='parent_value', - language_code='language_code_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - arg = args[0].parent - mock_val = 'parent_value' - assert arg == mock_val - arg = args[0].language_code - mock_val = 'language_code_value' - assert arg == mock_val - -@pytest.mark.asyncio -async def test_list_entity_types_flattened_error_async(): - client = EntityTypesAsyncClient( - 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_entity_types( - entity_type.ListEntityTypesRequest(), - parent='parent_value', - language_code='language_code_value', - ) - - -def test_list_entity_types_pager(transport_name: str = "grpc"): - client = EntityTypesClient( - credentials=ga_credentials.AnonymousCredentials, - transport=transport_name, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_entity_types), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - entity_type.ListEntityTypesResponse( - entity_types=[ - entity_type.EntityType(), - entity_type.EntityType(), - entity_type.EntityType(), - ], - next_page_token='abc', - ), - entity_type.ListEntityTypesResponse( - entity_types=[], - next_page_token='def', - ), - entity_type.ListEntityTypesResponse( - entity_types=[ - entity_type.EntityType(), - ], - next_page_token='ghi', - ), - entity_type.ListEntityTypesResponse( - entity_types=[ - entity_type.EntityType(), - entity_type.EntityType(), - ], - ), - RuntimeError, - ) - - metadata = () - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ('parent', ''), - )), - ) - pager = client.list_entity_types(request={}) - - assert pager._metadata == metadata - - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, entity_type.EntityType) - for i in results) -def test_list_entity_types_pages(transport_name: str = "grpc"): - client = EntityTypesClient( - credentials=ga_credentials.AnonymousCredentials, - transport=transport_name, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_entity_types), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - entity_type.ListEntityTypesResponse( - entity_types=[ - entity_type.EntityType(), - entity_type.EntityType(), - entity_type.EntityType(), - ], - next_page_token='abc', - ), - entity_type.ListEntityTypesResponse( - entity_types=[], - next_page_token='def', - ), - entity_type.ListEntityTypesResponse( - entity_types=[ - entity_type.EntityType(), - ], - next_page_token='ghi', - ), - entity_type.ListEntityTypesResponse( - entity_types=[ - entity_type.EntityType(), - entity_type.EntityType(), - ], - ), - RuntimeError, - ) - pages = list(client.list_entity_types(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_entity_types_async_pager(): - 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.list_entity_types), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - entity_type.ListEntityTypesResponse( - entity_types=[ - entity_type.EntityType(), - entity_type.EntityType(), - entity_type.EntityType(), - ], - next_page_token='abc', - ), - entity_type.ListEntityTypesResponse( - entity_types=[], - next_page_token='def', - ), - entity_type.ListEntityTypesResponse( - entity_types=[ - entity_type.EntityType(), - ], - next_page_token='ghi', - ), - entity_type.ListEntityTypesResponse( - entity_types=[ - entity_type.EntityType(), - entity_type.EntityType(), - ], - ), - RuntimeError, - ) - async_pager = await client.list_entity_types(request={},) - assert async_pager.next_page_token == 'abc' - responses = [] - async for response in async_pager: # pragma: no branch - responses.append(response) - - assert len(responses) == 6 - assert all(isinstance(i, entity_type.EntityType) - for i in responses) - - -@pytest.mark.asyncio -async def test_list_entity_types_async_pages(): - 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.list_entity_types), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - entity_type.ListEntityTypesResponse( - entity_types=[ - entity_type.EntityType(), - entity_type.EntityType(), - entity_type.EntityType(), - ], - next_page_token='abc', - ), - entity_type.ListEntityTypesResponse( - entity_types=[], - next_page_token='def', - ), - entity_type.ListEntityTypesResponse( - entity_types=[ - entity_type.EntityType(), - ], - next_page_token='ghi', - ), - entity_type.ListEntityTypesResponse( - entity_types=[ - entity_type.EntityType(), - entity_type.EntityType(), - ], - ), - RuntimeError, - ) - pages = [] - async for page_ in (await client.list_entity_types(request={})).pages: # pragma: no branch - pages.append(page_) - for page_, token in zip(pages, ['abc','def','ghi', '']): - assert page_.raw_page.next_page_token == token - -@pytest.mark.parametrize("request_type", [ - entity_type.GetEntityTypeRequest, - dict, -]) -def test_get_entity_type(request_type, transport: str = 'grpc'): - client = EntityTypesClient( - 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_entity_type), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = entity_type.EntityType( - name='name_value', - display_name='display_name_value', - kind=entity_type.EntityType.Kind.KIND_MAP, - 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 - - -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=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_entity_type), - '__call__') as call: - client.get_entity_type() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == entity_type.GetEntityTypeRequest() - -@pytest.mark.asyncio -async def test_get_entity_type_async(transport: str = 'grpc_asyncio', request_type=entity_type.GetEntityTypeRequest): - client = EntityTypesAsyncClient( - 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_entity_type), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(entity_type.EntityType( - name='name_value', - display_name='display_name_value', - kind=entity_type.EntityType.Kind.KIND_MAP, - auto_expansion_mode=entity_type.EntityType.AutoExpansionMode.AUTO_EXPANSION_MODE_DEFAULT, - 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 - - -@pytest.mark.asyncio -async def test_get_entity_type_async_from_dict(): - await test_get_entity_type_async(request_type=dict) - - -def test_get_entity_type_field_headers(): - 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. - 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_entity_type_field_headers_async(): - 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. - with mock.patch.object( - type(client.transport.get_entity_type), - '__call__') as call: - 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. - 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_entity_type_flattened(): - client = EntityTypesClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_entity_type), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = entity_type.EntityType() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.get_entity_type( - name='name_value', - language_code='language_code_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] - arg = args[0].name - mock_val = 'name_value' - assert arg == mock_val - arg = args[0].language_code - mock_val = 'language_code_value' - assert arg == mock_val - - -def test_get_entity_type_flattened_error(): - client = EntityTypesClient( - 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_entity_type( - entity_type.GetEntityTypeRequest(), - name='name_value', - language_code='language_code_value', - ) - -@pytest.mark.asyncio -async def test_get_entity_type_flattened_async(): - 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: - # Designate an appropriate return value for the call. - call.return_value = entity_type.EntityType() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(entity_type.EntityType()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.get_entity_type( - name='name_value', - language_code='language_code_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - arg = args[0].name - mock_val = 'name_value' - assert arg == mock_val - arg = args[0].language_code - mock_val = 'language_code_value' - assert arg == mock_val - -@pytest.mark.asyncio -async def test_get_entity_type_flattened_error_async(): - client = EntityTypesAsyncClient( - 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_entity_type( - entity_type.GetEntityTypeRequest(), - name='name_value', - language_code='language_code_value', - ) - - -@pytest.mark.parametrize("request_type", [ - gcd_entity_type.CreateEntityTypeRequest, - dict, -]) -def test_create_entity_type(request_type, transport: str = 'grpc'): - client = EntityTypesClient( - 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_entity_type), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcd_entity_type.EntityType( - name='name_value', - display_name='display_name_value', - kind=gcd_entity_type.EntityType.Kind.KIND_MAP, - 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 - - -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=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_entity_type), - '__call__') as call: - client.create_entity_type() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == gcd_entity_type.CreateEntityTypeRequest() - -@pytest.mark.asyncio -async def test_create_entity_type_async(transport: str = 'grpc_asyncio', request_type=gcd_entity_type.CreateEntityTypeRequest): - client = EntityTypesAsyncClient( - 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_entity_type), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gcd_entity_type.EntityType( - name='name_value', - display_name='display_name_value', - kind=gcd_entity_type.EntityType.Kind.KIND_MAP, - auto_expansion_mode=gcd_entity_type.EntityType.AutoExpansionMode.AUTO_EXPANSION_MODE_DEFAULT, - 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 - - -@pytest.mark.asyncio -async def test_create_entity_type_async_from_dict(): - await test_create_entity_type_async(request_type=dict) - - -def test_create_entity_type_field_headers(): - 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. - with mock.patch.object( - 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. - 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_entity_type_field_headers_async(): - 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. - with mock.patch.object( - type(client.transport.create_entity_type), - '__call__') as call: - 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. - 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_entity_type_flattened(): - 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.create_entity_type), - '__call__') 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( - parent='parent_value', - entity_type=gcd_entity_type.EntityType(name='name_value'), - language_code='language_code_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] - arg = args[0].parent - mock_val = 'parent_value' - assert arg == mock_val - arg = args[0].entity_type - mock_val = gcd_entity_type.EntityType(name='name_value') - assert arg == mock_val - arg = args[0].language_code - mock_val = 'language_code_value' - assert arg == mock_val - - -def test_create_entity_type_flattened_error(): - client = EntityTypesClient( - 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_entity_type( - gcd_entity_type.CreateEntityTypeRequest(), - parent='parent_value', - entity_type=gcd_entity_type.EntityType(name='name_value'), - language_code='language_code_value', - ) - -@pytest.mark.asyncio -async def test_create_entity_type_flattened_async(): - 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.create_entity_type), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcd_entity_type.EntityType() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcd_entity_type.EntityType()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.create_entity_type( - parent='parent_value', - entity_type=gcd_entity_type.EntityType(name='name_value'), - language_code='language_code_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - arg = args[0].parent - mock_val = 'parent_value' - assert arg == mock_val - arg = args[0].entity_type - mock_val = gcd_entity_type.EntityType(name='name_value') - assert arg == mock_val - arg = args[0].language_code - mock_val = 'language_code_value' - assert arg == mock_val - -@pytest.mark.asyncio -async def test_create_entity_type_flattened_error_async(): - client = EntityTypesAsyncClient( - 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_entity_type( - gcd_entity_type.CreateEntityTypeRequest(), - parent='parent_value', - entity_type=gcd_entity_type.EntityType(name='name_value'), - language_code='language_code_value', - ) - - -@pytest.mark.parametrize("request_type", [ - gcd_entity_type.UpdateEntityTypeRequest, - dict, -]) -def test_update_entity_type(request_type, transport: str = 'grpc'): - client = EntityTypesClient( - 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_entity_type), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcd_entity_type.EntityType( - name='name_value', - display_name='display_name_value', - kind=gcd_entity_type.EntityType.Kind.KIND_MAP, - 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 - - -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=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_entity_type), - '__call__') as call: - client.update_entity_type() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == gcd_entity_type.UpdateEntityTypeRequest() - -@pytest.mark.asyncio -async def test_update_entity_type_async(transport: str = 'grpc_asyncio', request_type=gcd_entity_type.UpdateEntityTypeRequest): - client = EntityTypesAsyncClient( - 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_entity_type), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gcd_entity_type.EntityType( - name='name_value', - display_name='display_name_value', - kind=gcd_entity_type.EntityType.Kind.KIND_MAP, - auto_expansion_mode=gcd_entity_type.EntityType.AutoExpansionMode.AUTO_EXPANSION_MODE_DEFAULT, - 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 - - -@pytest.mark.asyncio -async def test_update_entity_type_async_from_dict(): - await test_update_entity_type_async(request_type=dict) - - -def test_update_entity_type_field_headers(): - 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 = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - 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. - 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', - 'entity_type.name=name_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_update_entity_type_field_headers_async(): - 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 = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_entity_type), - '__call__') as call: - 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. - 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', - 'entity_type.name=name_value', - ) in kw['metadata'] - - -def test_update_entity_type_flattened(): - 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.update_entity_type), - '__call__') 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_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] - arg = args[0].entity_type - mock_val = gcd_entity_type.EntityType(name='name_value') - assert arg == mock_val - arg = args[0].language_code - mock_val = 'language_code_value' - assert arg == mock_val - arg = args[0].update_mask - mock_val = field_mask_pb2.FieldMask(paths=['paths_value']) - assert arg == mock_val - - -def test_update_entity_type_flattened_error(): - client = EntityTypesClient( - 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_entity_type( - gcd_entity_type.UpdateEntityTypeRequest(), - entity_type=gcd_entity_type.EntityType(name='name_value'), - language_code='language_code_value', - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - -@pytest.mark.asyncio -async def test_update_entity_type_flattened_async(): - 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.update_entity_type), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcd_entity_type.EntityType() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcd_entity_type.EntityType()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.update_entity_type( - entity_type=gcd_entity_type.EntityType(name='name_value'), - language_code='language_code_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] - arg = args[0].entity_type - mock_val = gcd_entity_type.EntityType(name='name_value') - assert arg == mock_val - arg = args[0].language_code - mock_val = 'language_code_value' - assert arg == mock_val - arg = args[0].update_mask - mock_val = field_mask_pb2.FieldMask(paths=['paths_value']) - assert arg == mock_val - -@pytest.mark.asyncio -async def test_update_entity_type_flattened_error_async(): - client = EntityTypesAsyncClient( - 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_entity_type( - gcd_entity_type.UpdateEntityTypeRequest(), - entity_type=gcd_entity_type.EntityType(name='name_value'), - language_code='language_code_value', - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - - -@pytest.mark.parametrize("request_type", [ - entity_type.DeleteEntityTypeRequest, - dict, -]) -def test_delete_entity_type(request_type, transport: str = 'grpc'): - client = EntityTypesClient( - 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_entity_type), - '__call__') 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. - assert response is None - - -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=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_entity_type), - '__call__') as call: - client.delete_entity_type() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == entity_type.DeleteEntityTypeRequest() - -@pytest.mark.asyncio -async def test_delete_entity_type_async(transport: str = 'grpc_asyncio', request_type=entity_type.DeleteEntityTypeRequest): - client = EntityTypesAsyncClient( - 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_entity_type), - '__call__') 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. - assert response is None - - -@pytest.mark.asyncio -async def test_delete_entity_type_async_from_dict(): - await test_delete_entity_type_async(request_type=dict) - - -def test_delete_entity_type_field_headers(): - 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. - with mock.patch.object( - 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. - 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_entity_type_field_headers_async(): - 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. - with mock.patch.object( - 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. - 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_entity_type_flattened(): - 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.delete_entity_type), - '__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_entity_type( - 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] - arg = args[0].name - mock_val = 'name_value' - assert arg == mock_val - - -def test_delete_entity_type_flattened_error(): - client = EntityTypesClient( - 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_entity_type( - entity_type.DeleteEntityTypeRequest(), - name='name_value', - ) - -@pytest.mark.asyncio -async def test_delete_entity_type_flattened_async(): - 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.delete_entity_type), - '__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_entity_type( - 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] - arg = args[0].name - mock_val = 'name_value' - assert arg == mock_val - -@pytest.mark.asyncio -async def test_delete_entity_type_flattened_error_async(): - client = EntityTypesAsyncClient( - 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_entity_type( - entity_type.DeleteEntityTypeRequest(), - name='name_value', - ) - - -@pytest.mark.parametrize("request_type", [ - entity_type.BatchUpdateEntityTypesRequest, - dict, -]) -def test_batch_update_entity_types(request_type, transport: str = 'grpc'): - client = EntityTypesClient( - 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.batch_update_entity_types), - '__call__') 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. - assert isinstance(response, future.Future) - - -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=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.batch_update_entity_types), - '__call__') as call: - client.batch_update_entity_types() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == entity_type.BatchUpdateEntityTypesRequest() - -@pytest.mark.asyncio -async def test_batch_update_entity_types_async(transport: str = 'grpc_asyncio', request_type=entity_type.BatchUpdateEntityTypesRequest): - client = EntityTypesAsyncClient( - 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.batch_update_entity_types), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name='operations/spam') - ) - response = await client.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. - assert isinstance(response, future.Future) - - -@pytest.mark.asyncio -async def test_batch_update_entity_types_async_from_dict(): - await test_batch_update_entity_types_async(request_type=dict) - - -def test_batch_update_entity_types_field_headers(): - 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. - with mock.patch.object( - 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. - 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_batch_update_entity_types_field_headers_async(): - 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. - with mock.patch.object( - type(client.transport.batch_update_entity_types), - '__call__') as call: - 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. - 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'] - - -@pytest.mark.parametrize("request_type", [ - entity_type.BatchDeleteEntityTypesRequest, - dict, -]) -def test_batch_delete_entity_types(request_type, transport: str = 'grpc'): - client = EntityTypesClient( - 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.batch_delete_entity_types), - '__call__') 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. - assert isinstance(response, future.Future) - - -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=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.batch_delete_entity_types), - '__call__') as call: - client.batch_delete_entity_types() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == entity_type.BatchDeleteEntityTypesRequest() - -@pytest.mark.asyncio -async def test_batch_delete_entity_types_async(transport: str = 'grpc_asyncio', request_type=entity_type.BatchDeleteEntityTypesRequest): - client = EntityTypesAsyncClient( - 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.batch_delete_entity_types), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name='operations/spam') - ) - response = await client.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. - assert isinstance(response, future.Future) - - -@pytest.mark.asyncio -async def test_batch_delete_entity_types_async_from_dict(): - await test_batch_delete_entity_types_async(request_type=dict) - - -def test_batch_delete_entity_types_field_headers(): - 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. - with mock.patch.object( - 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. - 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_batch_delete_entity_types_field_headers_async(): - 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. - with mock.patch.object( - type(client.transport.batch_delete_entity_types), - '__call__') as call: - 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. - 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_batch_delete_entity_types_flattened(): - 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.batch_delete_entity_types), - '__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.batch_delete_entity_types( - parent='parent_value', - entity_type_names=['entity_type_names_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] - arg = args[0].parent - mock_val = 'parent_value' - assert arg == mock_val - arg = args[0].entity_type_names - mock_val = ['entity_type_names_value'] - assert arg == mock_val - - -def test_batch_delete_entity_types_flattened_error(): - client = EntityTypesClient( - 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.batch_delete_entity_types( - entity_type.BatchDeleteEntityTypesRequest(), - parent='parent_value', - entity_type_names=['entity_type_names_value'], - ) - -@pytest.mark.asyncio -async def test_batch_delete_entity_types_flattened_async(): - 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.batch_delete_entity_types), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/op') - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name='operations/spam') - ) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.batch_delete_entity_types( - parent='parent_value', - entity_type_names=['entity_type_names_value'], - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - arg = args[0].parent - mock_val = 'parent_value' - assert arg == mock_val - arg = args[0].entity_type_names - mock_val = ['entity_type_names_value'] - assert arg == mock_val - -@pytest.mark.asyncio -async def test_batch_delete_entity_types_flattened_error_async(): - client = EntityTypesAsyncClient( - 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.batch_delete_entity_types( - entity_type.BatchDeleteEntityTypesRequest(), - parent='parent_value', - entity_type_names=['entity_type_names_value'], - ) - - -@pytest.mark.parametrize("request_type", [ - entity_type.BatchCreateEntitiesRequest, - dict, -]) -def test_batch_create_entities(request_type, transport: str = 'grpc'): - client = EntityTypesClient( - 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.batch_create_entities), - '__call__') 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. - assert isinstance(response, future.Future) - - -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=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.batch_create_entities), - '__call__') as call: - client.batch_create_entities() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == entity_type.BatchCreateEntitiesRequest() - -@pytest.mark.asyncio -async def test_batch_create_entities_async(transport: str = 'grpc_asyncio', request_type=entity_type.BatchCreateEntitiesRequest): - client = EntityTypesAsyncClient( - 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.batch_create_entities), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name='operations/spam') - ) - response = await client.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. - assert isinstance(response, future.Future) - - -@pytest.mark.asyncio -async def test_batch_create_entities_async_from_dict(): - await test_batch_create_entities_async(request_type=dict) - - -def test_batch_create_entities_field_headers(): - 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. - with mock.patch.object( - 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. - 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_batch_create_entities_field_headers_async(): - 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. - with mock.patch.object( - type(client.transport.batch_create_entities), - '__call__') as call: - 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. - 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_batch_create_entities_flattened(): - 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.batch_create_entities), - '__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.batch_create_entities( - parent='parent_value', - entities=[entity_type.EntityType.Entity(value='value_value')], - language_code='language_code_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] - arg = args[0].parent - mock_val = 'parent_value' - assert arg == mock_val - arg = args[0].entities - mock_val = [entity_type.EntityType.Entity(value='value_value')] - assert arg == mock_val - arg = args[0].language_code - mock_val = 'language_code_value' - assert arg == mock_val - - -def test_batch_create_entities_flattened_error(): - client = EntityTypesClient( - 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.batch_create_entities( - entity_type.BatchCreateEntitiesRequest(), - parent='parent_value', - entities=[entity_type.EntityType.Entity(value='value_value')], - language_code='language_code_value', - ) - -@pytest.mark.asyncio -async def test_batch_create_entities_flattened_async(): - 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.batch_create_entities), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/op') - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name='operations/spam') - ) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.batch_create_entities( - parent='parent_value', - entities=[entity_type.EntityType.Entity(value='value_value')], - language_code='language_code_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - arg = args[0].parent - mock_val = 'parent_value' - assert arg == mock_val - arg = args[0].entities - mock_val = [entity_type.EntityType.Entity(value='value_value')] - assert arg == mock_val - arg = args[0].language_code - mock_val = 'language_code_value' - assert arg == mock_val - -@pytest.mark.asyncio -async def test_batch_create_entities_flattened_error_async(): - client = EntityTypesAsyncClient( - 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.batch_create_entities( - entity_type.BatchCreateEntitiesRequest(), - parent='parent_value', - entities=[entity_type.EntityType.Entity(value='value_value')], - language_code='language_code_value', - ) - - -@pytest.mark.parametrize("request_type", [ - entity_type.BatchUpdateEntitiesRequest, - dict, -]) -def test_batch_update_entities(request_type, transport: str = 'grpc'): - client = EntityTypesClient( - 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.batch_update_entities), - '__call__') 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. - assert isinstance(response, future.Future) - - -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=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.batch_update_entities), - '__call__') as call: - client.batch_update_entities() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == entity_type.BatchUpdateEntitiesRequest() - -@pytest.mark.asyncio -async def test_batch_update_entities_async(transport: str = 'grpc_asyncio', request_type=entity_type.BatchUpdateEntitiesRequest): - client = EntityTypesAsyncClient( - 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.batch_update_entities), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name='operations/spam') - ) - response = await client.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. - assert isinstance(response, future.Future) - - -@pytest.mark.asyncio -async def test_batch_update_entities_async_from_dict(): - await test_batch_update_entities_async(request_type=dict) - - -def test_batch_update_entities_field_headers(): - 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. - with mock.patch.object( - 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. - 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_batch_update_entities_field_headers_async(): - 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. - with mock.patch.object( - type(client.transport.batch_update_entities), - '__call__') as call: - 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. - 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_batch_update_entities_flattened(): - 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.batch_update_entities), - '__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.batch_update_entities( - parent='parent_value', - entities=[entity_type.EntityType.Entity(value='value_value')], - language_code='language_code_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] - arg = args[0].parent - mock_val = 'parent_value' - assert arg == mock_val - arg = args[0].entities - mock_val = [entity_type.EntityType.Entity(value='value_value')] - assert arg == mock_val - arg = args[0].language_code - mock_val = 'language_code_value' - assert arg == mock_val - - -def test_batch_update_entities_flattened_error(): - client = EntityTypesClient( - 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.batch_update_entities( - entity_type.BatchUpdateEntitiesRequest(), - parent='parent_value', - entities=[entity_type.EntityType.Entity(value='value_value')], - language_code='language_code_value', - ) - -@pytest.mark.asyncio -async def test_batch_update_entities_flattened_async(): - 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.batch_update_entities), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/op') - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name='operations/spam') - ) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.batch_update_entities( - parent='parent_value', - entities=[entity_type.EntityType.Entity(value='value_value')], - language_code='language_code_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - arg = args[0].parent - mock_val = 'parent_value' - assert arg == mock_val - arg = args[0].entities - mock_val = [entity_type.EntityType.Entity(value='value_value')] - assert arg == mock_val - arg = args[0].language_code - mock_val = 'language_code_value' - assert arg == mock_val - -@pytest.mark.asyncio -async def test_batch_update_entities_flattened_error_async(): - client = EntityTypesAsyncClient( - 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.batch_update_entities( - entity_type.BatchUpdateEntitiesRequest(), - parent='parent_value', - entities=[entity_type.EntityType.Entity(value='value_value')], - language_code='language_code_value', - ) - - -@pytest.mark.parametrize("request_type", [ - entity_type.BatchDeleteEntitiesRequest, - dict, -]) -def test_batch_delete_entities(request_type, transport: str = 'grpc'): - client = EntityTypesClient( - 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.batch_delete_entities), - '__call__') 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. - assert isinstance(response, future.Future) - - -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=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.batch_delete_entities), - '__call__') as call: - client.batch_delete_entities() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == entity_type.BatchDeleteEntitiesRequest() - -@pytest.mark.asyncio -async def test_batch_delete_entities_async(transport: str = 'grpc_asyncio', request_type=entity_type.BatchDeleteEntitiesRequest): - client = EntityTypesAsyncClient( - 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.batch_delete_entities), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name='operations/spam') - ) - response = await client.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. - assert isinstance(response, future.Future) - - -@pytest.mark.asyncio -async def test_batch_delete_entities_async_from_dict(): - await test_batch_delete_entities_async(request_type=dict) - - -def test_batch_delete_entities_field_headers(): - 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. - with mock.patch.object( - 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. - 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_batch_delete_entities_field_headers_async(): - 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. - with mock.patch.object( - type(client.transport.batch_delete_entities), - '__call__') as call: - 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. - 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_batch_delete_entities_flattened(): - 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.batch_delete_entities), - '__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.batch_delete_entities( - parent='parent_value', - entity_values=['entity_values_value'], - language_code='language_code_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] - arg = args[0].parent - mock_val = 'parent_value' - assert arg == mock_val - arg = args[0].entity_values - mock_val = ['entity_values_value'] - assert arg == mock_val - arg = args[0].language_code - mock_val = 'language_code_value' - assert arg == mock_val - - -def test_batch_delete_entities_flattened_error(): - client = EntityTypesClient( - 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.batch_delete_entities( - entity_type.BatchDeleteEntitiesRequest(), - parent='parent_value', - entity_values=['entity_values_value'], - language_code='language_code_value', - ) - -@pytest.mark.asyncio -async def test_batch_delete_entities_flattened_async(): - 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.batch_delete_entities), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/op') - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name='operations/spam') - ) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.batch_delete_entities( - parent='parent_value', - entity_values=['entity_values_value'], - language_code='language_code_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - arg = args[0].parent - mock_val = 'parent_value' - assert arg == mock_val - arg = args[0].entity_values - mock_val = ['entity_values_value'] - assert arg == mock_val - arg = args[0].language_code - mock_val = 'language_code_value' - assert arg == mock_val - -@pytest.mark.asyncio -async def test_batch_delete_entities_flattened_error_async(): - client = EntityTypesAsyncClient( - 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.batch_delete_entities( - entity_type.BatchDeleteEntitiesRequest(), - parent='parent_value', - entity_values=['entity_values_value'], - language_code='language_code_value', - ) - - -@pytest.mark.parametrize("request_type", [ - entity_type.ListEntityTypesRequest, - dict, -]) -def test_list_entity_types_rest(request_type): - client = EntityTypesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1/agent'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = entity_type.ListEntityTypesResponse( - next_page_token='next_page_token_value', - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - pb_return_value = entity_type.ListEntityTypesResponse.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.list_entity_types(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListEntityTypesPager) - assert response.next_page_token == 'next_page_token_value' - - -def test_list_entity_types_rest_required_fields(request_type=entity_type.ListEntityTypesRequest): - transport_class = transports.EntityTypesRestTransport - - request_init = {} - request_init["parent"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - including_default_value_fields=False, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).list_entity_types._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["parent"] = 'parent_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).list_entity_types._get_unset_required_fields(jsonified_request) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("language_code", "page_size", "page_token", )) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "parent" in jsonified_request - assert jsonified_request["parent"] == 'parent_value' - - client = EntityTypesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = entity_type.ListEntityTypesResponse() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "get", - 'query_params': pb_request, - } - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - - pb_return_value = entity_type.ListEntityTypesResponse.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.list_entity_types(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_list_entity_types_rest_unset_required_fields(): - transport = transports.EntityTypesRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.list_entity_types._get_unset_required_fields({}) - assert set(unset_fields) == (set(("languageCode", "pageSize", "pageToken", )) & set(("parent", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_list_entity_types_rest_interceptors(null_interceptor): - transport = transports.EntityTypesRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.EntityTypesRestInterceptor(), - ) - client = EntityTypesClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.EntityTypesRestInterceptor, "post_list_entity_types") as post, \ - mock.patch.object(transports.EntityTypesRestInterceptor, "pre_list_entity_types") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = entity_type.ListEntityTypesRequest.pb(entity_type.ListEntityTypesRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = entity_type.ListEntityTypesResponse.to_json(entity_type.ListEntityTypesResponse()) - - request = entity_type.ListEntityTypesRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = entity_type.ListEntityTypesResponse() - - client.list_entity_types(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_list_entity_types_rest_bad_request(transport: str = 'rest', request_type=entity_type.ListEntityTypesRequest): - client = EntityTypesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1/agent'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.list_entity_types(request) - - -def test_list_entity_types_rest_flattened(): - client = EntityTypesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = entity_type.ListEntityTypesResponse() - - # get arguments that satisfy an http rule for this method - sample_request = {'parent': 'projects/sample1/agent'} - - # get truthy value for each flattened field - mock_args = dict( - parent='parent_value', - language_code='language_code_value', - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - pb_return_value = entity_type.ListEntityTypesResponse.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.list_entity_types(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v2beta1/{parent=projects/*/agent}/entityTypes" % client.transport._host, args[1]) - - -def test_list_entity_types_rest_flattened_error(transport: str = 'rest'): - client = EntityTypesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.list_entity_types( - entity_type.ListEntityTypesRequest(), - parent='parent_value', - language_code='language_code_value', - ) - - -def test_list_entity_types_rest_pager(transport: str = 'rest'): - client = EntityTypesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # TODO(kbandes): remove this mock unless there's a good reason for it. - #with mock.patch.object(path_template, 'transcode') as transcode: - # Set the response as a series of pages - response = ( - entity_type.ListEntityTypesResponse( - entity_types=[ - entity_type.EntityType(), - entity_type.EntityType(), - entity_type.EntityType(), - ], - next_page_token='abc', - ), - entity_type.ListEntityTypesResponse( - entity_types=[], - next_page_token='def', - ), - entity_type.ListEntityTypesResponse( - entity_types=[ - entity_type.EntityType(), - ], - next_page_token='ghi', - ), - entity_type.ListEntityTypesResponse( - entity_types=[ - entity_type.EntityType(), - entity_type.EntityType(), - ], - ), - ) - # Two responses for two calls - response = response + response - - # Wrap the values into proper Response objs - response = tuple(entity_type.ListEntityTypesResponse.to_json(x) for x in response) - return_values = tuple(Response() for i in response) - for return_val, response_val in zip(return_values, response): - return_val._content = response_val.encode('UTF-8') - return_val.status_code = 200 - req.side_effect = return_values - - sample_request = {'parent': 'projects/sample1/agent'} - - pager = client.list_entity_types(request=sample_request) - - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, entity_type.EntityType) - for i in results) - - pages = list(client.list_entity_types(request=sample_request).pages) - for page_, token in zip(pages, ['abc','def','ghi', '']): - assert page_.raw_page.next_page_token == token - - -@pytest.mark.parametrize("request_type", [ - entity_type.GetEntityTypeRequest, - dict, -]) -def test_get_entity_type_rest(request_type): - client = EntityTypesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/agent/entityTypes/sample2'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = entity_type.EntityType( - name='name_value', - display_name='display_name_value', - kind=entity_type.EntityType.Kind.KIND_MAP, - auto_expansion_mode=entity_type.EntityType.AutoExpansionMode.AUTO_EXPANSION_MODE_DEFAULT, - enable_fuzzy_extraction=True, - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - pb_return_value = entity_type.EntityType.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.get_entity_type(request) - - # 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 - - -def test_get_entity_type_rest_required_fields(request_type=entity_type.GetEntityTypeRequest): - transport_class = transports.EntityTypesRestTransport - - request_init = {} - request_init["name"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - including_default_value_fields=False, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_entity_type._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["name"] = 'name_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_entity_type._get_unset_required_fields(jsonified_request) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("language_code", )) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "name" in jsonified_request - assert jsonified_request["name"] == 'name_value' - - client = EntityTypesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = entity_type.EntityType() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "get", - 'query_params': pb_request, - } - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - - pb_return_value = entity_type.EntityType.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.get_entity_type(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_get_entity_type_rest_unset_required_fields(): - transport = transports.EntityTypesRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.get_entity_type._get_unset_required_fields({}) - assert set(unset_fields) == (set(("languageCode", )) & set(("name", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_get_entity_type_rest_interceptors(null_interceptor): - transport = transports.EntityTypesRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.EntityTypesRestInterceptor(), - ) - client = EntityTypesClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.EntityTypesRestInterceptor, "post_get_entity_type") as post, \ - mock.patch.object(transports.EntityTypesRestInterceptor, "pre_get_entity_type") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = entity_type.GetEntityTypeRequest.pb(entity_type.GetEntityTypeRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = entity_type.EntityType.to_json(entity_type.EntityType()) - - request = entity_type.GetEntityTypeRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = entity_type.EntityType() - - client.get_entity_type(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_get_entity_type_rest_bad_request(transport: str = 'rest', request_type=entity_type.GetEntityTypeRequest): - client = EntityTypesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/agent/entityTypes/sample2'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.get_entity_type(request) - - -def test_get_entity_type_rest_flattened(): - client = EntityTypesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = entity_type.EntityType() - - # get arguments that satisfy an http rule for this method - sample_request = {'name': 'projects/sample1/agent/entityTypes/sample2'} - - # get truthy value for each flattened field - mock_args = dict( - name='name_value', - language_code='language_code_value', - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - pb_return_value = entity_type.EntityType.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.get_entity_type(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v2beta1/{name=projects/*/agent/entityTypes/*}" % client.transport._host, args[1]) - - -def test_get_entity_type_rest_flattened_error(transport: str = 'rest'): - client = EntityTypesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.get_entity_type( - entity_type.GetEntityTypeRequest(), - name='name_value', - language_code='language_code_value', - ) - - -def test_get_entity_type_rest_error(): - client = EntityTypesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - gcd_entity_type.CreateEntityTypeRequest, - dict, -]) -def test_create_entity_type_rest(request_type): - client = EntityTypesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1/agent'} - request_init["entity_type"] = {'name': 'name_value', 'display_name': 'display_name_value', 'kind': 1, 'auto_expansion_mode': 1, 'entities': [{'value': 'value_value', 'synonyms': ['synonyms_value1', 'synonyms_value2']}], 'enable_fuzzy_extraction': True} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = gcd_entity_type.EntityType( - name='name_value', - display_name='display_name_value', - kind=gcd_entity_type.EntityType.Kind.KIND_MAP, - auto_expansion_mode=gcd_entity_type.EntityType.AutoExpansionMode.AUTO_EXPANSION_MODE_DEFAULT, - enable_fuzzy_extraction=True, - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - pb_return_value = gcd_entity_type.EntityType.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.create_entity_type(request) - - # 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 - - -def test_create_entity_type_rest_required_fields(request_type=gcd_entity_type.CreateEntityTypeRequest): - transport_class = transports.EntityTypesRestTransport - - request_init = {} - request_init["parent"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - including_default_value_fields=False, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_entity_type._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["parent"] = 'parent_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_entity_type._get_unset_required_fields(jsonified_request) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("language_code", )) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "parent" in jsonified_request - assert jsonified_request["parent"] == 'parent_value' - - client = EntityTypesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = gcd_entity_type.EntityType() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "post", - 'query_params': pb_request, - } - transcode_result['body'] = pb_request - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - - pb_return_value = gcd_entity_type.EntityType.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.create_entity_type(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_create_entity_type_rest_unset_required_fields(): - transport = transports.EntityTypesRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.create_entity_type._get_unset_required_fields({}) - assert set(unset_fields) == (set(("languageCode", )) & set(("parent", "entityType", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_create_entity_type_rest_interceptors(null_interceptor): - transport = transports.EntityTypesRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.EntityTypesRestInterceptor(), - ) - client = EntityTypesClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.EntityTypesRestInterceptor, "post_create_entity_type") as post, \ - mock.patch.object(transports.EntityTypesRestInterceptor, "pre_create_entity_type") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = gcd_entity_type.CreateEntityTypeRequest.pb(gcd_entity_type.CreateEntityTypeRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = gcd_entity_type.EntityType.to_json(gcd_entity_type.EntityType()) - - request = gcd_entity_type.CreateEntityTypeRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = gcd_entity_type.EntityType() - - client.create_entity_type(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_create_entity_type_rest_bad_request(transport: str = 'rest', request_type=gcd_entity_type.CreateEntityTypeRequest): - client = EntityTypesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1/agent'} - request_init["entity_type"] = {'name': 'name_value', 'display_name': 'display_name_value', 'kind': 1, 'auto_expansion_mode': 1, 'entities': [{'value': 'value_value', 'synonyms': ['synonyms_value1', 'synonyms_value2']}], 'enable_fuzzy_extraction': True} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.create_entity_type(request) - - -def test_create_entity_type_rest_flattened(): - client = EntityTypesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = gcd_entity_type.EntityType() - - # get arguments that satisfy an http rule for this method - sample_request = {'parent': 'projects/sample1/agent'} - - # get truthy value for each flattened field - mock_args = dict( - parent='parent_value', - entity_type=gcd_entity_type.EntityType(name='name_value'), - language_code='language_code_value', - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - pb_return_value = gcd_entity_type.EntityType.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.create_entity_type(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v2beta1/{parent=projects/*/agent}/entityTypes" % client.transport._host, args[1]) - - -def test_create_entity_type_rest_flattened_error(transport: str = 'rest'): - client = EntityTypesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.create_entity_type( - gcd_entity_type.CreateEntityTypeRequest(), - parent='parent_value', - entity_type=gcd_entity_type.EntityType(name='name_value'), - language_code='language_code_value', - ) - - -def test_create_entity_type_rest_error(): - client = EntityTypesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - gcd_entity_type.UpdateEntityTypeRequest, - dict, -]) -def test_update_entity_type_rest(request_type): - client = EntityTypesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'entity_type': {'name': 'projects/sample1/agent/entityTypes/sample2'}} - request_init["entity_type"] = {'name': 'projects/sample1/agent/entityTypes/sample2', 'display_name': 'display_name_value', 'kind': 1, 'auto_expansion_mode': 1, 'entities': [{'value': 'value_value', 'synonyms': ['synonyms_value1', 'synonyms_value2']}], 'enable_fuzzy_extraction': True} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = gcd_entity_type.EntityType( - name='name_value', - display_name='display_name_value', - kind=gcd_entity_type.EntityType.Kind.KIND_MAP, - auto_expansion_mode=gcd_entity_type.EntityType.AutoExpansionMode.AUTO_EXPANSION_MODE_DEFAULT, - enable_fuzzy_extraction=True, - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - pb_return_value = gcd_entity_type.EntityType.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.update_entity_type(request) - - # 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 - - -def test_update_entity_type_rest_required_fields(request_type=gcd_entity_type.UpdateEntityTypeRequest): - transport_class = transports.EntityTypesRestTransport - - request_init = {} - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - including_default_value_fields=False, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).update_entity_type._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).update_entity_type._get_unset_required_fields(jsonified_request) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("language_code", "update_mask", )) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - - client = EntityTypesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = gcd_entity_type.EntityType() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "patch", - 'query_params': pb_request, - } - transcode_result['body'] = pb_request - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - - pb_return_value = gcd_entity_type.EntityType.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.update_entity_type(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_update_entity_type_rest_unset_required_fields(): - transport = transports.EntityTypesRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.update_entity_type._get_unset_required_fields({}) - assert set(unset_fields) == (set(("languageCode", "updateMask", )) & set(("entityType", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_update_entity_type_rest_interceptors(null_interceptor): - transport = transports.EntityTypesRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.EntityTypesRestInterceptor(), - ) - client = EntityTypesClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.EntityTypesRestInterceptor, "post_update_entity_type") as post, \ - mock.patch.object(transports.EntityTypesRestInterceptor, "pre_update_entity_type") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = gcd_entity_type.UpdateEntityTypeRequest.pb(gcd_entity_type.UpdateEntityTypeRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = gcd_entity_type.EntityType.to_json(gcd_entity_type.EntityType()) - - request = gcd_entity_type.UpdateEntityTypeRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = gcd_entity_type.EntityType() - - client.update_entity_type(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_update_entity_type_rest_bad_request(transport: str = 'rest', request_type=gcd_entity_type.UpdateEntityTypeRequest): - client = EntityTypesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'entity_type': {'name': 'projects/sample1/agent/entityTypes/sample2'}} - request_init["entity_type"] = {'name': 'projects/sample1/agent/entityTypes/sample2', 'display_name': 'display_name_value', 'kind': 1, 'auto_expansion_mode': 1, 'entities': [{'value': 'value_value', 'synonyms': ['synonyms_value1', 'synonyms_value2']}], 'enable_fuzzy_extraction': True} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.update_entity_type(request) - - -def test_update_entity_type_rest_flattened(): - client = EntityTypesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = gcd_entity_type.EntityType() - - # get arguments that satisfy an http rule for this method - sample_request = {'entity_type': {'name': 'projects/sample1/agent/entityTypes/sample2'}} - - # get truthy value for each flattened field - mock_args = dict( - entity_type=gcd_entity_type.EntityType(name='name_value'), - language_code='language_code_value', - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - pb_return_value = gcd_entity_type.EntityType.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.update_entity_type(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v2beta1/{entity_type.name=projects/*/agent/entityTypes/*}" % client.transport._host, args[1]) - - -def test_update_entity_type_rest_flattened_error(transport: str = 'rest'): - client = EntityTypesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.update_entity_type( - gcd_entity_type.UpdateEntityTypeRequest(), - entity_type=gcd_entity_type.EntityType(name='name_value'), - language_code='language_code_value', - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - - -def test_update_entity_type_rest_error(): - client = EntityTypesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - entity_type.DeleteEntityTypeRequest, - dict, -]) -def test_delete_entity_type_rest(request_type): - client = EntityTypesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/agent/entityTypes/sample2'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = None - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = '' - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.delete_entity_type(request) - - # Establish that the response is the type that we expect. - assert response is None - - -def test_delete_entity_type_rest_required_fields(request_type=entity_type.DeleteEntityTypeRequest): - transport_class = transports.EntityTypesRestTransport - - request_init = {} - request_init["name"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - including_default_value_fields=False, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).delete_entity_type._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["name"] = 'name_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).delete_entity_type._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "name" in jsonified_request - assert jsonified_request["name"] == 'name_value' - - client = EntityTypesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = None - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "delete", - 'query_params': pb_request, - } - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - json_return_value = '' - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.delete_entity_type(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_delete_entity_type_rest_unset_required_fields(): - transport = transports.EntityTypesRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.delete_entity_type._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_delete_entity_type_rest_interceptors(null_interceptor): - transport = transports.EntityTypesRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.EntityTypesRestInterceptor(), - ) - client = EntityTypesClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.EntityTypesRestInterceptor, "pre_delete_entity_type") as pre: - pre.assert_not_called() - pb_message = entity_type.DeleteEntityTypeRequest.pb(entity_type.DeleteEntityTypeRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - - request = entity_type.DeleteEntityTypeRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - - client.delete_entity_type(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - - -def test_delete_entity_type_rest_bad_request(transport: str = 'rest', request_type=entity_type.DeleteEntityTypeRequest): - client = EntityTypesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/agent/entityTypes/sample2'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.delete_entity_type(request) - - -def test_delete_entity_type_rest_flattened(): - client = EntityTypesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = None - - # get arguments that satisfy an http rule for this method - sample_request = {'name': 'projects/sample1/agent/entityTypes/sample2'} - - # get truthy value for each flattened field - mock_args = dict( - name='name_value', - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = '' - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.delete_entity_type(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v2beta1/{name=projects/*/agent/entityTypes/*}" % client.transport._host, args[1]) - - -def test_delete_entity_type_rest_flattened_error(transport: str = 'rest'): - client = EntityTypesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.delete_entity_type( - entity_type.DeleteEntityTypeRequest(), - name='name_value', - ) - - -def test_delete_entity_type_rest_error(): - client = EntityTypesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - entity_type.BatchUpdateEntityTypesRequest, - dict, -]) -def test_batch_update_entity_types_rest(request_type): - client = EntityTypesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1/agent'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name='operations/spam') - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.batch_update_entity_types(request) - - # Establish that the response is the type that we expect. - assert response.operation.name == "operations/spam" - - -def test_batch_update_entity_types_rest_required_fields(request_type=entity_type.BatchUpdateEntityTypesRequest): - transport_class = transports.EntityTypesRestTransport - - request_init = {} - request_init["parent"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - including_default_value_fields=False, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).batch_update_entity_types._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["parent"] = 'parent_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).batch_update_entity_types._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "parent" in jsonified_request - assert jsonified_request["parent"] == 'parent_value' - - client = EntityTypesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name='operations/spam') - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "post", - 'query_params': pb_request, - } - transcode_result['body'] = pb_request - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.batch_update_entity_types(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_batch_update_entity_types_rest_unset_required_fields(): - transport = transports.EntityTypesRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.batch_update_entity_types._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("parent", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_batch_update_entity_types_rest_interceptors(null_interceptor): - transport = transports.EntityTypesRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.EntityTypesRestInterceptor(), - ) - client = EntityTypesClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(operation.Operation, "_set_result_from_operation"), \ - mock.patch.object(transports.EntityTypesRestInterceptor, "post_batch_update_entity_types") as post, \ - mock.patch.object(transports.EntityTypesRestInterceptor, "pre_batch_update_entity_types") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = entity_type.BatchUpdateEntityTypesRequest.pb(entity_type.BatchUpdateEntityTypesRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = json_format.MessageToJson(operations_pb2.Operation()) - - request = entity_type.BatchUpdateEntityTypesRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = operations_pb2.Operation() - - client.batch_update_entity_types(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_batch_update_entity_types_rest_bad_request(transport: str = 'rest', request_type=entity_type.BatchUpdateEntityTypesRequest): - client = EntityTypesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1/agent'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.batch_update_entity_types(request) - - -def test_batch_update_entity_types_rest_error(): - client = EntityTypesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - entity_type.BatchDeleteEntityTypesRequest, - dict, -]) -def test_batch_delete_entity_types_rest(request_type): - client = EntityTypesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1/agent'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name='operations/spam') - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.batch_delete_entity_types(request) - - # Establish that the response is the type that we expect. - assert response.operation.name == "operations/spam" - - -def test_batch_delete_entity_types_rest_required_fields(request_type=entity_type.BatchDeleteEntityTypesRequest): - transport_class = transports.EntityTypesRestTransport - - request_init = {} - request_init["parent"] = "" - request_init["entity_type_names"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - including_default_value_fields=False, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).batch_delete_entity_types._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["parent"] = 'parent_value' - jsonified_request["entityTypeNames"] = 'entity_type_names_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).batch_delete_entity_types._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "parent" in jsonified_request - assert jsonified_request["parent"] == 'parent_value' - assert "entityTypeNames" in jsonified_request - assert jsonified_request["entityTypeNames"] == 'entity_type_names_value' - - client = EntityTypesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name='operations/spam') - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "post", - 'query_params': pb_request, - } - transcode_result['body'] = pb_request - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.batch_delete_entity_types(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_batch_delete_entity_types_rest_unset_required_fields(): - transport = transports.EntityTypesRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.batch_delete_entity_types._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("parent", "entityTypeNames", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_batch_delete_entity_types_rest_interceptors(null_interceptor): - transport = transports.EntityTypesRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.EntityTypesRestInterceptor(), - ) - client = EntityTypesClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(operation.Operation, "_set_result_from_operation"), \ - mock.patch.object(transports.EntityTypesRestInterceptor, "post_batch_delete_entity_types") as post, \ - mock.patch.object(transports.EntityTypesRestInterceptor, "pre_batch_delete_entity_types") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = entity_type.BatchDeleteEntityTypesRequest.pb(entity_type.BatchDeleteEntityTypesRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = json_format.MessageToJson(operations_pb2.Operation()) - - request = entity_type.BatchDeleteEntityTypesRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = operations_pb2.Operation() - - client.batch_delete_entity_types(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_batch_delete_entity_types_rest_bad_request(transport: str = 'rest', request_type=entity_type.BatchDeleteEntityTypesRequest): - client = EntityTypesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1/agent'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.batch_delete_entity_types(request) - - -def test_batch_delete_entity_types_rest_flattened(): - client = EntityTypesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name='operations/spam') - - # get arguments that satisfy an http rule for this method - sample_request = {'parent': 'projects/sample1/agent'} - - # get truthy value for each flattened field - mock_args = dict( - parent='parent_value', - entity_type_names=['entity_type_names_value'], - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.batch_delete_entity_types(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v2beta1/{parent=projects/*/agent}/entityTypes:batchDelete" % client.transport._host, args[1]) - - -def test_batch_delete_entity_types_rest_flattened_error(transport: str = 'rest'): - client = EntityTypesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.batch_delete_entity_types( - entity_type.BatchDeleteEntityTypesRequest(), - parent='parent_value', - entity_type_names=['entity_type_names_value'], - ) - - -def test_batch_delete_entity_types_rest_error(): - client = EntityTypesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - entity_type.BatchCreateEntitiesRequest, - dict, -]) -def test_batch_create_entities_rest(request_type): - client = EntityTypesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1/agent/entityTypes/sample2'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name='operations/spam') - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.batch_create_entities(request) - - # Establish that the response is the type that we expect. - assert response.operation.name == "operations/spam" - - -def test_batch_create_entities_rest_required_fields(request_type=entity_type.BatchCreateEntitiesRequest): - transport_class = transports.EntityTypesRestTransport - - request_init = {} - request_init["parent"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - including_default_value_fields=False, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).batch_create_entities._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["parent"] = 'parent_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).batch_create_entities._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "parent" in jsonified_request - assert jsonified_request["parent"] == 'parent_value' - - client = EntityTypesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name='operations/spam') - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "post", - 'query_params': pb_request, - } - transcode_result['body'] = pb_request - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.batch_create_entities(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_batch_create_entities_rest_unset_required_fields(): - transport = transports.EntityTypesRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.batch_create_entities._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("parent", "entities", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_batch_create_entities_rest_interceptors(null_interceptor): - transport = transports.EntityTypesRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.EntityTypesRestInterceptor(), - ) - client = EntityTypesClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(operation.Operation, "_set_result_from_operation"), \ - mock.patch.object(transports.EntityTypesRestInterceptor, "post_batch_create_entities") as post, \ - mock.patch.object(transports.EntityTypesRestInterceptor, "pre_batch_create_entities") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = entity_type.BatchCreateEntitiesRequest.pb(entity_type.BatchCreateEntitiesRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = json_format.MessageToJson(operations_pb2.Operation()) - - request = entity_type.BatchCreateEntitiesRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = operations_pb2.Operation() - - client.batch_create_entities(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_batch_create_entities_rest_bad_request(transport: str = 'rest', request_type=entity_type.BatchCreateEntitiesRequest): - client = EntityTypesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1/agent/entityTypes/sample2'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.batch_create_entities(request) - - -def test_batch_create_entities_rest_flattened(): - client = EntityTypesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name='operations/spam') - - # get arguments that satisfy an http rule for this method - sample_request = {'parent': 'projects/sample1/agent/entityTypes/sample2'} - - # get truthy value for each flattened field - mock_args = dict( - parent='parent_value', - entities=[entity_type.EntityType.Entity(value='value_value')], - language_code='language_code_value', - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.batch_create_entities(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v2beta1/{parent=projects/*/agent/entityTypes/*}/entities:batchCreate" % client.transport._host, args[1]) - - -def test_batch_create_entities_rest_flattened_error(transport: str = 'rest'): - client = EntityTypesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.batch_create_entities( - entity_type.BatchCreateEntitiesRequest(), - parent='parent_value', - entities=[entity_type.EntityType.Entity(value='value_value')], - language_code='language_code_value', - ) - - -def test_batch_create_entities_rest_error(): - client = EntityTypesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - entity_type.BatchUpdateEntitiesRequest, - dict, -]) -def test_batch_update_entities_rest(request_type): - client = EntityTypesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1/agent/entityTypes/sample2'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name='operations/spam') - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.batch_update_entities(request) - - # Establish that the response is the type that we expect. - assert response.operation.name == "operations/spam" - - -def test_batch_update_entities_rest_required_fields(request_type=entity_type.BatchUpdateEntitiesRequest): - transport_class = transports.EntityTypesRestTransport - - request_init = {} - request_init["parent"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - including_default_value_fields=False, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).batch_update_entities._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["parent"] = 'parent_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).batch_update_entities._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "parent" in jsonified_request - assert jsonified_request["parent"] == 'parent_value' - - client = EntityTypesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name='operations/spam') - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "post", - 'query_params': pb_request, - } - transcode_result['body'] = pb_request - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.batch_update_entities(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_batch_update_entities_rest_unset_required_fields(): - transport = transports.EntityTypesRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.batch_update_entities._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("parent", "entities", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_batch_update_entities_rest_interceptors(null_interceptor): - transport = transports.EntityTypesRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.EntityTypesRestInterceptor(), - ) - client = EntityTypesClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(operation.Operation, "_set_result_from_operation"), \ - mock.patch.object(transports.EntityTypesRestInterceptor, "post_batch_update_entities") as post, \ - mock.patch.object(transports.EntityTypesRestInterceptor, "pre_batch_update_entities") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = entity_type.BatchUpdateEntitiesRequest.pb(entity_type.BatchUpdateEntitiesRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = json_format.MessageToJson(operations_pb2.Operation()) - - request = entity_type.BatchUpdateEntitiesRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = operations_pb2.Operation() - - client.batch_update_entities(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_batch_update_entities_rest_bad_request(transport: str = 'rest', request_type=entity_type.BatchUpdateEntitiesRequest): - client = EntityTypesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1/agent/entityTypes/sample2'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.batch_update_entities(request) - - -def test_batch_update_entities_rest_flattened(): - client = EntityTypesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name='operations/spam') - - # get arguments that satisfy an http rule for this method - sample_request = {'parent': 'projects/sample1/agent/entityTypes/sample2'} - - # get truthy value for each flattened field - mock_args = dict( - parent='parent_value', - entities=[entity_type.EntityType.Entity(value='value_value')], - language_code='language_code_value', - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.batch_update_entities(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v2beta1/{parent=projects/*/agent/entityTypes/*}/entities:batchUpdate" % client.transport._host, args[1]) - - -def test_batch_update_entities_rest_flattened_error(transport: str = 'rest'): - client = EntityTypesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.batch_update_entities( - entity_type.BatchUpdateEntitiesRequest(), - parent='parent_value', - entities=[entity_type.EntityType.Entity(value='value_value')], - language_code='language_code_value', - ) - - -def test_batch_update_entities_rest_error(): - client = EntityTypesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - entity_type.BatchDeleteEntitiesRequest, - dict, -]) -def test_batch_delete_entities_rest(request_type): - client = EntityTypesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1/agent/entityTypes/sample2'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name='operations/spam') - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.batch_delete_entities(request) - - # Establish that the response is the type that we expect. - assert response.operation.name == "operations/spam" - - -def test_batch_delete_entities_rest_required_fields(request_type=entity_type.BatchDeleteEntitiesRequest): - transport_class = transports.EntityTypesRestTransport - - request_init = {} - request_init["parent"] = "" - request_init["entity_values"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - including_default_value_fields=False, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).batch_delete_entities._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["parent"] = 'parent_value' - jsonified_request["entityValues"] = 'entity_values_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).batch_delete_entities._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "parent" in jsonified_request - assert jsonified_request["parent"] == 'parent_value' - assert "entityValues" in jsonified_request - assert jsonified_request["entityValues"] == 'entity_values_value' - - client = EntityTypesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name='operations/spam') - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "post", - 'query_params': pb_request, - } - transcode_result['body'] = pb_request - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.batch_delete_entities(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_batch_delete_entities_rest_unset_required_fields(): - transport = transports.EntityTypesRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.batch_delete_entities._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("parent", "entityValues", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_batch_delete_entities_rest_interceptors(null_interceptor): - transport = transports.EntityTypesRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.EntityTypesRestInterceptor(), - ) - client = EntityTypesClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(operation.Operation, "_set_result_from_operation"), \ - mock.patch.object(transports.EntityTypesRestInterceptor, "post_batch_delete_entities") as post, \ - mock.patch.object(transports.EntityTypesRestInterceptor, "pre_batch_delete_entities") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = entity_type.BatchDeleteEntitiesRequest.pb(entity_type.BatchDeleteEntitiesRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = json_format.MessageToJson(operations_pb2.Operation()) - - request = entity_type.BatchDeleteEntitiesRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = operations_pb2.Operation() - - client.batch_delete_entities(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_batch_delete_entities_rest_bad_request(transport: str = 'rest', request_type=entity_type.BatchDeleteEntitiesRequest): - client = EntityTypesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1/agent/entityTypes/sample2'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.batch_delete_entities(request) - - -def test_batch_delete_entities_rest_flattened(): - client = EntityTypesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name='operations/spam') - - # get arguments that satisfy an http rule for this method - sample_request = {'parent': 'projects/sample1/agent/entityTypes/sample2'} - - # get truthy value for each flattened field - mock_args = dict( - parent='parent_value', - entity_values=['entity_values_value'], - language_code='language_code_value', - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.batch_delete_entities(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v2beta1/{parent=projects/*/agent/entityTypes/*}/entities:batchDelete" % client.transport._host, args[1]) - - -def test_batch_delete_entities_rest_flattened_error(transport: str = 'rest'): - client = EntityTypesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.batch_delete_entities( - entity_type.BatchDeleteEntitiesRequest(), - parent='parent_value', - entity_values=['entity_values_value'], - language_code='language_code_value', - ) - - -def test_batch_delete_entities_rest_error(): - client = EntityTypesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -def test_credentials_transport_error(): - # It is an error to provide credentials and a transport instance. - transport = transports.EntityTypesGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = EntityTypesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # It is an error to provide a credentials file and a transport instance. - transport = transports.EntityTypesGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = EntityTypesClient( - client_options={"credentials_file": "credentials.json"}, - transport=transport, - ) - - # It is an error to provide an api_key and a transport instance. - transport = transports.EntityTypesGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - options = client_options.ClientOptions() - options.api_key = "api_key" - with pytest.raises(ValueError): - client = EntityTypesClient( - client_options=options, - transport=transport, - ) - - # It is an error to provide an api_key and a credential. - options = mock.Mock() - options.api_key = "api_key" - with pytest.raises(ValueError): - client = EntityTypesClient( - client_options=options, - credentials=ga_credentials.AnonymousCredentials() - ) - - # It is an error to provide scopes and a transport instance. - transport = transports.EntityTypesGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = EntityTypesClient( - client_options={"scopes": ["1", "2"]}, - transport=transport, - ) - - -def test_transport_instance(): - # A client may be instantiated with a custom transport instance. - transport = transports.EntityTypesGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - client = EntityTypesClient(transport=transport) - assert client.transport is transport - -def test_transport_get_channel(): - # A client may be instantiated with a custom transport instance. - transport = transports.EntityTypesGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - - transport = transports.EntityTypesGrpcAsyncIOTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - -@pytest.mark.parametrize("transport_class", [ - transports.EntityTypesGrpcTransport, - transports.EntityTypesGrpcAsyncIOTransport, - transports.EntityTypesRestTransport, -]) -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() - -@pytest.mark.parametrize("transport_name", [ - "grpc", - "rest", -]) -def test_transport_kind(transport_name): - transport = EntityTypesClient.get_transport_class(transport_name)( - credentials=ga_credentials.AnonymousCredentials(), - ) - assert transport.kind == transport_name - -def test_transport_grpc_default(): - # A client should use the gRPC transport by default. - 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(core_exceptions.DuplicateCredentialArgs): - transport = transports.EntityTypesTransport( - credentials=ga_credentials.AnonymousCredentials(), - credentials_file="credentials.json" - ) - - -def test_entity_types_base_transport(): - # Instantiate the base transport. - with mock.patch('google.cloud.dialogflow_v2beta1.services.entity_types.transports.EntityTypesTransport.__init__') as Transport: - Transport.return_value = None - transport = transports.EntityTypesTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Every method on the transport should just blindly - # raise NotImplementedError. - methods = ( - 'list_entity_types', - 'get_entity_type', - 'create_entity_type', - 'update_entity_type', - 'delete_entity_type', - 'batch_update_entity_types', - 'batch_delete_entity_types', - 'batch_create_entities', - 'batch_update_entities', - 'batch_delete_entities', - 'get_location', - 'list_locations', - 'get_operation', - 'cancel_operation', - 'list_operations', - ) - for method in methods: - with pytest.raises(NotImplementedError): - getattr(transport, method)(request=object()) - - with pytest.raises(NotImplementedError): - transport.close() - - # Additionally, the LRO client (a property) should - # also raise NotImplementedError - with pytest.raises(NotImplementedError): - transport.operations_client - - # Catch all for all remaining methods and properties - remainder = [ - 'kind', - ] - for r in remainder: - with pytest.raises(NotImplementedError): - getattr(transport, r)() - - -def test_entity_types_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.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", - ) - - -def test_entity_types_base_transport_with_adc(): - # Test the default credentials are used if credentials and credentials_file are None. - with mock.patch.object(google.auth, 'default', autospec=True) as adc, mock.patch('google.cloud.dialogflow_v2beta1.services.entity_types.transports.EntityTypesTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.EntityTypesTransport() - adc.assert_called_once() - - -def test_entity_types_auth_adc(): - # If no credentials are provided, we should use ADC credentials. - with mock.patch.object(google.auth, 'default', autospec=True) as adc: - 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, - ) - - -@pytest.mark.parametrize( - "transport_class", - [ - transports.EntityTypesGrpcTransport, - transports.EntityTypesGrpcAsyncIOTransport, - ], -) -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(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, - transports.EntityTypesRestTransport, - ], -) -def test_entity_types_transport_auth_gdch_credentials(transport_class): - host = 'https://language.com' - api_audience_tests = [None, 'https://language2.com'] - api_audience_expect = [host, 'https://language2.com'] - for t, e in zip(api_audience_tests, api_audience_expect): - with mock.patch.object(google.auth, 'default', autospec=True) as adc: - gdch_mock = mock.MagicMock() - type(gdch_mock).with_gdch_audience = mock.PropertyMock(return_value=gdch_mock) - adc.return_value = (gdch_mock, None) - transport_class(host=host, api_audience=t) - gdch_mock.with_gdch_audience.assert_called_once_with( - e - ) - - -@pytest.mark.parametrize( - "transport_class,grpc_helpers", - [ - (transports.EntityTypesGrpcTransport, grpc_helpers), - (transports.EntityTypesGrpcAsyncIOTransport, grpc_helpers_async) - ], -) -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", [transports.EntityTypesGrpcTransport, transports.EntityTypesGrpcAsyncIOTransport]) -def test_entity_types_grpc_transport_client_cert_source_for_mtls( - transport_class -): - cred = ga_credentials.AnonymousCredentials() - - # Check ssl_channel_credentials is used if provided. - with mock.patch.object(transport_class, "create_channel") as mock_create_channel: - mock_ssl_channel_creds = mock.Mock() - transport_class( - host="squid.clam.whelk", - credentials=cred, - ssl_channel_credentials=mock_ssl_channel_creds - ) - mock_create_channel.assert_called_once_with( - "squid.clam.whelk:443", - credentials=cred, - credentials_file=None, - scopes=None, - ssl_credentials=mock_ssl_channel_creds, - quota_project_id=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - # Check if ssl_channel_credentials is not provided, then client_cert_source_for_mtls - # is used. - with mock.patch.object(transport_class, "create_channel", return_value=mock.Mock()): - with mock.patch("grpc.ssl_channel_credentials") as mock_ssl_cred: - transport_class( - credentials=cred, - client_cert_source_for_mtls=client_cert_source_callback - ) - expected_cert, expected_key = client_cert_source_callback() - mock_ssl_cred.assert_called_once_with( - certificate_chain=expected_cert, - private_key=expected_key - ) - -def test_entity_types_http_transport_client_cert_source_for_mtls(): - cred = ga_credentials.AnonymousCredentials() - with mock.patch("google.auth.transport.requests.AuthorizedSession.configure_mtls_channel") as mock_configure_mtls_channel: - transports.EntityTypesRestTransport ( - credentials=cred, - client_cert_source_for_mtls=client_cert_source_callback - ) - mock_configure_mtls_channel.assert_called_once_with(client_cert_source_callback) - - -def test_entity_types_rest_lro_client(): - client = EntityTypesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - transport = client.transport - - # Ensure that we have a api-core operations client. - assert isinstance( - transport.operations_client, - operations_v1.AbstractOperationsClient, - ) - - # Ensure that subsequent calls to the property send the exact same object. - assert transport.operations_client is transport.operations_client - - -@pytest.mark.parametrize("transport_name", [ - "grpc", - "grpc_asyncio", - "rest", -]) -def test_entity_types_host_no_port(transport_name): - client = EntityTypesClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='dialogflow.googleapis.com'), - transport=transport_name, - ) - assert client.transport._host == ( - 'dialogflow.googleapis.com:443' - if transport_name in ['grpc', 'grpc_asyncio'] - else 'https://dialogflow.googleapis.com' - ) - -@pytest.mark.parametrize("transport_name", [ - "grpc", - "grpc_asyncio", - "rest", -]) -def test_entity_types_host_with_port(transport_name): - client = EntityTypesClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='dialogflow.googleapis.com:8000'), - transport=transport_name, - ) - assert client.transport._host == ( - 'dialogflow.googleapis.com:8000' - if transport_name in ['grpc', 'grpc_asyncio'] - else 'https://dialogflow.googleapis.com:8000' - ) - -@pytest.mark.parametrize("transport_name", [ - "rest", -]) -def test_entity_types_client_transport_session_collision(transport_name): - creds1 = ga_credentials.AnonymousCredentials() - creds2 = ga_credentials.AnonymousCredentials() - client1 = EntityTypesClient( - credentials=creds1, - transport=transport_name, - ) - client2 = EntityTypesClient( - credentials=creds2, - transport=transport_name, - ) - session1 = client1.transport.list_entity_types._session - session2 = client2.transport.list_entity_types._session - assert session1 != session2 - session1 = client1.transport.get_entity_type._session - session2 = client2.transport.get_entity_type._session - assert session1 != session2 - session1 = client1.transport.create_entity_type._session - session2 = client2.transport.create_entity_type._session - assert session1 != session2 - session1 = client1.transport.update_entity_type._session - session2 = client2.transport.update_entity_type._session - assert session1 != session2 - session1 = client1.transport.delete_entity_type._session - session2 = client2.transport.delete_entity_type._session - assert session1 != session2 - session1 = client1.transport.batch_update_entity_types._session - session2 = client2.transport.batch_update_entity_types._session - assert session1 != session2 - session1 = client1.transport.batch_delete_entity_types._session - session2 = client2.transport.batch_delete_entity_types._session - assert session1 != session2 - session1 = client1.transport.batch_create_entities._session - session2 = client2.transport.batch_create_entities._session - assert session1 != session2 - session1 = client1.transport.batch_update_entities._session - session2 = client2.transport.batch_update_entities._session - assert session1 != session2 - session1 = client1.transport.batch_delete_entities._session - session2 = client2.transport.batch_delete_entities._session - assert session1 != session2 -def test_entity_types_grpc_transport_channel(): - channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.EntityTypesGrpcTransport( - 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_entity_types_grpc_asyncio_transport_channel(): - channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.EntityTypesGrpcAsyncIOTransport( - 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.EntityTypesGrpcTransport, transports.EntityTypesGrpcAsyncIOTransport]) -def test_entity_types_transport_channel_mtls_with_client_cert_source( - transport_class -): - with mock.patch("grpc.ssl_channel_credentials", autospec=True) as grpc_ssl_channel_cred: - with mock.patch.object(transport_class, "create_channel") as grpc_create_channel: - mock_ssl_cred = mock.Mock() - grpc_ssl_channel_cred.return_value = mock_ssl_cred - - mock_grpc_channel = mock.Mock() - grpc_create_channel.return_value = mock_grpc_channel - - cred = ga_credentials.AnonymousCredentials() - with pytest.warns(DeprecationWarning): - with mock.patch.object(google.auth, 'default') as adc: - adc.return_value = (cred, None) - transport = transport_class( - host="squid.clam.whelk", - api_mtls_endpoint="mtls.squid.clam.whelk", - client_cert_source=client_cert_source_callback, - ) - adc.assert_called_once() - - grpc_ssl_channel_cred.assert_called_once_with( - certificate_chain=b"cert bytes", private_key=b"key bytes" - ) - grpc_create_channel.assert_called_once_with( - "mtls.squid.clam.whelk:443", - credentials=cred, - credentials_file=None, - scopes=None, - ssl_credentials=mock_ssl_cred, - quota_project_id=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - assert transport.grpc_channel == mock_grpc_channel - assert transport._ssl_channel_credentials == mock_ssl_cred - - -# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are -# removed from grpc/grpc_asyncio transport constructor. -@pytest.mark.parametrize("transport_class", [transports.EntityTypesGrpcTransport, transports.EntityTypesGrpcAsyncIOTransport]) -def test_entity_types_transport_channel_mtls_with_adc( - transport_class -): - mock_ssl_cred = mock.Mock() - with mock.patch.multiple( - "google.auth.transport.grpc.SslCredentials", - __init__=mock.Mock(return_value=None), - ssl_credentials=mock.PropertyMock(return_value=mock_ssl_cred), - ): - with mock.patch.object(transport_class, "create_channel") as grpc_create_channel: - mock_grpc_channel = mock.Mock() - grpc_create_channel.return_value = mock_grpc_channel - mock_cred = mock.Mock() - - with pytest.warns(DeprecationWarning): - transport = transport_class( - host="squid.clam.whelk", - credentials=mock_cred, - api_mtls_endpoint="mtls.squid.clam.whelk", - client_cert_source=None, - ) - - grpc_create_channel.assert_called_once_with( - "mtls.squid.clam.whelk:443", - credentials=mock_cred, - credentials_file=None, - scopes=None, - ssl_credentials=mock_ssl_cred, - quota_project_id=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - assert transport.grpc_channel == mock_grpc_channel - - -def test_entity_types_grpc_lro_client(): - client = EntityTypesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - transport = client.transport - - # Ensure that we have a api-core operations client. - assert isinstance( - transport.operations_client, - operations_v1.OperationsClient, - ) - - # Ensure that subsequent calls to the property send the exact same object. - assert transport.operations_client is transport.operations_client - - -def test_entity_types_grpc_lro_async_client(): - client = EntityTypesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc_asyncio', - ) - transport = client.transport - - # Ensure that we have a api-core operations client. - assert isinstance( - transport.operations_client, - operations_v1.OperationsAsyncClient, - ) - - # Ensure that subsequent calls to the property send the exact same object. - assert transport.operations_client is transport.operations_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, ) - actual = EntityTypesClient.entity_type_path(project, entity_type) - assert expected == actual - - -def test_parse_entity_type_path(): - expected = { - "project": "whelk", - "entity_type": "octopus", - } - path = EntityTypesClient.entity_type_path(**expected) - - # Check that the path construction is reversible. - actual = EntityTypesClient.parse_entity_type_path(path) - assert expected == actual - -def test_common_billing_account_path(): - billing_account = "oyster" - expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) - actual = EntityTypesClient.common_billing_account_path(billing_account) - assert expected == actual - - -def test_parse_common_billing_account_path(): - expected = { - "billing_account": "nudibranch", - } - path = EntityTypesClient.common_billing_account_path(**expected) - - # Check that the path construction is reversible. - actual = EntityTypesClient.parse_common_billing_account_path(path) - assert expected == actual - -def test_common_folder_path(): - folder = "cuttlefish" - expected = "folders/{folder}".format(folder=folder, ) - actual = EntityTypesClient.common_folder_path(folder) - assert expected == actual - - -def test_parse_common_folder_path(): - expected = { - "folder": "mussel", - } - path = EntityTypesClient.common_folder_path(**expected) - - # Check that the path construction is reversible. - actual = EntityTypesClient.parse_common_folder_path(path) - assert expected == actual - -def test_common_organization_path(): - organization = "winkle" - expected = "organizations/{organization}".format(organization=organization, ) - actual = EntityTypesClient.common_organization_path(organization) - assert expected == actual - - -def test_parse_common_organization_path(): - expected = { - "organization": "nautilus", - } - path = EntityTypesClient.common_organization_path(**expected) - - # Check that the path construction is reversible. - actual = EntityTypesClient.parse_common_organization_path(path) - assert expected == actual - -def test_common_project_path(): - project = "scallop" - expected = "projects/{project}".format(project=project, ) - actual = EntityTypesClient.common_project_path(project) - assert expected == actual - - -def test_parse_common_project_path(): - expected = { - "project": "abalone", - } - path = EntityTypesClient.common_project_path(**expected) - - # Check that the path construction is reversible. - actual = EntityTypesClient.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 = EntityTypesClient.common_location_path(project, location) - assert expected == actual - - -def test_parse_common_location_path(): - expected = { - "project": "whelk", - "location": "octopus", - } - path = EntityTypesClient.common_location_path(**expected) - - # Check that the path construction is reversible. - actual = EntityTypesClient.parse_common_location_path(path) - assert expected == actual - - -def test_client_with_default_client_info(): - client_info = gapic_v1.client_info.ClientInfo() - - with mock.patch.object(transports.EntityTypesTransport, '_prep_wrapped_messages') as prep: - client = EntityTypesClient( - credentials=ga_credentials.AnonymousCredentials(), - client_info=client_info, - ) - prep.assert_called_once_with(client_info) - - with mock.patch.object(transports.EntityTypesTransport, '_prep_wrapped_messages') as prep: - transport_class = EntityTypesClient.get_transport_class() - transport = transport_class( - credentials=ga_credentials.AnonymousCredentials(), - client_info=client_info, - ) - prep.assert_called_once_with(client_info) - -@pytest.mark.asyncio -async def test_transport_close_async(): - client = EntityTypesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - with mock.patch.object(type(getattr(client.transport, "grpc_channel")), "close") as close: - async with client: - close.assert_not_called() - close.assert_called_once() - - -def test_get_location_rest_bad_request(transport: str = 'rest', request_type=locations_pb2.GetLocationRequest): - client = EntityTypesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - request = request_type() - request = json_format.ParseDict({'name': 'projects/sample1/locations/sample2'}, request) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.get_location(request) - -@pytest.mark.parametrize("request_type", [ - locations_pb2.GetLocationRequest, - dict, -]) -def test_get_location_rest(request_type): - client = EntityTypesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request_init = {'name': 'projects/sample1/locations/sample2'} - request = request_type(**request_init) - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = locations_pb2.Location() - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.get_location(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, locations_pb2.Location) - -def test_list_locations_rest_bad_request(transport: str = 'rest', request_type=locations_pb2.ListLocationsRequest): - client = EntityTypesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - request = request_type() - request = json_format.ParseDict({'name': 'projects/sample1'}, request) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.list_locations(request) - -@pytest.mark.parametrize("request_type", [ - locations_pb2.ListLocationsRequest, - dict, -]) -def test_list_locations_rest(request_type): - client = EntityTypesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request_init = {'name': 'projects/sample1'} - request = request_type(**request_init) - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = locations_pb2.ListLocationsResponse() - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.list_locations(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, locations_pb2.ListLocationsResponse) - -def test_cancel_operation_rest_bad_request(transport: str = 'rest', request_type=operations_pb2.CancelOperationRequest): - client = EntityTypesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - request = request_type() - request = json_format.ParseDict({'name': 'projects/sample1/operations/sample2'}, request) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.cancel_operation(request) - -@pytest.mark.parametrize("request_type", [ - operations_pb2.CancelOperationRequest, - dict, -]) -def test_cancel_operation_rest(request_type): - client = EntityTypesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request_init = {'name': 'projects/sample1/operations/sample2'} - request = request_type(**request_init) - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = None - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = '{}' - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.cancel_operation(request) - - # Establish that the response is the type that we expect. - assert response is None - -def test_get_operation_rest_bad_request(transport: str = 'rest', request_type=operations_pb2.GetOperationRequest): - client = EntityTypesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - request = request_type() - request = json_format.ParseDict({'name': 'projects/sample1/operations/sample2'}, request) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.get_operation(request) - -@pytest.mark.parametrize("request_type", [ - operations_pb2.GetOperationRequest, - dict, -]) -def test_get_operation_rest(request_type): - client = EntityTypesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request_init = {'name': 'projects/sample1/operations/sample2'} - request = request_type(**request_init) - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation() - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.get_operation(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, operations_pb2.Operation) - -def test_list_operations_rest_bad_request(transport: str = 'rest', request_type=operations_pb2.ListOperationsRequest): - client = EntityTypesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - request = request_type() - request = json_format.ParseDict({'name': 'projects/sample1'}, request) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.list_operations(request) - -@pytest.mark.parametrize("request_type", [ - operations_pb2.ListOperationsRequest, - dict, -]) -def test_list_operations_rest(request_type): - client = EntityTypesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request_init = {'name': 'projects/sample1'} - request = request_type(**request_init) - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = operations_pb2.ListOperationsResponse() - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.list_operations(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, operations_pb2.ListOperationsResponse) - - -def test_cancel_operation(transport: str = "grpc"): - client = EntityTypesClient( - 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 = operations_pb2.CancelOperationRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = None - response = client.cancel_operation(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 response is the type that we expect. - assert response is None -@pytest.mark.asyncio -async def test_cancel_operation_async(transport: str = "grpc"): - client = EntityTypesAsyncClient( - 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 = operations_pb2.CancelOperationRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - None - ) - response = await client.cancel_operation(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 response is the type that we expect. - assert response is None - -def test_cancel_operation_field_headers(): - 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 = operations_pb2.CancelOperationRequest() - request.name = "locations" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call: - call.return_value = None - - client.cancel_operation(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=locations",) in kw["metadata"] -@pytest.mark.asyncio -async def test_cancel_operation_field_headers_async(): - 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 = operations_pb2.CancelOperationRequest() - request.name = "locations" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - None - ) - await client.cancel_operation(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=locations",) in kw["metadata"] - -def test_cancel_operation_from_dict(): - 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.cancel_operation), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = None - - response = client.cancel_operation( - request={ - "name": "locations", - } - ) - call.assert_called() -@pytest.mark.asyncio -async def test_cancel_operation_from_dict_async(): - 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.cancel_operation), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - None - ) - response = await client.cancel_operation( - request={ - "name": "locations", - } - ) - call.assert_called() - - -def test_get_operation(transport: str = "grpc"): - client = EntityTypesClient( - 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 = operations_pb2.GetOperationRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_operation), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation() - response = client.get_operation(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 response is the type that we expect. - assert isinstance(response, operations_pb2.Operation) -@pytest.mark.asyncio -async def test_get_operation_async(transport: str = "grpc"): - client = EntityTypesAsyncClient( - 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 = operations_pb2.GetOperationRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_operation), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation() - ) - response = await client.get_operation(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 response is the type that we expect. - assert isinstance(response, operations_pb2.Operation) - -def test_get_operation_field_headers(): - 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 = operations_pb2.GetOperationRequest() - request.name = "locations" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_operation), "__call__") as call: - call.return_value = operations_pb2.Operation() - - client.get_operation(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=locations",) in kw["metadata"] -@pytest.mark.asyncio -async def test_get_operation_field_headers_async(): - 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 = operations_pb2.GetOperationRequest() - request.name = "locations" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_operation), "__call__") as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation() - ) - await client.get_operation(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=locations",) in kw["metadata"] - -def test_get_operation_from_dict(): - 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_operation), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation() - - response = client.get_operation( - request={ - "name": "locations", - } - ) - call.assert_called() -@pytest.mark.asyncio -async def test_get_operation_from_dict_async(): - 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_operation), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation() - ) - response = await client.get_operation( - request={ - "name": "locations", - } - ) - call.assert_called() - - -def test_list_operations(transport: str = "grpc"): - client = EntityTypesClient( - 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 = operations_pb2.ListOperationsRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_operations), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.ListOperationsResponse() - response = client.list_operations(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 response is the type that we expect. - assert isinstance(response, operations_pb2.ListOperationsResponse) -@pytest.mark.asyncio -async def test_list_operations_async(transport: str = "grpc"): - client = EntityTypesAsyncClient( - 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 = operations_pb2.ListOperationsRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_operations), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.ListOperationsResponse() - ) - response = await client.list_operations(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 response is the type that we expect. - assert isinstance(response, operations_pb2.ListOperationsResponse) - -def test_list_operations_field_headers(): - 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 = operations_pb2.ListOperationsRequest() - request.name = "locations" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_operations), "__call__") as call: - call.return_value = operations_pb2.ListOperationsResponse() - - client.list_operations(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=locations",) in kw["metadata"] -@pytest.mark.asyncio -async def test_list_operations_field_headers_async(): - 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 = operations_pb2.ListOperationsRequest() - request.name = "locations" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_operations), "__call__") as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.ListOperationsResponse() - ) - await client.list_operations(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=locations",) in kw["metadata"] - -def test_list_operations_from_dict(): - 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.list_operations), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.ListOperationsResponse() - - response = client.list_operations( - request={ - "name": "locations", - } - ) - call.assert_called() -@pytest.mark.asyncio -async def test_list_operations_from_dict_async(): - 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.list_operations), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.ListOperationsResponse() - ) - response = await client.list_operations( - request={ - "name": "locations", - } - ) - call.assert_called() - - -def test_list_locations(transport: str = "grpc"): - client = EntityTypesClient( - 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 = locations_pb2.ListLocationsRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_locations), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = locations_pb2.ListLocationsResponse() - response = client.list_locations(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 response is the type that we expect. - assert isinstance(response, locations_pb2.ListLocationsResponse) -@pytest.mark.asyncio -async def test_list_locations_async(transport: str = "grpc"): - client = EntityTypesAsyncClient( - 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 = locations_pb2.ListLocationsRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_locations), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - locations_pb2.ListLocationsResponse() - ) - response = await client.list_locations(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 response is the type that we expect. - assert isinstance(response, locations_pb2.ListLocationsResponse) - -def test_list_locations_field_headers(): - 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 = locations_pb2.ListLocationsRequest() - request.name = "locations" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_locations), "__call__") as call: - call.return_value = locations_pb2.ListLocationsResponse() - - client.list_locations(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=locations",) in kw["metadata"] -@pytest.mark.asyncio -async def test_list_locations_field_headers_async(): - 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 = locations_pb2.ListLocationsRequest() - request.name = "locations" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_locations), "__call__") as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - locations_pb2.ListLocationsResponse() - ) - await client.list_locations(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=locations",) in kw["metadata"] - -def test_list_locations_from_dict(): - 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.list_locations), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = locations_pb2.ListLocationsResponse() - - response = client.list_locations( - request={ - "name": "locations", - } - ) - call.assert_called() -@pytest.mark.asyncio -async def test_list_locations_from_dict_async(): - 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.list_locations), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - locations_pb2.ListLocationsResponse() - ) - response = await client.list_locations( - request={ - "name": "locations", - } - ) - call.assert_called() - - -def test_get_location(transport: str = "grpc"): - client = EntityTypesClient( - 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 = locations_pb2.GetLocationRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_location), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = locations_pb2.Location() - response = client.get_location(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 response is the type that we expect. - assert isinstance(response, locations_pb2.Location) -@pytest.mark.asyncio -async def test_get_location_async(transport: str = "grpc_asyncio"): - client = EntityTypesAsyncClient( - 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 = locations_pb2.GetLocationRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_location), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - locations_pb2.Location() - ) - response = await client.get_location(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 response is the type that we expect. - assert isinstance(response, locations_pb2.Location) - -def test_get_location_field_headers(): - 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 = locations_pb2.GetLocationRequest() - request.name = "locations/abc" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_location), "__call__") as call: - call.return_value = locations_pb2.Location() - - client.get_location(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=locations/abc",) in kw["metadata"] -@pytest.mark.asyncio -async def test_get_location_field_headers_async(): - 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 = locations_pb2.GetLocationRequest() - request.name = "locations/abc" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_location), "__call__") as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - locations_pb2.Location() - ) - await client.get_location(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=locations/abc",) in kw["metadata"] - -def test_get_location_from_dict(): - 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.list_locations), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = locations_pb2.Location() - - response = client.get_location( - request={ - "name": "locations/abc", - } - ) - call.assert_called() -@pytest.mark.asyncio -async def test_get_location_from_dict_async(): - 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.list_locations), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - locations_pb2.Location() - ) - response = await client.get_location( - request={ - "name": "locations", - } - ) - call.assert_called() - - -def test_transport_close(): - transports = { - "rest": "_session", - "grpc": "_grpc_channel", - } - - for transport, close_name in transports.items(): - client = EntityTypesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport - ) - with mock.patch.object(type(getattr(client.transport, close_name)), "close") as close: - with client: - close.assert_not_called() - close.assert_called_once() - -def test_client_ctx(): - transports = [ - 'rest', - 'grpc', - ] - for transport in transports: - client = EntityTypesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport - ) - # Test client calls underlying transport. - with mock.patch.object(type(client.transport), "close") as close: - close.assert_not_called() - with client: - pass - close.assert_called() - -@pytest.mark.parametrize("client_class,transport_class", [ - (EntityTypesClient, transports.EntityTypesGrpcTransport), - (EntityTypesAsyncClient, transports.EntityTypesGrpcAsyncIOTransport), -]) -def test_api_key_credentials(client_class, transport_class): - with mock.patch.object( - google.auth._default, "get_api_key_credentials", create=True - ) as get_api_key_credentials: - mock_cred = mock.Mock() - get_api_key_credentials.return_value = mock_cred - options = client_options.ClientOptions() - options.api_key = "api_key" - 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=mock_cred, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) diff --git a/owl-bot-staging/v2beta1/tests/unit/gapic/dialogflow_v2beta1/test_environments.py b/owl-bot-staging/v2beta1/tests/unit/gapic/dialogflow_v2beta1/test_environments.py deleted file mode 100644 index d4b53c2fb..000000000 --- a/owl-bot-staging/v2beta1/tests/unit/gapic/dialogflow_v2beta1/test_environments.py +++ /dev/null @@ -1,4837 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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 -# try/except added for compatibility with python < 3.8 -try: - from unittest import mock - from unittest.mock import AsyncMock # pragma: NO COVER -except ImportError: # pragma: NO COVER - import mock - -import grpc -from grpc.experimental import aio -from collections.abc import Iterable -from google.protobuf import json_format -import json -import math -import pytest -from proto.marshal.rules.dates import DurationRule, TimestampRule -from proto.marshal.rules import wrappers -from requests import Response -from requests import Request, PreparedRequest -from requests.sessions import Session -from google.protobuf import json_format - -from google.api_core import client_options -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import grpc_helpers -from google.api_core import grpc_helpers_async -from google.api_core import path_template -from google.auth import credentials as ga_credentials -from google.auth.exceptions import MutualTLSChannelError -from google.cloud.dialogflow_v2beta1.services.environments import EnvironmentsAsyncClient -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.types import audio_config -from google.cloud.dialogflow_v2beta1.types import environment -from google.cloud.dialogflow_v2beta1.types import fulfillment -from google.cloud.location import locations_pb2 -from google.longrunning import operations_pb2 -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 - - -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 EnvironmentsClient._get_default_mtls_endpoint(None) is None - assert EnvironmentsClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint - assert EnvironmentsClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint - assert EnvironmentsClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint - assert EnvironmentsClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint - assert EnvironmentsClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi - - -@pytest.mark.parametrize("client_class,transport_name", [ - (EnvironmentsClient, "grpc"), - (EnvironmentsAsyncClient, "grpc_asyncio"), - (EnvironmentsClient, "rest"), -]) -def test_environments_client_from_service_account_info(client_class, transport_name): - 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, transport=transport_name) - assert client.transport._credentials == creds - assert isinstance(client, client_class) - - assert client.transport._host == ( - 'dialogflow.googleapis.com:443' - if transport_name in ['grpc', 'grpc_asyncio'] - else - 'https://dialogflow.googleapis.com' - ) - - -@pytest.mark.parametrize("transport_class,transport_name", [ - (transports.EnvironmentsGrpcTransport, "grpc"), - (transports.EnvironmentsGrpcAsyncIOTransport, "grpc_asyncio"), - (transports.EnvironmentsRestTransport, "rest"), -]) -def test_environments_client_service_account_always_use_jwt(transport_class, transport_name): - with mock.patch.object(service_account.Credentials, 'with_always_use_jwt_access', create=True) as use_jwt: - creds = service_account.Credentials(None, None, None) - transport = transport_class(credentials=creds, always_use_jwt_access=True) - use_jwt.assert_called_once_with(True) - - with mock.patch.object(service_account.Credentials, 'with_always_use_jwt_access', create=True) as use_jwt: - creds = service_account.Credentials(None, None, None) - transport = transport_class(credentials=creds, always_use_jwt_access=False) - use_jwt.assert_not_called() - - -@pytest.mark.parametrize("client_class,transport_name", [ - (EnvironmentsClient, "grpc"), - (EnvironmentsAsyncClient, "grpc_asyncio"), - (EnvironmentsClient, "rest"), -]) -def test_environments_client_from_service_account_file(client_class, transport_name): - 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", transport=transport_name) - assert client.transport._credentials == creds - assert isinstance(client, client_class) - - client = client_class.from_service_account_json("dummy/file/path.json", transport=transport_name) - assert client.transport._credentials == creds - assert isinstance(client, client_class) - - assert client.transport._host == ( - 'dialogflow.googleapis.com:443' - if transport_name in ['grpc', 'grpc_asyncio'] - else - 'https://dialogflow.googleapis.com' - ) - - -def test_environments_client_get_transport_class(): - transport = EnvironmentsClient.get_transport_class() - available_transports = [ - transports.EnvironmentsGrpcTransport, - transports.EnvironmentsRestTransport, - ] - assert transport in available_transports - - transport = EnvironmentsClient.get_transport_class("grpc") - assert transport == transports.EnvironmentsGrpcTransport - - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (EnvironmentsClient, transports.EnvironmentsGrpcTransport, "grpc"), - (EnvironmentsAsyncClient, transports.EnvironmentsGrpcAsyncIOTransport, "grpc_asyncio"), - (EnvironmentsClient, transports.EnvironmentsRestTransport, "rest"), -]) -@mock.patch.object(EnvironmentsClient, "DEFAULT_ENDPOINT", modify_default_endpoint(EnvironmentsClient)) -@mock.patch.object(EnvironmentsAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(EnvironmentsAsyncClient)) -def test_environments_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(EnvironmentsClient, '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(EnvironmentsClient, 'get_transport_class') as gtc: - client = client_class(transport=transport_name) - gtc.assert_called() - - # Check the case api_endpoint is provided. - options = client_options.ClientOptions(api_endpoint="squid.clam.whelk") - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(transport=transport_name, client_options=options) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host="squid.clam.whelk", - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is - # "never". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is - # "always". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_MTLS_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # 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(transport=transport_name) - - # 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(transport=transport_name) - - # 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, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id="octopus", - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - # Check the case api_endpoint is provided - options = client_options.ClientOptions(api_audience="https://language.googleapis.com") - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience="https://language.googleapis.com" - ) - -@pytest.mark.parametrize("client_class,transport_class,transport_name,use_client_cert_env", [ - (EnvironmentsClient, transports.EnvironmentsGrpcTransport, "grpc", "true"), - (EnvironmentsAsyncClient, transports.EnvironmentsGrpcAsyncIOTransport, "grpc_asyncio", "true"), - (EnvironmentsClient, transports.EnvironmentsGrpcTransport, "grpc", "false"), - (EnvironmentsAsyncClient, transports.EnvironmentsGrpcAsyncIOTransport, "grpc_asyncio", "false"), - (EnvironmentsClient, transports.EnvironmentsRestTransport, "rest", "true"), - (EnvironmentsClient, transports.EnvironmentsRestTransport, "rest", "false"), -]) -@mock.patch.object(EnvironmentsClient, "DEFAULT_ENDPOINT", modify_default_endpoint(EnvironmentsClient)) -@mock.patch.object(EnvironmentsAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(EnvironmentsAsyncClient)) -@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) -def test_environments_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, transport=transport_name) - - if use_client_cert_env == "false": - expected_client_cert_source = None - expected_host = client.DEFAULT_ENDPOINT - else: - expected_client_cert_source = client_cert_source_callback - expected_host = client.DEFAULT_MTLS_ENDPOINT - - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=expected_host, - scopes=None, - client_cert_source_for_mtls=expected_client_cert_source, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case ADC client cert is provided. Whether client cert is used depends on - # GOOGLE_API_USE_CLIENT_CERTIFICATE value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): - with mock.patch.object(transport_class, '__init__') as patched: - with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): - with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=client_cert_source_callback): - if use_client_cert_env == "false": - expected_host = client.DEFAULT_ENDPOINT - expected_client_cert_source = None - else: - expected_host = client.DEFAULT_MTLS_ENDPOINT - expected_client_cert_source = client_cert_source_callback - - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=expected_host, - scopes=None, - client_cert_source_for_mtls=expected_client_cert_source, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case client_cert_source and ADC client cert are not provided. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): - with mock.patch.object(transport_class, '__init__') as patched: - with mock.patch("google.auth.transport.mtls.has_default_client_cert_source", return_value=False): - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - -@pytest.mark.parametrize("client_class", [ - EnvironmentsClient, EnvironmentsAsyncClient -]) -@mock.patch.object(EnvironmentsClient, "DEFAULT_ENDPOINT", modify_default_endpoint(EnvironmentsClient)) -@mock.patch.object(EnvironmentsAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(EnvironmentsAsyncClient)) -def test_environments_client_get_mtls_endpoint_and_cert_source(client_class): - mock_client_cert_source = mock.Mock() - - # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "true". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - mock_api_endpoint = "foo" - options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) - assert api_endpoint == mock_api_endpoint - assert cert_source == mock_client_cert_source - - # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "false". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): - mock_client_cert_source = mock.Mock() - mock_api_endpoint = "foo" - options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) - assert api_endpoint == mock_api_endpoint - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "never". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_ENDPOINT - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "always". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert doesn't exist. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=False): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_ENDPOINT - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert exists. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - 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=mock_client_cert_source): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT - assert cert_source == mock_client_cert_source - - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (EnvironmentsClient, transports.EnvironmentsGrpcTransport, "grpc"), - (EnvironmentsAsyncClient, transports.EnvironmentsGrpcAsyncIOTransport, "grpc_asyncio"), - (EnvironmentsClient, transports.EnvironmentsRestTransport, "rest"), -]) -def test_environments_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, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=["1", "2"], - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - -@pytest.mark.parametrize("client_class,transport_class,transport_name,grpc_helpers", [ - (EnvironmentsClient, transports.EnvironmentsGrpcTransport, "grpc", grpc_helpers), - (EnvironmentsAsyncClient, transports.EnvironmentsGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), - (EnvironmentsClient, transports.EnvironmentsRestTransport, "rest", None), -]) -def test_environments_client_client_options_credentials_file(client_class, transport_class, transport_name, grpc_helpers): - # 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, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file="credentials.json", - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - -def test_environments_client_client_options_from_dict(): - with mock.patch('google.cloud.dialogflow_v2beta1.services.environments.transports.EnvironmentsGrpcTransport.__init__') as grpc_transport: - grpc_transport.return_value = None - client = EnvironmentsClient( - client_options={'api_endpoint': 'squid.clam.whelk'} - ) - grpc_transport.assert_called_once_with( - credentials=None, - credentials_file=None, - host="squid.clam.whelk", - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - -@pytest.mark.parametrize("client_class,transport_class,transport_name,grpc_helpers", [ - (EnvironmentsClient, transports.EnvironmentsGrpcTransport, "grpc", grpc_helpers), - (EnvironmentsAsyncClient, transports.EnvironmentsGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), -]) -def test_environments_client_create_channel_credentials_file(client_class, transport_class, transport_name, grpc_helpers): - # 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, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file="credentials.json", - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # test that the credentials from file are saved and used as the credentials. - with mock.patch.object( - google.auth, "load_credentials_from_file", autospec=True - ) as load_creds, mock.patch.object( - google.auth, "default", autospec=True - ) as adc, mock.patch.object( - grpc_helpers, "create_channel" - ) as create_channel: - creds = ga_credentials.AnonymousCredentials() - file_creds = ga_credentials.AnonymousCredentials() - load_creds.return_value = (file_creds, None) - adc.return_value = (creds, None) - client = client_class(client_options=options, transport=transport_name) - create_channel.assert_called_with( - "dialogflow.googleapis.com:443", - credentials=file_creds, - credentials_file=None, - quota_project_id=None, - default_scopes=( - 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/dialogflow', -), - scopes=None, - default_host="dialogflow.googleapis.com", - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - -@pytest.mark.parametrize("request_type", [ - environment.ListEnvironmentsRequest, - dict, -]) -def test_list_environments(request_type, transport: str = 'grpc'): - 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.list_environments), - '__call__') as call: - # Designate an appropriate return value for the call. - 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' - - -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=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_environments), - '__call__') as call: - client.list_environments() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == environment.ListEnvironmentsRequest() - -@pytest.mark.asyncio -async def test_list_environments_async(transport: str = 'grpc_asyncio', request_type=environment.ListEnvironmentsRequest): - 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.list_environments), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(environment.ListEnvironmentsResponse( - 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' - - -@pytest.mark.asyncio -async def test_list_environments_async_from_dict(): - await test_list_environments_async(request_type=dict) - - -def test_list_environments_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.ListEnvironmentsRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - 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. - 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_environments_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.ListEnvironmentsRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_environments), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(environment.ListEnvironmentsResponse()) - 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] == 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_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] - arg = args[0].parent - mock_val = 'parent_value' - assert arg == mock_val - - -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] - arg = args[0].parent - mock_val = 'parent_value' - assert arg == mock_val - -@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(transport_name: str = "grpc"): - client = EnvironmentsClient( - credentials=ga_credentials.AnonymousCredentials, - transport=transport_name, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_environments), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - environment.ListEnvironmentsResponse( - environments=[ - environment.Environment(), - environment.Environment(), - environment.Environment(), - ], - next_page_token='abc', - ), - environment.ListEnvironmentsResponse( - environments=[], - next_page_token='def', - ), - environment.ListEnvironmentsResponse( - environments=[ - environment.Environment(), - ], - next_page_token='ghi', - ), - environment.ListEnvironmentsResponse( - environments=[ - environment.Environment(), - environment.Environment(), - ], - ), - RuntimeError, - ) - - metadata = () - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ('parent', ''), - )), - ) - pager = client.list_environments(request={}) - - assert pager._metadata == metadata - - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, environment.Environment) - for i in results) -def test_list_environments_pages(transport_name: str = "grpc"): - client = EnvironmentsClient( - credentials=ga_credentials.AnonymousCredentials, - transport=transport_name, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_environments), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - environment.ListEnvironmentsResponse( - environments=[ - environment.Environment(), - environment.Environment(), - environment.Environment(), - ], - next_page_token='abc', - ), - environment.ListEnvironmentsResponse( - environments=[], - next_page_token='def', - ), - environment.ListEnvironmentsResponse( - environments=[ - environment.Environment(), - ], - next_page_token='ghi', - ), - environment.ListEnvironmentsResponse( - environments=[ - environment.Environment(), - environment.Environment(), - ], - ), - RuntimeError, - ) - pages = list(client.list_environments(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_environments_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.list_environments), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - environment.ListEnvironmentsResponse( - environments=[ - environment.Environment(), - environment.Environment(), - environment.Environment(), - ], - next_page_token='abc', - ), - environment.ListEnvironmentsResponse( - environments=[], - next_page_token='def', - ), - environment.ListEnvironmentsResponse( - environments=[ - environment.Environment(), - ], - next_page_token='ghi', - ), - environment.ListEnvironmentsResponse( - environments=[ - environment.Environment(), - environment.Environment(), - ], - ), - RuntimeError, - ) - async_pager = await client.list_environments(request={},) - assert async_pager.next_page_token == 'abc' - responses = [] - async for response in async_pager: # pragma: no branch - responses.append(response) - - assert len(responses) == 6 - assert all(isinstance(i, environment.Environment) - for i in responses) - - -@pytest.mark.asyncio -async def test_list_environments_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.list_environments), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - environment.ListEnvironmentsResponse( - environments=[ - environment.Environment(), - environment.Environment(), - environment.Environment(), - ], - next_page_token='abc', - ), - environment.ListEnvironmentsResponse( - environments=[], - next_page_token='def', - ), - environment.ListEnvironmentsResponse( - environments=[ - environment.Environment(), - ], - next_page_token='ghi', - ), - environment.ListEnvironmentsResponse( - environments=[ - environment.Environment(), - environment.Environment(), - ], - ), - RuntimeError, - ) - pages = [] - async for page_ in (await client.list_environments(request={})).pages: # pragma: no branch - pages.append(page_) - for page_, token in zip(pages, ['abc','def','ghi', '']): - assert page_.raw_page.next_page_token == token - -@pytest.mark.parametrize("request_type", [ - environment.GetEnvironmentRequest, - dict, -]) -def test_get_environment(request_type, transport: str = 'grpc'): - 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), - '__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() - - # 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_empty_call(): - # 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), - '__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, - ) - - # 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() - - # 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_get_environment_async_from_dict(): - await test_get_environment_async(request_type=dict) - - -def test_get_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.GetEnvironmentRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_environment), - '__call__') as call: - call.return_value = environment.Environment() - client.get_environment(request) - - # Establish that the underlying gRPC stub method was called. - 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_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.GetEnvironmentRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_environment), - '__call__') as call: - call.return_value = 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 - - # 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("request_type", [ - environment.CreateEnvironmentRequest, - dict, -]) -def test_create_environment(request_type, transport: str = 'grpc'): - 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.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_empty_call(): - # 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'] - - -@pytest.mark.parametrize("request_type", [ - environment.UpdateEnvironmentRequest, - dict, -]) -def test_update_environment(request_type, transport: str = 'grpc'): - 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_empty_call(): - # 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 = '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=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 = '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=name_value', - ) in kw['metadata'] - - -@pytest.mark.parametrize("request_type", [ - environment.DeleteEnvironmentRequest, - dict, -]) -def test_delete_environment(request_type, transport: str = 'grpc'): - 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_empty_call(): - # 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'] - - -@pytest.mark.parametrize("request_type", [ - environment.GetEnvironmentHistoryRequest, - dict, -]) -def test_get_environment_history(request_type, transport: str = 'grpc'): - 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_empty_call(): - # 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(transport_name: str = "grpc"): - client = EnvironmentsClient( - credentials=ga_credentials.AnonymousCredentials, - transport=transport_name, - ) - - # 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 = list(pager) - assert len(results) == 6 - assert all(isinstance(i, environment.EnvironmentHistory.Entry) - for i in results) -def test_get_environment_history_pages(transport_name: str = "grpc"): - client = EnvironmentsClient( - credentials=ga_credentials.AnonymousCredentials, - transport=transport_name, - ) - - # 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: # pragma: no branch - 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: # pragma: no branch - pages.append(page_) - for page_, token in zip(pages, ['abc','def','ghi', '']): - assert page_.raw_page.next_page_token == token - - -@pytest.mark.parametrize("request_type", [ - environment.ListEnvironmentsRequest, - dict, -]) -def test_list_environments_rest(request_type): - client = EnvironmentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1/agent'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = environment.ListEnvironmentsResponse( - next_page_token='next_page_token_value', - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - pb_return_value = environment.ListEnvironmentsResponse.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.list_environments(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListEnvironmentsPager) - assert response.next_page_token == 'next_page_token_value' - - -def test_list_environments_rest_required_fields(request_type=environment.ListEnvironmentsRequest): - transport_class = transports.EnvironmentsRestTransport - - request_init = {} - request_init["parent"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - including_default_value_fields=False, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).list_environments._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["parent"] = 'parent_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).list_environments._get_unset_required_fields(jsonified_request) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("page_size", "page_token", )) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "parent" in jsonified_request - assert jsonified_request["parent"] == 'parent_value' - - client = EnvironmentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = environment.ListEnvironmentsResponse() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "get", - 'query_params': pb_request, - } - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - - pb_return_value = environment.ListEnvironmentsResponse.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.list_environments(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_list_environments_rest_unset_required_fields(): - transport = transports.EnvironmentsRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.list_environments._get_unset_required_fields({}) - assert set(unset_fields) == (set(("pageSize", "pageToken", )) & set(("parent", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_list_environments_rest_interceptors(null_interceptor): - transport = transports.EnvironmentsRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.EnvironmentsRestInterceptor(), - ) - client = EnvironmentsClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.EnvironmentsRestInterceptor, "post_list_environments") as post, \ - mock.patch.object(transports.EnvironmentsRestInterceptor, "pre_list_environments") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = environment.ListEnvironmentsRequest.pb(environment.ListEnvironmentsRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = environment.ListEnvironmentsResponse.to_json(environment.ListEnvironmentsResponse()) - - request = environment.ListEnvironmentsRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = environment.ListEnvironmentsResponse() - - client.list_environments(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_list_environments_rest_bad_request(transport: str = 'rest', request_type=environment.ListEnvironmentsRequest): - client = EnvironmentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1/agent'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.list_environments(request) - - -def test_list_environments_rest_flattened(): - client = EnvironmentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = environment.ListEnvironmentsResponse() - - # get arguments that satisfy an http rule for this method - sample_request = {'parent': 'projects/sample1/agent'} - - # get truthy value for each flattened field - mock_args = dict( - parent='parent_value', - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - pb_return_value = environment.ListEnvironmentsResponse.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.list_environments(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v2beta1/{parent=projects/*/agent}/environments" % client.transport._host, args[1]) - - -def test_list_environments_rest_flattened_error(transport: str = 'rest'): - client = EnvironmentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # 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', - ) - - -def test_list_environments_rest_pager(transport: str = 'rest'): - client = EnvironmentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # TODO(kbandes): remove this mock unless there's a good reason for it. - #with mock.patch.object(path_template, 'transcode') as transcode: - # Set the response as a series of pages - response = ( - environment.ListEnvironmentsResponse( - environments=[ - environment.Environment(), - environment.Environment(), - environment.Environment(), - ], - next_page_token='abc', - ), - environment.ListEnvironmentsResponse( - environments=[], - next_page_token='def', - ), - environment.ListEnvironmentsResponse( - environments=[ - environment.Environment(), - ], - next_page_token='ghi', - ), - environment.ListEnvironmentsResponse( - environments=[ - environment.Environment(), - environment.Environment(), - ], - ), - ) - # Two responses for two calls - response = response + response - - # Wrap the values into proper Response objs - response = tuple(environment.ListEnvironmentsResponse.to_json(x) for x in response) - return_values = tuple(Response() for i in response) - for return_val, response_val in zip(return_values, response): - return_val._content = response_val.encode('UTF-8') - return_val.status_code = 200 - req.side_effect = return_values - - sample_request = {'parent': 'projects/sample1/agent'} - - pager = client.list_environments(request=sample_request) - - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, environment.Environment) - for i in results) - - pages = list(client.list_environments(request=sample_request).pages) - for page_, token in zip(pages, ['abc','def','ghi', '']): - assert page_.raw_page.next_page_token == token - - -@pytest.mark.parametrize("request_type", [ - environment.GetEnvironmentRequest, - dict, -]) -def test_get_environment_rest(request_type): - client = EnvironmentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/agent/environments/sample2'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = environment.Environment( - name='name_value', - description='description_value', - agent_version='agent_version_value', - state=environment.Environment.State.STOPPED, - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - pb_return_value = environment.Environment.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.get_environment(request) - - # 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_rest_required_fields(request_type=environment.GetEnvironmentRequest): - transport_class = transports.EnvironmentsRestTransport - - request_init = {} - request_init["name"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - including_default_value_fields=False, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_environment._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["name"] = 'name_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_environment._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "name" in jsonified_request - assert jsonified_request["name"] == 'name_value' - - client = EnvironmentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = environment.Environment() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "get", - 'query_params': pb_request, - } - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - - pb_return_value = environment.Environment.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.get_environment(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_get_environment_rest_unset_required_fields(): - transport = transports.EnvironmentsRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.get_environment._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_get_environment_rest_interceptors(null_interceptor): - transport = transports.EnvironmentsRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.EnvironmentsRestInterceptor(), - ) - client = EnvironmentsClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.EnvironmentsRestInterceptor, "post_get_environment") as post, \ - mock.patch.object(transports.EnvironmentsRestInterceptor, "pre_get_environment") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = environment.GetEnvironmentRequest.pb(environment.GetEnvironmentRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = environment.Environment.to_json(environment.Environment()) - - request = environment.GetEnvironmentRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = environment.Environment() - - client.get_environment(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_get_environment_rest_bad_request(transport: str = 'rest', request_type=environment.GetEnvironmentRequest): - client = EnvironmentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/agent/environments/sample2'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.get_environment(request) - - -def test_get_environment_rest_error(): - client = EnvironmentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - environment.CreateEnvironmentRequest, - dict, -]) -def test_create_environment_rest(request_type): - client = EnvironmentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1/agent'} - request_init["environment"] = {'name': 'name_value', 'description': 'description_value', 'agent_version': 'agent_version_value', 'state': 1, 'update_time': {'seconds': 751, 'nanos': 543}, 'text_to_speech_settings': {'enable_text_to_speech': True, 'output_audio_encoding': 1, 'sample_rate_hertz': 1817, 'synthesize_speech_configs': {}}, 'fulfillment': {'name': 'name_value', 'display_name': 'display_name_value', 'generic_web_service': {'uri': 'uri_value', 'username': 'username_value', 'password': 'password_value', 'request_headers': {}, 'is_cloud_function': True}, 'enabled': True, 'features': [{'type_': 1}]}} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = environment.Environment( - name='name_value', - description='description_value', - agent_version='agent_version_value', - state=environment.Environment.State.STOPPED, - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - pb_return_value = environment.Environment.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.create_environment(request) - - # 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_rest_required_fields(request_type=environment.CreateEnvironmentRequest): - transport_class = transports.EnvironmentsRestTransport - - request_init = {} - request_init["parent"] = "" - request_init["environment_id"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - including_default_value_fields=False, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - assert "environmentId" not in jsonified_request - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_environment._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - assert "environmentId" in jsonified_request - assert jsonified_request["environmentId"] == request_init["environment_id"] - - jsonified_request["parent"] = 'parent_value' - jsonified_request["environmentId"] = 'environment_id_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_environment._get_unset_required_fields(jsonified_request) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("environment_id", )) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "parent" in jsonified_request - assert jsonified_request["parent"] == 'parent_value' - assert "environmentId" in jsonified_request - assert jsonified_request["environmentId"] == 'environment_id_value' - - client = EnvironmentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = environment.Environment() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "post", - 'query_params': pb_request, - } - transcode_result['body'] = pb_request - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - - pb_return_value = environment.Environment.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.create_environment(request) - - expected_params = [ - ( - "environmentId", - "", - ), - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_create_environment_rest_unset_required_fields(): - transport = transports.EnvironmentsRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.create_environment._get_unset_required_fields({}) - assert set(unset_fields) == (set(("environmentId", )) & set(("parent", "environment", "environmentId", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_create_environment_rest_interceptors(null_interceptor): - transport = transports.EnvironmentsRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.EnvironmentsRestInterceptor(), - ) - client = EnvironmentsClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.EnvironmentsRestInterceptor, "post_create_environment") as post, \ - mock.patch.object(transports.EnvironmentsRestInterceptor, "pre_create_environment") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = environment.CreateEnvironmentRequest.pb(environment.CreateEnvironmentRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = environment.Environment.to_json(environment.Environment()) - - request = environment.CreateEnvironmentRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = environment.Environment() - - client.create_environment(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_create_environment_rest_bad_request(transport: str = 'rest', request_type=environment.CreateEnvironmentRequest): - client = EnvironmentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1/agent'} - request_init["environment"] = {'name': 'name_value', 'description': 'description_value', 'agent_version': 'agent_version_value', 'state': 1, 'update_time': {'seconds': 751, 'nanos': 543}, 'text_to_speech_settings': {'enable_text_to_speech': True, 'output_audio_encoding': 1, 'sample_rate_hertz': 1817, 'synthesize_speech_configs': {}}, 'fulfillment': {'name': 'name_value', 'display_name': 'display_name_value', 'generic_web_service': {'uri': 'uri_value', 'username': 'username_value', 'password': 'password_value', 'request_headers': {}, 'is_cloud_function': True}, 'enabled': True, 'features': [{'type_': 1}]}} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.create_environment(request) - - -def test_create_environment_rest_error(): - client = EnvironmentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - environment.UpdateEnvironmentRequest, - dict, -]) -def test_update_environment_rest(request_type): - client = EnvironmentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'environment': {'name': 'projects/sample1/agent/environments/sample2'}} - request_init["environment"] = {'name': 'projects/sample1/agent/environments/sample2', 'description': 'description_value', 'agent_version': 'agent_version_value', 'state': 1, 'update_time': {'seconds': 751, 'nanos': 543}, 'text_to_speech_settings': {'enable_text_to_speech': True, 'output_audio_encoding': 1, 'sample_rate_hertz': 1817, 'synthesize_speech_configs': {}}, 'fulfillment': {'name': 'name_value', 'display_name': 'display_name_value', 'generic_web_service': {'uri': 'uri_value', 'username': 'username_value', 'password': 'password_value', 'request_headers': {}, 'is_cloud_function': True}, 'enabled': True, 'features': [{'type_': 1}]}} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = environment.Environment( - name='name_value', - description='description_value', - agent_version='agent_version_value', - state=environment.Environment.State.STOPPED, - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - pb_return_value = environment.Environment.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.update_environment(request) - - # 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_rest_required_fields(request_type=environment.UpdateEnvironmentRequest): - transport_class = transports.EnvironmentsRestTransport - - request_init = {} - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - including_default_value_fields=False, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).update_environment._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).update_environment._get_unset_required_fields(jsonified_request) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("allow_load_to_draft_and_discard_changes", "update_mask", )) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - - client = EnvironmentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = environment.Environment() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "patch", - 'query_params': pb_request, - } - transcode_result['body'] = pb_request - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - - pb_return_value = environment.Environment.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.update_environment(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_update_environment_rest_unset_required_fields(): - transport = transports.EnvironmentsRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.update_environment._get_unset_required_fields({}) - assert set(unset_fields) == (set(("allowLoadToDraftAndDiscardChanges", "updateMask", )) & set(("environment", "updateMask", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_update_environment_rest_interceptors(null_interceptor): - transport = transports.EnvironmentsRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.EnvironmentsRestInterceptor(), - ) - client = EnvironmentsClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.EnvironmentsRestInterceptor, "post_update_environment") as post, \ - mock.patch.object(transports.EnvironmentsRestInterceptor, "pre_update_environment") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = environment.UpdateEnvironmentRequest.pb(environment.UpdateEnvironmentRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = environment.Environment.to_json(environment.Environment()) - - request = environment.UpdateEnvironmentRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = environment.Environment() - - client.update_environment(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_update_environment_rest_bad_request(transport: str = 'rest', request_type=environment.UpdateEnvironmentRequest): - client = EnvironmentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'environment': {'name': 'projects/sample1/agent/environments/sample2'}} - request_init["environment"] = {'name': 'projects/sample1/agent/environments/sample2', 'description': 'description_value', 'agent_version': 'agent_version_value', 'state': 1, 'update_time': {'seconds': 751, 'nanos': 543}, 'text_to_speech_settings': {'enable_text_to_speech': True, 'output_audio_encoding': 1, 'sample_rate_hertz': 1817, 'synthesize_speech_configs': {}}, 'fulfillment': {'name': 'name_value', 'display_name': 'display_name_value', 'generic_web_service': {'uri': 'uri_value', 'username': 'username_value', 'password': 'password_value', 'request_headers': {}, 'is_cloud_function': True}, 'enabled': True, 'features': [{'type_': 1}]}} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.update_environment(request) - - -def test_update_environment_rest_error(): - client = EnvironmentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - environment.DeleteEnvironmentRequest, - dict, -]) -def test_delete_environment_rest(request_type): - client = EnvironmentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/agent/environments/sample2'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = None - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = '' - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.delete_environment(request) - - # Establish that the response is the type that we expect. - assert response is None - - -def test_delete_environment_rest_required_fields(request_type=environment.DeleteEnvironmentRequest): - transport_class = transports.EnvironmentsRestTransport - - request_init = {} - request_init["name"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - including_default_value_fields=False, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).delete_environment._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["name"] = 'name_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).delete_environment._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "name" in jsonified_request - assert jsonified_request["name"] == 'name_value' - - client = EnvironmentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = None - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "delete", - 'query_params': pb_request, - } - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - json_return_value = '' - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.delete_environment(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_delete_environment_rest_unset_required_fields(): - transport = transports.EnvironmentsRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.delete_environment._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_delete_environment_rest_interceptors(null_interceptor): - transport = transports.EnvironmentsRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.EnvironmentsRestInterceptor(), - ) - client = EnvironmentsClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.EnvironmentsRestInterceptor, "pre_delete_environment") as pre: - pre.assert_not_called() - pb_message = environment.DeleteEnvironmentRequest.pb(environment.DeleteEnvironmentRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - - request = environment.DeleteEnvironmentRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - - client.delete_environment(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - - -def test_delete_environment_rest_bad_request(transport: str = 'rest', request_type=environment.DeleteEnvironmentRequest): - client = EnvironmentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/agent/environments/sample2'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.delete_environment(request) - - -def test_delete_environment_rest_error(): - client = EnvironmentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - environment.GetEnvironmentHistoryRequest, - dict, -]) -def test_get_environment_history_rest(request_type): - client = EnvironmentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1/agent/environments/sample2'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = environment.EnvironmentHistory( - parent='parent_value', - next_page_token='next_page_token_value', - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - pb_return_value = environment.EnvironmentHistory.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.get_environment_history(request) - - # 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_rest_required_fields(request_type=environment.GetEnvironmentHistoryRequest): - transport_class = transports.EnvironmentsRestTransport - - request_init = {} - request_init["parent"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - including_default_value_fields=False, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_environment_history._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["parent"] = 'parent_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_environment_history._get_unset_required_fields(jsonified_request) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("page_size", "page_token", )) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "parent" in jsonified_request - assert jsonified_request["parent"] == 'parent_value' - - client = EnvironmentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = environment.EnvironmentHistory() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "get", - 'query_params': pb_request, - } - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - - pb_return_value = environment.EnvironmentHistory.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.get_environment_history(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_get_environment_history_rest_unset_required_fields(): - transport = transports.EnvironmentsRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.get_environment_history._get_unset_required_fields({}) - assert set(unset_fields) == (set(("pageSize", "pageToken", )) & set(("parent", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_get_environment_history_rest_interceptors(null_interceptor): - transport = transports.EnvironmentsRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.EnvironmentsRestInterceptor(), - ) - client = EnvironmentsClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.EnvironmentsRestInterceptor, "post_get_environment_history") as post, \ - mock.patch.object(transports.EnvironmentsRestInterceptor, "pre_get_environment_history") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = environment.GetEnvironmentHistoryRequest.pb(environment.GetEnvironmentHistoryRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = environment.EnvironmentHistory.to_json(environment.EnvironmentHistory()) - - request = environment.GetEnvironmentHistoryRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = environment.EnvironmentHistory() - - client.get_environment_history(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_get_environment_history_rest_bad_request(transport: str = 'rest', request_type=environment.GetEnvironmentHistoryRequest): - client = EnvironmentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1/agent/environments/sample2'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.get_environment_history(request) - - -def test_get_environment_history_rest_pager(transport: str = 'rest'): - client = EnvironmentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # TODO(kbandes): remove this mock unless there's a good reason for it. - #with mock.patch.object(path_template, 'transcode') as transcode: - # Set the response as a series of pages - response = ( - 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(), - ], - ), - ) - # Two responses for two calls - response = response + response - - # Wrap the values into proper Response objs - response = tuple(environment.EnvironmentHistory.to_json(x) for x in response) - return_values = tuple(Response() for i in response) - for return_val, response_val in zip(return_values, response): - return_val._content = response_val.encode('UTF-8') - return_val.status_code = 200 - req.side_effect = return_values - - sample_request = {'parent': 'projects/sample1/agent/environments/sample2'} - - pager = client.get_environment_history(request=sample_request) - - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, environment.EnvironmentHistory.Entry) - for i in results) - - pages = list(client.get_environment_history(request=sample_request).pages) - 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 an api_key and a transport instance. - transport = transports.EnvironmentsGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - options = client_options.ClientOptions() - options.api_key = "api_key" - with pytest.raises(ValueError): - client = EnvironmentsClient( - client_options=options, - transport=transport, - ) - - # It is an error to provide an api_key and a credential. - options = mock.Mock() - options.api_key = "api_key" - with pytest.raises(ValueError): - client = EnvironmentsClient( - client_options=options, - credentials=ga_credentials.AnonymousCredentials() - ) - - # 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, - transports.EnvironmentsRestTransport, -]) -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() - -@pytest.mark.parametrize("transport_name", [ - "grpc", - "rest", -]) -def test_transport_kind(transport_name): - transport = EnvironmentsClient.get_transport_class(transport_name)( - credentials=ga_credentials.AnonymousCredentials(), - ) - assert transport.kind == transport_name - -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', - 'get_location', - 'list_locations', - 'get_operation', - 'cancel_operation', - 'list_operations', - ) - for method in methods: - with pytest.raises(NotImplementedError): - getattr(transport, method)(request=object()) - - with pytest.raises(NotImplementedError): - transport.close() - - # Catch all for all remaining methods and properties - remainder = [ - 'kind', - ] - for r in remainder: - with pytest.raises(NotImplementedError): - getattr(transport, r)() - - -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", - ) - - -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() - - -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, - ) - - -@pytest.mark.parametrize( - "transport_class", - [ - transports.EnvironmentsGrpcTransport, - transports.EnvironmentsGrpcAsyncIOTransport, - ], -) -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, - transports.EnvironmentsRestTransport, - ], -) -def test_environments_transport_auth_gdch_credentials(transport_class): - host = 'https://language.com' - api_audience_tests = [None, 'https://language2.com'] - api_audience_expect = [host, 'https://language2.com'] - for t, e in zip(api_audience_tests, api_audience_expect): - with mock.patch.object(google.auth, 'default', autospec=True) as adc: - gdch_mock = mock.MagicMock() - type(gdch_mock).with_gdch_audience = mock.PropertyMock(return_value=gdch_mock) - adc.return_value = (gdch_mock, None) - transport_class(host=host, api_audience=t) - gdch_mock.with_gdch_audience.assert_called_once_with( - e - ) - - -@pytest.mark.parametrize( - "transport_class,grpc_helpers", - [ - (transports.EnvironmentsGrpcTransport, grpc_helpers), - (transports.EnvironmentsGrpcAsyncIOTransport, grpc_helpers_async) - ], -) -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", [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=None, - ssl_credentials=mock_ssl_channel_creds, - quota_project_id=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - # Check if ssl_channel_credentials is not provided, then client_cert_source_for_mtls - # is used. - with mock.patch.object(transport_class, "create_channel", return_value=mock.Mock()): - with mock.patch("grpc.ssl_channel_credentials") as mock_ssl_cred: - transport_class( - credentials=cred, - client_cert_source_for_mtls=client_cert_source_callback - ) - expected_cert, expected_key = client_cert_source_callback() - mock_ssl_cred.assert_called_once_with( - certificate_chain=expected_cert, - private_key=expected_key - ) - -def test_environments_http_transport_client_cert_source_for_mtls(): - cred = ga_credentials.AnonymousCredentials() - with mock.patch("google.auth.transport.requests.AuthorizedSession.configure_mtls_channel") as mock_configure_mtls_channel: - transports.EnvironmentsRestTransport ( - credentials=cred, - client_cert_source_for_mtls=client_cert_source_callback - ) - mock_configure_mtls_channel.assert_called_once_with(client_cert_source_callback) - - -@pytest.mark.parametrize("transport_name", [ - "grpc", - "grpc_asyncio", - "rest", -]) -def test_environments_host_no_port(transport_name): - client = EnvironmentsClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='dialogflow.googleapis.com'), - transport=transport_name, - ) - assert client.transport._host == ( - 'dialogflow.googleapis.com:443' - if transport_name in ['grpc', 'grpc_asyncio'] - else 'https://dialogflow.googleapis.com' - ) - -@pytest.mark.parametrize("transport_name", [ - "grpc", - "grpc_asyncio", - "rest", -]) -def test_environments_host_with_port(transport_name): - client = EnvironmentsClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='dialogflow.googleapis.com:8000'), - transport=transport_name, - ) - assert client.transport._host == ( - 'dialogflow.googleapis.com:8000' - if transport_name in ['grpc', 'grpc_asyncio'] - else 'https://dialogflow.googleapis.com:8000' - ) - -@pytest.mark.parametrize("transport_name", [ - "rest", -]) -def test_environments_client_transport_session_collision(transport_name): - creds1 = ga_credentials.AnonymousCredentials() - creds2 = ga_credentials.AnonymousCredentials() - client1 = EnvironmentsClient( - credentials=creds1, - transport=transport_name, - ) - client2 = EnvironmentsClient( - credentials=creds2, - transport=transport_name, - ) - session1 = client1.transport.list_environments._session - session2 = client2.transport.list_environments._session - assert session1 != session2 - session1 = client1.transport.get_environment._session - session2 = client2.transport.get_environment._session - assert session1 != session2 - session1 = client1.transport.create_environment._session - session2 = client2.transport.create_environment._session - assert session1 != session2 - session1 = client1.transport.update_environment._session - session2 = client2.transport.update_environment._session - assert session1 != session2 - session1 = client1.transport.delete_environment._session - session2 = client2.transport.delete_environment._session - assert session1 != session2 - session1 = client1.transport.get_environment_history._session - session2 = client2.transport.get_environment_history._session - assert session1 != session2 -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, - ) - assert transport.grpc_channel == channel - assert transport._host == "squid.clam.whelk:443" - assert transport._ssl_channel_credentials == None - - -def test_environments_grpc_asyncio_transport_channel(): - channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.EnvironmentsGrpcAsyncIOTransport( - 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.EnvironmentsGrpcTransport, transports.EnvironmentsGrpcAsyncIOTransport]) -def test_environments_transport_channel_mtls_with_client_cert_source( - transport_class -): - with mock.patch("grpc.ssl_channel_credentials", autospec=True) as grpc_ssl_channel_cred: - with mock.patch.object(transport_class, "create_channel") as grpc_create_channel: - mock_ssl_cred = mock.Mock() - grpc_ssl_channel_cred.return_value = mock_ssl_cred - - mock_grpc_channel = mock.Mock() - grpc_create_channel.return_value = mock_grpc_channel - - cred = ga_credentials.AnonymousCredentials() - with pytest.warns(DeprecationWarning): - with mock.patch.object(google.auth, 'default') as adc: - adc.return_value = (cred, None) - transport = transport_class( - host="squid.clam.whelk", - api_mtls_endpoint="mtls.squid.clam.whelk", - client_cert_source=client_cert_source_callback, - ) - adc.assert_called_once() - - grpc_ssl_channel_cred.assert_called_once_with( - certificate_chain=b"cert bytes", private_key=b"key bytes" - ) - grpc_create_channel.assert_called_once_with( - "mtls.squid.clam.whelk:443", - credentials=cred, - credentials_file=None, - scopes=None, - ssl_credentials=mock_ssl_cred, - quota_project_id=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - assert transport.grpc_channel == mock_grpc_channel - assert transport._ssl_channel_credentials == mock_ssl_cred - - -# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are -# removed from grpc/grpc_asyncio transport constructor. -@pytest.mark.parametrize("transport_class", [transports.EnvironmentsGrpcTransport, transports.EnvironmentsGrpcAsyncIOTransport]) -def test_environments_transport_channel_mtls_with_adc( - transport_class -): - mock_ssl_cred = mock.Mock() - with mock.patch.multiple( - "google.auth.transport.grpc.SslCredentials", - __init__=mock.Mock(return_value=None), - ssl_credentials=mock.PropertyMock(return_value=mock_ssl_cred), - ): - with mock.patch.object(transport_class, "create_channel") as grpc_create_channel: - mock_grpc_channel = mock.Mock() - grpc_create_channel.return_value = mock_grpc_channel - mock_cred = mock.Mock() - - with pytest.warns(DeprecationWarning): - transport = transport_class( - host="squid.clam.whelk", - credentials=mock_cred, - api_mtls_endpoint="mtls.squid.clam.whelk", - client_cert_source=None, - ) - - grpc_create_channel.assert_called_once_with( - "mtls.squid.clam.whelk:443", - credentials=mock_cred, - credentials_file=None, - scopes=None, - ssl_credentials=mock_ssl_cred, - quota_project_id=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - assert transport.grpc_channel == mock_grpc_channel - - -def test_environment_path(): - project = "squid" - environment = "clam" - expected = "projects/{project}/agent/environments/{environment}".format(project=project, environment=environment, ) - actual = EnvironmentsClient.environment_path(project, environment) - assert expected == actual - - -def test_parse_environment_path(): - expected = { - "project": "whelk", - "environment": "octopus", - } - path = EnvironmentsClient.environment_path(**expected) - - # Check that the path construction is reversible. - actual = EnvironmentsClient.parse_environment_path(path) - assert expected == actual - -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_version_path(): - project = "cuttlefish" - version = "mussel" - expected = "projects/{project}/agent/versions/{version}".format(project=project, version=version, ) - actual = EnvironmentsClient.version_path(project, version) - assert expected == actual - - -def test_parse_version_path(): - expected = { - "project": "winkle", - "version": "nautilus", - } - path = EnvironmentsClient.version_path(**expected) - - # Check that the path construction is reversible. - actual = EnvironmentsClient.parse_version_path(path) - assert expected == actual - -def test_common_billing_account_path(): - billing_account = "scallop" - expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) - actual = EnvironmentsClient.common_billing_account_path(billing_account) - assert expected == actual - - -def test_parse_common_billing_account_path(): - expected = { - "billing_account": "abalone", - } - path = EnvironmentsClient.common_billing_account_path(**expected) - - # Check that the path construction is reversible. - actual = EnvironmentsClient.parse_common_billing_account_path(path) - assert expected == actual - -def test_common_folder_path(): - folder = "squid" - expected = "folders/{folder}".format(folder=folder, ) - actual = EnvironmentsClient.common_folder_path(folder) - assert expected == actual - - -def test_parse_common_folder_path(): - expected = { - "folder": "clam", - } - path = EnvironmentsClient.common_folder_path(**expected) - - # Check that the path construction is reversible. - actual = EnvironmentsClient.parse_common_folder_path(path) - assert expected == actual - -def test_common_organization_path(): - organization = "whelk" - expected = "organizations/{organization}".format(organization=organization, ) - actual = EnvironmentsClient.common_organization_path(organization) - assert expected == actual - - -def test_parse_common_organization_path(): - expected = { - "organization": "octopus", - } - path = EnvironmentsClient.common_organization_path(**expected) - - # Check that the path construction is reversible. - actual = EnvironmentsClient.parse_common_organization_path(path) - assert expected == actual - -def test_common_project_path(): - project = "oyster" - expected = "projects/{project}".format(project=project, ) - actual = EnvironmentsClient.common_project_path(project) - assert expected == actual - - -def test_parse_common_project_path(): - expected = { - "project": "nudibranch", - } - path = EnvironmentsClient.common_project_path(**expected) - - # Check that the path construction is reversible. - actual = EnvironmentsClient.parse_common_project_path(path) - assert expected == actual - -def test_common_location_path(): - project = "cuttlefish" - location = "mussel" - expected = "projects/{project}/locations/{location}".format(project=project, location=location, ) - actual = EnvironmentsClient.common_location_path(project, location) - assert expected == actual - - -def test_parse_common_location_path(): - expected = { - "project": "winkle", - "location": "nautilus", - } - path = EnvironmentsClient.common_location_path(**expected) - - # Check that the path construction is reversible. - actual = EnvironmentsClient.parse_common_location_path(path) - assert expected == actual - - -def test_client_with_default_client_info(): - client_info = gapic_v1.client_info.ClientInfo() - - with mock.patch.object(transports.EnvironmentsTransport, '_prep_wrapped_messages') as prep: - client = EnvironmentsClient( - credentials=ga_credentials.AnonymousCredentials(), - client_info=client_info, - ) - prep.assert_called_once_with(client_info) - - with mock.patch.object(transports.EnvironmentsTransport, '_prep_wrapped_messages') as prep: - transport_class = EnvironmentsClient.get_transport_class() - transport = transport_class( - credentials=ga_credentials.AnonymousCredentials(), - client_info=client_info, - ) - prep.assert_called_once_with(client_info) - -@pytest.mark.asyncio -async def test_transport_close_async(): - client = EnvironmentsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - with mock.patch.object(type(getattr(client.transport, "grpc_channel")), "close") as close: - async with client: - close.assert_not_called() - close.assert_called_once() - - -def test_get_location_rest_bad_request(transport: str = 'rest', request_type=locations_pb2.GetLocationRequest): - client = EnvironmentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - request = request_type() - request = json_format.ParseDict({'name': 'projects/sample1/locations/sample2'}, request) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.get_location(request) - -@pytest.mark.parametrize("request_type", [ - locations_pb2.GetLocationRequest, - dict, -]) -def test_get_location_rest(request_type): - client = EnvironmentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request_init = {'name': 'projects/sample1/locations/sample2'} - request = request_type(**request_init) - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = locations_pb2.Location() - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.get_location(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, locations_pb2.Location) - -def test_list_locations_rest_bad_request(transport: str = 'rest', request_type=locations_pb2.ListLocationsRequest): - client = EnvironmentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - request = request_type() - request = json_format.ParseDict({'name': 'projects/sample1'}, request) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.list_locations(request) - -@pytest.mark.parametrize("request_type", [ - locations_pb2.ListLocationsRequest, - dict, -]) -def test_list_locations_rest(request_type): - client = EnvironmentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request_init = {'name': 'projects/sample1'} - request = request_type(**request_init) - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = locations_pb2.ListLocationsResponse() - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.list_locations(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, locations_pb2.ListLocationsResponse) - -def test_cancel_operation_rest_bad_request(transport: str = 'rest', request_type=operations_pb2.CancelOperationRequest): - client = EnvironmentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - request = request_type() - request = json_format.ParseDict({'name': 'projects/sample1/operations/sample2'}, request) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.cancel_operation(request) - -@pytest.mark.parametrize("request_type", [ - operations_pb2.CancelOperationRequest, - dict, -]) -def test_cancel_operation_rest(request_type): - client = EnvironmentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request_init = {'name': 'projects/sample1/operations/sample2'} - request = request_type(**request_init) - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = None - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = '{}' - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.cancel_operation(request) - - # Establish that the response is the type that we expect. - assert response is None - -def test_get_operation_rest_bad_request(transport: str = 'rest', request_type=operations_pb2.GetOperationRequest): - client = EnvironmentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - request = request_type() - request = json_format.ParseDict({'name': 'projects/sample1/operations/sample2'}, request) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.get_operation(request) - -@pytest.mark.parametrize("request_type", [ - operations_pb2.GetOperationRequest, - dict, -]) -def test_get_operation_rest(request_type): - client = EnvironmentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request_init = {'name': 'projects/sample1/operations/sample2'} - request = request_type(**request_init) - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation() - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.get_operation(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, operations_pb2.Operation) - -def test_list_operations_rest_bad_request(transport: str = 'rest', request_type=operations_pb2.ListOperationsRequest): - client = EnvironmentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - request = request_type() - request = json_format.ParseDict({'name': 'projects/sample1'}, request) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.list_operations(request) - -@pytest.mark.parametrize("request_type", [ - operations_pb2.ListOperationsRequest, - dict, -]) -def test_list_operations_rest(request_type): - client = EnvironmentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request_init = {'name': 'projects/sample1'} - request = request_type(**request_init) - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = operations_pb2.ListOperationsResponse() - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.list_operations(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, operations_pb2.ListOperationsResponse) - - -def test_cancel_operation(transport: str = "grpc"): - 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 = operations_pb2.CancelOperationRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = None - response = client.cancel_operation(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 response is the type that we expect. - assert response is None -@pytest.mark.asyncio -async def test_cancel_operation_async(transport: str = "grpc"): - 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 = operations_pb2.CancelOperationRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - None - ) - response = await client.cancel_operation(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 response is the type that we expect. - assert response is None - -def test_cancel_operation_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 = operations_pb2.CancelOperationRequest() - request.name = "locations" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call: - call.return_value = None - - client.cancel_operation(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=locations",) in kw["metadata"] -@pytest.mark.asyncio -async def test_cancel_operation_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 = operations_pb2.CancelOperationRequest() - request.name = "locations" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - None - ) - await client.cancel_operation(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=locations",) in kw["metadata"] - -def test_cancel_operation_from_dict(): - 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.cancel_operation), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = None - - response = client.cancel_operation( - request={ - "name": "locations", - } - ) - call.assert_called() -@pytest.mark.asyncio -async def test_cancel_operation_from_dict_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.cancel_operation), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - None - ) - response = await client.cancel_operation( - request={ - "name": "locations", - } - ) - call.assert_called() - - -def test_get_operation(transport: str = "grpc"): - 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 = operations_pb2.GetOperationRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_operation), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation() - response = client.get_operation(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 response is the type that we expect. - assert isinstance(response, operations_pb2.Operation) -@pytest.mark.asyncio -async def test_get_operation_async(transport: str = "grpc"): - 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 = operations_pb2.GetOperationRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_operation), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation() - ) - response = await client.get_operation(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 response is the type that we expect. - assert isinstance(response, operations_pb2.Operation) - -def test_get_operation_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 = operations_pb2.GetOperationRequest() - request.name = "locations" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_operation), "__call__") as call: - call.return_value = operations_pb2.Operation() - - client.get_operation(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=locations",) in kw["metadata"] -@pytest.mark.asyncio -async def test_get_operation_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 = operations_pb2.GetOperationRequest() - request.name = "locations" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_operation), "__call__") as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation() - ) - await client.get_operation(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=locations",) in kw["metadata"] - -def test_get_operation_from_dict(): - 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_operation), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation() - - response = client.get_operation( - request={ - "name": "locations", - } - ) - call.assert_called() -@pytest.mark.asyncio -async def test_get_operation_from_dict_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.get_operation), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation() - ) - response = await client.get_operation( - request={ - "name": "locations", - } - ) - call.assert_called() - - -def test_list_operations(transport: str = "grpc"): - 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 = operations_pb2.ListOperationsRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_operations), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.ListOperationsResponse() - response = client.list_operations(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 response is the type that we expect. - assert isinstance(response, operations_pb2.ListOperationsResponse) -@pytest.mark.asyncio -async def test_list_operations_async(transport: str = "grpc"): - 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 = operations_pb2.ListOperationsRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_operations), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.ListOperationsResponse() - ) - response = await client.list_operations(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 response is the type that we expect. - assert isinstance(response, operations_pb2.ListOperationsResponse) - -def test_list_operations_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 = operations_pb2.ListOperationsRequest() - request.name = "locations" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_operations), "__call__") as call: - call.return_value = operations_pb2.ListOperationsResponse() - - client.list_operations(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=locations",) in kw["metadata"] -@pytest.mark.asyncio -async def test_list_operations_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 = operations_pb2.ListOperationsRequest() - request.name = "locations" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_operations), "__call__") as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.ListOperationsResponse() - ) - await client.list_operations(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=locations",) in kw["metadata"] - -def test_list_operations_from_dict(): - 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_operations), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.ListOperationsResponse() - - response = client.list_operations( - request={ - "name": "locations", - } - ) - call.assert_called() -@pytest.mark.asyncio -async def test_list_operations_from_dict_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_operations), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.ListOperationsResponse() - ) - response = await client.list_operations( - request={ - "name": "locations", - } - ) - call.assert_called() - - -def test_list_locations(transport: str = "grpc"): - 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 = locations_pb2.ListLocationsRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_locations), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = locations_pb2.ListLocationsResponse() - response = client.list_locations(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 response is the type that we expect. - assert isinstance(response, locations_pb2.ListLocationsResponse) -@pytest.mark.asyncio -async def test_list_locations_async(transport: str = "grpc"): - 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 = locations_pb2.ListLocationsRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_locations), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - locations_pb2.ListLocationsResponse() - ) - response = await client.list_locations(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 response is the type that we expect. - assert isinstance(response, locations_pb2.ListLocationsResponse) - -def test_list_locations_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 = locations_pb2.ListLocationsRequest() - request.name = "locations" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_locations), "__call__") as call: - call.return_value = locations_pb2.ListLocationsResponse() - - client.list_locations(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=locations",) in kw["metadata"] -@pytest.mark.asyncio -async def test_list_locations_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 = locations_pb2.ListLocationsRequest() - request.name = "locations" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_locations), "__call__") as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - locations_pb2.ListLocationsResponse() - ) - await client.list_locations(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=locations",) in kw["metadata"] - -def test_list_locations_from_dict(): - 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_locations), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = locations_pb2.ListLocationsResponse() - - response = client.list_locations( - request={ - "name": "locations", - } - ) - call.assert_called() -@pytest.mark.asyncio -async def test_list_locations_from_dict_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_locations), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - locations_pb2.ListLocationsResponse() - ) - response = await client.list_locations( - request={ - "name": "locations", - } - ) - call.assert_called() - - -def test_get_location(transport: str = "grpc"): - 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 = locations_pb2.GetLocationRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_location), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = locations_pb2.Location() - response = client.get_location(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 response is the type that we expect. - assert isinstance(response, locations_pb2.Location) -@pytest.mark.asyncio -async def test_get_location_async(transport: str = "grpc_asyncio"): - 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 = locations_pb2.GetLocationRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_location), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - locations_pb2.Location() - ) - response = await client.get_location(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 response is the type that we expect. - assert isinstance(response, locations_pb2.Location) - -def test_get_location_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 = locations_pb2.GetLocationRequest() - request.name = "locations/abc" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_location), "__call__") as call: - call.return_value = locations_pb2.Location() - - client.get_location(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=locations/abc",) in kw["metadata"] -@pytest.mark.asyncio -async def test_get_location_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 = locations_pb2.GetLocationRequest() - request.name = "locations/abc" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_location), "__call__") as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - locations_pb2.Location() - ) - await client.get_location(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=locations/abc",) in kw["metadata"] - -def test_get_location_from_dict(): - 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_locations), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = locations_pb2.Location() - - response = client.get_location( - request={ - "name": "locations/abc", - } - ) - call.assert_called() -@pytest.mark.asyncio -async def test_get_location_from_dict_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_locations), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - locations_pb2.Location() - ) - response = await client.get_location( - request={ - "name": "locations", - } - ) - call.assert_called() - - -def test_transport_close(): - transports = { - "rest": "_session", - "grpc": "_grpc_channel", - } - - for transport, close_name in transports.items(): - client = EnvironmentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport - ) - with mock.patch.object(type(getattr(client.transport, close_name)), "close") as close: - with client: - close.assert_not_called() - close.assert_called_once() - -def test_client_ctx(): - transports = [ - 'rest', - 'grpc', - ] - for transport in transports: - client = EnvironmentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport - ) - # Test client calls underlying transport. - with mock.patch.object(type(client.transport), "close") as close: - close.assert_not_called() - with client: - pass - close.assert_called() - -@pytest.mark.parametrize("client_class,transport_class", [ - (EnvironmentsClient, transports.EnvironmentsGrpcTransport), - (EnvironmentsAsyncClient, transports.EnvironmentsGrpcAsyncIOTransport), -]) -def test_api_key_credentials(client_class, transport_class): - with mock.patch.object( - google.auth._default, "get_api_key_credentials", create=True - ) as get_api_key_credentials: - mock_cred = mock.Mock() - get_api_key_credentials.return_value = mock_cred - options = client_options.ClientOptions() - options.api_key = "api_key" - 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=mock_cred, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) diff --git a/owl-bot-staging/v2beta1/tests/unit/gapic/dialogflow_v2beta1/test_fulfillments.py b/owl-bot-staging/v2beta1/tests/unit/gapic/dialogflow_v2beta1/test_fulfillments.py deleted file mode 100644 index 733d72837..000000000 --- a/owl-bot-staging/v2beta1/tests/unit/gapic/dialogflow_v2beta1/test_fulfillments.py +++ /dev/null @@ -1,3080 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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 -# try/except added for compatibility with python < 3.8 -try: - from unittest import mock - from unittest.mock import AsyncMock # pragma: NO COVER -except ImportError: # pragma: NO COVER - import mock - -import grpc -from grpc.experimental import aio -from collections.abc import Iterable -from google.protobuf import json_format -import json -import math -import pytest -from proto.marshal.rules.dates import DurationRule, TimestampRule -from proto.marshal.rules import wrappers -from requests import Response -from requests import Request, PreparedRequest -from requests.sessions import Session -from google.protobuf import json_format - -from google.api_core import client_options -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import grpc_helpers -from google.api_core import grpc_helpers_async -from google.api_core import path_template -from google.auth import credentials as ga_credentials -from google.auth.exceptions import MutualTLSChannelError -from google.cloud.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.types import fulfillment -from google.cloud.dialogflow_v2beta1.types import fulfillment as gcd_fulfillment -from google.cloud.location import locations_pb2 -from google.longrunning import operations_pb2 -from google.oauth2 import service_account -from google.protobuf import field_mask_pb2 # type: ignore -import google.auth - - -def client_cert_source_callback(): - return b"cert bytes", b"key bytes" - - -# If default endpoint is localhost, then default mtls endpoint will be the same. -# This method modifies the default endpoint so the client can produce a different -# mtls endpoint for endpoint testing purposes. -def modify_default_endpoint(client): - return "foo.googleapis.com" if ("localhost" in client.DEFAULT_ENDPOINT) else client.DEFAULT_ENDPOINT - - -def test__get_default_mtls_endpoint(): - api_endpoint = "example.googleapis.com" - api_mtls_endpoint = "example.mtls.googleapis.com" - sandbox_endpoint = "example.sandbox.googleapis.com" - sandbox_mtls_endpoint = "example.mtls.sandbox.googleapis.com" - non_googleapi = "api.example.com" - - assert 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,transport_name", [ - (FulfillmentsClient, "grpc"), - (FulfillmentsAsyncClient, "grpc_asyncio"), - (FulfillmentsClient, "rest"), -]) -def test_fulfillments_client_from_service_account_info(client_class, transport_name): - 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, transport=transport_name) - assert client.transport._credentials == creds - assert isinstance(client, client_class) - - assert client.transport._host == ( - 'dialogflow.googleapis.com:443' - if transport_name in ['grpc', 'grpc_asyncio'] - else - 'https://dialogflow.googleapis.com' - ) - - -@pytest.mark.parametrize("transport_class,transport_name", [ - (transports.FulfillmentsGrpcTransport, "grpc"), - (transports.FulfillmentsGrpcAsyncIOTransport, "grpc_asyncio"), - (transports.FulfillmentsRestTransport, "rest"), -]) -def test_fulfillments_client_service_account_always_use_jwt(transport_class, transport_name): - with mock.patch.object(service_account.Credentials, 'with_always_use_jwt_access', create=True) as use_jwt: - creds = service_account.Credentials(None, None, None) - transport = transport_class(credentials=creds, always_use_jwt_access=True) - use_jwt.assert_called_once_with(True) - - with mock.patch.object(service_account.Credentials, 'with_always_use_jwt_access', create=True) as use_jwt: - creds = service_account.Credentials(None, None, None) - transport = transport_class(credentials=creds, always_use_jwt_access=False) - use_jwt.assert_not_called() - - -@pytest.mark.parametrize("client_class,transport_name", [ - (FulfillmentsClient, "grpc"), - (FulfillmentsAsyncClient, "grpc_asyncio"), - (FulfillmentsClient, "rest"), -]) -def test_fulfillments_client_from_service_account_file(client_class, transport_name): - 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", transport=transport_name) - assert client.transport._credentials == creds - assert isinstance(client, client_class) - - client = client_class.from_service_account_json("dummy/file/path.json", transport=transport_name) - assert client.transport._credentials == creds - assert isinstance(client, client_class) - - assert client.transport._host == ( - 'dialogflow.googleapis.com:443' - if transport_name in ['grpc', 'grpc_asyncio'] - else - 'https://dialogflow.googleapis.com' - ) - - -def test_fulfillments_client_get_transport_class(): - transport = FulfillmentsClient.get_transport_class() - available_transports = [ - transports.FulfillmentsGrpcTransport, - transports.FulfillmentsRestTransport, - ] - 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"), - (FulfillmentsClient, transports.FulfillmentsRestTransport, "rest"), -]) -@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(transport=transport_name, client_options=options) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host="squid.clam.whelk", - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is - # "never". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is - # "always". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_MTLS_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # 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(transport=transport_name) - - # 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(transport=transport_name) - - # 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, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id="octopus", - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - # Check the case api_endpoint is provided - options = client_options.ClientOptions(api_audience="https://language.googleapis.com") - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience="https://language.googleapis.com" - ) - -@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"), - (FulfillmentsClient, transports.FulfillmentsRestTransport, "rest", "true"), - (FulfillmentsClient, transports.FulfillmentsRestTransport, "rest", "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, transport=transport_name) - - if use_client_cert_env == "false": - expected_client_cert_source = None - expected_host = client.DEFAULT_ENDPOINT - else: - expected_client_cert_source = client_cert_source_callback - expected_host = client.DEFAULT_MTLS_ENDPOINT - - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=expected_host, - scopes=None, - client_cert_source_for_mtls=expected_client_cert_source, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case ADC client cert is provided. Whether client cert is used depends on - # GOOGLE_API_USE_CLIENT_CERTIFICATE value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): - with mock.patch.object(transport_class, '__init__') as patched: - with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): - with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=client_cert_source_callback): - if use_client_cert_env == "false": - expected_host = client.DEFAULT_ENDPOINT - expected_client_cert_source = None - else: - expected_host = client.DEFAULT_MTLS_ENDPOINT - expected_client_cert_source = client_cert_source_callback - - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=expected_host, - scopes=None, - client_cert_source_for_mtls=expected_client_cert_source, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case client_cert_source and ADC client cert are not provided. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): - with mock.patch.object(transport_class, '__init__') as patched: - with mock.patch("google.auth.transport.mtls.has_default_client_cert_source", return_value=False): - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - -@pytest.mark.parametrize("client_class", [ - FulfillmentsClient, FulfillmentsAsyncClient -]) -@mock.patch.object(FulfillmentsClient, "DEFAULT_ENDPOINT", modify_default_endpoint(FulfillmentsClient)) -@mock.patch.object(FulfillmentsAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(FulfillmentsAsyncClient)) -def test_fulfillments_client_get_mtls_endpoint_and_cert_source(client_class): - mock_client_cert_source = mock.Mock() - - # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "true". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - mock_api_endpoint = "foo" - options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) - assert api_endpoint == mock_api_endpoint - assert cert_source == mock_client_cert_source - - # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "false". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): - mock_client_cert_source = mock.Mock() - mock_api_endpoint = "foo" - options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) - assert api_endpoint == mock_api_endpoint - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "never". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_ENDPOINT - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "always". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert doesn't exist. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=False): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_ENDPOINT - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert exists. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - 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=mock_client_cert_source): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT - assert cert_source == mock_client_cert_source - - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (FulfillmentsClient, transports.FulfillmentsGrpcTransport, "grpc"), - (FulfillmentsAsyncClient, transports.FulfillmentsGrpcAsyncIOTransport, "grpc_asyncio"), - (FulfillmentsClient, transports.FulfillmentsRestTransport, "rest"), -]) -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, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=["1", "2"], - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - -@pytest.mark.parametrize("client_class,transport_class,transport_name,grpc_helpers", [ - (FulfillmentsClient, transports.FulfillmentsGrpcTransport, "grpc", grpc_helpers), - (FulfillmentsAsyncClient, transports.FulfillmentsGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), - (FulfillmentsClient, transports.FulfillmentsRestTransport, "rest", None), -]) -def test_fulfillments_client_client_options_credentials_file(client_class, transport_class, transport_name, grpc_helpers): - # 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, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file="credentials.json", - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - -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, - always_use_jwt_access=True, - api_audience=None, - ) - - -@pytest.mark.parametrize("client_class,transport_class,transport_name,grpc_helpers", [ - (FulfillmentsClient, transports.FulfillmentsGrpcTransport, "grpc", grpc_helpers), - (FulfillmentsAsyncClient, transports.FulfillmentsGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), -]) -def test_fulfillments_client_create_channel_credentials_file(client_class, transport_class, transport_name, grpc_helpers): - # 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, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file="credentials.json", - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # test that the credentials from file are saved and used as the credentials. - with mock.patch.object( - google.auth, "load_credentials_from_file", autospec=True - ) as load_creds, mock.patch.object( - google.auth, "default", autospec=True - ) as adc, mock.patch.object( - grpc_helpers, "create_channel" - ) as create_channel: - creds = ga_credentials.AnonymousCredentials() - file_creds = ga_credentials.AnonymousCredentials() - load_creds.return_value = (file_creds, None) - adc.return_value = (creds, None) - client = client_class(client_options=options, transport=transport_name) - create_channel.assert_called_with( - "dialogflow.googleapis.com:443", - credentials=file_creds, - credentials_file=None, - quota_project_id=None, - default_scopes=( - 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/dialogflow', -), - scopes=None, - default_host="dialogflow.googleapis.com", - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - -@pytest.mark.parametrize("request_type", [ - fulfillment.GetFulfillmentRequest, - dict, -]) -def test_get_fulfillment(request_type, transport: str = 'grpc'): - 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_empty_call(): - # 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] - arg = args[0].name - mock_val = 'name_value' - assert arg == mock_val - - -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] - arg = args[0].name - mock_val = 'name_value' - assert arg == mock_val - -@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', - ) - - -@pytest.mark.parametrize("request_type", [ - gcd_fulfillment.UpdateFulfillmentRequest, - dict, -]) -def test_update_fulfillment(request_type, transport: str = 'grpc'): - 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_empty_call(): - # 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 = '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=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 = '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=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] - arg = args[0].fulfillment - mock_val = gcd_fulfillment.Fulfillment(name='name_value') - assert arg == mock_val - arg = args[0].update_mask - mock_val = field_mask_pb2.FieldMask(paths=['paths_value']) - assert arg == mock_val - - -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] - arg = args[0].fulfillment - mock_val = gcd_fulfillment.Fulfillment(name='name_value') - assert arg == mock_val - arg = args[0].update_mask - mock_val = field_mask_pb2.FieldMask(paths=['paths_value']) - assert arg == mock_val - -@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']), - ) - - -@pytest.mark.parametrize("request_type", [ - fulfillment.GetFulfillmentRequest, - dict, -]) -def test_get_fulfillment_rest(request_type): - client = FulfillmentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/agent/fulfillment'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = fulfillment.Fulfillment( - name='name_value', - display_name='display_name_value', - enabled=True, - generic_web_service=fulfillment.Fulfillment.GenericWebService(uri='uri_value'), - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - pb_return_value = fulfillment.Fulfillment.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.get_fulfillment(request) - - # 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_rest_required_fields(request_type=fulfillment.GetFulfillmentRequest): - transport_class = transports.FulfillmentsRestTransport - - request_init = {} - request_init["name"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - including_default_value_fields=False, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_fulfillment._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["name"] = 'name_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_fulfillment._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "name" in jsonified_request - assert jsonified_request["name"] == 'name_value' - - client = FulfillmentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = fulfillment.Fulfillment() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "get", - 'query_params': pb_request, - } - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - - pb_return_value = fulfillment.Fulfillment.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.get_fulfillment(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_get_fulfillment_rest_unset_required_fields(): - transport = transports.FulfillmentsRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.get_fulfillment._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_get_fulfillment_rest_interceptors(null_interceptor): - transport = transports.FulfillmentsRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.FulfillmentsRestInterceptor(), - ) - client = FulfillmentsClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.FulfillmentsRestInterceptor, "post_get_fulfillment") as post, \ - mock.patch.object(transports.FulfillmentsRestInterceptor, "pre_get_fulfillment") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = fulfillment.GetFulfillmentRequest.pb(fulfillment.GetFulfillmentRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = fulfillment.Fulfillment.to_json(fulfillment.Fulfillment()) - - request = fulfillment.GetFulfillmentRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = fulfillment.Fulfillment() - - client.get_fulfillment(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_get_fulfillment_rest_bad_request(transport: str = 'rest', request_type=fulfillment.GetFulfillmentRequest): - client = FulfillmentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/agent/fulfillment'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.get_fulfillment(request) - - -def test_get_fulfillment_rest_flattened(): - client = FulfillmentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = fulfillment.Fulfillment() - - # get arguments that satisfy an http rule for this method - sample_request = {'name': 'projects/sample1/agent/fulfillment'} - - # get truthy value for each flattened field - mock_args = dict( - name='name_value', - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - pb_return_value = fulfillment.Fulfillment.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.get_fulfillment(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v2beta1/{name=projects/*/agent/fulfillment}" % client.transport._host, args[1]) - - -def test_get_fulfillment_rest_flattened_error(transport: str = 'rest'): - client = FulfillmentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # 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', - ) - - -def test_get_fulfillment_rest_error(): - client = FulfillmentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - gcd_fulfillment.UpdateFulfillmentRequest, - dict, -]) -def test_update_fulfillment_rest(request_type): - client = FulfillmentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'fulfillment': {'name': 'projects/sample1/agent/fulfillment'}} - request_init["fulfillment"] = {'name': 'projects/sample1/agent/fulfillment', 'display_name': 'display_name_value', 'generic_web_service': {'uri': 'uri_value', 'username': 'username_value', 'password': 'password_value', 'request_headers': {}, 'is_cloud_function': True}, 'enabled': True, 'features': [{'type_': 1}]} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - 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'), - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - pb_return_value = gcd_fulfillment.Fulfillment.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.update_fulfillment(request) - - # 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_rest_required_fields(request_type=gcd_fulfillment.UpdateFulfillmentRequest): - transport_class = transports.FulfillmentsRestTransport - - request_init = {} - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - including_default_value_fields=False, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).update_fulfillment._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).update_fulfillment._get_unset_required_fields(jsonified_request) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("update_mask", )) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - - client = FulfillmentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = gcd_fulfillment.Fulfillment() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "patch", - 'query_params': pb_request, - } - transcode_result['body'] = pb_request - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - - pb_return_value = gcd_fulfillment.Fulfillment.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.update_fulfillment(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_update_fulfillment_rest_unset_required_fields(): - transport = transports.FulfillmentsRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.update_fulfillment._get_unset_required_fields({}) - assert set(unset_fields) == (set(("updateMask", )) & set(("fulfillment", "updateMask", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_update_fulfillment_rest_interceptors(null_interceptor): - transport = transports.FulfillmentsRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.FulfillmentsRestInterceptor(), - ) - client = FulfillmentsClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.FulfillmentsRestInterceptor, "post_update_fulfillment") as post, \ - mock.patch.object(transports.FulfillmentsRestInterceptor, "pre_update_fulfillment") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = gcd_fulfillment.UpdateFulfillmentRequest.pb(gcd_fulfillment.UpdateFulfillmentRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = gcd_fulfillment.Fulfillment.to_json(gcd_fulfillment.Fulfillment()) - - request = gcd_fulfillment.UpdateFulfillmentRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = gcd_fulfillment.Fulfillment() - - client.update_fulfillment(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_update_fulfillment_rest_bad_request(transport: str = 'rest', request_type=gcd_fulfillment.UpdateFulfillmentRequest): - client = FulfillmentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'fulfillment': {'name': 'projects/sample1/agent/fulfillment'}} - request_init["fulfillment"] = {'name': 'projects/sample1/agent/fulfillment', 'display_name': 'display_name_value', 'generic_web_service': {'uri': 'uri_value', 'username': 'username_value', 'password': 'password_value', 'request_headers': {}, 'is_cloud_function': True}, 'enabled': True, 'features': [{'type_': 1}]} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.update_fulfillment(request) - - -def test_update_fulfillment_rest_flattened(): - client = FulfillmentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = gcd_fulfillment.Fulfillment() - - # get arguments that satisfy an http rule for this method - sample_request = {'fulfillment': {'name': 'projects/sample1/agent/fulfillment'}} - - # get truthy value for each flattened field - mock_args = dict( - fulfillment=gcd_fulfillment.Fulfillment(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - pb_return_value = gcd_fulfillment.Fulfillment.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.update_fulfillment(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v2beta1/{fulfillment.name=projects/*/agent/fulfillment}" % client.transport._host, args[1]) - - -def test_update_fulfillment_rest_flattened_error(transport: str = 'rest'): - client = FulfillmentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # 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']), - ) - - -def test_update_fulfillment_rest_error(): - client = FulfillmentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -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 an api_key and a transport instance. - transport = transports.FulfillmentsGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - options = client_options.ClientOptions() - options.api_key = "api_key" - with pytest.raises(ValueError): - client = FulfillmentsClient( - client_options=options, - transport=transport, - ) - - # It is an error to provide an api_key and a credential. - options = mock.Mock() - options.api_key = "api_key" - with pytest.raises(ValueError): - client = FulfillmentsClient( - client_options=options, - credentials=ga_credentials.AnonymousCredentials() - ) - - # 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, - transports.FulfillmentsRestTransport, -]) -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() - -@pytest.mark.parametrize("transport_name", [ - "grpc", - "rest", -]) -def test_transport_kind(transport_name): - transport = FulfillmentsClient.get_transport_class(transport_name)( - credentials=ga_credentials.AnonymousCredentials(), - ) - assert transport.kind == transport_name - -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', - 'get_location', - 'list_locations', - 'get_operation', - 'cancel_operation', - 'list_operations', - ) - for method in methods: - with pytest.raises(NotImplementedError): - getattr(transport, method)(request=object()) - - with pytest.raises(NotImplementedError): - transport.close() - - # Catch all for all remaining methods and properties - remainder = [ - 'kind', - ] - for r in remainder: - with pytest.raises(NotImplementedError): - getattr(transport, r)() - - -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", - ) - - -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() - - -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, - ) - - -@pytest.mark.parametrize( - "transport_class", - [ - transports.FulfillmentsGrpcTransport, - transports.FulfillmentsGrpcAsyncIOTransport, - ], -) -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, - transports.FulfillmentsRestTransport, - ], -) -def test_fulfillments_transport_auth_gdch_credentials(transport_class): - host = 'https://language.com' - api_audience_tests = [None, 'https://language2.com'] - api_audience_expect = [host, 'https://language2.com'] - for t, e in zip(api_audience_tests, api_audience_expect): - with mock.patch.object(google.auth, 'default', autospec=True) as adc: - gdch_mock = mock.MagicMock() - type(gdch_mock).with_gdch_audience = mock.PropertyMock(return_value=gdch_mock) - adc.return_value = (gdch_mock, None) - transport_class(host=host, api_audience=t) - gdch_mock.with_gdch_audience.assert_called_once_with( - e - ) - - -@pytest.mark.parametrize( - "transport_class,grpc_helpers", - [ - (transports.FulfillmentsGrpcTransport, grpc_helpers), - (transports.FulfillmentsGrpcAsyncIOTransport, grpc_helpers_async) - ], -) -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", [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=None, - ssl_credentials=mock_ssl_channel_creds, - quota_project_id=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - # Check if ssl_channel_credentials is not provided, then client_cert_source_for_mtls - # is used. - with mock.patch.object(transport_class, "create_channel", return_value=mock.Mock()): - with mock.patch("grpc.ssl_channel_credentials") as mock_ssl_cred: - transport_class( - credentials=cred, - client_cert_source_for_mtls=client_cert_source_callback - ) - expected_cert, expected_key = client_cert_source_callback() - mock_ssl_cred.assert_called_once_with( - certificate_chain=expected_cert, - private_key=expected_key - ) - -def test_fulfillments_http_transport_client_cert_source_for_mtls(): - cred = ga_credentials.AnonymousCredentials() - with mock.patch("google.auth.transport.requests.AuthorizedSession.configure_mtls_channel") as mock_configure_mtls_channel: - transports.FulfillmentsRestTransport ( - credentials=cred, - client_cert_source_for_mtls=client_cert_source_callback - ) - mock_configure_mtls_channel.assert_called_once_with(client_cert_source_callback) - - -@pytest.mark.parametrize("transport_name", [ - "grpc", - "grpc_asyncio", - "rest", -]) -def test_fulfillments_host_no_port(transport_name): - client = FulfillmentsClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='dialogflow.googleapis.com'), - transport=transport_name, - ) - assert client.transport._host == ( - 'dialogflow.googleapis.com:443' - if transport_name in ['grpc', 'grpc_asyncio'] - else 'https://dialogflow.googleapis.com' - ) - -@pytest.mark.parametrize("transport_name", [ - "grpc", - "grpc_asyncio", - "rest", -]) -def test_fulfillments_host_with_port(transport_name): - client = FulfillmentsClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='dialogflow.googleapis.com:8000'), - transport=transport_name, - ) - assert client.transport._host == ( - 'dialogflow.googleapis.com:8000' - if transport_name in ['grpc', 'grpc_asyncio'] - else 'https://dialogflow.googleapis.com:8000' - ) - -@pytest.mark.parametrize("transport_name", [ - "rest", -]) -def test_fulfillments_client_transport_session_collision(transport_name): - creds1 = ga_credentials.AnonymousCredentials() - creds2 = ga_credentials.AnonymousCredentials() - client1 = FulfillmentsClient( - credentials=creds1, - transport=transport_name, - ) - client2 = FulfillmentsClient( - credentials=creds2, - transport=transport_name, - ) - session1 = client1.transport.get_fulfillment._session - session2 = client2.transport.get_fulfillment._session - assert session1 != session2 - session1 = client1.transport.update_fulfillment._session - session2 = client2.transport.update_fulfillment._session - assert session1 != session2 -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=None, - ssl_credentials=mock_ssl_cred, - quota_project_id=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - assert transport.grpc_channel == mock_grpc_channel - assert transport._ssl_channel_credentials == mock_ssl_cred - - -# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are -# removed from grpc/grpc_asyncio transport constructor. -@pytest.mark.parametrize("transport_class", [transports.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=None, - ssl_credentials=mock_ssl_cred, - quota_project_id=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - assert transport.grpc_channel == mock_grpc_channel - - -def test_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_with_default_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) - -@pytest.mark.asyncio -async def test_transport_close_async(): - client = FulfillmentsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - with mock.patch.object(type(getattr(client.transport, "grpc_channel")), "close") as close: - async with client: - close.assert_not_called() - close.assert_called_once() - - -def test_get_location_rest_bad_request(transport: str = 'rest', request_type=locations_pb2.GetLocationRequest): - client = FulfillmentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - request = request_type() - request = json_format.ParseDict({'name': 'projects/sample1/locations/sample2'}, request) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.get_location(request) - -@pytest.mark.parametrize("request_type", [ - locations_pb2.GetLocationRequest, - dict, -]) -def test_get_location_rest(request_type): - client = FulfillmentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request_init = {'name': 'projects/sample1/locations/sample2'} - request = request_type(**request_init) - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = locations_pb2.Location() - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.get_location(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, locations_pb2.Location) - -def test_list_locations_rest_bad_request(transport: str = 'rest', request_type=locations_pb2.ListLocationsRequest): - client = FulfillmentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - request = request_type() - request = json_format.ParseDict({'name': 'projects/sample1'}, request) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.list_locations(request) - -@pytest.mark.parametrize("request_type", [ - locations_pb2.ListLocationsRequest, - dict, -]) -def test_list_locations_rest(request_type): - client = FulfillmentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request_init = {'name': 'projects/sample1'} - request = request_type(**request_init) - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = locations_pb2.ListLocationsResponse() - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.list_locations(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, locations_pb2.ListLocationsResponse) - -def test_cancel_operation_rest_bad_request(transport: str = 'rest', request_type=operations_pb2.CancelOperationRequest): - client = FulfillmentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - request = request_type() - request = json_format.ParseDict({'name': 'projects/sample1/operations/sample2'}, request) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.cancel_operation(request) - -@pytest.mark.parametrize("request_type", [ - operations_pb2.CancelOperationRequest, - dict, -]) -def test_cancel_operation_rest(request_type): - client = FulfillmentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request_init = {'name': 'projects/sample1/operations/sample2'} - request = request_type(**request_init) - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = None - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = '{}' - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.cancel_operation(request) - - # Establish that the response is the type that we expect. - assert response is None - -def test_get_operation_rest_bad_request(transport: str = 'rest', request_type=operations_pb2.GetOperationRequest): - client = FulfillmentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - request = request_type() - request = json_format.ParseDict({'name': 'projects/sample1/operations/sample2'}, request) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.get_operation(request) - -@pytest.mark.parametrize("request_type", [ - operations_pb2.GetOperationRequest, - dict, -]) -def test_get_operation_rest(request_type): - client = FulfillmentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request_init = {'name': 'projects/sample1/operations/sample2'} - request = request_type(**request_init) - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation() - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.get_operation(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, operations_pb2.Operation) - -def test_list_operations_rest_bad_request(transport: str = 'rest', request_type=operations_pb2.ListOperationsRequest): - client = FulfillmentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - request = request_type() - request = json_format.ParseDict({'name': 'projects/sample1'}, request) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.list_operations(request) - -@pytest.mark.parametrize("request_type", [ - operations_pb2.ListOperationsRequest, - dict, -]) -def test_list_operations_rest(request_type): - client = FulfillmentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request_init = {'name': 'projects/sample1'} - request = request_type(**request_init) - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = operations_pb2.ListOperationsResponse() - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.list_operations(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, operations_pb2.ListOperationsResponse) - - -def test_cancel_operation(transport: str = "grpc"): - 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 = operations_pb2.CancelOperationRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = None - response = client.cancel_operation(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 response is the type that we expect. - assert response is None -@pytest.mark.asyncio -async def test_cancel_operation_async(transport: str = "grpc"): - 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 = operations_pb2.CancelOperationRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - None - ) - response = await client.cancel_operation(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 response is the type that we expect. - assert response is None - -def test_cancel_operation_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 = operations_pb2.CancelOperationRequest() - request.name = "locations" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call: - call.return_value = None - - client.cancel_operation(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=locations",) in kw["metadata"] -@pytest.mark.asyncio -async def test_cancel_operation_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 = operations_pb2.CancelOperationRequest() - request.name = "locations" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - None - ) - await client.cancel_operation(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=locations",) in kw["metadata"] - -def test_cancel_operation_from_dict(): - 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.cancel_operation), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = None - - response = client.cancel_operation( - request={ - "name": "locations", - } - ) - call.assert_called() -@pytest.mark.asyncio -async def test_cancel_operation_from_dict_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.cancel_operation), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - None - ) - response = await client.cancel_operation( - request={ - "name": "locations", - } - ) - call.assert_called() - - -def test_get_operation(transport: str = "grpc"): - 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 = operations_pb2.GetOperationRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_operation), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation() - response = client.get_operation(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 response is the type that we expect. - assert isinstance(response, operations_pb2.Operation) -@pytest.mark.asyncio -async def test_get_operation_async(transport: str = "grpc"): - 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 = operations_pb2.GetOperationRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_operation), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation() - ) - response = await client.get_operation(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 response is the type that we expect. - assert isinstance(response, operations_pb2.Operation) - -def test_get_operation_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 = operations_pb2.GetOperationRequest() - request.name = "locations" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_operation), "__call__") as call: - call.return_value = operations_pb2.Operation() - - client.get_operation(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=locations",) in kw["metadata"] -@pytest.mark.asyncio -async def test_get_operation_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 = operations_pb2.GetOperationRequest() - request.name = "locations" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_operation), "__call__") as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation() - ) - await client.get_operation(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=locations",) in kw["metadata"] - -def test_get_operation_from_dict(): - 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_operation), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation() - - response = client.get_operation( - request={ - "name": "locations", - } - ) - call.assert_called() -@pytest.mark.asyncio -async def test_get_operation_from_dict_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_operation), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation() - ) - response = await client.get_operation( - request={ - "name": "locations", - } - ) - call.assert_called() - - -def test_list_operations(transport: str = "grpc"): - 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 = operations_pb2.ListOperationsRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_operations), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.ListOperationsResponse() - response = client.list_operations(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 response is the type that we expect. - assert isinstance(response, operations_pb2.ListOperationsResponse) -@pytest.mark.asyncio -async def test_list_operations_async(transport: str = "grpc"): - 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 = operations_pb2.ListOperationsRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_operations), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.ListOperationsResponse() - ) - response = await client.list_operations(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 response is the type that we expect. - assert isinstance(response, operations_pb2.ListOperationsResponse) - -def test_list_operations_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 = operations_pb2.ListOperationsRequest() - request.name = "locations" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_operations), "__call__") as call: - call.return_value = operations_pb2.ListOperationsResponse() - - client.list_operations(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=locations",) in kw["metadata"] -@pytest.mark.asyncio -async def test_list_operations_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 = operations_pb2.ListOperationsRequest() - request.name = "locations" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_operations), "__call__") as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.ListOperationsResponse() - ) - await client.list_operations(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=locations",) in kw["metadata"] - -def test_list_operations_from_dict(): - 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.list_operations), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.ListOperationsResponse() - - response = client.list_operations( - request={ - "name": "locations", - } - ) - call.assert_called() -@pytest.mark.asyncio -async def test_list_operations_from_dict_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.list_operations), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.ListOperationsResponse() - ) - response = await client.list_operations( - request={ - "name": "locations", - } - ) - call.assert_called() - - -def test_list_locations(transport: str = "grpc"): - 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 = locations_pb2.ListLocationsRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_locations), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = locations_pb2.ListLocationsResponse() - response = client.list_locations(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 response is the type that we expect. - assert isinstance(response, locations_pb2.ListLocationsResponse) -@pytest.mark.asyncio -async def test_list_locations_async(transport: str = "grpc"): - 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 = locations_pb2.ListLocationsRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_locations), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - locations_pb2.ListLocationsResponse() - ) - response = await client.list_locations(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 response is the type that we expect. - assert isinstance(response, locations_pb2.ListLocationsResponse) - -def test_list_locations_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 = locations_pb2.ListLocationsRequest() - request.name = "locations" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_locations), "__call__") as call: - call.return_value = locations_pb2.ListLocationsResponse() - - client.list_locations(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=locations",) in kw["metadata"] -@pytest.mark.asyncio -async def test_list_locations_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 = locations_pb2.ListLocationsRequest() - request.name = "locations" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_locations), "__call__") as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - locations_pb2.ListLocationsResponse() - ) - await client.list_locations(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=locations",) in kw["metadata"] - -def test_list_locations_from_dict(): - 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.list_locations), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = locations_pb2.ListLocationsResponse() - - response = client.list_locations( - request={ - "name": "locations", - } - ) - call.assert_called() -@pytest.mark.asyncio -async def test_list_locations_from_dict_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.list_locations), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - locations_pb2.ListLocationsResponse() - ) - response = await client.list_locations( - request={ - "name": "locations", - } - ) - call.assert_called() - - -def test_get_location(transport: str = "grpc"): - 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 = locations_pb2.GetLocationRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_location), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = locations_pb2.Location() - response = client.get_location(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 response is the type that we expect. - assert isinstance(response, locations_pb2.Location) -@pytest.mark.asyncio -async def test_get_location_async(transport: str = "grpc_asyncio"): - 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 = locations_pb2.GetLocationRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_location), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - locations_pb2.Location() - ) - response = await client.get_location(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 response is the type that we expect. - assert isinstance(response, locations_pb2.Location) - -def test_get_location_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 = locations_pb2.GetLocationRequest() - request.name = "locations/abc" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_location), "__call__") as call: - call.return_value = locations_pb2.Location() - - client.get_location(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=locations/abc",) in kw["metadata"] -@pytest.mark.asyncio -async def test_get_location_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 = locations_pb2.GetLocationRequest() - request.name = "locations/abc" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_location), "__call__") as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - locations_pb2.Location() - ) - await client.get_location(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=locations/abc",) in kw["metadata"] - -def test_get_location_from_dict(): - 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.list_locations), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = locations_pb2.Location() - - response = client.get_location( - request={ - "name": "locations/abc", - } - ) - call.assert_called() -@pytest.mark.asyncio -async def test_get_location_from_dict_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.list_locations), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - locations_pb2.Location() - ) - response = await client.get_location( - request={ - "name": "locations", - } - ) - call.assert_called() - - -def test_transport_close(): - transports = { - "rest": "_session", - "grpc": "_grpc_channel", - } - - for transport, close_name in transports.items(): - client = FulfillmentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport - ) - with mock.patch.object(type(getattr(client.transport, close_name)), "close") as close: - with client: - close.assert_not_called() - close.assert_called_once() - -def test_client_ctx(): - transports = [ - 'rest', - 'grpc', - ] - for transport in transports: - client = FulfillmentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport - ) - # Test client calls underlying transport. - with mock.patch.object(type(client.transport), "close") as close: - close.assert_not_called() - with client: - pass - close.assert_called() - -@pytest.mark.parametrize("client_class,transport_class", [ - (FulfillmentsClient, transports.FulfillmentsGrpcTransport), - (FulfillmentsAsyncClient, transports.FulfillmentsGrpcAsyncIOTransport), -]) -def test_api_key_credentials(client_class, transport_class): - with mock.patch.object( - google.auth._default, "get_api_key_credentials", create=True - ) as get_api_key_credentials: - mock_cred = mock.Mock() - get_api_key_credentials.return_value = mock_cred - options = client_options.ClientOptions() - options.api_key = "api_key" - 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=mock_cred, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) diff --git a/owl-bot-staging/v2beta1/tests/unit/gapic/dialogflow_v2beta1/test_intents.py b/owl-bot-staging/v2beta1/tests/unit/gapic/dialogflow_v2beta1/test_intents.py deleted file mode 100644 index 933b70b8d..000000000 --- a/owl-bot-staging/v2beta1/tests/unit/gapic/dialogflow_v2beta1/test_intents.py +++ /dev/null @@ -1,6058 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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 -# try/except added for compatibility with python < 3.8 -try: - from unittest import mock - from unittest.mock import AsyncMock # pragma: NO COVER -except ImportError: # pragma: NO COVER - import mock - -import grpc -from grpc.experimental import aio -from collections.abc import Iterable -from google.protobuf import json_format -import json -import math -import pytest -from proto.marshal.rules.dates import DurationRule, TimestampRule -from proto.marshal.rules import wrappers -from requests import Response -from requests import Request, PreparedRequest -from requests.sessions import Session -from google.protobuf import json_format - -from google.api_core import client_options -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 -from google.api_core import operation_async # type: ignore -from google.api_core import operations_v1 -from google.api_core import path_template -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.types import context -from google.cloud.dialogflow_v2beta1.types import intent -from google.cloud.dialogflow_v2beta1.types import intent as gcd_intent -from google.cloud.location import locations_pb2 -from google.longrunning import operations_pb2 -from google.oauth2 import service_account -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 -import google.auth - - -def client_cert_source_callback(): - return b"cert bytes", b"key bytes" - - -# If default endpoint is localhost, then default mtls endpoint will be the same. -# This method modifies the default endpoint so the client can produce a different -# mtls endpoint for endpoint testing purposes. -def modify_default_endpoint(client): - return "foo.googleapis.com" if ("localhost" in client.DEFAULT_ENDPOINT) else client.DEFAULT_ENDPOINT - - -def test__get_default_mtls_endpoint(): - api_endpoint = "example.googleapis.com" - api_mtls_endpoint = "example.mtls.googleapis.com" - sandbox_endpoint = "example.sandbox.googleapis.com" - sandbox_mtls_endpoint = "example.mtls.sandbox.googleapis.com" - non_googleapi = "api.example.com" - - assert IntentsClient._get_default_mtls_endpoint(None) is None - assert IntentsClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint - assert IntentsClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint - assert IntentsClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint - assert IntentsClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint - assert IntentsClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi - - -@pytest.mark.parametrize("client_class,transport_name", [ - (IntentsClient, "grpc"), - (IntentsAsyncClient, "grpc_asyncio"), - (IntentsClient, "rest"), -]) -def test_intents_client_from_service_account_info(client_class, transport_name): - 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, transport=transport_name) - assert client.transport._credentials == creds - assert isinstance(client, client_class) - - assert client.transport._host == ( - 'dialogflow.googleapis.com:443' - if transport_name in ['grpc', 'grpc_asyncio'] - else - 'https://dialogflow.googleapis.com' - ) - - -@pytest.mark.parametrize("transport_class,transport_name", [ - (transports.IntentsGrpcTransport, "grpc"), - (transports.IntentsGrpcAsyncIOTransport, "grpc_asyncio"), - (transports.IntentsRestTransport, "rest"), -]) -def test_intents_client_service_account_always_use_jwt(transport_class, transport_name): - with mock.patch.object(service_account.Credentials, 'with_always_use_jwt_access', create=True) as use_jwt: - creds = service_account.Credentials(None, None, None) - transport = transport_class(credentials=creds, always_use_jwt_access=True) - use_jwt.assert_called_once_with(True) - - with mock.patch.object(service_account.Credentials, 'with_always_use_jwt_access', create=True) as use_jwt: - creds = service_account.Credentials(None, None, None) - transport = transport_class(credentials=creds, always_use_jwt_access=False) - use_jwt.assert_not_called() - - -@pytest.mark.parametrize("client_class,transport_name", [ - (IntentsClient, "grpc"), - (IntentsAsyncClient, "grpc_asyncio"), - (IntentsClient, "rest"), -]) -def test_intents_client_from_service_account_file(client_class, transport_name): - 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", transport=transport_name) - assert client.transport._credentials == creds - assert isinstance(client, client_class) - - client = client_class.from_service_account_json("dummy/file/path.json", transport=transport_name) - assert client.transport._credentials == creds - assert isinstance(client, client_class) - - assert client.transport._host == ( - 'dialogflow.googleapis.com:443' - if transport_name in ['grpc', 'grpc_asyncio'] - else - 'https://dialogflow.googleapis.com' - ) - - -def test_intents_client_get_transport_class(): - transport = IntentsClient.get_transport_class() - available_transports = [ - transports.IntentsGrpcTransport, - transports.IntentsRestTransport, - ] - assert transport in available_transports - - transport = IntentsClient.get_transport_class("grpc") - assert transport == transports.IntentsGrpcTransport - - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (IntentsClient, transports.IntentsGrpcTransport, "grpc"), - (IntentsAsyncClient, transports.IntentsGrpcAsyncIOTransport, "grpc_asyncio"), - (IntentsClient, transports.IntentsRestTransport, "rest"), -]) -@mock.patch.object(IntentsClient, "DEFAULT_ENDPOINT", modify_default_endpoint(IntentsClient)) -@mock.patch.object(IntentsAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(IntentsAsyncClient)) -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=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(IntentsClient, 'get_transport_class') as gtc: - client = client_class(transport=transport_name) - gtc.assert_called() - - # Check the case api_endpoint is provided. - options = client_options.ClientOptions(api_endpoint="squid.clam.whelk") - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(transport=transport_name, client_options=options) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host="squid.clam.whelk", - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is - # "never". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is - # "always". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_MTLS_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # 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(transport=transport_name) - - # 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(transport=transport_name) - - # 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, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id="octopus", - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - # Check the case api_endpoint is provided - options = client_options.ClientOptions(api_audience="https://language.googleapis.com") - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience="https://language.googleapis.com" - ) - -@pytest.mark.parametrize("client_class,transport_class,transport_name,use_client_cert_env", [ - (IntentsClient, transports.IntentsGrpcTransport, "grpc", "true"), - (IntentsAsyncClient, transports.IntentsGrpcAsyncIOTransport, "grpc_asyncio", "true"), - (IntentsClient, transports.IntentsGrpcTransport, "grpc", "false"), - (IntentsAsyncClient, transports.IntentsGrpcAsyncIOTransport, "grpc_asyncio", "false"), - (IntentsClient, transports.IntentsRestTransport, "rest", "true"), - (IntentsClient, transports.IntentsRestTransport, "rest", "false"), -]) -@mock.patch.object(IntentsClient, "DEFAULT_ENDPOINT", modify_default_endpoint(IntentsClient)) -@mock.patch.object(IntentsAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(IntentsAsyncClient)) -@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) -def test_intents_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, transport=transport_name) - - if use_client_cert_env == "false": - expected_client_cert_source = None - expected_host = client.DEFAULT_ENDPOINT - else: - expected_client_cert_source = client_cert_source_callback - expected_host = client.DEFAULT_MTLS_ENDPOINT - - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=expected_host, - scopes=None, - client_cert_source_for_mtls=expected_client_cert_source, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case ADC client cert is provided. Whether client cert is used depends on - # GOOGLE_API_USE_CLIENT_CERTIFICATE value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): - with mock.patch.object(transport_class, '__init__') as patched: - with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): - with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=client_cert_source_callback): - if use_client_cert_env == "false": - expected_host = client.DEFAULT_ENDPOINT - expected_client_cert_source = None - else: - expected_host = client.DEFAULT_MTLS_ENDPOINT - expected_client_cert_source = client_cert_source_callback - - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=expected_host, - scopes=None, - client_cert_source_for_mtls=expected_client_cert_source, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case client_cert_source and ADC client cert are not provided. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): - with mock.patch.object(transport_class, '__init__') as patched: - with mock.patch("google.auth.transport.mtls.has_default_client_cert_source", return_value=False): - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - -@pytest.mark.parametrize("client_class", [ - IntentsClient, IntentsAsyncClient -]) -@mock.patch.object(IntentsClient, "DEFAULT_ENDPOINT", modify_default_endpoint(IntentsClient)) -@mock.patch.object(IntentsAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(IntentsAsyncClient)) -def test_intents_client_get_mtls_endpoint_and_cert_source(client_class): - mock_client_cert_source = mock.Mock() - - # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "true". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - mock_api_endpoint = "foo" - options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) - assert api_endpoint == mock_api_endpoint - assert cert_source == mock_client_cert_source - - # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "false". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): - mock_client_cert_source = mock.Mock() - mock_api_endpoint = "foo" - options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) - assert api_endpoint == mock_api_endpoint - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "never". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_ENDPOINT - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "always". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert doesn't exist. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=False): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_ENDPOINT - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert exists. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - 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=mock_client_cert_source): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT - assert cert_source == mock_client_cert_source - - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (IntentsClient, transports.IntentsGrpcTransport, "grpc"), - (IntentsAsyncClient, transports.IntentsGrpcAsyncIOTransport, "grpc_asyncio"), - (IntentsClient, transports.IntentsRestTransport, "rest"), -]) -def test_intents_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, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=["1", "2"], - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - -@pytest.mark.parametrize("client_class,transport_class,transport_name,grpc_helpers", [ - (IntentsClient, transports.IntentsGrpcTransport, "grpc", grpc_helpers), - (IntentsAsyncClient, transports.IntentsGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), - (IntentsClient, transports.IntentsRestTransport, "rest", None), -]) -def test_intents_client_client_options_credentials_file(client_class, transport_class, transport_name, grpc_helpers): - # 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, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file="credentials.json", - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - -def test_intents_client_client_options_from_dict(): - with mock.patch('google.cloud.dialogflow_v2beta1.services.intents.transports.IntentsGrpcTransport.__init__') as grpc_transport: - grpc_transport.return_value = None - client = IntentsClient( - client_options={'api_endpoint': 'squid.clam.whelk'} - ) - grpc_transport.assert_called_once_with( - credentials=None, - credentials_file=None, - host="squid.clam.whelk", - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - -@pytest.mark.parametrize("client_class,transport_class,transport_name,grpc_helpers", [ - (IntentsClient, transports.IntentsGrpcTransport, "grpc", grpc_helpers), - (IntentsAsyncClient, transports.IntentsGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), -]) -def test_intents_client_create_channel_credentials_file(client_class, transport_class, transport_name, grpc_helpers): - # 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, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file="credentials.json", - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # test that the credentials from file are saved and used as the credentials. - with mock.patch.object( - google.auth, "load_credentials_from_file", autospec=True - ) as load_creds, mock.patch.object( - google.auth, "default", autospec=True - ) as adc, mock.patch.object( - grpc_helpers, "create_channel" - ) as create_channel: - creds = ga_credentials.AnonymousCredentials() - file_creds = ga_credentials.AnonymousCredentials() - load_creds.return_value = (file_creds, None) - adc.return_value = (creds, None) - client = client_class(client_options=options, transport=transport_name) - create_channel.assert_called_with( - "dialogflow.googleapis.com:443", - credentials=file_creds, - credentials_file=None, - quota_project_id=None, - default_scopes=( - 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/dialogflow', -), - scopes=None, - default_host="dialogflow.googleapis.com", - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - -@pytest.mark.parametrize("request_type", [ - intent.ListIntentsRequest, - dict, -]) -def test_list_intents(request_type, transport: str = 'grpc'): - client = IntentsClient( - 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_intents), - '__call__') as call: - # Designate an appropriate return value for the call. - 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' - - -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=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_intents), - '__call__') as call: - client.list_intents() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == intent.ListIntentsRequest() - -@pytest.mark.asyncio -async def test_list_intents_async(transport: str = 'grpc_asyncio', request_type=intent.ListIntentsRequest): - client = IntentsAsyncClient( - 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_intents), - '__call__') as call: - # Designate an appropriate return value for the call. - 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' - - -@pytest.mark.asyncio -async def test_list_intents_async_from_dict(): - await test_list_intents_async(request_type=dict) - - -def test_list_intents_field_headers(): - 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. - 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_intents_field_headers_async(): - 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. - with mock.patch.object( - type(client.transport.list_intents), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(intent.ListIntentsResponse()) - 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] == 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_intents_flattened(): - client = IntentsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_intents), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = intent.ListIntentsResponse() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.list_intents( - parent='parent_value', - language_code='language_code_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] - arg = args[0].parent - mock_val = 'parent_value' - assert arg == mock_val - arg = args[0].language_code - mock_val = 'language_code_value' - assert arg == mock_val - - -def test_list_intents_flattened_error(): - client = IntentsClient( - 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_intents( - intent.ListIntentsRequest(), - parent='parent_value', - language_code='language_code_value', - ) - -@pytest.mark.asyncio -async def test_list_intents_flattened_async(): - 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: - # Designate an appropriate return value for the call. - call.return_value = intent.ListIntentsResponse() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(intent.ListIntentsResponse()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.list_intents( - parent='parent_value', - language_code='language_code_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - arg = args[0].parent - mock_val = 'parent_value' - assert arg == mock_val - arg = args[0].language_code - mock_val = 'language_code_value' - assert arg == mock_val - -@pytest.mark.asyncio -async def test_list_intents_flattened_error_async(): - client = IntentsAsyncClient( - 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_intents( - intent.ListIntentsRequest(), - parent='parent_value', - language_code='language_code_value', - ) - - -def test_list_intents_pager(transport_name: str = "grpc"): - client = IntentsClient( - credentials=ga_credentials.AnonymousCredentials, - transport=transport_name, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_intents), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - intent.ListIntentsResponse( - intents=[ - intent.Intent(), - intent.Intent(), - intent.Intent(), - ], - next_page_token='abc', - ), - intent.ListIntentsResponse( - intents=[], - next_page_token='def', - ), - intent.ListIntentsResponse( - intents=[ - intent.Intent(), - ], - next_page_token='ghi', - ), - intent.ListIntentsResponse( - intents=[ - intent.Intent(), - intent.Intent(), - ], - ), - RuntimeError, - ) - - metadata = () - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ('parent', ''), - )), - ) - pager = client.list_intents(request={}) - - assert pager._metadata == metadata - - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, intent.Intent) - for i in results) -def test_list_intents_pages(transport_name: str = "grpc"): - client = IntentsClient( - credentials=ga_credentials.AnonymousCredentials, - transport=transport_name, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_intents), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - intent.ListIntentsResponse( - intents=[ - intent.Intent(), - intent.Intent(), - intent.Intent(), - ], - next_page_token='abc', - ), - intent.ListIntentsResponse( - intents=[], - next_page_token='def', - ), - intent.ListIntentsResponse( - intents=[ - intent.Intent(), - ], - next_page_token='ghi', - ), - intent.ListIntentsResponse( - intents=[ - intent.Intent(), - intent.Intent(), - ], - ), - RuntimeError, - ) - pages = list(client.list_intents(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_intents_async_pager(): - 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__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - intent.ListIntentsResponse( - intents=[ - intent.Intent(), - intent.Intent(), - intent.Intent(), - ], - next_page_token='abc', - ), - intent.ListIntentsResponse( - intents=[], - next_page_token='def', - ), - intent.ListIntentsResponse( - intents=[ - intent.Intent(), - ], - next_page_token='ghi', - ), - intent.ListIntentsResponse( - intents=[ - intent.Intent(), - intent.Intent(), - ], - ), - RuntimeError, - ) - async_pager = await client.list_intents(request={},) - assert async_pager.next_page_token == 'abc' - responses = [] - async for response in async_pager: # pragma: no branch - responses.append(response) - - assert len(responses) == 6 - assert all(isinstance(i, intent.Intent) - for i in responses) - - -@pytest.mark.asyncio -async def test_list_intents_async_pages(): - 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__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - intent.ListIntentsResponse( - intents=[ - intent.Intent(), - intent.Intent(), - intent.Intent(), - ], - next_page_token='abc', - ), - intent.ListIntentsResponse( - intents=[], - next_page_token='def', - ), - intent.ListIntentsResponse( - intents=[ - intent.Intent(), - ], - next_page_token='ghi', - ), - intent.ListIntentsResponse( - intents=[ - intent.Intent(), - intent.Intent(), - ], - ), - RuntimeError, - ) - pages = [] - async for page_ in (await client.list_intents(request={})).pages: # pragma: no branch - pages.append(page_) - for page_, token in zip(pages, ['abc','def','ghi', '']): - assert page_.raw_page.next_page_token == token - -@pytest.mark.parametrize("request_type", [ - intent.GetIntentRequest, - dict, -]) -def test_get_intent(request_type, transport: str = 'grpc'): - client = IntentsClient( - 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_intent), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = intent.Intent( - name='name_value', - display_name='display_name_value', - webhook_state=intent.Intent.WebhookState.WEBHOOK_STATE_ENABLED, - priority=898, - is_fallback=True, - ml_enabled=True, - ml_disabled=True, - live_agent_handoff=True, - end_interaction=True, - input_context_names=['input_context_names_value'], - events=['events_value'], - action='action_value', - reset_contexts=True, - default_response_platforms=[intent.Intent.Message.Platform.FACEBOOK], - 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' - - -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=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_intent), - '__call__') as call: - client.get_intent() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == intent.GetIntentRequest() - -@pytest.mark.asyncio -async def test_get_intent_async(transport: str = 'grpc_asyncio', request_type=intent.GetIntentRequest): - client = IntentsAsyncClient( - 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_intent), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(intent.Intent( - name='name_value', - display_name='display_name_value', - webhook_state=intent.Intent.WebhookState.WEBHOOK_STATE_ENABLED, - priority=898, - is_fallback=True, - ml_enabled=True, - ml_disabled=True, - live_agent_handoff=True, - end_interaction=True, - input_context_names=['input_context_names_value'], - events=['events_value'], - action='action_value', - reset_contexts=True, - default_response_platforms=[intent.Intent.Message.Platform.FACEBOOK], - root_followup_intent_name='root_followup_intent_name_value', - 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' - - -@pytest.mark.asyncio -async def test_get_intent_async_from_dict(): - await test_get_intent_async(request_type=dict) - - -def test_get_intent_field_headers(): - 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. - 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_intent_field_headers_async(): - 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. - 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_intent_flattened(): - client = IntentsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_intent), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = intent.Intent() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.get_intent( - name='name_value', - language_code='language_code_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] - arg = args[0].name - mock_val = 'name_value' - assert arg == mock_val - arg = args[0].language_code - mock_val = 'language_code_value' - assert arg == mock_val - - -def test_get_intent_flattened_error(): - client = IntentsClient( - 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_intent( - intent.GetIntentRequest(), - name='name_value', - language_code='language_code_value', - ) - -@pytest.mark.asyncio -async def test_get_intent_flattened_async(): - 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: - # Designate an appropriate return value for the call. - call.return_value = intent.Intent() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(intent.Intent()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.get_intent( - name='name_value', - language_code='language_code_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - arg = args[0].name - mock_val = 'name_value' - assert arg == mock_val - arg = args[0].language_code - mock_val = 'language_code_value' - assert arg == mock_val - -@pytest.mark.asyncio -async def test_get_intent_flattened_error_async(): - client = IntentsAsyncClient( - 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_intent( - intent.GetIntentRequest(), - name='name_value', - language_code='language_code_value', - ) - - -@pytest.mark.parametrize("request_type", [ - gcd_intent.CreateIntentRequest, - dict, -]) -def test_create_intent(request_type, transport: str = 'grpc'): - client = IntentsClient( - 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_intent), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcd_intent.Intent( - name='name_value', - display_name='display_name_value', - webhook_state=gcd_intent.Intent.WebhookState.WEBHOOK_STATE_ENABLED, - priority=898, - is_fallback=True, - ml_enabled=True, - ml_disabled=True, - live_agent_handoff=True, - end_interaction=True, - input_context_names=['input_context_names_value'], - events=['events_value'], - action='action_value', - reset_contexts=True, - default_response_platforms=[gcd_intent.Intent.Message.Platform.FACEBOOK], - 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' - - -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=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_intent), - '__call__') as call: - client.create_intent() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == gcd_intent.CreateIntentRequest() - -@pytest.mark.asyncio -async def test_create_intent_async(transport: str = 'grpc_asyncio', request_type=gcd_intent.CreateIntentRequest): - client = IntentsAsyncClient( - 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_intent), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gcd_intent.Intent( - name='name_value', - display_name='display_name_value', - webhook_state=gcd_intent.Intent.WebhookState.WEBHOOK_STATE_ENABLED, - priority=898, - is_fallback=True, - ml_enabled=True, - ml_disabled=True, - live_agent_handoff=True, - end_interaction=True, - input_context_names=['input_context_names_value'], - events=['events_value'], - action='action_value', - reset_contexts=True, - default_response_platforms=[gcd_intent.Intent.Message.Platform.FACEBOOK], - root_followup_intent_name='root_followup_intent_name_value', - 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' - - -@pytest.mark.asyncio -async def test_create_intent_async_from_dict(): - await test_create_intent_async(request_type=dict) - - -def test_create_intent_field_headers(): - 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. - 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_intent_field_headers_async(): - 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. - 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_intent_flattened(): - 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( - parent='parent_value', - intent=gcd_intent.Intent(name='name_value'), - language_code='language_code_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] - arg = args[0].parent - mock_val = 'parent_value' - assert arg == mock_val - arg = args[0].intent - mock_val = gcd_intent.Intent(name='name_value') - assert arg == mock_val - arg = args[0].language_code - mock_val = 'language_code_value' - assert arg == mock_val - - -def test_create_intent_flattened_error(): - client = IntentsClient( - 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_intent( - gcd_intent.CreateIntentRequest(), - parent='parent_value', - intent=gcd_intent.Intent(name='name_value'), - language_code='language_code_value', - ) - -@pytest.mark.asyncio -async def test_create_intent_flattened_async(): - 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: - # Designate an appropriate return value for the call. - call.return_value = gcd_intent.Intent() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcd_intent.Intent()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.create_intent( - parent='parent_value', - intent=gcd_intent.Intent(name='name_value'), - language_code='language_code_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - arg = args[0].parent - mock_val = 'parent_value' - assert arg == mock_val - arg = args[0].intent - mock_val = gcd_intent.Intent(name='name_value') - assert arg == mock_val - arg = args[0].language_code - mock_val = 'language_code_value' - assert arg == mock_val - -@pytest.mark.asyncio -async def test_create_intent_flattened_error_async(): - client = IntentsAsyncClient( - 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_intent( - gcd_intent.CreateIntentRequest(), - parent='parent_value', - intent=gcd_intent.Intent(name='name_value'), - language_code='language_code_value', - ) - - -@pytest.mark.parametrize("request_type", [ - gcd_intent.UpdateIntentRequest, - dict, -]) -def test_update_intent(request_type, transport: str = 'grpc'): - client = IntentsClient( - 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_intent), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcd_intent.Intent( - name='name_value', - display_name='display_name_value', - webhook_state=gcd_intent.Intent.WebhookState.WEBHOOK_STATE_ENABLED, - priority=898, - is_fallback=True, - ml_enabled=True, - ml_disabled=True, - live_agent_handoff=True, - end_interaction=True, - input_context_names=['input_context_names_value'], - events=['events_value'], - action='action_value', - reset_contexts=True, - default_response_platforms=[gcd_intent.Intent.Message.Platform.FACEBOOK], - 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' - - -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=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_intent), - '__call__') as call: - client.update_intent() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == gcd_intent.UpdateIntentRequest() - -@pytest.mark.asyncio -async def test_update_intent_async(transport: str = 'grpc_asyncio', request_type=gcd_intent.UpdateIntentRequest): - client = IntentsAsyncClient( - 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_intent), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gcd_intent.Intent( - name='name_value', - display_name='display_name_value', - webhook_state=gcd_intent.Intent.WebhookState.WEBHOOK_STATE_ENABLED, - priority=898, - is_fallback=True, - ml_enabled=True, - ml_disabled=True, - live_agent_handoff=True, - end_interaction=True, - input_context_names=['input_context_names_value'], - events=['events_value'], - action='action_value', - reset_contexts=True, - default_response_platforms=[gcd_intent.Intent.Message.Platform.FACEBOOK], - root_followup_intent_name='root_followup_intent_name_value', - 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' - - -@pytest.mark.asyncio -async def test_update_intent_async_from_dict(): - await test_update_intent_async(request_type=dict) - - -def test_update_intent_field_headers(): - 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 = '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. - 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', - 'intent.name=name_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_update_intent_field_headers_async(): - 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 = '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. - 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', - 'intent.name=name_value', - ) in kw['metadata'] - - -def test_update_intent_flattened(): - 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_pb2.FieldMask(paths=['paths_value']), - language_code='language_code_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] - arg = args[0].intent - mock_val = gcd_intent.Intent(name='name_value') - assert arg == mock_val - arg = args[0].update_mask - mock_val = field_mask_pb2.FieldMask(paths=['paths_value']) - assert arg == mock_val - arg = args[0].language_code - mock_val = 'language_code_value' - assert arg == mock_val - - -def test_update_intent_flattened_error(): - client = IntentsClient( - 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_intent( - gcd_intent.UpdateIntentRequest(), - intent=gcd_intent.Intent(name='name_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=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.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcd_intent.Intent()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.update_intent( - intent=gcd_intent.Intent(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - language_code='language_code_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - arg = args[0].intent - mock_val = gcd_intent.Intent(name='name_value') - assert arg == mock_val - arg = args[0].update_mask - mock_val = field_mask_pb2.FieldMask(paths=['paths_value']) - assert arg == mock_val - arg = args[0].language_code - mock_val = 'language_code_value' - assert arg == mock_val - -@pytest.mark.asyncio -async def test_update_intent_flattened_error_async(): - client = IntentsAsyncClient( - 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_intent( - gcd_intent.UpdateIntentRequest(), - intent=gcd_intent.Intent(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - language_code='language_code_value', - ) - - -@pytest.mark.parametrize("request_type", [ - intent.DeleteIntentRequest, - dict, -]) -def test_delete_intent(request_type, transport: str = 'grpc'): - client = IntentsClient( - 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_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. - assert response is None - - -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=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_intent), - '__call__') as call: - client.delete_intent() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == intent.DeleteIntentRequest() - -@pytest.mark.asyncio -async def test_delete_intent_async(transport: str = 'grpc_asyncio', request_type=intent.DeleteIntentRequest): - client = IntentsAsyncClient( - 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_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. - assert response is None - - -@pytest.mark.asyncio -async def test_delete_intent_async_from_dict(): - await test_delete_intent_async(request_type=dict) - - -def test_delete_intent_field_headers(): - 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. - 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_intent_field_headers_async(): - 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. - 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_intent_flattened(): - 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', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - arg = args[0].name - mock_val = 'name_value' - assert arg == mock_val - - -def test_delete_intent_flattened_error(): - client = IntentsClient( - 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_intent( - intent.DeleteIntentRequest(), - name='name_value', - ) - -@pytest.mark.asyncio -async def test_delete_intent_flattened_async(): - 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: - # 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_intent( - 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] - arg = args[0].name - mock_val = 'name_value' - assert arg == mock_val - -@pytest.mark.asyncio -async def test_delete_intent_flattened_error_async(): - client = IntentsAsyncClient( - 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_intent( - intent.DeleteIntentRequest(), - name='name_value', - ) - - -@pytest.mark.parametrize("request_type", [ - intent.BatchUpdateIntentsRequest, - dict, -]) -def test_batch_update_intents(request_type, transport: str = 'grpc'): - client = IntentsClient( - 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.batch_update_intents), - '__call__') 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. - assert isinstance(response, future.Future) - - -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=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.batch_update_intents), - '__call__') as call: - client.batch_update_intents() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == intent.BatchUpdateIntentsRequest() - -@pytest.mark.asyncio -async def test_batch_update_intents_async(transport: str = 'grpc_asyncio', request_type=intent.BatchUpdateIntentsRequest): - client = IntentsAsyncClient( - 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.batch_update_intents), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name='operations/spam') - ) - response = await client.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. - assert isinstance(response, future.Future) - - -@pytest.mark.asyncio -async def test_batch_update_intents_async_from_dict(): - await test_batch_update_intents_async(request_type=dict) - - -def test_batch_update_intents_field_headers(): - 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. - with mock.patch.object( - 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. - 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_batch_update_intents_field_headers_async(): - 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. - with mock.patch.object( - type(client.transport.batch_update_intents), - '__call__') as call: - 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. - 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_batch_update_intents_flattened(): - 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.batch_update_intents), - '__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.batch_update_intents( - parent='parent_value', - intent_batch_uri='intent_batch_uri_value', - intent_batch_inline=intent.IntentBatch(intents=[intent.Intent(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] - arg = args[0].parent - mock_val = 'parent_value' - assert arg == mock_val - assert args[0].intent_batch_inline == intent.IntentBatch(intents=[intent.Intent(name='name_value')]) - - -def test_batch_update_intents_flattened_error(): - client = IntentsClient( - 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.batch_update_intents( - intent.BatchUpdateIntentsRequest(), - parent='parent_value', - intent_batch_uri='intent_batch_uri_value', - intent_batch_inline=intent.IntentBatch(intents=[intent.Intent(name='name_value')]), - ) - -@pytest.mark.asyncio -async def test_batch_update_intents_flattened_async(): - 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.batch_update_intents), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/op') - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name='operations/spam') - ) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.batch_update_intents( - parent='parent_value', - intent_batch_uri='intent_batch_uri_value', - intent_batch_inline=intent.IntentBatch(intents=[intent.Intent(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] - arg = args[0].parent - mock_val = 'parent_value' - assert arg == mock_val - assert args[0].intent_batch_inline == intent.IntentBatch(intents=[intent.Intent(name='name_value')]) - -@pytest.mark.asyncio -async def test_batch_update_intents_flattened_error_async(): - client = IntentsAsyncClient( - 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.batch_update_intents( - intent.BatchUpdateIntentsRequest(), - parent='parent_value', - intent_batch_uri='intent_batch_uri_value', - intent_batch_inline=intent.IntentBatch(intents=[intent.Intent(name='name_value')]), - ) - - -@pytest.mark.parametrize("request_type", [ - intent.BatchDeleteIntentsRequest, - dict, -]) -def test_batch_delete_intents(request_type, transport: str = 'grpc'): - client = IntentsClient( - 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.batch_delete_intents), - '__call__') 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. - assert isinstance(response, future.Future) - - -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=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.batch_delete_intents), - '__call__') as call: - client.batch_delete_intents() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == intent.BatchDeleteIntentsRequest() - -@pytest.mark.asyncio -async def test_batch_delete_intents_async(transport: str = 'grpc_asyncio', request_type=intent.BatchDeleteIntentsRequest): - client = IntentsAsyncClient( - 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.batch_delete_intents), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name='operations/spam') - ) - response = await client.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. - assert isinstance(response, future.Future) - - -@pytest.mark.asyncio -async def test_batch_delete_intents_async_from_dict(): - await test_batch_delete_intents_async(request_type=dict) - - -def test_batch_delete_intents_field_headers(): - 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. - with mock.patch.object( - 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. - 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_batch_delete_intents_field_headers_async(): - 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. - with mock.patch.object( - type(client.transport.batch_delete_intents), - '__call__') as call: - 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. - 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_batch_delete_intents_flattened(): - 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.batch_delete_intents), - '__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.batch_delete_intents( - parent='parent_value', - intents=[intent.Intent(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] - arg = args[0].parent - mock_val = 'parent_value' - assert arg == mock_val - arg = args[0].intents - mock_val = [intent.Intent(name='name_value')] - assert arg == mock_val - - -def test_batch_delete_intents_flattened_error(): - client = IntentsClient( - 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.batch_delete_intents( - intent.BatchDeleteIntentsRequest(), - parent='parent_value', - intents=[intent.Intent(name='name_value')], - ) - -@pytest.mark.asyncio -async def test_batch_delete_intents_flattened_async(): - 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.batch_delete_intents), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/op') - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name='operations/spam') - ) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.batch_delete_intents( - parent='parent_value', - intents=[intent.Intent(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] - arg = args[0].parent - mock_val = 'parent_value' - assert arg == mock_val - arg = args[0].intents - mock_val = [intent.Intent(name='name_value')] - assert arg == mock_val - -@pytest.mark.asyncio -async def test_batch_delete_intents_flattened_error_async(): - client = IntentsAsyncClient( - 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.batch_delete_intents( - intent.BatchDeleteIntentsRequest(), - parent='parent_value', - intents=[intent.Intent(name='name_value')], - ) - - -@pytest.mark.parametrize("request_type", [ - intent.ListIntentsRequest, - dict, -]) -def test_list_intents_rest(request_type): - client = IntentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1/agent'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = intent.ListIntentsResponse( - next_page_token='next_page_token_value', - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - pb_return_value = intent.ListIntentsResponse.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.list_intents(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListIntentsPager) - assert response.next_page_token == 'next_page_token_value' - - -def test_list_intents_rest_required_fields(request_type=intent.ListIntentsRequest): - transport_class = transports.IntentsRestTransport - - request_init = {} - request_init["parent"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - including_default_value_fields=False, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).list_intents._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["parent"] = 'parent_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).list_intents._get_unset_required_fields(jsonified_request) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("intent_view", "language_code", "page_size", "page_token", )) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "parent" in jsonified_request - assert jsonified_request["parent"] == 'parent_value' - - client = IntentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = intent.ListIntentsResponse() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "get", - 'query_params': pb_request, - } - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - - pb_return_value = intent.ListIntentsResponse.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.list_intents(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_list_intents_rest_unset_required_fields(): - transport = transports.IntentsRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.list_intents._get_unset_required_fields({}) - assert set(unset_fields) == (set(("intentView", "languageCode", "pageSize", "pageToken", )) & set(("parent", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_list_intents_rest_interceptors(null_interceptor): - transport = transports.IntentsRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.IntentsRestInterceptor(), - ) - client = IntentsClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.IntentsRestInterceptor, "post_list_intents") as post, \ - mock.patch.object(transports.IntentsRestInterceptor, "pre_list_intents") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = intent.ListIntentsRequest.pb(intent.ListIntentsRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = intent.ListIntentsResponse.to_json(intent.ListIntentsResponse()) - - request = intent.ListIntentsRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = intent.ListIntentsResponse() - - client.list_intents(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_list_intents_rest_bad_request(transport: str = 'rest', request_type=intent.ListIntentsRequest): - client = IntentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1/agent'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.list_intents(request) - - -def test_list_intents_rest_flattened(): - client = IntentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = intent.ListIntentsResponse() - - # get arguments that satisfy an http rule for this method - sample_request = {'parent': 'projects/sample1/agent'} - - # get truthy value for each flattened field - mock_args = dict( - parent='parent_value', - language_code='language_code_value', - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - pb_return_value = intent.ListIntentsResponse.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.list_intents(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v2beta1/{parent=projects/*/agent}/intents" % client.transport._host, args[1]) - - -def test_list_intents_rest_flattened_error(transport: str = 'rest'): - client = IntentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.list_intents( - intent.ListIntentsRequest(), - parent='parent_value', - language_code='language_code_value', - ) - - -def test_list_intents_rest_pager(transport: str = 'rest'): - client = IntentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # TODO(kbandes): remove this mock unless there's a good reason for it. - #with mock.patch.object(path_template, 'transcode') as transcode: - # Set the response as a series of pages - response = ( - intent.ListIntentsResponse( - intents=[ - intent.Intent(), - intent.Intent(), - intent.Intent(), - ], - next_page_token='abc', - ), - intent.ListIntentsResponse( - intents=[], - next_page_token='def', - ), - intent.ListIntentsResponse( - intents=[ - intent.Intent(), - ], - next_page_token='ghi', - ), - intent.ListIntentsResponse( - intents=[ - intent.Intent(), - intent.Intent(), - ], - ), - ) - # Two responses for two calls - response = response + response - - # Wrap the values into proper Response objs - response = tuple(intent.ListIntentsResponse.to_json(x) for x in response) - return_values = tuple(Response() for i in response) - for return_val, response_val in zip(return_values, response): - return_val._content = response_val.encode('UTF-8') - return_val.status_code = 200 - req.side_effect = return_values - - sample_request = {'parent': 'projects/sample1/agent'} - - pager = client.list_intents(request=sample_request) - - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, intent.Intent) - for i in results) - - pages = list(client.list_intents(request=sample_request).pages) - for page_, token in zip(pages, ['abc','def','ghi', '']): - assert page_.raw_page.next_page_token == token - - -@pytest.mark.parametrize("request_type", [ - intent.GetIntentRequest, - dict, -]) -def test_get_intent_rest(request_type): - client = IntentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/agent/intents/sample2'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = intent.Intent( - name='name_value', - display_name='display_name_value', - webhook_state=intent.Intent.WebhookState.WEBHOOK_STATE_ENABLED, - priority=898, - is_fallback=True, - ml_enabled=True, - ml_disabled=True, - live_agent_handoff=True, - end_interaction=True, - input_context_names=['input_context_names_value'], - events=['events_value'], - action='action_value', - reset_contexts=True, - default_response_platforms=[intent.Intent.Message.Platform.FACEBOOK], - root_followup_intent_name='root_followup_intent_name_value', - parent_followup_intent_name='parent_followup_intent_name_value', - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - pb_return_value = intent.Intent.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.get_intent(request) - - # 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' - - -def test_get_intent_rest_required_fields(request_type=intent.GetIntentRequest): - transport_class = transports.IntentsRestTransport - - request_init = {} - request_init["name"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - including_default_value_fields=False, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_intent._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["name"] = 'name_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_intent._get_unset_required_fields(jsonified_request) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("intent_view", "language_code", )) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "name" in jsonified_request - assert jsonified_request["name"] == 'name_value' - - client = IntentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = intent.Intent() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "get", - 'query_params': pb_request, - } - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - - pb_return_value = intent.Intent.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.get_intent(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_get_intent_rest_unset_required_fields(): - transport = transports.IntentsRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.get_intent._get_unset_required_fields({}) - assert set(unset_fields) == (set(("intentView", "languageCode", )) & set(("name", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_get_intent_rest_interceptors(null_interceptor): - transport = transports.IntentsRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.IntentsRestInterceptor(), - ) - client = IntentsClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.IntentsRestInterceptor, "post_get_intent") as post, \ - mock.patch.object(transports.IntentsRestInterceptor, "pre_get_intent") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = intent.GetIntentRequest.pb(intent.GetIntentRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = intent.Intent.to_json(intent.Intent()) - - request = intent.GetIntentRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = intent.Intent() - - client.get_intent(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_get_intent_rest_bad_request(transport: str = 'rest', request_type=intent.GetIntentRequest): - client = IntentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/agent/intents/sample2'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.get_intent(request) - - -def test_get_intent_rest_flattened(): - client = IntentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = intent.Intent() - - # get arguments that satisfy an http rule for this method - sample_request = {'name': 'projects/sample1/agent/intents/sample2'} - - # get truthy value for each flattened field - mock_args = dict( - name='name_value', - language_code='language_code_value', - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - pb_return_value = intent.Intent.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.get_intent(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v2beta1/{name=projects/*/agent/intents/*}" % client.transport._host, args[1]) - - -def test_get_intent_rest_flattened_error(transport: str = 'rest'): - client = IntentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.get_intent( - intent.GetIntentRequest(), - name='name_value', - language_code='language_code_value', - ) - - -def test_get_intent_rest_error(): - client = IntentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - gcd_intent.CreateIntentRequest, - dict, -]) -def test_create_intent_rest(request_type): - client = IntentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1/agent'} - request_init["intent"] = {'name': 'name_value', 'display_name': 'display_name_value', 'webhook_state': 1, 'priority': 898, 'is_fallback': True, 'ml_enabled': True, 'ml_disabled': True, 'live_agent_handoff': True, 'end_interaction': True, 'input_context_names': ['input_context_names_value1', 'input_context_names_value2'], 'events': ['events_value1', 'events_value2'], 'training_phrases': [{'name': 'name_value', 'type_': 1, 'parts': [{'text': 'text_value', 'entity_type': 'entity_type_value', 'alias': 'alias_value', 'user_defined': True}], 'times_added_count': 1787}], 'action': 'action_value', 'output_contexts': [{'name': 'name_value', 'lifespan_count': 1498, 'parameters': {'fields': {}}}], 'reset_contexts': True, 'parameters': [{'name': 'name_value', 'display_name': 'display_name_value', 'value': 'value_value', 'default_value': 'default_value_value', 'entity_type_display_name': 'entity_type_display_name_value', 'mandatory': True, 'prompts': ['prompts_value1', 'prompts_value2'], 'is_list': True}], 'messages': [{'text': {'text': ['text_value1', 'text_value2']}, 'image': {'image_uri': 'image_uri_value', 'accessibility_text': 'accessibility_text_value'}, 'quick_replies': {'title': 'title_value', 'quick_replies': ['quick_replies_value1', 'quick_replies_value2']}, 'card': {'title': 'title_value', 'subtitle': 'subtitle_value', 'image_uri': 'image_uri_value', 'buttons': [{'text': 'text_value', 'postback': 'postback_value'}]}, 'payload': {}, 'simple_responses': {'simple_responses': [{'text_to_speech': 'text_to_speech_value', 'ssml': 'ssml_value', 'display_text': 'display_text_value'}]}, 'basic_card': {'title': 'title_value', 'subtitle': 'subtitle_value', 'formatted_text': 'formatted_text_value', 'image': {}, 'buttons': [{'title': 'title_value', 'open_uri_action': {'uri': 'uri_value'}}]}, 'suggestions': {'suggestions': [{'title': 'title_value'}]}, 'link_out_suggestion': {'destination_name': 'destination_name_value', 'uri': 'uri_value'}, 'list_select': {'title': 'title_value', 'items': [{'info': {'key': 'key_value', 'synonyms': ['synonyms_value1', 'synonyms_value2']}, 'title': 'title_value', 'description': 'description_value', 'image': {}}], 'subtitle': 'subtitle_value'}, 'carousel_select': {'items': [{'info': {}, 'title': 'title_value', 'description': 'description_value', 'image': {}}]}, 'telephony_play_audio': {'audio_uri': 'audio_uri_value'}, 'telephony_synthesize_speech': {'text': 'text_value', 'ssml': 'ssml_value'}, 'telephony_transfer_call': {'phone_number': 'phone_number_value'}, 'rbm_text': {'text': 'text_value', 'rbm_suggestion': [{'reply': {'text': 'text_value', 'postback_data': 'postback_data_value'}, 'action': {'text': 'text_value', 'postback_data': 'postback_data_value', 'dial': {'phone_number': 'phone_number_value'}, 'open_url': {'uri': 'uri_value'}, 'share_location': {}}}]}, 'rbm_standalone_rich_card': {'card_orientation': 1, 'thumbnail_image_alignment': 1, 'card_content': {'title': 'title_value', 'description': 'description_value', 'media': {'file_uri': 'file_uri_value', 'thumbnail_uri': 'thumbnail_uri_value', 'height': 1}, 'suggestions': {}}}, 'rbm_carousel_rich_card': {'card_width': 1, 'card_contents': {}}, 'browse_carousel_card': {'items': [{'open_uri_action': {'url': 'url_value', 'url_type_hint': 1}, 'title': 'title_value', 'description': 'description_value', 'image': {}, 'footer': 'footer_value'}], 'image_display_options': 1}, 'table_card': {'title': 'title_value', 'subtitle': 'subtitle_value', 'image': {}, 'column_properties': [{'header': 'header_value', 'horizontal_alignment': 1}], 'rows': [{'cells': [{'text': 'text_value'}], 'divider_after': True}], 'buttons': {}}, 'media_content': {'media_type': 1, 'media_objects': [{'name': 'name_value', 'description': 'description_value', 'large_image': {}, 'icon': {}, 'content_url': 'content_url_value'}]}, 'platform': 1}], 'default_response_platforms': [1], 'root_followup_intent_name': 'root_followup_intent_name_value', 'parent_followup_intent_name': 'parent_followup_intent_name_value', 'followup_intent_info': [{'followup_intent_name': 'followup_intent_name_value', 'parent_followup_intent_name': 'parent_followup_intent_name_value'}]} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = gcd_intent.Intent( - name='name_value', - display_name='display_name_value', - webhook_state=gcd_intent.Intent.WebhookState.WEBHOOK_STATE_ENABLED, - priority=898, - is_fallback=True, - ml_enabled=True, - ml_disabled=True, - live_agent_handoff=True, - end_interaction=True, - input_context_names=['input_context_names_value'], - events=['events_value'], - action='action_value', - reset_contexts=True, - default_response_platforms=[gcd_intent.Intent.Message.Platform.FACEBOOK], - root_followup_intent_name='root_followup_intent_name_value', - parent_followup_intent_name='parent_followup_intent_name_value', - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - pb_return_value = gcd_intent.Intent.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.create_intent(request) - - # 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' - - -def test_create_intent_rest_required_fields(request_type=gcd_intent.CreateIntentRequest): - transport_class = transports.IntentsRestTransport - - request_init = {} - request_init["parent"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - including_default_value_fields=False, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_intent._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["parent"] = 'parent_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_intent._get_unset_required_fields(jsonified_request) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("intent_view", "language_code", )) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "parent" in jsonified_request - assert jsonified_request["parent"] == 'parent_value' - - client = IntentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = gcd_intent.Intent() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "post", - 'query_params': pb_request, - } - transcode_result['body'] = pb_request - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - - pb_return_value = gcd_intent.Intent.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.create_intent(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_create_intent_rest_unset_required_fields(): - transport = transports.IntentsRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.create_intent._get_unset_required_fields({}) - assert set(unset_fields) == (set(("intentView", "languageCode", )) & set(("parent", "intent", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_create_intent_rest_interceptors(null_interceptor): - transport = transports.IntentsRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.IntentsRestInterceptor(), - ) - client = IntentsClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.IntentsRestInterceptor, "post_create_intent") as post, \ - mock.patch.object(transports.IntentsRestInterceptor, "pre_create_intent") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = gcd_intent.CreateIntentRequest.pb(gcd_intent.CreateIntentRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = gcd_intent.Intent.to_json(gcd_intent.Intent()) - - request = gcd_intent.CreateIntentRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = gcd_intent.Intent() - - client.create_intent(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_create_intent_rest_bad_request(transport: str = 'rest', request_type=gcd_intent.CreateIntentRequest): - client = IntentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1/agent'} - request_init["intent"] = {'name': 'name_value', 'display_name': 'display_name_value', 'webhook_state': 1, 'priority': 898, 'is_fallback': True, 'ml_enabled': True, 'ml_disabled': True, 'live_agent_handoff': True, 'end_interaction': True, 'input_context_names': ['input_context_names_value1', 'input_context_names_value2'], 'events': ['events_value1', 'events_value2'], 'training_phrases': [{'name': 'name_value', 'type_': 1, 'parts': [{'text': 'text_value', 'entity_type': 'entity_type_value', 'alias': 'alias_value', 'user_defined': True}], 'times_added_count': 1787}], 'action': 'action_value', 'output_contexts': [{'name': 'name_value', 'lifespan_count': 1498, 'parameters': {'fields': {}}}], 'reset_contexts': True, 'parameters': [{'name': 'name_value', 'display_name': 'display_name_value', 'value': 'value_value', 'default_value': 'default_value_value', 'entity_type_display_name': 'entity_type_display_name_value', 'mandatory': True, 'prompts': ['prompts_value1', 'prompts_value2'], 'is_list': True}], 'messages': [{'text': {'text': ['text_value1', 'text_value2']}, 'image': {'image_uri': 'image_uri_value', 'accessibility_text': 'accessibility_text_value'}, 'quick_replies': {'title': 'title_value', 'quick_replies': ['quick_replies_value1', 'quick_replies_value2']}, 'card': {'title': 'title_value', 'subtitle': 'subtitle_value', 'image_uri': 'image_uri_value', 'buttons': [{'text': 'text_value', 'postback': 'postback_value'}]}, 'payload': {}, 'simple_responses': {'simple_responses': [{'text_to_speech': 'text_to_speech_value', 'ssml': 'ssml_value', 'display_text': 'display_text_value'}]}, 'basic_card': {'title': 'title_value', 'subtitle': 'subtitle_value', 'formatted_text': 'formatted_text_value', 'image': {}, 'buttons': [{'title': 'title_value', 'open_uri_action': {'uri': 'uri_value'}}]}, 'suggestions': {'suggestions': [{'title': 'title_value'}]}, 'link_out_suggestion': {'destination_name': 'destination_name_value', 'uri': 'uri_value'}, 'list_select': {'title': 'title_value', 'items': [{'info': {'key': 'key_value', 'synonyms': ['synonyms_value1', 'synonyms_value2']}, 'title': 'title_value', 'description': 'description_value', 'image': {}}], 'subtitle': 'subtitle_value'}, 'carousel_select': {'items': [{'info': {}, 'title': 'title_value', 'description': 'description_value', 'image': {}}]}, 'telephony_play_audio': {'audio_uri': 'audio_uri_value'}, 'telephony_synthesize_speech': {'text': 'text_value', 'ssml': 'ssml_value'}, 'telephony_transfer_call': {'phone_number': 'phone_number_value'}, 'rbm_text': {'text': 'text_value', 'rbm_suggestion': [{'reply': {'text': 'text_value', 'postback_data': 'postback_data_value'}, 'action': {'text': 'text_value', 'postback_data': 'postback_data_value', 'dial': {'phone_number': 'phone_number_value'}, 'open_url': {'uri': 'uri_value'}, 'share_location': {}}}]}, 'rbm_standalone_rich_card': {'card_orientation': 1, 'thumbnail_image_alignment': 1, 'card_content': {'title': 'title_value', 'description': 'description_value', 'media': {'file_uri': 'file_uri_value', 'thumbnail_uri': 'thumbnail_uri_value', 'height': 1}, 'suggestions': {}}}, 'rbm_carousel_rich_card': {'card_width': 1, 'card_contents': {}}, 'browse_carousel_card': {'items': [{'open_uri_action': {'url': 'url_value', 'url_type_hint': 1}, 'title': 'title_value', 'description': 'description_value', 'image': {}, 'footer': 'footer_value'}], 'image_display_options': 1}, 'table_card': {'title': 'title_value', 'subtitle': 'subtitle_value', 'image': {}, 'column_properties': [{'header': 'header_value', 'horizontal_alignment': 1}], 'rows': [{'cells': [{'text': 'text_value'}], 'divider_after': True}], 'buttons': {}}, 'media_content': {'media_type': 1, 'media_objects': [{'name': 'name_value', 'description': 'description_value', 'large_image': {}, 'icon': {}, 'content_url': 'content_url_value'}]}, 'platform': 1}], 'default_response_platforms': [1], 'root_followup_intent_name': 'root_followup_intent_name_value', 'parent_followup_intent_name': 'parent_followup_intent_name_value', 'followup_intent_info': [{'followup_intent_name': 'followup_intent_name_value', 'parent_followup_intent_name': 'parent_followup_intent_name_value'}]} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.create_intent(request) - - -def test_create_intent_rest_flattened(): - client = IntentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = gcd_intent.Intent() - - # get arguments that satisfy an http rule for this method - sample_request = {'parent': 'projects/sample1/agent'} - - # get truthy value for each flattened field - mock_args = dict( - parent='parent_value', - intent=gcd_intent.Intent(name='name_value'), - language_code='language_code_value', - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - pb_return_value = gcd_intent.Intent.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.create_intent(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v2beta1/{parent=projects/*/agent}/intents" % client.transport._host, args[1]) - - -def test_create_intent_rest_flattened_error(transport: str = 'rest'): - client = IntentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.create_intent( - gcd_intent.CreateIntentRequest(), - parent='parent_value', - intent=gcd_intent.Intent(name='name_value'), - language_code='language_code_value', - ) - - -def test_create_intent_rest_error(): - client = IntentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - gcd_intent.UpdateIntentRequest, - dict, -]) -def test_update_intent_rest(request_type): - client = IntentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'intent': {'name': 'projects/sample1/agent/intents/sample2'}} - request_init["intent"] = {'name': 'projects/sample1/agent/intents/sample2', 'display_name': 'display_name_value', 'webhook_state': 1, 'priority': 898, 'is_fallback': True, 'ml_enabled': True, 'ml_disabled': True, 'live_agent_handoff': True, 'end_interaction': True, 'input_context_names': ['input_context_names_value1', 'input_context_names_value2'], 'events': ['events_value1', 'events_value2'], 'training_phrases': [{'name': 'name_value', 'type_': 1, 'parts': [{'text': 'text_value', 'entity_type': 'entity_type_value', 'alias': 'alias_value', 'user_defined': True}], 'times_added_count': 1787}], 'action': 'action_value', 'output_contexts': [{'name': 'name_value', 'lifespan_count': 1498, 'parameters': {'fields': {}}}], 'reset_contexts': True, 'parameters': [{'name': 'name_value', 'display_name': 'display_name_value', 'value': 'value_value', 'default_value': 'default_value_value', 'entity_type_display_name': 'entity_type_display_name_value', 'mandatory': True, 'prompts': ['prompts_value1', 'prompts_value2'], 'is_list': True}], 'messages': [{'text': {'text': ['text_value1', 'text_value2']}, 'image': {'image_uri': 'image_uri_value', 'accessibility_text': 'accessibility_text_value'}, 'quick_replies': {'title': 'title_value', 'quick_replies': ['quick_replies_value1', 'quick_replies_value2']}, 'card': {'title': 'title_value', 'subtitle': 'subtitle_value', 'image_uri': 'image_uri_value', 'buttons': [{'text': 'text_value', 'postback': 'postback_value'}]}, 'payload': {}, 'simple_responses': {'simple_responses': [{'text_to_speech': 'text_to_speech_value', 'ssml': 'ssml_value', 'display_text': 'display_text_value'}]}, 'basic_card': {'title': 'title_value', 'subtitle': 'subtitle_value', 'formatted_text': 'formatted_text_value', 'image': {}, 'buttons': [{'title': 'title_value', 'open_uri_action': {'uri': 'uri_value'}}]}, 'suggestions': {'suggestions': [{'title': 'title_value'}]}, 'link_out_suggestion': {'destination_name': 'destination_name_value', 'uri': 'uri_value'}, 'list_select': {'title': 'title_value', 'items': [{'info': {'key': 'key_value', 'synonyms': ['synonyms_value1', 'synonyms_value2']}, 'title': 'title_value', 'description': 'description_value', 'image': {}}], 'subtitle': 'subtitle_value'}, 'carousel_select': {'items': [{'info': {}, 'title': 'title_value', 'description': 'description_value', 'image': {}}]}, 'telephony_play_audio': {'audio_uri': 'audio_uri_value'}, 'telephony_synthesize_speech': {'text': 'text_value', 'ssml': 'ssml_value'}, 'telephony_transfer_call': {'phone_number': 'phone_number_value'}, 'rbm_text': {'text': 'text_value', 'rbm_suggestion': [{'reply': {'text': 'text_value', 'postback_data': 'postback_data_value'}, 'action': {'text': 'text_value', 'postback_data': 'postback_data_value', 'dial': {'phone_number': 'phone_number_value'}, 'open_url': {'uri': 'uri_value'}, 'share_location': {}}}]}, 'rbm_standalone_rich_card': {'card_orientation': 1, 'thumbnail_image_alignment': 1, 'card_content': {'title': 'title_value', 'description': 'description_value', 'media': {'file_uri': 'file_uri_value', 'thumbnail_uri': 'thumbnail_uri_value', 'height': 1}, 'suggestions': {}}}, 'rbm_carousel_rich_card': {'card_width': 1, 'card_contents': {}}, 'browse_carousel_card': {'items': [{'open_uri_action': {'url': 'url_value', 'url_type_hint': 1}, 'title': 'title_value', 'description': 'description_value', 'image': {}, 'footer': 'footer_value'}], 'image_display_options': 1}, 'table_card': {'title': 'title_value', 'subtitle': 'subtitle_value', 'image': {}, 'column_properties': [{'header': 'header_value', 'horizontal_alignment': 1}], 'rows': [{'cells': [{'text': 'text_value'}], 'divider_after': True}], 'buttons': {}}, 'media_content': {'media_type': 1, 'media_objects': [{'name': 'name_value', 'description': 'description_value', 'large_image': {}, 'icon': {}, 'content_url': 'content_url_value'}]}, 'platform': 1}], 'default_response_platforms': [1], 'root_followup_intent_name': 'root_followup_intent_name_value', 'parent_followup_intent_name': 'parent_followup_intent_name_value', 'followup_intent_info': [{'followup_intent_name': 'followup_intent_name_value', 'parent_followup_intent_name': 'parent_followup_intent_name_value'}]} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = gcd_intent.Intent( - name='name_value', - display_name='display_name_value', - webhook_state=gcd_intent.Intent.WebhookState.WEBHOOK_STATE_ENABLED, - priority=898, - is_fallback=True, - ml_enabled=True, - ml_disabled=True, - live_agent_handoff=True, - end_interaction=True, - input_context_names=['input_context_names_value'], - events=['events_value'], - action='action_value', - reset_contexts=True, - default_response_platforms=[gcd_intent.Intent.Message.Platform.FACEBOOK], - root_followup_intent_name='root_followup_intent_name_value', - parent_followup_intent_name='parent_followup_intent_name_value', - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - pb_return_value = gcd_intent.Intent.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.update_intent(request) - - # 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' - - -def test_update_intent_rest_required_fields(request_type=gcd_intent.UpdateIntentRequest): - transport_class = transports.IntentsRestTransport - - request_init = {} - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - including_default_value_fields=False, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).update_intent._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).update_intent._get_unset_required_fields(jsonified_request) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("intent_view", "language_code", "update_mask", )) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - - client = IntentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = gcd_intent.Intent() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "patch", - 'query_params': pb_request, - } - transcode_result['body'] = pb_request - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - - pb_return_value = gcd_intent.Intent.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.update_intent(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_update_intent_rest_unset_required_fields(): - transport = transports.IntentsRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.update_intent._get_unset_required_fields({}) - assert set(unset_fields) == (set(("intentView", "languageCode", "updateMask", )) & set(("intent", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_update_intent_rest_interceptors(null_interceptor): - transport = transports.IntentsRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.IntentsRestInterceptor(), - ) - client = IntentsClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.IntentsRestInterceptor, "post_update_intent") as post, \ - mock.patch.object(transports.IntentsRestInterceptor, "pre_update_intent") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = gcd_intent.UpdateIntentRequest.pb(gcd_intent.UpdateIntentRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = gcd_intent.Intent.to_json(gcd_intent.Intent()) - - request = gcd_intent.UpdateIntentRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = gcd_intent.Intent() - - client.update_intent(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_update_intent_rest_bad_request(transport: str = 'rest', request_type=gcd_intent.UpdateIntentRequest): - client = IntentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'intent': {'name': 'projects/sample1/agent/intents/sample2'}} - request_init["intent"] = {'name': 'projects/sample1/agent/intents/sample2', 'display_name': 'display_name_value', 'webhook_state': 1, 'priority': 898, 'is_fallback': True, 'ml_enabled': True, 'ml_disabled': True, 'live_agent_handoff': True, 'end_interaction': True, 'input_context_names': ['input_context_names_value1', 'input_context_names_value2'], 'events': ['events_value1', 'events_value2'], 'training_phrases': [{'name': 'name_value', 'type_': 1, 'parts': [{'text': 'text_value', 'entity_type': 'entity_type_value', 'alias': 'alias_value', 'user_defined': True}], 'times_added_count': 1787}], 'action': 'action_value', 'output_contexts': [{'name': 'name_value', 'lifespan_count': 1498, 'parameters': {'fields': {}}}], 'reset_contexts': True, 'parameters': [{'name': 'name_value', 'display_name': 'display_name_value', 'value': 'value_value', 'default_value': 'default_value_value', 'entity_type_display_name': 'entity_type_display_name_value', 'mandatory': True, 'prompts': ['prompts_value1', 'prompts_value2'], 'is_list': True}], 'messages': [{'text': {'text': ['text_value1', 'text_value2']}, 'image': {'image_uri': 'image_uri_value', 'accessibility_text': 'accessibility_text_value'}, 'quick_replies': {'title': 'title_value', 'quick_replies': ['quick_replies_value1', 'quick_replies_value2']}, 'card': {'title': 'title_value', 'subtitle': 'subtitle_value', 'image_uri': 'image_uri_value', 'buttons': [{'text': 'text_value', 'postback': 'postback_value'}]}, 'payload': {}, 'simple_responses': {'simple_responses': [{'text_to_speech': 'text_to_speech_value', 'ssml': 'ssml_value', 'display_text': 'display_text_value'}]}, 'basic_card': {'title': 'title_value', 'subtitle': 'subtitle_value', 'formatted_text': 'formatted_text_value', 'image': {}, 'buttons': [{'title': 'title_value', 'open_uri_action': {'uri': 'uri_value'}}]}, 'suggestions': {'suggestions': [{'title': 'title_value'}]}, 'link_out_suggestion': {'destination_name': 'destination_name_value', 'uri': 'uri_value'}, 'list_select': {'title': 'title_value', 'items': [{'info': {'key': 'key_value', 'synonyms': ['synonyms_value1', 'synonyms_value2']}, 'title': 'title_value', 'description': 'description_value', 'image': {}}], 'subtitle': 'subtitle_value'}, 'carousel_select': {'items': [{'info': {}, 'title': 'title_value', 'description': 'description_value', 'image': {}}]}, 'telephony_play_audio': {'audio_uri': 'audio_uri_value'}, 'telephony_synthesize_speech': {'text': 'text_value', 'ssml': 'ssml_value'}, 'telephony_transfer_call': {'phone_number': 'phone_number_value'}, 'rbm_text': {'text': 'text_value', 'rbm_suggestion': [{'reply': {'text': 'text_value', 'postback_data': 'postback_data_value'}, 'action': {'text': 'text_value', 'postback_data': 'postback_data_value', 'dial': {'phone_number': 'phone_number_value'}, 'open_url': {'uri': 'uri_value'}, 'share_location': {}}}]}, 'rbm_standalone_rich_card': {'card_orientation': 1, 'thumbnail_image_alignment': 1, 'card_content': {'title': 'title_value', 'description': 'description_value', 'media': {'file_uri': 'file_uri_value', 'thumbnail_uri': 'thumbnail_uri_value', 'height': 1}, 'suggestions': {}}}, 'rbm_carousel_rich_card': {'card_width': 1, 'card_contents': {}}, 'browse_carousel_card': {'items': [{'open_uri_action': {'url': 'url_value', 'url_type_hint': 1}, 'title': 'title_value', 'description': 'description_value', 'image': {}, 'footer': 'footer_value'}], 'image_display_options': 1}, 'table_card': {'title': 'title_value', 'subtitle': 'subtitle_value', 'image': {}, 'column_properties': [{'header': 'header_value', 'horizontal_alignment': 1}], 'rows': [{'cells': [{'text': 'text_value'}], 'divider_after': True}], 'buttons': {}}, 'media_content': {'media_type': 1, 'media_objects': [{'name': 'name_value', 'description': 'description_value', 'large_image': {}, 'icon': {}, 'content_url': 'content_url_value'}]}, 'platform': 1}], 'default_response_platforms': [1], 'root_followup_intent_name': 'root_followup_intent_name_value', 'parent_followup_intent_name': 'parent_followup_intent_name_value', 'followup_intent_info': [{'followup_intent_name': 'followup_intent_name_value', 'parent_followup_intent_name': 'parent_followup_intent_name_value'}]} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.update_intent(request) - - -def test_update_intent_rest_flattened(): - client = IntentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = gcd_intent.Intent() - - # get arguments that satisfy an http rule for this method - sample_request = {'intent': {'name': 'projects/sample1/agent/intents/sample2'}} - - # get truthy value for each flattened field - mock_args = dict( - intent=gcd_intent.Intent(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - language_code='language_code_value', - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - pb_return_value = gcd_intent.Intent.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.update_intent(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v2beta1/{intent.name=projects/*/agent/intents/*}" % client.transport._host, args[1]) - - -def test_update_intent_rest_flattened_error(transport: str = 'rest'): - client = IntentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.update_intent( - gcd_intent.UpdateIntentRequest(), - intent=gcd_intent.Intent(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - language_code='language_code_value', - ) - - -def test_update_intent_rest_error(): - client = IntentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - intent.DeleteIntentRequest, - dict, -]) -def test_delete_intent_rest(request_type): - client = IntentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/agent/intents/sample2'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = None - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = '' - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.delete_intent(request) - - # Establish that the response is the type that we expect. - assert response is None - - -def test_delete_intent_rest_required_fields(request_type=intent.DeleteIntentRequest): - transport_class = transports.IntentsRestTransport - - request_init = {} - request_init["name"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - including_default_value_fields=False, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).delete_intent._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["name"] = 'name_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).delete_intent._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "name" in jsonified_request - assert jsonified_request["name"] == 'name_value' - - client = IntentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = None - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "delete", - 'query_params': pb_request, - } - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - json_return_value = '' - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.delete_intent(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_delete_intent_rest_unset_required_fields(): - transport = transports.IntentsRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.delete_intent._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_delete_intent_rest_interceptors(null_interceptor): - transport = transports.IntentsRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.IntentsRestInterceptor(), - ) - client = IntentsClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.IntentsRestInterceptor, "pre_delete_intent") as pre: - pre.assert_not_called() - pb_message = intent.DeleteIntentRequest.pb(intent.DeleteIntentRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - - request = intent.DeleteIntentRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - - client.delete_intent(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - - -def test_delete_intent_rest_bad_request(transport: str = 'rest', request_type=intent.DeleteIntentRequest): - client = IntentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/agent/intents/sample2'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.delete_intent(request) - - -def test_delete_intent_rest_flattened(): - client = IntentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = None - - # get arguments that satisfy an http rule for this method - sample_request = {'name': 'projects/sample1/agent/intents/sample2'} - - # get truthy value for each flattened field - mock_args = dict( - name='name_value', - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = '' - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.delete_intent(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v2beta1/{name=projects/*/agent/intents/*}" % client.transport._host, args[1]) - - -def test_delete_intent_rest_flattened_error(transport: str = 'rest'): - client = IntentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.delete_intent( - intent.DeleteIntentRequest(), - name='name_value', - ) - - -def test_delete_intent_rest_error(): - client = IntentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - intent.BatchUpdateIntentsRequest, - dict, -]) -def test_batch_update_intents_rest(request_type): - client = IntentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1/agent'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name='operations/spam') - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.batch_update_intents(request) - - # Establish that the response is the type that we expect. - assert response.operation.name == "operations/spam" - - -def test_batch_update_intents_rest_required_fields(request_type=intent.BatchUpdateIntentsRequest): - transport_class = transports.IntentsRestTransport - - request_init = {} - request_init["parent"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - including_default_value_fields=False, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).batch_update_intents._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["parent"] = 'parent_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).batch_update_intents._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "parent" in jsonified_request - assert jsonified_request["parent"] == 'parent_value' - - client = IntentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name='operations/spam') - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "post", - 'query_params': pb_request, - } - transcode_result['body'] = pb_request - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.batch_update_intents(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_batch_update_intents_rest_unset_required_fields(): - transport = transports.IntentsRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.batch_update_intents._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("parent", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_batch_update_intents_rest_interceptors(null_interceptor): - transport = transports.IntentsRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.IntentsRestInterceptor(), - ) - client = IntentsClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(operation.Operation, "_set_result_from_operation"), \ - mock.patch.object(transports.IntentsRestInterceptor, "post_batch_update_intents") as post, \ - mock.patch.object(transports.IntentsRestInterceptor, "pre_batch_update_intents") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = intent.BatchUpdateIntentsRequest.pb(intent.BatchUpdateIntentsRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = json_format.MessageToJson(operations_pb2.Operation()) - - request = intent.BatchUpdateIntentsRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = operations_pb2.Operation() - - client.batch_update_intents(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_batch_update_intents_rest_bad_request(transport: str = 'rest', request_type=intent.BatchUpdateIntentsRequest): - client = IntentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1/agent'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.batch_update_intents(request) - - -def test_batch_update_intents_rest_flattened(): - client = IntentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name='operations/spam') - - # get arguments that satisfy an http rule for this method - sample_request = {'parent': 'projects/sample1/agent'} - - # get truthy value for each flattened field - mock_args = dict( - parent='parent_value', - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.batch_update_intents(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v2beta1/{parent=projects/*/agent}/intents:batchUpdate" % client.transport._host, args[1]) - - -def test_batch_update_intents_rest_flattened_error(transport: str = 'rest'): - client = IntentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.batch_update_intents( - intent.BatchUpdateIntentsRequest(), - parent='parent_value', - intent_batch_uri='intent_batch_uri_value', - intent_batch_inline=intent.IntentBatch(intents=[intent.Intent(name='name_value')]), - ) - - -def test_batch_update_intents_rest_error(): - client = IntentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - intent.BatchDeleteIntentsRequest, - dict, -]) -def test_batch_delete_intents_rest(request_type): - client = IntentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1/agent'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name='operations/spam') - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.batch_delete_intents(request) - - # Establish that the response is the type that we expect. - assert response.operation.name == "operations/spam" - - -def test_batch_delete_intents_rest_required_fields(request_type=intent.BatchDeleteIntentsRequest): - transport_class = transports.IntentsRestTransport - - request_init = {} - request_init["parent"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - including_default_value_fields=False, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).batch_delete_intents._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["parent"] = 'parent_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).batch_delete_intents._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "parent" in jsonified_request - assert jsonified_request["parent"] == 'parent_value' - - client = IntentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name='operations/spam') - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "post", - 'query_params': pb_request, - } - transcode_result['body'] = pb_request - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.batch_delete_intents(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_batch_delete_intents_rest_unset_required_fields(): - transport = transports.IntentsRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.batch_delete_intents._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("parent", "intents", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_batch_delete_intents_rest_interceptors(null_interceptor): - transport = transports.IntentsRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.IntentsRestInterceptor(), - ) - client = IntentsClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(operation.Operation, "_set_result_from_operation"), \ - mock.patch.object(transports.IntentsRestInterceptor, "post_batch_delete_intents") as post, \ - mock.patch.object(transports.IntentsRestInterceptor, "pre_batch_delete_intents") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = intent.BatchDeleteIntentsRequest.pb(intent.BatchDeleteIntentsRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = json_format.MessageToJson(operations_pb2.Operation()) - - request = intent.BatchDeleteIntentsRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = operations_pb2.Operation() - - client.batch_delete_intents(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_batch_delete_intents_rest_bad_request(transport: str = 'rest', request_type=intent.BatchDeleteIntentsRequest): - client = IntentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1/agent'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.batch_delete_intents(request) - - -def test_batch_delete_intents_rest_flattened(): - client = IntentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name='operations/spam') - - # get arguments that satisfy an http rule for this method - sample_request = {'parent': 'projects/sample1/agent'} - - # get truthy value for each flattened field - mock_args = dict( - parent='parent_value', - intents=[intent.Intent(name='name_value')], - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.batch_delete_intents(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v2beta1/{parent=projects/*/agent}/intents:batchDelete" % client.transport._host, args[1]) - - -def test_batch_delete_intents_rest_flattened_error(transport: str = 'rest'): - client = IntentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.batch_delete_intents( - intent.BatchDeleteIntentsRequest(), - parent='parent_value', - intents=[intent.Intent(name='name_value')], - ) - - -def test_batch_delete_intents_rest_error(): - client = IntentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -def test_credentials_transport_error(): - # It is an error to provide credentials and a transport instance. - transport = transports.IntentsGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = IntentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # It is an error to provide a credentials file and a transport instance. - transport = transports.IntentsGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = IntentsClient( - client_options={"credentials_file": "credentials.json"}, - transport=transport, - ) - - # It is an error to provide an api_key and a transport instance. - transport = transports.IntentsGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - options = client_options.ClientOptions() - options.api_key = "api_key" - with pytest.raises(ValueError): - client = IntentsClient( - client_options=options, - transport=transport, - ) - - # It is an error to provide an api_key and a credential. - options = mock.Mock() - options.api_key = "api_key" - with pytest.raises(ValueError): - client = IntentsClient( - client_options=options, - credentials=ga_credentials.AnonymousCredentials() - ) - - # It is an error to provide scopes and a transport instance. - transport = transports.IntentsGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = IntentsClient( - client_options={"scopes": ["1", "2"]}, - transport=transport, - ) - - -def test_transport_instance(): - # A client may be instantiated with a custom transport instance. - transport = transports.IntentsGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - client = IntentsClient(transport=transport) - assert client.transport is transport - -def test_transport_get_channel(): - # A client may be instantiated with a custom transport instance. - transport = transports.IntentsGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - - transport = transports.IntentsGrpcAsyncIOTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - -@pytest.mark.parametrize("transport_class", [ - transports.IntentsGrpcTransport, - transports.IntentsGrpcAsyncIOTransport, - transports.IntentsRestTransport, -]) -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() - -@pytest.mark.parametrize("transport_name", [ - "grpc", - "rest", -]) -def test_transport_kind(transport_name): - transport = IntentsClient.get_transport_class(transport_name)( - credentials=ga_credentials.AnonymousCredentials(), - ) - assert transport.kind == transport_name - -def test_transport_grpc_default(): - # A client should use the gRPC transport by default. - 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(core_exceptions.DuplicateCredentialArgs): - transport = transports.IntentsTransport( - credentials=ga_credentials.AnonymousCredentials(), - credentials_file="credentials.json" - ) - - -def test_intents_base_transport(): - # Instantiate the base transport. - with mock.patch('google.cloud.dialogflow_v2beta1.services.intents.transports.IntentsTransport.__init__') as Transport: - Transport.return_value = None - transport = transports.IntentsTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Every method on the transport should just blindly - # raise NotImplementedError. - methods = ( - 'list_intents', - 'get_intent', - 'create_intent', - 'update_intent', - 'delete_intent', - 'batch_update_intents', - 'batch_delete_intents', - 'get_location', - 'list_locations', - 'get_operation', - 'cancel_operation', - 'list_operations', - ) - for method in methods: - with pytest.raises(NotImplementedError): - getattr(transport, method)(request=object()) - - with pytest.raises(NotImplementedError): - transport.close() - - # Additionally, the LRO client (a property) should - # also raise NotImplementedError - with pytest.raises(NotImplementedError): - transport.operations_client - - # Catch all for all remaining methods and properties - remainder = [ - 'kind', - ] - for r in remainder: - with pytest.raises(NotImplementedError): - getattr(transport, r)() - - -def test_intents_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.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", - ) - - -def test_intents_base_transport_with_adc(): - # Test the default credentials are used if credentials and credentials_file are None. - with mock.patch.object(google.auth, 'default', autospec=True) as adc, mock.patch('google.cloud.dialogflow_v2beta1.services.intents.transports.IntentsTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.IntentsTransport() - adc.assert_called_once() - - -def test_intents_auth_adc(): - # If no credentials are provided, we should use ADC credentials. - with mock.patch.object(google.auth, 'default', autospec=True) as adc: - 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, - ) - - -@pytest.mark.parametrize( - "transport_class", - [ - transports.IntentsGrpcTransport, - transports.IntentsGrpcAsyncIOTransport, - ], -) -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(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, - transports.IntentsRestTransport, - ], -) -def test_intents_transport_auth_gdch_credentials(transport_class): - host = 'https://language.com' - api_audience_tests = [None, 'https://language2.com'] - api_audience_expect = [host, 'https://language2.com'] - for t, e in zip(api_audience_tests, api_audience_expect): - with mock.patch.object(google.auth, 'default', autospec=True) as adc: - gdch_mock = mock.MagicMock() - type(gdch_mock).with_gdch_audience = mock.PropertyMock(return_value=gdch_mock) - adc.return_value = (gdch_mock, None) - transport_class(host=host, api_audience=t) - gdch_mock.with_gdch_audience.assert_called_once_with( - e - ) - - -@pytest.mark.parametrize( - "transport_class,grpc_helpers", - [ - (transports.IntentsGrpcTransport, grpc_helpers), - (transports.IntentsGrpcAsyncIOTransport, grpc_helpers_async) - ], -) -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", [transports.IntentsGrpcTransport, transports.IntentsGrpcAsyncIOTransport]) -def test_intents_grpc_transport_client_cert_source_for_mtls( - transport_class -): - cred = ga_credentials.AnonymousCredentials() - - # Check ssl_channel_credentials is used if provided. - with mock.patch.object(transport_class, "create_channel") as mock_create_channel: - mock_ssl_channel_creds = mock.Mock() - transport_class( - host="squid.clam.whelk", - credentials=cred, - ssl_channel_credentials=mock_ssl_channel_creds - ) - mock_create_channel.assert_called_once_with( - "squid.clam.whelk:443", - credentials=cred, - credentials_file=None, - scopes=None, - ssl_credentials=mock_ssl_channel_creds, - quota_project_id=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - # Check if ssl_channel_credentials is not provided, then client_cert_source_for_mtls - # is used. - with mock.patch.object(transport_class, "create_channel", return_value=mock.Mock()): - with mock.patch("grpc.ssl_channel_credentials") as mock_ssl_cred: - transport_class( - credentials=cred, - client_cert_source_for_mtls=client_cert_source_callback - ) - expected_cert, expected_key = client_cert_source_callback() - mock_ssl_cred.assert_called_once_with( - certificate_chain=expected_cert, - private_key=expected_key - ) - -def test_intents_http_transport_client_cert_source_for_mtls(): - cred = ga_credentials.AnonymousCredentials() - with mock.patch("google.auth.transport.requests.AuthorizedSession.configure_mtls_channel") as mock_configure_mtls_channel: - transports.IntentsRestTransport ( - credentials=cred, - client_cert_source_for_mtls=client_cert_source_callback - ) - mock_configure_mtls_channel.assert_called_once_with(client_cert_source_callback) - - -def test_intents_rest_lro_client(): - client = IntentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - transport = client.transport - - # Ensure that we have a api-core operations client. - assert isinstance( - transport.operations_client, - operations_v1.AbstractOperationsClient, - ) - - # Ensure that subsequent calls to the property send the exact same object. - assert transport.operations_client is transport.operations_client - - -@pytest.mark.parametrize("transport_name", [ - "grpc", - "grpc_asyncio", - "rest", -]) -def test_intents_host_no_port(transport_name): - client = IntentsClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='dialogflow.googleapis.com'), - transport=transport_name, - ) - assert client.transport._host == ( - 'dialogflow.googleapis.com:443' - if transport_name in ['grpc', 'grpc_asyncio'] - else 'https://dialogflow.googleapis.com' - ) - -@pytest.mark.parametrize("transport_name", [ - "grpc", - "grpc_asyncio", - "rest", -]) -def test_intents_host_with_port(transport_name): - client = IntentsClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='dialogflow.googleapis.com:8000'), - transport=transport_name, - ) - assert client.transport._host == ( - 'dialogflow.googleapis.com:8000' - if transport_name in ['grpc', 'grpc_asyncio'] - else 'https://dialogflow.googleapis.com:8000' - ) - -@pytest.mark.parametrize("transport_name", [ - "rest", -]) -def test_intents_client_transport_session_collision(transport_name): - creds1 = ga_credentials.AnonymousCredentials() - creds2 = ga_credentials.AnonymousCredentials() - client1 = IntentsClient( - credentials=creds1, - transport=transport_name, - ) - client2 = IntentsClient( - credentials=creds2, - transport=transport_name, - ) - session1 = client1.transport.list_intents._session - session2 = client2.transport.list_intents._session - assert session1 != session2 - session1 = client1.transport.get_intent._session - session2 = client2.transport.get_intent._session - assert session1 != session2 - session1 = client1.transport.create_intent._session - session2 = client2.transport.create_intent._session - assert session1 != session2 - session1 = client1.transport.update_intent._session - session2 = client2.transport.update_intent._session - assert session1 != session2 - session1 = client1.transport.delete_intent._session - session2 = client2.transport.delete_intent._session - assert session1 != session2 - session1 = client1.transport.batch_update_intents._session - session2 = client2.transport.batch_update_intents._session - assert session1 != session2 - session1 = client1.transport.batch_delete_intents._session - session2 = client2.transport.batch_delete_intents._session - assert session1 != session2 -def test_intents_grpc_transport_channel(): - channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.IntentsGrpcTransport( - 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_intents_grpc_asyncio_transport_channel(): - channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.IntentsGrpcAsyncIOTransport( - 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.IntentsGrpcTransport, transports.IntentsGrpcAsyncIOTransport]) -def test_intents_transport_channel_mtls_with_client_cert_source( - transport_class -): - with mock.patch("grpc.ssl_channel_credentials", autospec=True) as grpc_ssl_channel_cred: - with mock.patch.object(transport_class, "create_channel") as grpc_create_channel: - mock_ssl_cred = mock.Mock() - grpc_ssl_channel_cred.return_value = mock_ssl_cred - - mock_grpc_channel = mock.Mock() - grpc_create_channel.return_value = mock_grpc_channel - - cred = ga_credentials.AnonymousCredentials() - with pytest.warns(DeprecationWarning): - with mock.patch.object(google.auth, 'default') as adc: - adc.return_value = (cred, None) - transport = transport_class( - host="squid.clam.whelk", - api_mtls_endpoint="mtls.squid.clam.whelk", - client_cert_source=client_cert_source_callback, - ) - adc.assert_called_once() - - grpc_ssl_channel_cred.assert_called_once_with( - certificate_chain=b"cert bytes", private_key=b"key bytes" - ) - grpc_create_channel.assert_called_once_with( - "mtls.squid.clam.whelk:443", - credentials=cred, - credentials_file=None, - scopes=None, - ssl_credentials=mock_ssl_cred, - quota_project_id=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - assert transport.grpc_channel == mock_grpc_channel - assert transport._ssl_channel_credentials == mock_ssl_cred - - -# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are -# removed from grpc/grpc_asyncio transport constructor. -@pytest.mark.parametrize("transport_class", [transports.IntentsGrpcTransport, transports.IntentsGrpcAsyncIOTransport]) -def test_intents_transport_channel_mtls_with_adc( - transport_class -): - mock_ssl_cred = mock.Mock() - with mock.patch.multiple( - "google.auth.transport.grpc.SslCredentials", - __init__=mock.Mock(return_value=None), - ssl_credentials=mock.PropertyMock(return_value=mock_ssl_cred), - ): - with mock.patch.object(transport_class, "create_channel") as grpc_create_channel: - mock_grpc_channel = mock.Mock() - grpc_create_channel.return_value = mock_grpc_channel - mock_cred = mock.Mock() - - with pytest.warns(DeprecationWarning): - transport = transport_class( - host="squid.clam.whelk", - credentials=mock_cred, - api_mtls_endpoint="mtls.squid.clam.whelk", - client_cert_source=None, - ) - - grpc_create_channel.assert_called_once_with( - "mtls.squid.clam.whelk:443", - credentials=mock_cred, - credentials_file=None, - scopes=None, - ssl_credentials=mock_ssl_cred, - quota_project_id=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - assert transport.grpc_channel == mock_grpc_channel - - -def test_intents_grpc_lro_client(): - client = IntentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - transport = client.transport - - # Ensure that we have a api-core operations client. - assert isinstance( - transport.operations_client, - operations_v1.OperationsClient, - ) - - # Ensure that subsequent calls to the property send the exact same object. - assert transport.operations_client is transport.operations_client - - -def test_intents_grpc_lro_async_client(): - client = IntentsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc_asyncio', - ) - transport = client.transport - - # Ensure that we have a api-core operations client. - assert isinstance( - transport.operations_client, - operations_v1.OperationsAsyncClient, - ) - - # Ensure that subsequent calls to the property send the exact same object. - assert transport.operations_client is transport.operations_client - - -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, ) - actual = IntentsClient.context_path(project, session, context) - assert expected == actual - - -def test_parse_context_path(): - expected = { - "project": "octopus", - "session": "oyster", - "context": "nudibranch", - } - path = IntentsClient.context_path(**expected) - - # Check that the path construction is reversible. - actual = IntentsClient.parse_context_path(path) - assert expected == actual - -def test_intent_path(): - project = "cuttlefish" - intent = "mussel" - expected = "projects/{project}/agent/intents/{intent}".format(project=project, intent=intent, ) - actual = IntentsClient.intent_path(project, intent) - assert expected == actual - - -def test_parse_intent_path(): - expected = { - "project": "winkle", - "intent": "nautilus", - } - path = IntentsClient.intent_path(**expected) - - # Check that the path construction is reversible. - actual = IntentsClient.parse_intent_path(path) - assert expected == actual - -def test_common_billing_account_path(): - billing_account = "scallop" - expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) - actual = IntentsClient.common_billing_account_path(billing_account) - assert expected == actual - - -def test_parse_common_billing_account_path(): - expected = { - "billing_account": "abalone", - } - path = IntentsClient.common_billing_account_path(**expected) - - # Check that the path construction is reversible. - actual = IntentsClient.parse_common_billing_account_path(path) - assert expected == actual - -def test_common_folder_path(): - folder = "squid" - expected = "folders/{folder}".format(folder=folder, ) - actual = IntentsClient.common_folder_path(folder) - assert expected == actual - - -def test_parse_common_folder_path(): - expected = { - "folder": "clam", - } - path = IntentsClient.common_folder_path(**expected) - - # Check that the path construction is reversible. - actual = IntentsClient.parse_common_folder_path(path) - assert expected == actual - -def test_common_organization_path(): - organization = "whelk" - expected = "organizations/{organization}".format(organization=organization, ) - actual = IntentsClient.common_organization_path(organization) - assert expected == actual - - -def test_parse_common_organization_path(): - expected = { - "organization": "octopus", - } - path = IntentsClient.common_organization_path(**expected) - - # Check that the path construction is reversible. - actual = IntentsClient.parse_common_organization_path(path) - assert expected == actual - -def test_common_project_path(): - project = "oyster" - expected = "projects/{project}".format(project=project, ) - actual = IntentsClient.common_project_path(project) - assert expected == actual - - -def test_parse_common_project_path(): - expected = { - "project": "nudibranch", - } - path = IntentsClient.common_project_path(**expected) - - # Check that the path construction is reversible. - actual = IntentsClient.parse_common_project_path(path) - assert expected == actual - -def test_common_location_path(): - project = "cuttlefish" - location = "mussel" - expected = "projects/{project}/locations/{location}".format(project=project, location=location, ) - actual = IntentsClient.common_location_path(project, location) - assert expected == actual - - -def test_parse_common_location_path(): - expected = { - "project": "winkle", - "location": "nautilus", - } - path = IntentsClient.common_location_path(**expected) - - # Check that the path construction is reversible. - actual = IntentsClient.parse_common_location_path(path) - assert expected == actual - - -def test_client_with_default_client_info(): - client_info = gapic_v1.client_info.ClientInfo() - - with mock.patch.object(transports.IntentsTransport, '_prep_wrapped_messages') as prep: - client = IntentsClient( - credentials=ga_credentials.AnonymousCredentials(), - client_info=client_info, - ) - prep.assert_called_once_with(client_info) - - with mock.patch.object(transports.IntentsTransport, '_prep_wrapped_messages') as prep: - transport_class = IntentsClient.get_transport_class() - transport = transport_class( - credentials=ga_credentials.AnonymousCredentials(), - client_info=client_info, - ) - prep.assert_called_once_with(client_info) - -@pytest.mark.asyncio -async def test_transport_close_async(): - client = IntentsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - with mock.patch.object(type(getattr(client.transport, "grpc_channel")), "close") as close: - async with client: - close.assert_not_called() - close.assert_called_once() - - -def test_get_location_rest_bad_request(transport: str = 'rest', request_type=locations_pb2.GetLocationRequest): - client = IntentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - request = request_type() - request = json_format.ParseDict({'name': 'projects/sample1/locations/sample2'}, request) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.get_location(request) - -@pytest.mark.parametrize("request_type", [ - locations_pb2.GetLocationRequest, - dict, -]) -def test_get_location_rest(request_type): - client = IntentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request_init = {'name': 'projects/sample1/locations/sample2'} - request = request_type(**request_init) - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = locations_pb2.Location() - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.get_location(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, locations_pb2.Location) - -def test_list_locations_rest_bad_request(transport: str = 'rest', request_type=locations_pb2.ListLocationsRequest): - client = IntentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - request = request_type() - request = json_format.ParseDict({'name': 'projects/sample1'}, request) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.list_locations(request) - -@pytest.mark.parametrize("request_type", [ - locations_pb2.ListLocationsRequest, - dict, -]) -def test_list_locations_rest(request_type): - client = IntentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request_init = {'name': 'projects/sample1'} - request = request_type(**request_init) - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = locations_pb2.ListLocationsResponse() - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.list_locations(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, locations_pb2.ListLocationsResponse) - -def test_cancel_operation_rest_bad_request(transport: str = 'rest', request_type=operations_pb2.CancelOperationRequest): - client = IntentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - request = request_type() - request = json_format.ParseDict({'name': 'projects/sample1/operations/sample2'}, request) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.cancel_operation(request) - -@pytest.mark.parametrize("request_type", [ - operations_pb2.CancelOperationRequest, - dict, -]) -def test_cancel_operation_rest(request_type): - client = IntentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request_init = {'name': 'projects/sample1/operations/sample2'} - request = request_type(**request_init) - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = None - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = '{}' - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.cancel_operation(request) - - # Establish that the response is the type that we expect. - assert response is None - -def test_get_operation_rest_bad_request(transport: str = 'rest', request_type=operations_pb2.GetOperationRequest): - client = IntentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - request = request_type() - request = json_format.ParseDict({'name': 'projects/sample1/operations/sample2'}, request) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.get_operation(request) - -@pytest.mark.parametrize("request_type", [ - operations_pb2.GetOperationRequest, - dict, -]) -def test_get_operation_rest(request_type): - client = IntentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request_init = {'name': 'projects/sample1/operations/sample2'} - request = request_type(**request_init) - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation() - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.get_operation(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, operations_pb2.Operation) - -def test_list_operations_rest_bad_request(transport: str = 'rest', request_type=operations_pb2.ListOperationsRequest): - client = IntentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - request = request_type() - request = json_format.ParseDict({'name': 'projects/sample1'}, request) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.list_operations(request) - -@pytest.mark.parametrize("request_type", [ - operations_pb2.ListOperationsRequest, - dict, -]) -def test_list_operations_rest(request_type): - client = IntentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request_init = {'name': 'projects/sample1'} - request = request_type(**request_init) - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = operations_pb2.ListOperationsResponse() - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.list_operations(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, operations_pb2.ListOperationsResponse) - - -def test_cancel_operation(transport: str = "grpc"): - client = IntentsClient( - 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 = operations_pb2.CancelOperationRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = None - response = client.cancel_operation(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 response is the type that we expect. - assert response is None -@pytest.mark.asyncio -async def test_cancel_operation_async(transport: str = "grpc"): - client = IntentsAsyncClient( - 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 = operations_pb2.CancelOperationRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - None - ) - response = await client.cancel_operation(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 response is the type that we expect. - assert response is None - -def test_cancel_operation_field_headers(): - 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 = operations_pb2.CancelOperationRequest() - request.name = "locations" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call: - call.return_value = None - - client.cancel_operation(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=locations",) in kw["metadata"] -@pytest.mark.asyncio -async def test_cancel_operation_field_headers_async(): - 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 = operations_pb2.CancelOperationRequest() - request.name = "locations" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - None - ) - await client.cancel_operation(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=locations",) in kw["metadata"] - -def test_cancel_operation_from_dict(): - 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.cancel_operation), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = None - - response = client.cancel_operation( - request={ - "name": "locations", - } - ) - call.assert_called() -@pytest.mark.asyncio -async def test_cancel_operation_from_dict_async(): - 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.cancel_operation), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - None - ) - response = await client.cancel_operation( - request={ - "name": "locations", - } - ) - call.assert_called() - - -def test_get_operation(transport: str = "grpc"): - client = IntentsClient( - 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 = operations_pb2.GetOperationRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_operation), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation() - response = client.get_operation(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 response is the type that we expect. - assert isinstance(response, operations_pb2.Operation) -@pytest.mark.asyncio -async def test_get_operation_async(transport: str = "grpc"): - client = IntentsAsyncClient( - 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 = operations_pb2.GetOperationRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_operation), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation() - ) - response = await client.get_operation(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 response is the type that we expect. - assert isinstance(response, operations_pb2.Operation) - -def test_get_operation_field_headers(): - 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 = operations_pb2.GetOperationRequest() - request.name = "locations" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_operation), "__call__") as call: - call.return_value = operations_pb2.Operation() - - client.get_operation(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=locations",) in kw["metadata"] -@pytest.mark.asyncio -async def test_get_operation_field_headers_async(): - 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 = operations_pb2.GetOperationRequest() - request.name = "locations" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_operation), "__call__") as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation() - ) - await client.get_operation(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=locations",) in kw["metadata"] - -def test_get_operation_from_dict(): - 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_operation), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation() - - response = client.get_operation( - request={ - "name": "locations", - } - ) - call.assert_called() -@pytest.mark.asyncio -async def test_get_operation_from_dict_async(): - 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_operation), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation() - ) - response = await client.get_operation( - request={ - "name": "locations", - } - ) - call.assert_called() - - -def test_list_operations(transport: str = "grpc"): - client = IntentsClient( - 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 = operations_pb2.ListOperationsRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_operations), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.ListOperationsResponse() - response = client.list_operations(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 response is the type that we expect. - assert isinstance(response, operations_pb2.ListOperationsResponse) -@pytest.mark.asyncio -async def test_list_operations_async(transport: str = "grpc"): - client = IntentsAsyncClient( - 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 = operations_pb2.ListOperationsRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_operations), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.ListOperationsResponse() - ) - response = await client.list_operations(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 response is the type that we expect. - assert isinstance(response, operations_pb2.ListOperationsResponse) - -def test_list_operations_field_headers(): - 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 = operations_pb2.ListOperationsRequest() - request.name = "locations" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_operations), "__call__") as call: - call.return_value = operations_pb2.ListOperationsResponse() - - client.list_operations(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=locations",) in kw["metadata"] -@pytest.mark.asyncio -async def test_list_operations_field_headers_async(): - 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 = operations_pb2.ListOperationsRequest() - request.name = "locations" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_operations), "__call__") as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.ListOperationsResponse() - ) - await client.list_operations(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=locations",) in kw["metadata"] - -def test_list_operations_from_dict(): - 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_operations), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.ListOperationsResponse() - - response = client.list_operations( - request={ - "name": "locations", - } - ) - call.assert_called() -@pytest.mark.asyncio -async def test_list_operations_from_dict_async(): - 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_operations), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.ListOperationsResponse() - ) - response = await client.list_operations( - request={ - "name": "locations", - } - ) - call.assert_called() - - -def test_list_locations(transport: str = "grpc"): - client = IntentsClient( - 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 = locations_pb2.ListLocationsRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_locations), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = locations_pb2.ListLocationsResponse() - response = client.list_locations(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 response is the type that we expect. - assert isinstance(response, locations_pb2.ListLocationsResponse) -@pytest.mark.asyncio -async def test_list_locations_async(transport: str = "grpc"): - client = IntentsAsyncClient( - 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 = locations_pb2.ListLocationsRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_locations), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - locations_pb2.ListLocationsResponse() - ) - response = await client.list_locations(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 response is the type that we expect. - assert isinstance(response, locations_pb2.ListLocationsResponse) - -def test_list_locations_field_headers(): - 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 = locations_pb2.ListLocationsRequest() - request.name = "locations" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_locations), "__call__") as call: - call.return_value = locations_pb2.ListLocationsResponse() - - client.list_locations(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=locations",) in kw["metadata"] -@pytest.mark.asyncio -async def test_list_locations_field_headers_async(): - 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 = locations_pb2.ListLocationsRequest() - request.name = "locations" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_locations), "__call__") as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - locations_pb2.ListLocationsResponse() - ) - await client.list_locations(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=locations",) in kw["metadata"] - -def test_list_locations_from_dict(): - 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_locations), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = locations_pb2.ListLocationsResponse() - - response = client.list_locations( - request={ - "name": "locations", - } - ) - call.assert_called() -@pytest.mark.asyncio -async def test_list_locations_from_dict_async(): - 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_locations), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - locations_pb2.ListLocationsResponse() - ) - response = await client.list_locations( - request={ - "name": "locations", - } - ) - call.assert_called() - - -def test_get_location(transport: str = "grpc"): - client = IntentsClient( - 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 = locations_pb2.GetLocationRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_location), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = locations_pb2.Location() - response = client.get_location(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 response is the type that we expect. - assert isinstance(response, locations_pb2.Location) -@pytest.mark.asyncio -async def test_get_location_async(transport: str = "grpc_asyncio"): - client = IntentsAsyncClient( - 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 = locations_pb2.GetLocationRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_location), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - locations_pb2.Location() - ) - response = await client.get_location(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 response is the type that we expect. - assert isinstance(response, locations_pb2.Location) - -def test_get_location_field_headers(): - 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 = locations_pb2.GetLocationRequest() - request.name = "locations/abc" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_location), "__call__") as call: - call.return_value = locations_pb2.Location() - - client.get_location(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=locations/abc",) in kw["metadata"] -@pytest.mark.asyncio -async def test_get_location_field_headers_async(): - 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 = locations_pb2.GetLocationRequest() - request.name = "locations/abc" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_location), "__call__") as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - locations_pb2.Location() - ) - await client.get_location(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=locations/abc",) in kw["metadata"] - -def test_get_location_from_dict(): - 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_locations), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = locations_pb2.Location() - - response = client.get_location( - request={ - "name": "locations/abc", - } - ) - call.assert_called() -@pytest.mark.asyncio -async def test_get_location_from_dict_async(): - 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_locations), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - locations_pb2.Location() - ) - response = await client.get_location( - request={ - "name": "locations", - } - ) - call.assert_called() - - -def test_transport_close(): - transports = { - "rest": "_session", - "grpc": "_grpc_channel", - } - - for transport, close_name in transports.items(): - client = IntentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport - ) - with mock.patch.object(type(getattr(client.transport, close_name)), "close") as close: - with client: - close.assert_not_called() - close.assert_called_once() - -def test_client_ctx(): - transports = [ - 'rest', - 'grpc', - ] - for transport in transports: - client = IntentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport - ) - # Test client calls underlying transport. - with mock.patch.object(type(client.transport), "close") as close: - close.assert_not_called() - with client: - pass - close.assert_called() - -@pytest.mark.parametrize("client_class,transport_class", [ - (IntentsClient, transports.IntentsGrpcTransport), - (IntentsAsyncClient, transports.IntentsGrpcAsyncIOTransport), -]) -def test_api_key_credentials(client_class, transport_class): - with mock.patch.object( - google.auth._default, "get_api_key_credentials", create=True - ) as get_api_key_credentials: - mock_cred = mock.Mock() - get_api_key_credentials.return_value = mock_cred - options = client_options.ClientOptions() - options.api_key = "api_key" - 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=mock_cred, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) diff --git a/owl-bot-staging/v2beta1/tests/unit/gapic/dialogflow_v2beta1/test_knowledge_bases.py b/owl-bot-staging/v2beta1/tests/unit/gapic/dialogflow_v2beta1/test_knowledge_bases.py deleted file mode 100644 index fa8be6926..000000000 --- a/owl-bot-staging/v2beta1/tests/unit/gapic/dialogflow_v2beta1/test_knowledge_bases.py +++ /dev/null @@ -1,4742 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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 -# try/except added for compatibility with python < 3.8 -try: - from unittest import mock - from unittest.mock import AsyncMock # pragma: NO COVER -except ImportError: # pragma: NO COVER - import mock - -import grpc -from grpc.experimental import aio -from collections.abc import Iterable -from google.protobuf import json_format -import json -import math -import pytest -from proto.marshal.rules.dates import DurationRule, TimestampRule -from proto.marshal.rules import wrappers -from requests import Response -from requests import Request, PreparedRequest -from requests.sessions import Session -from google.protobuf import json_format - -from google.api_core import client_options -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import grpc_helpers -from google.api_core import grpc_helpers_async -from google.api_core import path_template -from google.auth import credentials as ga_credentials -from google.auth.exceptions import MutualTLSChannelError -from google.cloud.dialogflow_v2beta1.services.knowledge_bases import KnowledgeBasesAsyncClient -from google.cloud.dialogflow_v2beta1.services.knowledge_bases import KnowledgeBasesClient -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.types import knowledge_base -from google.cloud.dialogflow_v2beta1.types import knowledge_base as gcd_knowledge_base -from google.cloud.location import locations_pb2 -from google.longrunning import operations_pb2 -from google.oauth2 import service_account -from google.protobuf import field_mask_pb2 # type: ignore -import google.auth - - -def client_cert_source_callback(): - return b"cert bytes", b"key bytes" - - -# If default endpoint is localhost, then default mtls endpoint will be the same. -# This method modifies the default endpoint so the client can produce a different -# mtls endpoint for endpoint testing purposes. -def modify_default_endpoint(client): - return "foo.googleapis.com" if ("localhost" in client.DEFAULT_ENDPOINT) else client.DEFAULT_ENDPOINT - - -def test__get_default_mtls_endpoint(): - api_endpoint = "example.googleapis.com" - api_mtls_endpoint = "example.mtls.googleapis.com" - sandbox_endpoint = "example.sandbox.googleapis.com" - sandbox_mtls_endpoint = "example.mtls.sandbox.googleapis.com" - non_googleapi = "api.example.com" - - assert KnowledgeBasesClient._get_default_mtls_endpoint(None) is None - assert KnowledgeBasesClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint - assert KnowledgeBasesClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint - assert KnowledgeBasesClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint - assert KnowledgeBasesClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint - assert KnowledgeBasesClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi - - -@pytest.mark.parametrize("client_class,transport_name", [ - (KnowledgeBasesClient, "grpc"), - (KnowledgeBasesAsyncClient, "grpc_asyncio"), - (KnowledgeBasesClient, "rest"), -]) -def test_knowledge_bases_client_from_service_account_info(client_class, transport_name): - 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, transport=transport_name) - assert client.transport._credentials == creds - assert isinstance(client, client_class) - - assert client.transport._host == ( - 'dialogflow.googleapis.com:443' - if transport_name in ['grpc', 'grpc_asyncio'] - else - 'https://dialogflow.googleapis.com' - ) - - -@pytest.mark.parametrize("transport_class,transport_name", [ - (transports.KnowledgeBasesGrpcTransport, "grpc"), - (transports.KnowledgeBasesGrpcAsyncIOTransport, "grpc_asyncio"), - (transports.KnowledgeBasesRestTransport, "rest"), -]) -def test_knowledge_bases_client_service_account_always_use_jwt(transport_class, transport_name): - with mock.patch.object(service_account.Credentials, 'with_always_use_jwt_access', create=True) as use_jwt: - creds = service_account.Credentials(None, None, None) - transport = transport_class(credentials=creds, always_use_jwt_access=True) - use_jwt.assert_called_once_with(True) - - with mock.patch.object(service_account.Credentials, 'with_always_use_jwt_access', create=True) as use_jwt: - creds = service_account.Credentials(None, None, None) - transport = transport_class(credentials=creds, always_use_jwt_access=False) - use_jwt.assert_not_called() - - -@pytest.mark.parametrize("client_class,transport_name", [ - (KnowledgeBasesClient, "grpc"), - (KnowledgeBasesAsyncClient, "grpc_asyncio"), - (KnowledgeBasesClient, "rest"), -]) -def test_knowledge_bases_client_from_service_account_file(client_class, transport_name): - 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", transport=transport_name) - assert client.transport._credentials == creds - assert isinstance(client, client_class) - - client = client_class.from_service_account_json("dummy/file/path.json", transport=transport_name) - assert client.transport._credentials == creds - assert isinstance(client, client_class) - - assert client.transport._host == ( - 'dialogflow.googleapis.com:443' - if transport_name in ['grpc', 'grpc_asyncio'] - else - 'https://dialogflow.googleapis.com' - ) - - -def test_knowledge_bases_client_get_transport_class(): - transport = KnowledgeBasesClient.get_transport_class() - available_transports = [ - transports.KnowledgeBasesGrpcTransport, - transports.KnowledgeBasesRestTransport, - ] - assert transport in available_transports - - transport = KnowledgeBasesClient.get_transport_class("grpc") - assert transport == transports.KnowledgeBasesGrpcTransport - - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (KnowledgeBasesClient, transports.KnowledgeBasesGrpcTransport, "grpc"), - (KnowledgeBasesAsyncClient, transports.KnowledgeBasesGrpcAsyncIOTransport, "grpc_asyncio"), - (KnowledgeBasesClient, transports.KnowledgeBasesRestTransport, "rest"), -]) -@mock.patch.object(KnowledgeBasesClient, "DEFAULT_ENDPOINT", modify_default_endpoint(KnowledgeBasesClient)) -@mock.patch.object(KnowledgeBasesAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(KnowledgeBasesAsyncClient)) -def test_knowledge_bases_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(KnowledgeBasesClient, '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(KnowledgeBasesClient, 'get_transport_class') as gtc: - client = client_class(transport=transport_name) - gtc.assert_called() - - # Check the case api_endpoint is provided. - options = client_options.ClientOptions(api_endpoint="squid.clam.whelk") - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(transport=transport_name, client_options=options) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host="squid.clam.whelk", - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is - # "never". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is - # "always". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_MTLS_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # 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(transport=transport_name) - - # 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(transport=transport_name) - - # 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, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id="octopus", - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - # Check the case api_endpoint is provided - options = client_options.ClientOptions(api_audience="https://language.googleapis.com") - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience="https://language.googleapis.com" - ) - -@pytest.mark.parametrize("client_class,transport_class,transport_name,use_client_cert_env", [ - (KnowledgeBasesClient, transports.KnowledgeBasesGrpcTransport, "grpc", "true"), - (KnowledgeBasesAsyncClient, transports.KnowledgeBasesGrpcAsyncIOTransport, "grpc_asyncio", "true"), - (KnowledgeBasesClient, transports.KnowledgeBasesGrpcTransport, "grpc", "false"), - (KnowledgeBasesAsyncClient, transports.KnowledgeBasesGrpcAsyncIOTransport, "grpc_asyncio", "false"), - (KnowledgeBasesClient, transports.KnowledgeBasesRestTransport, "rest", "true"), - (KnowledgeBasesClient, transports.KnowledgeBasesRestTransport, "rest", "false"), -]) -@mock.patch.object(KnowledgeBasesClient, "DEFAULT_ENDPOINT", modify_default_endpoint(KnowledgeBasesClient)) -@mock.patch.object(KnowledgeBasesAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(KnowledgeBasesAsyncClient)) -@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) -def test_knowledge_bases_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, transport=transport_name) - - if use_client_cert_env == "false": - expected_client_cert_source = None - expected_host = client.DEFAULT_ENDPOINT - else: - expected_client_cert_source = client_cert_source_callback - expected_host = client.DEFAULT_MTLS_ENDPOINT - - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=expected_host, - scopes=None, - client_cert_source_for_mtls=expected_client_cert_source, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case ADC client cert is provided. Whether client cert is used depends on - # GOOGLE_API_USE_CLIENT_CERTIFICATE value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): - with mock.patch.object(transport_class, '__init__') as patched: - with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): - with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=client_cert_source_callback): - if use_client_cert_env == "false": - expected_host = client.DEFAULT_ENDPOINT - expected_client_cert_source = None - else: - expected_host = client.DEFAULT_MTLS_ENDPOINT - expected_client_cert_source = client_cert_source_callback - - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=expected_host, - scopes=None, - client_cert_source_for_mtls=expected_client_cert_source, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case client_cert_source and ADC client cert are not provided. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): - with mock.patch.object(transport_class, '__init__') as patched: - with mock.patch("google.auth.transport.mtls.has_default_client_cert_source", return_value=False): - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - -@pytest.mark.parametrize("client_class", [ - KnowledgeBasesClient, KnowledgeBasesAsyncClient -]) -@mock.patch.object(KnowledgeBasesClient, "DEFAULT_ENDPOINT", modify_default_endpoint(KnowledgeBasesClient)) -@mock.patch.object(KnowledgeBasesAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(KnowledgeBasesAsyncClient)) -def test_knowledge_bases_client_get_mtls_endpoint_and_cert_source(client_class): - mock_client_cert_source = mock.Mock() - - # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "true". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - mock_api_endpoint = "foo" - options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) - assert api_endpoint == mock_api_endpoint - assert cert_source == mock_client_cert_source - - # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "false". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): - mock_client_cert_source = mock.Mock() - mock_api_endpoint = "foo" - options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) - assert api_endpoint == mock_api_endpoint - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "never". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_ENDPOINT - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "always". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert doesn't exist. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=False): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_ENDPOINT - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert exists. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - 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=mock_client_cert_source): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT - assert cert_source == mock_client_cert_source - - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (KnowledgeBasesClient, transports.KnowledgeBasesGrpcTransport, "grpc"), - (KnowledgeBasesAsyncClient, transports.KnowledgeBasesGrpcAsyncIOTransport, "grpc_asyncio"), - (KnowledgeBasesClient, transports.KnowledgeBasesRestTransport, "rest"), -]) -def test_knowledge_bases_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, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=["1", "2"], - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - -@pytest.mark.parametrize("client_class,transport_class,transport_name,grpc_helpers", [ - (KnowledgeBasesClient, transports.KnowledgeBasesGrpcTransport, "grpc", grpc_helpers), - (KnowledgeBasesAsyncClient, transports.KnowledgeBasesGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), - (KnowledgeBasesClient, transports.KnowledgeBasesRestTransport, "rest", None), -]) -def test_knowledge_bases_client_client_options_credentials_file(client_class, transport_class, transport_name, grpc_helpers): - # 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, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file="credentials.json", - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - -def test_knowledge_bases_client_client_options_from_dict(): - with mock.patch('google.cloud.dialogflow_v2beta1.services.knowledge_bases.transports.KnowledgeBasesGrpcTransport.__init__') as grpc_transport: - grpc_transport.return_value = None - client = KnowledgeBasesClient( - client_options={'api_endpoint': 'squid.clam.whelk'} - ) - grpc_transport.assert_called_once_with( - credentials=None, - credentials_file=None, - host="squid.clam.whelk", - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - -@pytest.mark.parametrize("client_class,transport_class,transport_name,grpc_helpers", [ - (KnowledgeBasesClient, transports.KnowledgeBasesGrpcTransport, "grpc", grpc_helpers), - (KnowledgeBasesAsyncClient, transports.KnowledgeBasesGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), -]) -def test_knowledge_bases_client_create_channel_credentials_file(client_class, transport_class, transport_name, grpc_helpers): - # 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, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file="credentials.json", - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # test that the credentials from file are saved and used as the credentials. - with mock.patch.object( - google.auth, "load_credentials_from_file", autospec=True - ) as load_creds, mock.patch.object( - google.auth, "default", autospec=True - ) as adc, mock.patch.object( - grpc_helpers, "create_channel" - ) as create_channel: - creds = ga_credentials.AnonymousCredentials() - file_creds = ga_credentials.AnonymousCredentials() - load_creds.return_value = (file_creds, None) - adc.return_value = (creds, None) - client = client_class(client_options=options, transport=transport_name) - create_channel.assert_called_with( - "dialogflow.googleapis.com:443", - credentials=file_creds, - credentials_file=None, - quota_project_id=None, - default_scopes=( - 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/dialogflow', -), - scopes=None, - default_host="dialogflow.googleapis.com", - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - -@pytest.mark.parametrize("request_type", [ - knowledge_base.ListKnowledgeBasesRequest, - dict, -]) -def test_list_knowledge_bases(request_type, transport: str = 'grpc'): - client = KnowledgeBasesClient( - 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_knowledge_bases), - '__call__') as call: - # Designate an appropriate return value for the call. - 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' - - -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=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_knowledge_bases), - '__call__') as call: - client.list_knowledge_bases() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == knowledge_base.ListKnowledgeBasesRequest() - -@pytest.mark.asyncio -async def test_list_knowledge_bases_async(transport: str = 'grpc_asyncio', request_type=knowledge_base.ListKnowledgeBasesRequest): - client = KnowledgeBasesAsyncClient( - 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_knowledge_bases), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(knowledge_base.ListKnowledgeBasesResponse( - 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' - - -@pytest.mark.asyncio -async def test_list_knowledge_bases_async_from_dict(): - await test_list_knowledge_bases_async(request_type=dict) - - -def test_list_knowledge_bases_field_headers(): - 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. - with mock.patch.object( - 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. - 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_knowledge_bases_field_headers_async(): - 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. - with mock.patch.object( - type(client.transport.list_knowledge_bases), - '__call__') as call: - 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. - 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_knowledge_bases_flattened(): - client = KnowledgeBasesClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_knowledge_bases), - '__call__') 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', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - arg = args[0].parent - mock_val = 'parent_value' - assert arg == mock_val - - -def test_list_knowledge_bases_flattened_error(): - client = KnowledgeBasesClient( - 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_knowledge_bases( - knowledge_base.ListKnowledgeBasesRequest(), - parent='parent_value', - ) - -@pytest.mark.asyncio -async def test_list_knowledge_bases_flattened_async(): - client = KnowledgeBasesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_knowledge_bases), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = knowledge_base.ListKnowledgeBasesResponse() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(knowledge_base.ListKnowledgeBasesResponse()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.list_knowledge_bases( - 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] - arg = args[0].parent - mock_val = 'parent_value' - assert arg == mock_val - -@pytest.mark.asyncio -async def test_list_knowledge_bases_flattened_error_async(): - client = KnowledgeBasesAsyncClient( - 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_knowledge_bases( - knowledge_base.ListKnowledgeBasesRequest(), - parent='parent_value', - ) - - -def test_list_knowledge_bases_pager(transport_name: str = "grpc"): - client = KnowledgeBasesClient( - credentials=ga_credentials.AnonymousCredentials, - transport=transport_name, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_knowledge_bases), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - knowledge_base.ListKnowledgeBasesResponse( - knowledge_bases=[ - knowledge_base.KnowledgeBase(), - knowledge_base.KnowledgeBase(), - knowledge_base.KnowledgeBase(), - ], - next_page_token='abc', - ), - knowledge_base.ListKnowledgeBasesResponse( - knowledge_bases=[], - next_page_token='def', - ), - knowledge_base.ListKnowledgeBasesResponse( - knowledge_bases=[ - knowledge_base.KnowledgeBase(), - ], - next_page_token='ghi', - ), - knowledge_base.ListKnowledgeBasesResponse( - knowledge_bases=[ - knowledge_base.KnowledgeBase(), - knowledge_base.KnowledgeBase(), - ], - ), - RuntimeError, - ) - - metadata = () - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ('parent', ''), - )), - ) - pager = client.list_knowledge_bases(request={}) - - assert pager._metadata == metadata - - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, knowledge_base.KnowledgeBase) - for i in results) -def test_list_knowledge_bases_pages(transport_name: str = "grpc"): - client = KnowledgeBasesClient( - credentials=ga_credentials.AnonymousCredentials, - transport=transport_name, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_knowledge_bases), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - knowledge_base.ListKnowledgeBasesResponse( - knowledge_bases=[ - knowledge_base.KnowledgeBase(), - knowledge_base.KnowledgeBase(), - knowledge_base.KnowledgeBase(), - ], - next_page_token='abc', - ), - knowledge_base.ListKnowledgeBasesResponse( - knowledge_bases=[], - next_page_token='def', - ), - knowledge_base.ListKnowledgeBasesResponse( - knowledge_bases=[ - knowledge_base.KnowledgeBase(), - ], - next_page_token='ghi', - ), - knowledge_base.ListKnowledgeBasesResponse( - knowledge_bases=[ - knowledge_base.KnowledgeBase(), - knowledge_base.KnowledgeBase(), - ], - ), - RuntimeError, - ) - pages = list(client.list_knowledge_bases(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_knowledge_bases_async_pager(): - client = KnowledgeBasesAsyncClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_knowledge_bases), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - knowledge_base.ListKnowledgeBasesResponse( - knowledge_bases=[ - knowledge_base.KnowledgeBase(), - knowledge_base.KnowledgeBase(), - knowledge_base.KnowledgeBase(), - ], - next_page_token='abc', - ), - knowledge_base.ListKnowledgeBasesResponse( - knowledge_bases=[], - next_page_token='def', - ), - knowledge_base.ListKnowledgeBasesResponse( - knowledge_bases=[ - knowledge_base.KnowledgeBase(), - ], - next_page_token='ghi', - ), - knowledge_base.ListKnowledgeBasesResponse( - knowledge_bases=[ - knowledge_base.KnowledgeBase(), - knowledge_base.KnowledgeBase(), - ], - ), - RuntimeError, - ) - async_pager = await client.list_knowledge_bases(request={},) - assert async_pager.next_page_token == 'abc' - responses = [] - async for response in async_pager: # pragma: no branch - responses.append(response) - - assert len(responses) == 6 - assert all(isinstance(i, knowledge_base.KnowledgeBase) - for i in responses) - - -@pytest.mark.asyncio -async def test_list_knowledge_bases_async_pages(): - client = KnowledgeBasesAsyncClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_knowledge_bases), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - knowledge_base.ListKnowledgeBasesResponse( - knowledge_bases=[ - knowledge_base.KnowledgeBase(), - knowledge_base.KnowledgeBase(), - knowledge_base.KnowledgeBase(), - ], - next_page_token='abc', - ), - knowledge_base.ListKnowledgeBasesResponse( - knowledge_bases=[], - next_page_token='def', - ), - knowledge_base.ListKnowledgeBasesResponse( - knowledge_bases=[ - knowledge_base.KnowledgeBase(), - ], - next_page_token='ghi', - ), - knowledge_base.ListKnowledgeBasesResponse( - knowledge_bases=[ - knowledge_base.KnowledgeBase(), - knowledge_base.KnowledgeBase(), - ], - ), - RuntimeError, - ) - pages = [] - async for page_ in (await client.list_knowledge_bases(request={})).pages: # pragma: no branch - pages.append(page_) - for page_, token in zip(pages, ['abc','def','ghi', '']): - assert page_.raw_page.next_page_token == token - -@pytest.mark.parametrize("request_type", [ - knowledge_base.GetKnowledgeBaseRequest, - dict, -]) -def test_get_knowledge_base(request_type, transport: str = 'grpc'): - client = KnowledgeBasesClient( - 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_knowledge_base), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = knowledge_base.KnowledgeBase( - name='name_value', - 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' - - -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=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_knowledge_base), - '__call__') as call: - client.get_knowledge_base() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == knowledge_base.GetKnowledgeBaseRequest() - -@pytest.mark.asyncio -async def test_get_knowledge_base_async(transport: str = 'grpc_asyncio', request_type=knowledge_base.GetKnowledgeBaseRequest): - client = KnowledgeBasesAsyncClient( - 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_knowledge_base), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(knowledge_base.KnowledgeBase( - name='name_value', - display_name='display_name_value', - 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' - - -@pytest.mark.asyncio -async def test_get_knowledge_base_async_from_dict(): - await test_get_knowledge_base_async(request_type=dict) - - -def test_get_knowledge_base_field_headers(): - 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. - with mock.patch.object( - 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. - 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_knowledge_base_field_headers_async(): - 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. - with mock.patch.object( - type(client.transport.get_knowledge_base), - '__call__') as call: - 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. - 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_knowledge_base_flattened(): - client = KnowledgeBasesClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_knowledge_base), - '__call__') 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', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - arg = args[0].name - mock_val = 'name_value' - assert arg == mock_val - - -def test_get_knowledge_base_flattened_error(): - client = KnowledgeBasesClient( - 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_knowledge_base( - knowledge_base.GetKnowledgeBaseRequest(), - name='name_value', - ) - -@pytest.mark.asyncio -async def test_get_knowledge_base_flattened_async(): - client = KnowledgeBasesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_knowledge_base), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = knowledge_base.KnowledgeBase() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(knowledge_base.KnowledgeBase()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.get_knowledge_base( - 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] - arg = args[0].name - mock_val = 'name_value' - assert arg == mock_val - -@pytest.mark.asyncio -async def test_get_knowledge_base_flattened_error_async(): - client = KnowledgeBasesAsyncClient( - 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_knowledge_base( - knowledge_base.GetKnowledgeBaseRequest(), - name='name_value', - ) - - -@pytest.mark.parametrize("request_type", [ - gcd_knowledge_base.CreateKnowledgeBaseRequest, - dict, -]) -def test_create_knowledge_base(request_type, transport: str = 'grpc'): - client = KnowledgeBasesClient( - 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_knowledge_base), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcd_knowledge_base.KnowledgeBase( - name='name_value', - 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' - - -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=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_knowledge_base), - '__call__') as call: - client.create_knowledge_base() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == gcd_knowledge_base.CreateKnowledgeBaseRequest() - -@pytest.mark.asyncio -async def test_create_knowledge_base_async(transport: str = 'grpc_asyncio', request_type=gcd_knowledge_base.CreateKnowledgeBaseRequest): - client = KnowledgeBasesAsyncClient( - 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_knowledge_base), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gcd_knowledge_base.KnowledgeBase( - name='name_value', - display_name='display_name_value', - 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' - - -@pytest.mark.asyncio -async def test_create_knowledge_base_async_from_dict(): - await test_create_knowledge_base_async(request_type=dict) - - -def test_create_knowledge_base_field_headers(): - 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. - with mock.patch.object( - 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. - 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_knowledge_base_field_headers_async(): - 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. - with mock.patch.object( - type(client.transport.create_knowledge_base), - '__call__') as call: - 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. - 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_knowledge_base_flattened(): - client = KnowledgeBasesClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_knowledge_base), - '__call__') 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( - parent='parent_value', - knowledge_base=gcd_knowledge_base.KnowledgeBase(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] - arg = args[0].parent - mock_val = 'parent_value' - assert arg == mock_val - arg = args[0].knowledge_base - mock_val = gcd_knowledge_base.KnowledgeBase(name='name_value') - assert arg == mock_val - - -def test_create_knowledge_base_flattened_error(): - client = KnowledgeBasesClient( - 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_knowledge_base( - gcd_knowledge_base.CreateKnowledgeBaseRequest(), - parent='parent_value', - knowledge_base=gcd_knowledge_base.KnowledgeBase(name='name_value'), - ) - -@pytest.mark.asyncio -async def test_create_knowledge_base_flattened_async(): - client = KnowledgeBasesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_knowledge_base), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcd_knowledge_base.KnowledgeBase() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcd_knowledge_base.KnowledgeBase()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.create_knowledge_base( - parent='parent_value', - knowledge_base=gcd_knowledge_base.KnowledgeBase(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] - arg = args[0].parent - mock_val = 'parent_value' - assert arg == mock_val - arg = args[0].knowledge_base - mock_val = gcd_knowledge_base.KnowledgeBase(name='name_value') - assert arg == mock_val - -@pytest.mark.asyncio -async def test_create_knowledge_base_flattened_error_async(): - client = KnowledgeBasesAsyncClient( - 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_knowledge_base( - gcd_knowledge_base.CreateKnowledgeBaseRequest(), - parent='parent_value', - knowledge_base=gcd_knowledge_base.KnowledgeBase(name='name_value'), - ) - - -@pytest.mark.parametrize("request_type", [ - knowledge_base.DeleteKnowledgeBaseRequest, - dict, -]) -def test_delete_knowledge_base(request_type, transport: str = 'grpc'): - client = KnowledgeBasesClient( - 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_knowledge_base), - '__call__') 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. - assert response is None - - -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=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_knowledge_base), - '__call__') as call: - client.delete_knowledge_base() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == knowledge_base.DeleteKnowledgeBaseRequest() - -@pytest.mark.asyncio -async def test_delete_knowledge_base_async(transport: str = 'grpc_asyncio', request_type=knowledge_base.DeleteKnowledgeBaseRequest): - client = KnowledgeBasesAsyncClient( - 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_knowledge_base), - '__call__') 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. - assert response is None - - -@pytest.mark.asyncio -async def test_delete_knowledge_base_async_from_dict(): - await test_delete_knowledge_base_async(request_type=dict) - - -def test_delete_knowledge_base_field_headers(): - 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. - with mock.patch.object( - 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. - 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_knowledge_base_field_headers_async(): - 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. - with mock.patch.object( - 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. - 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_knowledge_base_flattened(): - client = KnowledgeBasesClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_knowledge_base), - '__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_knowledge_base( - 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] - arg = args[0].name - mock_val = 'name_value' - assert arg == mock_val - - -def test_delete_knowledge_base_flattened_error(): - client = KnowledgeBasesClient( - 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_knowledge_base( - knowledge_base.DeleteKnowledgeBaseRequest(), - name='name_value', - ) - -@pytest.mark.asyncio -async def test_delete_knowledge_base_flattened_async(): - client = KnowledgeBasesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_knowledge_base), - '__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_knowledge_base( - 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] - arg = args[0].name - mock_val = 'name_value' - assert arg == mock_val - -@pytest.mark.asyncio -async def test_delete_knowledge_base_flattened_error_async(): - client = KnowledgeBasesAsyncClient( - 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_knowledge_base( - knowledge_base.DeleteKnowledgeBaseRequest(), - name='name_value', - ) - - -@pytest.mark.parametrize("request_type", [ - gcd_knowledge_base.UpdateKnowledgeBaseRequest, - dict, -]) -def test_update_knowledge_base(request_type, transport: str = 'grpc'): - client = KnowledgeBasesClient( - 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_knowledge_base), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcd_knowledge_base.KnowledgeBase( - name='name_value', - 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' - - -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=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_knowledge_base), - '__call__') as call: - client.update_knowledge_base() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == gcd_knowledge_base.UpdateKnowledgeBaseRequest() - -@pytest.mark.asyncio -async def test_update_knowledge_base_async(transport: str = 'grpc_asyncio', request_type=gcd_knowledge_base.UpdateKnowledgeBaseRequest): - client = KnowledgeBasesAsyncClient( - 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_knowledge_base), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gcd_knowledge_base.KnowledgeBase( - name='name_value', - display_name='display_name_value', - 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' - - -@pytest.mark.asyncio -async def test_update_knowledge_base_async_from_dict(): - await test_update_knowledge_base_async(request_type=dict) - - -def test_update_knowledge_base_field_headers(): - 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 = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - 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. - 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', - 'knowledge_base.name=name_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_update_knowledge_base_field_headers_async(): - 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 = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_knowledge_base), - '__call__') as call: - 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. - 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', - 'knowledge_base.name=name_value', - ) in kw['metadata'] - - -def test_update_knowledge_base_flattened(): - client = KnowledgeBasesClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_knowledge_base), - '__call__') 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_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] - arg = args[0].knowledge_base - mock_val = gcd_knowledge_base.KnowledgeBase(name='name_value') - assert arg == mock_val - arg = args[0].update_mask - mock_val = field_mask_pb2.FieldMask(paths=['paths_value']) - assert arg == mock_val - - -def test_update_knowledge_base_flattened_error(): - client = KnowledgeBasesClient( - 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_knowledge_base( - gcd_knowledge_base.UpdateKnowledgeBaseRequest(), - knowledge_base=gcd_knowledge_base.KnowledgeBase(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - -@pytest.mark.asyncio -async def test_update_knowledge_base_flattened_async(): - client = KnowledgeBasesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_knowledge_base), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcd_knowledge_base.KnowledgeBase() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcd_knowledge_base.KnowledgeBase()) - # Call the method with a truthy value for each flattened field, - # 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_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] - arg = args[0].knowledge_base - mock_val = gcd_knowledge_base.KnowledgeBase(name='name_value') - assert arg == mock_val - arg = args[0].update_mask - mock_val = field_mask_pb2.FieldMask(paths=['paths_value']) - assert arg == mock_val - -@pytest.mark.asyncio -async def test_update_knowledge_base_flattened_error_async(): - client = KnowledgeBasesAsyncClient( - 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_knowledge_base( - gcd_knowledge_base.UpdateKnowledgeBaseRequest(), - knowledge_base=gcd_knowledge_base.KnowledgeBase(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - - -@pytest.mark.parametrize("request_type", [ - knowledge_base.ListKnowledgeBasesRequest, - dict, -]) -def test_list_knowledge_bases_rest(request_type): - client = KnowledgeBasesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = knowledge_base.ListKnowledgeBasesResponse( - next_page_token='next_page_token_value', - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - pb_return_value = knowledge_base.ListKnowledgeBasesResponse.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.list_knowledge_bases(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListKnowledgeBasesPager) - assert response.next_page_token == 'next_page_token_value' - - -def test_list_knowledge_bases_rest_required_fields(request_type=knowledge_base.ListKnowledgeBasesRequest): - transport_class = transports.KnowledgeBasesRestTransport - - request_init = {} - request_init["parent"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - including_default_value_fields=False, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).list_knowledge_bases._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["parent"] = 'parent_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).list_knowledge_bases._get_unset_required_fields(jsonified_request) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("filter", "page_size", "page_token", )) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "parent" in jsonified_request - assert jsonified_request["parent"] == 'parent_value' - - client = KnowledgeBasesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = knowledge_base.ListKnowledgeBasesResponse() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "get", - 'query_params': pb_request, - } - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - - pb_return_value = knowledge_base.ListKnowledgeBasesResponse.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.list_knowledge_bases(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_list_knowledge_bases_rest_unset_required_fields(): - transport = transports.KnowledgeBasesRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.list_knowledge_bases._get_unset_required_fields({}) - assert set(unset_fields) == (set(("filter", "pageSize", "pageToken", )) & set(("parent", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_list_knowledge_bases_rest_interceptors(null_interceptor): - transport = transports.KnowledgeBasesRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.KnowledgeBasesRestInterceptor(), - ) - client = KnowledgeBasesClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.KnowledgeBasesRestInterceptor, "post_list_knowledge_bases") as post, \ - mock.patch.object(transports.KnowledgeBasesRestInterceptor, "pre_list_knowledge_bases") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = knowledge_base.ListKnowledgeBasesRequest.pb(knowledge_base.ListKnowledgeBasesRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = knowledge_base.ListKnowledgeBasesResponse.to_json(knowledge_base.ListKnowledgeBasesResponse()) - - request = knowledge_base.ListKnowledgeBasesRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = knowledge_base.ListKnowledgeBasesResponse() - - client.list_knowledge_bases(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_list_knowledge_bases_rest_bad_request(transport: str = 'rest', request_type=knowledge_base.ListKnowledgeBasesRequest): - client = KnowledgeBasesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.list_knowledge_bases(request) - - -def test_list_knowledge_bases_rest_flattened(): - client = KnowledgeBasesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = knowledge_base.ListKnowledgeBasesResponse() - - # get arguments that satisfy an http rule for this method - sample_request = {'parent': 'projects/sample1'} - - # get truthy value for each flattened field - mock_args = dict( - parent='parent_value', - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - pb_return_value = knowledge_base.ListKnowledgeBasesResponse.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.list_knowledge_bases(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v2beta1/{parent=projects/*}/knowledgeBases" % client.transport._host, args[1]) - - -def test_list_knowledge_bases_rest_flattened_error(transport: str = 'rest'): - client = KnowledgeBasesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.list_knowledge_bases( - knowledge_base.ListKnowledgeBasesRequest(), - parent='parent_value', - ) - - -def test_list_knowledge_bases_rest_pager(transport: str = 'rest'): - client = KnowledgeBasesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # TODO(kbandes): remove this mock unless there's a good reason for it. - #with mock.patch.object(path_template, 'transcode') as transcode: - # Set the response as a series of pages - response = ( - knowledge_base.ListKnowledgeBasesResponse( - knowledge_bases=[ - knowledge_base.KnowledgeBase(), - knowledge_base.KnowledgeBase(), - knowledge_base.KnowledgeBase(), - ], - next_page_token='abc', - ), - knowledge_base.ListKnowledgeBasesResponse( - knowledge_bases=[], - next_page_token='def', - ), - knowledge_base.ListKnowledgeBasesResponse( - knowledge_bases=[ - knowledge_base.KnowledgeBase(), - ], - next_page_token='ghi', - ), - knowledge_base.ListKnowledgeBasesResponse( - knowledge_bases=[ - knowledge_base.KnowledgeBase(), - knowledge_base.KnowledgeBase(), - ], - ), - ) - # Two responses for two calls - response = response + response - - # Wrap the values into proper Response objs - response = tuple(knowledge_base.ListKnowledgeBasesResponse.to_json(x) for x in response) - return_values = tuple(Response() for i in response) - for return_val, response_val in zip(return_values, response): - return_val._content = response_val.encode('UTF-8') - return_val.status_code = 200 - req.side_effect = return_values - - sample_request = {'parent': 'projects/sample1'} - - pager = client.list_knowledge_bases(request=sample_request) - - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, knowledge_base.KnowledgeBase) - for i in results) - - pages = list(client.list_knowledge_bases(request=sample_request).pages) - for page_, token in zip(pages, ['abc','def','ghi', '']): - assert page_.raw_page.next_page_token == token - - -@pytest.mark.parametrize("request_type", [ - knowledge_base.GetKnowledgeBaseRequest, - dict, -]) -def test_get_knowledge_base_rest(request_type): - client = KnowledgeBasesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/knowledgeBases/sample2'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = knowledge_base.KnowledgeBase( - name='name_value', - display_name='display_name_value', - language_code='language_code_value', - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - pb_return_value = knowledge_base.KnowledgeBase.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.get_knowledge_base(request) - - # 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' - - -def test_get_knowledge_base_rest_required_fields(request_type=knowledge_base.GetKnowledgeBaseRequest): - transport_class = transports.KnowledgeBasesRestTransport - - request_init = {} - request_init["name"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - including_default_value_fields=False, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_knowledge_base._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["name"] = 'name_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_knowledge_base._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "name" in jsonified_request - assert jsonified_request["name"] == 'name_value' - - client = KnowledgeBasesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = knowledge_base.KnowledgeBase() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "get", - 'query_params': pb_request, - } - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - - pb_return_value = knowledge_base.KnowledgeBase.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.get_knowledge_base(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_get_knowledge_base_rest_unset_required_fields(): - transport = transports.KnowledgeBasesRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.get_knowledge_base._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_get_knowledge_base_rest_interceptors(null_interceptor): - transport = transports.KnowledgeBasesRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.KnowledgeBasesRestInterceptor(), - ) - client = KnowledgeBasesClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.KnowledgeBasesRestInterceptor, "post_get_knowledge_base") as post, \ - mock.patch.object(transports.KnowledgeBasesRestInterceptor, "pre_get_knowledge_base") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = knowledge_base.GetKnowledgeBaseRequest.pb(knowledge_base.GetKnowledgeBaseRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = knowledge_base.KnowledgeBase.to_json(knowledge_base.KnowledgeBase()) - - request = knowledge_base.GetKnowledgeBaseRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = knowledge_base.KnowledgeBase() - - client.get_knowledge_base(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_get_knowledge_base_rest_bad_request(transport: str = 'rest', request_type=knowledge_base.GetKnowledgeBaseRequest): - client = KnowledgeBasesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/knowledgeBases/sample2'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.get_knowledge_base(request) - - -def test_get_knowledge_base_rest_flattened(): - client = KnowledgeBasesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = knowledge_base.KnowledgeBase() - - # get arguments that satisfy an http rule for this method - sample_request = {'name': 'projects/sample1/knowledgeBases/sample2'} - - # get truthy value for each flattened field - mock_args = dict( - name='name_value', - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - pb_return_value = knowledge_base.KnowledgeBase.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.get_knowledge_base(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v2beta1/{name=projects/*/knowledgeBases/*}" % client.transport._host, args[1]) - - -def test_get_knowledge_base_rest_flattened_error(transport: str = 'rest'): - client = KnowledgeBasesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.get_knowledge_base( - knowledge_base.GetKnowledgeBaseRequest(), - name='name_value', - ) - - -def test_get_knowledge_base_rest_error(): - client = KnowledgeBasesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - gcd_knowledge_base.CreateKnowledgeBaseRequest, - dict, -]) -def test_create_knowledge_base_rest(request_type): - client = KnowledgeBasesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1'} - request_init["knowledge_base"] = {'name': 'name_value', 'display_name': 'display_name_value', 'language_code': 'language_code_value'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = gcd_knowledge_base.KnowledgeBase( - name='name_value', - display_name='display_name_value', - language_code='language_code_value', - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - pb_return_value = gcd_knowledge_base.KnowledgeBase.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.create_knowledge_base(request) - - # 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' - - -def test_create_knowledge_base_rest_required_fields(request_type=gcd_knowledge_base.CreateKnowledgeBaseRequest): - transport_class = transports.KnowledgeBasesRestTransport - - request_init = {} - request_init["parent"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - including_default_value_fields=False, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_knowledge_base._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["parent"] = 'parent_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_knowledge_base._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "parent" in jsonified_request - assert jsonified_request["parent"] == 'parent_value' - - client = KnowledgeBasesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = gcd_knowledge_base.KnowledgeBase() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "post", - 'query_params': pb_request, - } - transcode_result['body'] = pb_request - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - - pb_return_value = gcd_knowledge_base.KnowledgeBase.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.create_knowledge_base(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_create_knowledge_base_rest_unset_required_fields(): - transport = transports.KnowledgeBasesRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.create_knowledge_base._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("parent", "knowledgeBase", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_create_knowledge_base_rest_interceptors(null_interceptor): - transport = transports.KnowledgeBasesRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.KnowledgeBasesRestInterceptor(), - ) - client = KnowledgeBasesClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.KnowledgeBasesRestInterceptor, "post_create_knowledge_base") as post, \ - mock.patch.object(transports.KnowledgeBasesRestInterceptor, "pre_create_knowledge_base") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = gcd_knowledge_base.CreateKnowledgeBaseRequest.pb(gcd_knowledge_base.CreateKnowledgeBaseRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = gcd_knowledge_base.KnowledgeBase.to_json(gcd_knowledge_base.KnowledgeBase()) - - request = gcd_knowledge_base.CreateKnowledgeBaseRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = gcd_knowledge_base.KnowledgeBase() - - client.create_knowledge_base(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_create_knowledge_base_rest_bad_request(transport: str = 'rest', request_type=gcd_knowledge_base.CreateKnowledgeBaseRequest): - client = KnowledgeBasesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1'} - request_init["knowledge_base"] = {'name': 'name_value', 'display_name': 'display_name_value', 'language_code': 'language_code_value'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.create_knowledge_base(request) - - -def test_create_knowledge_base_rest_flattened(): - client = KnowledgeBasesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = gcd_knowledge_base.KnowledgeBase() - - # get arguments that satisfy an http rule for this method - sample_request = {'parent': 'projects/sample1'} - - # get truthy value for each flattened field - mock_args = dict( - parent='parent_value', - knowledge_base=gcd_knowledge_base.KnowledgeBase(name='name_value'), - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - pb_return_value = gcd_knowledge_base.KnowledgeBase.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.create_knowledge_base(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v2beta1/{parent=projects/*}/knowledgeBases" % client.transport._host, args[1]) - - -def test_create_knowledge_base_rest_flattened_error(transport: str = 'rest'): - client = KnowledgeBasesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.create_knowledge_base( - gcd_knowledge_base.CreateKnowledgeBaseRequest(), - parent='parent_value', - knowledge_base=gcd_knowledge_base.KnowledgeBase(name='name_value'), - ) - - -def test_create_knowledge_base_rest_error(): - client = KnowledgeBasesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - knowledge_base.DeleteKnowledgeBaseRequest, - dict, -]) -def test_delete_knowledge_base_rest(request_type): - client = KnowledgeBasesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/knowledgeBases/sample2'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = None - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = '' - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.delete_knowledge_base(request) - - # Establish that the response is the type that we expect. - assert response is None - - -def test_delete_knowledge_base_rest_required_fields(request_type=knowledge_base.DeleteKnowledgeBaseRequest): - transport_class = transports.KnowledgeBasesRestTransport - - request_init = {} - request_init["name"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - including_default_value_fields=False, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).delete_knowledge_base._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["name"] = 'name_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).delete_knowledge_base._get_unset_required_fields(jsonified_request) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("force", )) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "name" in jsonified_request - assert jsonified_request["name"] == 'name_value' - - client = KnowledgeBasesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = None - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "delete", - 'query_params': pb_request, - } - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - json_return_value = '' - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.delete_knowledge_base(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_delete_knowledge_base_rest_unset_required_fields(): - transport = transports.KnowledgeBasesRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.delete_knowledge_base._get_unset_required_fields({}) - assert set(unset_fields) == (set(("force", )) & set(("name", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_delete_knowledge_base_rest_interceptors(null_interceptor): - transport = transports.KnowledgeBasesRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.KnowledgeBasesRestInterceptor(), - ) - client = KnowledgeBasesClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.KnowledgeBasesRestInterceptor, "pre_delete_knowledge_base") as pre: - pre.assert_not_called() - pb_message = knowledge_base.DeleteKnowledgeBaseRequest.pb(knowledge_base.DeleteKnowledgeBaseRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - - request = knowledge_base.DeleteKnowledgeBaseRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - - client.delete_knowledge_base(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - - -def test_delete_knowledge_base_rest_bad_request(transport: str = 'rest', request_type=knowledge_base.DeleteKnowledgeBaseRequest): - client = KnowledgeBasesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/knowledgeBases/sample2'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.delete_knowledge_base(request) - - -def test_delete_knowledge_base_rest_flattened(): - client = KnowledgeBasesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = None - - # get arguments that satisfy an http rule for this method - sample_request = {'name': 'projects/sample1/knowledgeBases/sample2'} - - # get truthy value for each flattened field - mock_args = dict( - name='name_value', - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = '' - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.delete_knowledge_base(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v2beta1/{name=projects/*/knowledgeBases/*}" % client.transport._host, args[1]) - - -def test_delete_knowledge_base_rest_flattened_error(transport: str = 'rest'): - client = KnowledgeBasesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.delete_knowledge_base( - knowledge_base.DeleteKnowledgeBaseRequest(), - name='name_value', - ) - - -def test_delete_knowledge_base_rest_error(): - client = KnowledgeBasesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - gcd_knowledge_base.UpdateKnowledgeBaseRequest, - dict, -]) -def test_update_knowledge_base_rest(request_type): - client = KnowledgeBasesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'knowledge_base': {'name': 'projects/sample1/knowledgeBases/sample2'}} - request_init["knowledge_base"] = {'name': 'projects/sample1/knowledgeBases/sample2', 'display_name': 'display_name_value', 'language_code': 'language_code_value'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = gcd_knowledge_base.KnowledgeBase( - name='name_value', - display_name='display_name_value', - language_code='language_code_value', - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - pb_return_value = gcd_knowledge_base.KnowledgeBase.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.update_knowledge_base(request) - - # 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' - - -def test_update_knowledge_base_rest_required_fields(request_type=gcd_knowledge_base.UpdateKnowledgeBaseRequest): - transport_class = transports.KnowledgeBasesRestTransport - - request_init = {} - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - including_default_value_fields=False, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).update_knowledge_base._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).update_knowledge_base._get_unset_required_fields(jsonified_request) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("update_mask", )) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - - client = KnowledgeBasesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = gcd_knowledge_base.KnowledgeBase() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "patch", - 'query_params': pb_request, - } - transcode_result['body'] = pb_request - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - - pb_return_value = gcd_knowledge_base.KnowledgeBase.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.update_knowledge_base(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_update_knowledge_base_rest_unset_required_fields(): - transport = transports.KnowledgeBasesRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.update_knowledge_base._get_unset_required_fields({}) - assert set(unset_fields) == (set(("updateMask", )) & set(("knowledgeBase", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_update_knowledge_base_rest_interceptors(null_interceptor): - transport = transports.KnowledgeBasesRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.KnowledgeBasesRestInterceptor(), - ) - client = KnowledgeBasesClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.KnowledgeBasesRestInterceptor, "post_update_knowledge_base") as post, \ - mock.patch.object(transports.KnowledgeBasesRestInterceptor, "pre_update_knowledge_base") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = gcd_knowledge_base.UpdateKnowledgeBaseRequest.pb(gcd_knowledge_base.UpdateKnowledgeBaseRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = gcd_knowledge_base.KnowledgeBase.to_json(gcd_knowledge_base.KnowledgeBase()) - - request = gcd_knowledge_base.UpdateKnowledgeBaseRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = gcd_knowledge_base.KnowledgeBase() - - client.update_knowledge_base(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_update_knowledge_base_rest_bad_request(transport: str = 'rest', request_type=gcd_knowledge_base.UpdateKnowledgeBaseRequest): - client = KnowledgeBasesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'knowledge_base': {'name': 'projects/sample1/knowledgeBases/sample2'}} - request_init["knowledge_base"] = {'name': 'projects/sample1/knowledgeBases/sample2', 'display_name': 'display_name_value', 'language_code': 'language_code_value'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.update_knowledge_base(request) - - -def test_update_knowledge_base_rest_flattened(): - client = KnowledgeBasesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = gcd_knowledge_base.KnowledgeBase() - - # get arguments that satisfy an http rule for this method - sample_request = {'knowledge_base': {'name': 'projects/sample1/knowledgeBases/sample2'}} - - # get truthy value for each flattened field - mock_args = dict( - knowledge_base=gcd_knowledge_base.KnowledgeBase(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - pb_return_value = gcd_knowledge_base.KnowledgeBase.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.update_knowledge_base(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v2beta1/{knowledge_base.name=projects/*/knowledgeBases/*}" % client.transport._host, args[1]) - - -def test_update_knowledge_base_rest_flattened_error(transport: str = 'rest'): - client = KnowledgeBasesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.update_knowledge_base( - gcd_knowledge_base.UpdateKnowledgeBaseRequest(), - knowledge_base=gcd_knowledge_base.KnowledgeBase(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - - -def test_update_knowledge_base_rest_error(): - client = KnowledgeBasesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -def test_credentials_transport_error(): - # It is an error to provide credentials and a transport instance. - transport = transports.KnowledgeBasesGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = KnowledgeBasesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # It is an error to provide a credentials file and a transport instance. - transport = transports.KnowledgeBasesGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = KnowledgeBasesClient( - client_options={"credentials_file": "credentials.json"}, - transport=transport, - ) - - # It is an error to provide an api_key and a transport instance. - transport = transports.KnowledgeBasesGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - options = client_options.ClientOptions() - options.api_key = "api_key" - with pytest.raises(ValueError): - client = KnowledgeBasesClient( - client_options=options, - transport=transport, - ) - - # It is an error to provide an api_key and a credential. - options = mock.Mock() - options.api_key = "api_key" - with pytest.raises(ValueError): - client = KnowledgeBasesClient( - client_options=options, - credentials=ga_credentials.AnonymousCredentials() - ) - - # It is an error to provide scopes and a transport instance. - transport = transports.KnowledgeBasesGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = KnowledgeBasesClient( - client_options={"scopes": ["1", "2"]}, - transport=transport, - ) - - -def test_transport_instance(): - # A client may be instantiated with a custom transport instance. - transport = transports.KnowledgeBasesGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - client = KnowledgeBasesClient(transport=transport) - assert client.transport is transport - -def test_transport_get_channel(): - # A client may be instantiated with a custom transport instance. - transport = transports.KnowledgeBasesGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - - transport = transports.KnowledgeBasesGrpcAsyncIOTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - -@pytest.mark.parametrize("transport_class", [ - transports.KnowledgeBasesGrpcTransport, - transports.KnowledgeBasesGrpcAsyncIOTransport, - transports.KnowledgeBasesRestTransport, -]) -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() - -@pytest.mark.parametrize("transport_name", [ - "grpc", - "rest", -]) -def test_transport_kind(transport_name): - transport = KnowledgeBasesClient.get_transport_class(transport_name)( - credentials=ga_credentials.AnonymousCredentials(), - ) - assert transport.kind == transport_name - -def test_transport_grpc_default(): - # A client should use the gRPC transport by default. - 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(core_exceptions.DuplicateCredentialArgs): - transport = transports.KnowledgeBasesTransport( - credentials=ga_credentials.AnonymousCredentials(), - credentials_file="credentials.json" - ) - - -def test_knowledge_bases_base_transport(): - # Instantiate the base transport. - with mock.patch('google.cloud.dialogflow_v2beta1.services.knowledge_bases.transports.KnowledgeBasesTransport.__init__') as Transport: - Transport.return_value = None - transport = transports.KnowledgeBasesTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Every method on the transport should just blindly - # raise NotImplementedError. - methods = ( - 'list_knowledge_bases', - 'get_knowledge_base', - 'create_knowledge_base', - 'delete_knowledge_base', - 'update_knowledge_base', - 'get_location', - 'list_locations', - 'get_operation', - 'cancel_operation', - 'list_operations', - ) - for method in methods: - with pytest.raises(NotImplementedError): - getattr(transport, method)(request=object()) - - with pytest.raises(NotImplementedError): - transport.close() - - # Catch all for all remaining methods and properties - remainder = [ - 'kind', - ] - for r in remainder: - with pytest.raises(NotImplementedError): - getattr(transport, r)() - - -def test_knowledge_bases_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.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", - ) - - -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(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 = (ga_credentials.AnonymousCredentials(), None) - transport = transports.KnowledgeBasesTransport() - adc.assert_called_once() - - -def test_knowledge_bases_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) - 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, - ) - - -@pytest.mark.parametrize( - "transport_class", - [ - transports.KnowledgeBasesGrpcTransport, - transports.KnowledgeBasesGrpcAsyncIOTransport, - ], -) -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(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, - transports.KnowledgeBasesRestTransport, - ], -) -def test_knowledge_bases_transport_auth_gdch_credentials(transport_class): - host = 'https://language.com' - api_audience_tests = [None, 'https://language2.com'] - api_audience_expect = [host, 'https://language2.com'] - for t, e in zip(api_audience_tests, api_audience_expect): - with mock.patch.object(google.auth, 'default', autospec=True) as adc: - gdch_mock = mock.MagicMock() - type(gdch_mock).with_gdch_audience = mock.PropertyMock(return_value=gdch_mock) - adc.return_value = (gdch_mock, None) - transport_class(host=host, api_audience=t) - gdch_mock.with_gdch_audience.assert_called_once_with( - e - ) - - -@pytest.mark.parametrize( - "transport_class,grpc_helpers", - [ - (transports.KnowledgeBasesGrpcTransport, grpc_helpers), - (transports.KnowledgeBasesGrpcAsyncIOTransport, grpc_helpers_async) - ], -) -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", [transports.KnowledgeBasesGrpcTransport, transports.KnowledgeBasesGrpcAsyncIOTransport]) -def test_knowledge_bases_grpc_transport_client_cert_source_for_mtls( - transport_class -): - cred = ga_credentials.AnonymousCredentials() - - # Check ssl_channel_credentials is used if provided. - with mock.patch.object(transport_class, "create_channel") as mock_create_channel: - mock_ssl_channel_creds = mock.Mock() - transport_class( - host="squid.clam.whelk", - credentials=cred, - ssl_channel_credentials=mock_ssl_channel_creds - ) - mock_create_channel.assert_called_once_with( - "squid.clam.whelk:443", - credentials=cred, - credentials_file=None, - scopes=None, - ssl_credentials=mock_ssl_channel_creds, - quota_project_id=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - # Check if ssl_channel_credentials is not provided, then client_cert_source_for_mtls - # is used. - with mock.patch.object(transport_class, "create_channel", return_value=mock.Mock()): - with mock.patch("grpc.ssl_channel_credentials") as mock_ssl_cred: - transport_class( - credentials=cred, - client_cert_source_for_mtls=client_cert_source_callback - ) - expected_cert, expected_key = client_cert_source_callback() - mock_ssl_cred.assert_called_once_with( - certificate_chain=expected_cert, - private_key=expected_key - ) - -def test_knowledge_bases_http_transport_client_cert_source_for_mtls(): - cred = ga_credentials.AnonymousCredentials() - with mock.patch("google.auth.transport.requests.AuthorizedSession.configure_mtls_channel") as mock_configure_mtls_channel: - transports.KnowledgeBasesRestTransport ( - credentials=cred, - client_cert_source_for_mtls=client_cert_source_callback - ) - mock_configure_mtls_channel.assert_called_once_with(client_cert_source_callback) - - -@pytest.mark.parametrize("transport_name", [ - "grpc", - "grpc_asyncio", - "rest", -]) -def test_knowledge_bases_host_no_port(transport_name): - client = KnowledgeBasesClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='dialogflow.googleapis.com'), - transport=transport_name, - ) - assert client.transport._host == ( - 'dialogflow.googleapis.com:443' - if transport_name in ['grpc', 'grpc_asyncio'] - else 'https://dialogflow.googleapis.com' - ) - -@pytest.mark.parametrize("transport_name", [ - "grpc", - "grpc_asyncio", - "rest", -]) -def test_knowledge_bases_host_with_port(transport_name): - client = KnowledgeBasesClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='dialogflow.googleapis.com:8000'), - transport=transport_name, - ) - assert client.transport._host == ( - 'dialogflow.googleapis.com:8000' - if transport_name in ['grpc', 'grpc_asyncio'] - else 'https://dialogflow.googleapis.com:8000' - ) - -@pytest.mark.parametrize("transport_name", [ - "rest", -]) -def test_knowledge_bases_client_transport_session_collision(transport_name): - creds1 = ga_credentials.AnonymousCredentials() - creds2 = ga_credentials.AnonymousCredentials() - client1 = KnowledgeBasesClient( - credentials=creds1, - transport=transport_name, - ) - client2 = KnowledgeBasesClient( - credentials=creds2, - transport=transport_name, - ) - session1 = client1.transport.list_knowledge_bases._session - session2 = client2.transport.list_knowledge_bases._session - assert session1 != session2 - session1 = client1.transport.get_knowledge_base._session - session2 = client2.transport.get_knowledge_base._session - assert session1 != session2 - session1 = client1.transport.create_knowledge_base._session - session2 = client2.transport.create_knowledge_base._session - assert session1 != session2 - session1 = client1.transport.delete_knowledge_base._session - session2 = client2.transport.delete_knowledge_base._session - assert session1 != session2 - session1 = client1.transport.update_knowledge_base._session - session2 = client2.transport.update_knowledge_base._session - assert session1 != session2 -def test_knowledge_bases_grpc_transport_channel(): - channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.KnowledgeBasesGrpcTransport( - 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_knowledge_bases_grpc_asyncio_transport_channel(): - channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.KnowledgeBasesGrpcAsyncIOTransport( - 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.KnowledgeBasesGrpcTransport, transports.KnowledgeBasesGrpcAsyncIOTransport]) -def test_knowledge_bases_transport_channel_mtls_with_client_cert_source( - transport_class -): - with mock.patch("grpc.ssl_channel_credentials", autospec=True) as grpc_ssl_channel_cred: - with mock.patch.object(transport_class, "create_channel") as grpc_create_channel: - mock_ssl_cred = mock.Mock() - grpc_ssl_channel_cred.return_value = mock_ssl_cred - - mock_grpc_channel = mock.Mock() - grpc_create_channel.return_value = mock_grpc_channel - - cred = ga_credentials.AnonymousCredentials() - with pytest.warns(DeprecationWarning): - with mock.patch.object(google.auth, 'default') as adc: - adc.return_value = (cred, None) - transport = transport_class( - host="squid.clam.whelk", - api_mtls_endpoint="mtls.squid.clam.whelk", - client_cert_source=client_cert_source_callback, - ) - adc.assert_called_once() - - grpc_ssl_channel_cred.assert_called_once_with( - certificate_chain=b"cert bytes", private_key=b"key bytes" - ) - grpc_create_channel.assert_called_once_with( - "mtls.squid.clam.whelk:443", - credentials=cred, - credentials_file=None, - scopes=None, - ssl_credentials=mock_ssl_cred, - quota_project_id=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - assert transport.grpc_channel == mock_grpc_channel - assert transport._ssl_channel_credentials == mock_ssl_cred - - -# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are -# removed from grpc/grpc_asyncio transport constructor. -@pytest.mark.parametrize("transport_class", [transports.KnowledgeBasesGrpcTransport, transports.KnowledgeBasesGrpcAsyncIOTransport]) -def test_knowledge_bases_transport_channel_mtls_with_adc( - transport_class -): - mock_ssl_cred = mock.Mock() - with mock.patch.multiple( - "google.auth.transport.grpc.SslCredentials", - __init__=mock.Mock(return_value=None), - ssl_credentials=mock.PropertyMock(return_value=mock_ssl_cred), - ): - with mock.patch.object(transport_class, "create_channel") as grpc_create_channel: - mock_grpc_channel = mock.Mock() - grpc_create_channel.return_value = mock_grpc_channel - mock_cred = mock.Mock() - - with pytest.warns(DeprecationWarning): - transport = transport_class( - host="squid.clam.whelk", - credentials=mock_cred, - api_mtls_endpoint="mtls.squid.clam.whelk", - client_cert_source=None, - ) - - grpc_create_channel.assert_called_once_with( - "mtls.squid.clam.whelk:443", - credentials=mock_cred, - credentials_file=None, - scopes=None, - ssl_credentials=mock_ssl_cred, - quota_project_id=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - assert transport.grpc_channel == mock_grpc_channel - - -def test_knowledge_base_path(): - project = "squid" - knowledge_base = "clam" - expected = "projects/{project}/knowledgeBases/{knowledge_base}".format(project=project, knowledge_base=knowledge_base, ) - actual = KnowledgeBasesClient.knowledge_base_path(project, knowledge_base) - assert expected == actual - - -def test_parse_knowledge_base_path(): - expected = { - "project": "whelk", - "knowledge_base": "octopus", - } - path = KnowledgeBasesClient.knowledge_base_path(**expected) - - # Check that the path construction is reversible. - actual = KnowledgeBasesClient.parse_knowledge_base_path(path) - assert expected == actual - -def test_common_billing_account_path(): - billing_account = "oyster" - expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) - actual = KnowledgeBasesClient.common_billing_account_path(billing_account) - assert expected == actual - - -def test_parse_common_billing_account_path(): - expected = { - "billing_account": "nudibranch", - } - path = KnowledgeBasesClient.common_billing_account_path(**expected) - - # Check that the path construction is reversible. - actual = KnowledgeBasesClient.parse_common_billing_account_path(path) - assert expected == actual - -def test_common_folder_path(): - folder = "cuttlefish" - expected = "folders/{folder}".format(folder=folder, ) - actual = KnowledgeBasesClient.common_folder_path(folder) - assert expected == actual - - -def test_parse_common_folder_path(): - expected = { - "folder": "mussel", - } - path = KnowledgeBasesClient.common_folder_path(**expected) - - # Check that the path construction is reversible. - actual = KnowledgeBasesClient.parse_common_folder_path(path) - assert expected == actual - -def test_common_organization_path(): - organization = "winkle" - expected = "organizations/{organization}".format(organization=organization, ) - actual = KnowledgeBasesClient.common_organization_path(organization) - assert expected == actual - - -def test_parse_common_organization_path(): - expected = { - "organization": "nautilus", - } - path = KnowledgeBasesClient.common_organization_path(**expected) - - # Check that the path construction is reversible. - actual = KnowledgeBasesClient.parse_common_organization_path(path) - assert expected == actual - -def test_common_project_path(): - project = "scallop" - expected = "projects/{project}".format(project=project, ) - actual = KnowledgeBasesClient.common_project_path(project) - assert expected == actual - - -def test_parse_common_project_path(): - expected = { - "project": "abalone", - } - path = KnowledgeBasesClient.common_project_path(**expected) - - # Check that the path construction is reversible. - actual = KnowledgeBasesClient.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 = KnowledgeBasesClient.common_location_path(project, location) - assert expected == actual - - -def test_parse_common_location_path(): - expected = { - "project": "whelk", - "location": "octopus", - } - path = KnowledgeBasesClient.common_location_path(**expected) - - # Check that the path construction is reversible. - actual = KnowledgeBasesClient.parse_common_location_path(path) - assert expected == actual - - -def test_client_with_default_client_info(): - client_info = gapic_v1.client_info.ClientInfo() - - with mock.patch.object(transports.KnowledgeBasesTransport, '_prep_wrapped_messages') as prep: - client = KnowledgeBasesClient( - credentials=ga_credentials.AnonymousCredentials(), - client_info=client_info, - ) - prep.assert_called_once_with(client_info) - - with mock.patch.object(transports.KnowledgeBasesTransport, '_prep_wrapped_messages') as prep: - transport_class = KnowledgeBasesClient.get_transport_class() - transport = transport_class( - credentials=ga_credentials.AnonymousCredentials(), - client_info=client_info, - ) - prep.assert_called_once_with(client_info) - -@pytest.mark.asyncio -async def test_transport_close_async(): - client = KnowledgeBasesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - with mock.patch.object(type(getattr(client.transport, "grpc_channel")), "close") as close: - async with client: - close.assert_not_called() - close.assert_called_once() - - -def test_get_location_rest_bad_request(transport: str = 'rest', request_type=locations_pb2.GetLocationRequest): - client = KnowledgeBasesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - request = request_type() - request = json_format.ParseDict({'name': 'projects/sample1/locations/sample2'}, request) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.get_location(request) - -@pytest.mark.parametrize("request_type", [ - locations_pb2.GetLocationRequest, - dict, -]) -def test_get_location_rest(request_type): - client = KnowledgeBasesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request_init = {'name': 'projects/sample1/locations/sample2'} - request = request_type(**request_init) - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = locations_pb2.Location() - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.get_location(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, locations_pb2.Location) - -def test_list_locations_rest_bad_request(transport: str = 'rest', request_type=locations_pb2.ListLocationsRequest): - client = KnowledgeBasesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - request = request_type() - request = json_format.ParseDict({'name': 'projects/sample1'}, request) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.list_locations(request) - -@pytest.mark.parametrize("request_type", [ - locations_pb2.ListLocationsRequest, - dict, -]) -def test_list_locations_rest(request_type): - client = KnowledgeBasesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request_init = {'name': 'projects/sample1'} - request = request_type(**request_init) - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = locations_pb2.ListLocationsResponse() - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.list_locations(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, locations_pb2.ListLocationsResponse) - -def test_cancel_operation_rest_bad_request(transport: str = 'rest', request_type=operations_pb2.CancelOperationRequest): - client = KnowledgeBasesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - request = request_type() - request = json_format.ParseDict({'name': 'projects/sample1/operations/sample2'}, request) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.cancel_operation(request) - -@pytest.mark.parametrize("request_type", [ - operations_pb2.CancelOperationRequest, - dict, -]) -def test_cancel_operation_rest(request_type): - client = KnowledgeBasesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request_init = {'name': 'projects/sample1/operations/sample2'} - request = request_type(**request_init) - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = None - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = '{}' - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.cancel_operation(request) - - # Establish that the response is the type that we expect. - assert response is None - -def test_get_operation_rest_bad_request(transport: str = 'rest', request_type=operations_pb2.GetOperationRequest): - client = KnowledgeBasesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - request = request_type() - request = json_format.ParseDict({'name': 'projects/sample1/operations/sample2'}, request) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.get_operation(request) - -@pytest.mark.parametrize("request_type", [ - operations_pb2.GetOperationRequest, - dict, -]) -def test_get_operation_rest(request_type): - client = KnowledgeBasesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request_init = {'name': 'projects/sample1/operations/sample2'} - request = request_type(**request_init) - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation() - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.get_operation(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, operations_pb2.Operation) - -def test_list_operations_rest_bad_request(transport: str = 'rest', request_type=operations_pb2.ListOperationsRequest): - client = KnowledgeBasesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - request = request_type() - request = json_format.ParseDict({'name': 'projects/sample1'}, request) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.list_operations(request) - -@pytest.mark.parametrize("request_type", [ - operations_pb2.ListOperationsRequest, - dict, -]) -def test_list_operations_rest(request_type): - client = KnowledgeBasesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request_init = {'name': 'projects/sample1'} - request = request_type(**request_init) - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = operations_pb2.ListOperationsResponse() - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.list_operations(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, operations_pb2.ListOperationsResponse) - - -def test_cancel_operation(transport: str = "grpc"): - client = KnowledgeBasesClient( - 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 = operations_pb2.CancelOperationRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = None - response = client.cancel_operation(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 response is the type that we expect. - assert response is None -@pytest.mark.asyncio -async def test_cancel_operation_async(transport: str = "grpc"): - client = KnowledgeBasesAsyncClient( - 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 = operations_pb2.CancelOperationRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - None - ) - response = await client.cancel_operation(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 response is the type that we expect. - assert response is None - -def test_cancel_operation_field_headers(): - 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 = operations_pb2.CancelOperationRequest() - request.name = "locations" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call: - call.return_value = None - - client.cancel_operation(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=locations",) in kw["metadata"] -@pytest.mark.asyncio -async def test_cancel_operation_field_headers_async(): - 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 = operations_pb2.CancelOperationRequest() - request.name = "locations" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - None - ) - await client.cancel_operation(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=locations",) in kw["metadata"] - -def test_cancel_operation_from_dict(): - client = KnowledgeBasesClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = None - - response = client.cancel_operation( - request={ - "name": "locations", - } - ) - call.assert_called() -@pytest.mark.asyncio -async def test_cancel_operation_from_dict_async(): - client = KnowledgeBasesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - None - ) - response = await client.cancel_operation( - request={ - "name": "locations", - } - ) - call.assert_called() - - -def test_get_operation(transport: str = "grpc"): - client = KnowledgeBasesClient( - 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 = operations_pb2.GetOperationRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_operation), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation() - response = client.get_operation(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 response is the type that we expect. - assert isinstance(response, operations_pb2.Operation) -@pytest.mark.asyncio -async def test_get_operation_async(transport: str = "grpc"): - client = KnowledgeBasesAsyncClient( - 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 = operations_pb2.GetOperationRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_operation), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation() - ) - response = await client.get_operation(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 response is the type that we expect. - assert isinstance(response, operations_pb2.Operation) - -def test_get_operation_field_headers(): - 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 = operations_pb2.GetOperationRequest() - request.name = "locations" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_operation), "__call__") as call: - call.return_value = operations_pb2.Operation() - - client.get_operation(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=locations",) in kw["metadata"] -@pytest.mark.asyncio -async def test_get_operation_field_headers_async(): - 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 = operations_pb2.GetOperationRequest() - request.name = "locations" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_operation), "__call__") as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation() - ) - await client.get_operation(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=locations",) in kw["metadata"] - -def test_get_operation_from_dict(): - client = KnowledgeBasesClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_operation), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation() - - response = client.get_operation( - request={ - "name": "locations", - } - ) - call.assert_called() -@pytest.mark.asyncio -async def test_get_operation_from_dict_async(): - client = KnowledgeBasesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_operation), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation() - ) - response = await client.get_operation( - request={ - "name": "locations", - } - ) - call.assert_called() - - -def test_list_operations(transport: str = "grpc"): - client = KnowledgeBasesClient( - 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 = operations_pb2.ListOperationsRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_operations), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.ListOperationsResponse() - response = client.list_operations(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 response is the type that we expect. - assert isinstance(response, operations_pb2.ListOperationsResponse) -@pytest.mark.asyncio -async def test_list_operations_async(transport: str = "grpc"): - client = KnowledgeBasesAsyncClient( - 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 = operations_pb2.ListOperationsRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_operations), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.ListOperationsResponse() - ) - response = await client.list_operations(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 response is the type that we expect. - assert isinstance(response, operations_pb2.ListOperationsResponse) - -def test_list_operations_field_headers(): - 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 = operations_pb2.ListOperationsRequest() - request.name = "locations" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_operations), "__call__") as call: - call.return_value = operations_pb2.ListOperationsResponse() - - client.list_operations(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=locations",) in kw["metadata"] -@pytest.mark.asyncio -async def test_list_operations_field_headers_async(): - 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 = operations_pb2.ListOperationsRequest() - request.name = "locations" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_operations), "__call__") as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.ListOperationsResponse() - ) - await client.list_operations(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=locations",) in kw["metadata"] - -def test_list_operations_from_dict(): - client = KnowledgeBasesClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_operations), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.ListOperationsResponse() - - response = client.list_operations( - request={ - "name": "locations", - } - ) - call.assert_called() -@pytest.mark.asyncio -async def test_list_operations_from_dict_async(): - client = KnowledgeBasesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_operations), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.ListOperationsResponse() - ) - response = await client.list_operations( - request={ - "name": "locations", - } - ) - call.assert_called() - - -def test_list_locations(transport: str = "grpc"): - client = KnowledgeBasesClient( - 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 = locations_pb2.ListLocationsRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_locations), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = locations_pb2.ListLocationsResponse() - response = client.list_locations(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 response is the type that we expect. - assert isinstance(response, locations_pb2.ListLocationsResponse) -@pytest.mark.asyncio -async def test_list_locations_async(transport: str = "grpc"): - client = KnowledgeBasesAsyncClient( - 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 = locations_pb2.ListLocationsRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_locations), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - locations_pb2.ListLocationsResponse() - ) - response = await client.list_locations(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 response is the type that we expect. - assert isinstance(response, locations_pb2.ListLocationsResponse) - -def test_list_locations_field_headers(): - 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 = locations_pb2.ListLocationsRequest() - request.name = "locations" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_locations), "__call__") as call: - call.return_value = locations_pb2.ListLocationsResponse() - - client.list_locations(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=locations",) in kw["metadata"] -@pytest.mark.asyncio -async def test_list_locations_field_headers_async(): - 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 = locations_pb2.ListLocationsRequest() - request.name = "locations" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_locations), "__call__") as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - locations_pb2.ListLocationsResponse() - ) - await client.list_locations(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=locations",) in kw["metadata"] - -def test_list_locations_from_dict(): - client = KnowledgeBasesClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_locations), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = locations_pb2.ListLocationsResponse() - - response = client.list_locations( - request={ - "name": "locations", - } - ) - call.assert_called() -@pytest.mark.asyncio -async def test_list_locations_from_dict_async(): - client = KnowledgeBasesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_locations), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - locations_pb2.ListLocationsResponse() - ) - response = await client.list_locations( - request={ - "name": "locations", - } - ) - call.assert_called() - - -def test_get_location(transport: str = "grpc"): - client = KnowledgeBasesClient( - 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 = locations_pb2.GetLocationRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_location), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = locations_pb2.Location() - response = client.get_location(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 response is the type that we expect. - assert isinstance(response, locations_pb2.Location) -@pytest.mark.asyncio -async def test_get_location_async(transport: str = "grpc_asyncio"): - client = KnowledgeBasesAsyncClient( - 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 = locations_pb2.GetLocationRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_location), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - locations_pb2.Location() - ) - response = await client.get_location(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 response is the type that we expect. - assert isinstance(response, locations_pb2.Location) - -def test_get_location_field_headers(): - 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 = locations_pb2.GetLocationRequest() - request.name = "locations/abc" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_location), "__call__") as call: - call.return_value = locations_pb2.Location() - - client.get_location(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=locations/abc",) in kw["metadata"] -@pytest.mark.asyncio -async def test_get_location_field_headers_async(): - 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 = locations_pb2.GetLocationRequest() - request.name = "locations/abc" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_location), "__call__") as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - locations_pb2.Location() - ) - await client.get_location(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=locations/abc",) in kw["metadata"] - -def test_get_location_from_dict(): - client = KnowledgeBasesClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_locations), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = locations_pb2.Location() - - response = client.get_location( - request={ - "name": "locations/abc", - } - ) - call.assert_called() -@pytest.mark.asyncio -async def test_get_location_from_dict_async(): - client = KnowledgeBasesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_locations), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - locations_pb2.Location() - ) - response = await client.get_location( - request={ - "name": "locations", - } - ) - call.assert_called() - - -def test_transport_close(): - transports = { - "rest": "_session", - "grpc": "_grpc_channel", - } - - for transport, close_name in transports.items(): - client = KnowledgeBasesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport - ) - with mock.patch.object(type(getattr(client.transport, close_name)), "close") as close: - with client: - close.assert_not_called() - close.assert_called_once() - -def test_client_ctx(): - transports = [ - 'rest', - 'grpc', - ] - for transport in transports: - client = KnowledgeBasesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport - ) - # Test client calls underlying transport. - with mock.patch.object(type(client.transport), "close") as close: - close.assert_not_called() - with client: - pass - close.assert_called() - -@pytest.mark.parametrize("client_class,transport_class", [ - (KnowledgeBasesClient, transports.KnowledgeBasesGrpcTransport), - (KnowledgeBasesAsyncClient, transports.KnowledgeBasesGrpcAsyncIOTransport), -]) -def test_api_key_credentials(client_class, transport_class): - with mock.patch.object( - google.auth._default, "get_api_key_credentials", create=True - ) as get_api_key_credentials: - mock_cred = mock.Mock() - get_api_key_credentials.return_value = mock_cred - options = client_options.ClientOptions() - options.api_key = "api_key" - 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=mock_cred, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) diff --git a/owl-bot-staging/v2beta1/tests/unit/gapic/dialogflow_v2beta1/test_participants.py b/owl-bot-staging/v2beta1/tests/unit/gapic/dialogflow_v2beta1/test_participants.py deleted file mode 100644 index 738b6e31b..000000000 --- a/owl-bot-staging/v2beta1/tests/unit/gapic/dialogflow_v2beta1/test_participants.py +++ /dev/null @@ -1,7200 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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 -# try/except added for compatibility with python < 3.8 -try: - from unittest import mock - from unittest.mock import AsyncMock # pragma: NO COVER -except ImportError: # pragma: NO COVER - import mock - -import grpc -from grpc.experimental import aio -from collections.abc import Iterable -from google.protobuf import json_format -import json -import math -import pytest -from proto.marshal.rules.dates import DurationRule, TimestampRule -from proto.marshal.rules import wrappers -from requests import Response -from requests import Request, PreparedRequest -from requests.sessions import Session -from google.protobuf import json_format - -from google.api_core import client_options -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import grpc_helpers -from google.api_core import grpc_helpers_async -from google.api_core import path_template -from google.auth import credentials as ga_credentials -from google.auth.exceptions import MutualTLSChannelError -from google.cloud.dialogflow_v2beta1.services.participants import ParticipantsAsyncClient -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.types import agent -from google.cloud.dialogflow_v2beta1.types import audio_config -from google.cloud.dialogflow_v2beta1.types import context -from google.cloud.dialogflow_v2beta1.types import entity_type -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.cloud.dialogflow_v2beta1.types import session_entity_type -from google.cloud.location import locations_pb2 -from google.longrunning import operations_pb2 -from google.oauth2 import service_account -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.protobuf import timestamp_pb2 # type: ignore -from google.type import latlng_pb2 # type: ignore -import google.auth - - -def client_cert_source_callback(): - return b"cert bytes", b"key bytes" - - -# If default endpoint is localhost, then default mtls endpoint will be the same. -# This method modifies the default endpoint so the client can produce a different -# mtls endpoint for endpoint testing purposes. -def modify_default_endpoint(client): - return "foo.googleapis.com" if ("localhost" in client.DEFAULT_ENDPOINT) else client.DEFAULT_ENDPOINT - - -def test__get_default_mtls_endpoint(): - api_endpoint = "example.googleapis.com" - api_mtls_endpoint = "example.mtls.googleapis.com" - sandbox_endpoint = "example.sandbox.googleapis.com" - sandbox_mtls_endpoint = "example.mtls.sandbox.googleapis.com" - non_googleapi = "api.example.com" - - assert ParticipantsClient._get_default_mtls_endpoint(None) is None - assert ParticipantsClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint - assert ParticipantsClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint - assert ParticipantsClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint - assert ParticipantsClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint - assert ParticipantsClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi - - -@pytest.mark.parametrize("client_class,transport_name", [ - (ParticipantsClient, "grpc"), - (ParticipantsAsyncClient, "grpc_asyncio"), - (ParticipantsClient, "rest"), -]) -def test_participants_client_from_service_account_info(client_class, transport_name): - 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, transport=transport_name) - assert client.transport._credentials == creds - assert isinstance(client, client_class) - - assert client.transport._host == ( - 'dialogflow.googleapis.com:443' - if transport_name in ['grpc', 'grpc_asyncio'] - else - 'https://dialogflow.googleapis.com' - ) - - -@pytest.mark.parametrize("transport_class,transport_name", [ - (transports.ParticipantsGrpcTransport, "grpc"), - (transports.ParticipantsGrpcAsyncIOTransport, "grpc_asyncio"), - (transports.ParticipantsRestTransport, "rest"), -]) -def test_participants_client_service_account_always_use_jwt(transport_class, transport_name): - with mock.patch.object(service_account.Credentials, 'with_always_use_jwt_access', create=True) as use_jwt: - creds = service_account.Credentials(None, None, None) - transport = transport_class(credentials=creds, always_use_jwt_access=True) - use_jwt.assert_called_once_with(True) - - with mock.patch.object(service_account.Credentials, 'with_always_use_jwt_access', create=True) as use_jwt: - creds = service_account.Credentials(None, None, None) - transport = transport_class(credentials=creds, always_use_jwt_access=False) - use_jwt.assert_not_called() - - -@pytest.mark.parametrize("client_class,transport_name", [ - (ParticipantsClient, "grpc"), - (ParticipantsAsyncClient, "grpc_asyncio"), - (ParticipantsClient, "rest"), -]) -def test_participants_client_from_service_account_file(client_class, transport_name): - 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", transport=transport_name) - assert client.transport._credentials == creds - assert isinstance(client, client_class) - - client = client_class.from_service_account_json("dummy/file/path.json", transport=transport_name) - assert client.transport._credentials == creds - assert isinstance(client, client_class) - - assert client.transport._host == ( - 'dialogflow.googleapis.com:443' - if transport_name in ['grpc', 'grpc_asyncio'] - else - 'https://dialogflow.googleapis.com' - ) - - -def test_participants_client_get_transport_class(): - transport = ParticipantsClient.get_transport_class() - available_transports = [ - transports.ParticipantsGrpcTransport, - transports.ParticipantsRestTransport, - ] - assert transport in available_transports - - transport = ParticipantsClient.get_transport_class("grpc") - assert transport == transports.ParticipantsGrpcTransport - - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (ParticipantsClient, transports.ParticipantsGrpcTransport, "grpc"), - (ParticipantsAsyncClient, transports.ParticipantsGrpcAsyncIOTransport, "grpc_asyncio"), - (ParticipantsClient, transports.ParticipantsRestTransport, "rest"), -]) -@mock.patch.object(ParticipantsClient, "DEFAULT_ENDPOINT", modify_default_endpoint(ParticipantsClient)) -@mock.patch.object(ParticipantsAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(ParticipantsAsyncClient)) -def test_participants_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(ParticipantsClient, '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(ParticipantsClient, 'get_transport_class') as gtc: - client = client_class(transport=transport_name) - gtc.assert_called() - - # Check the case api_endpoint is provided. - options = client_options.ClientOptions(api_endpoint="squid.clam.whelk") - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(transport=transport_name, client_options=options) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host="squid.clam.whelk", - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is - # "never". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is - # "always". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_MTLS_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # 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(transport=transport_name) - - # 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(transport=transport_name) - - # 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, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id="octopus", - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - # Check the case api_endpoint is provided - options = client_options.ClientOptions(api_audience="https://language.googleapis.com") - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience="https://language.googleapis.com" - ) - -@pytest.mark.parametrize("client_class,transport_class,transport_name,use_client_cert_env", [ - (ParticipantsClient, transports.ParticipantsGrpcTransport, "grpc", "true"), - (ParticipantsAsyncClient, transports.ParticipantsGrpcAsyncIOTransport, "grpc_asyncio", "true"), - (ParticipantsClient, transports.ParticipantsGrpcTransport, "grpc", "false"), - (ParticipantsAsyncClient, transports.ParticipantsGrpcAsyncIOTransport, "grpc_asyncio", "false"), - (ParticipantsClient, transports.ParticipantsRestTransport, "rest", "true"), - (ParticipantsClient, transports.ParticipantsRestTransport, "rest", "false"), -]) -@mock.patch.object(ParticipantsClient, "DEFAULT_ENDPOINT", modify_default_endpoint(ParticipantsClient)) -@mock.patch.object(ParticipantsAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(ParticipantsAsyncClient)) -@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) -def test_participants_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, transport=transport_name) - - if use_client_cert_env == "false": - expected_client_cert_source = None - expected_host = client.DEFAULT_ENDPOINT - else: - expected_client_cert_source = client_cert_source_callback - expected_host = client.DEFAULT_MTLS_ENDPOINT - - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=expected_host, - scopes=None, - client_cert_source_for_mtls=expected_client_cert_source, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case ADC client cert is provided. Whether client cert is used depends on - # GOOGLE_API_USE_CLIENT_CERTIFICATE value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): - with mock.patch.object(transport_class, '__init__') as patched: - with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): - with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=client_cert_source_callback): - if use_client_cert_env == "false": - expected_host = client.DEFAULT_ENDPOINT - expected_client_cert_source = None - else: - expected_host = client.DEFAULT_MTLS_ENDPOINT - expected_client_cert_source = client_cert_source_callback - - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=expected_host, - scopes=None, - client_cert_source_for_mtls=expected_client_cert_source, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case client_cert_source and ADC client cert are not provided. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): - with mock.patch.object(transport_class, '__init__') as patched: - with mock.patch("google.auth.transport.mtls.has_default_client_cert_source", return_value=False): - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - -@pytest.mark.parametrize("client_class", [ - ParticipantsClient, ParticipantsAsyncClient -]) -@mock.patch.object(ParticipantsClient, "DEFAULT_ENDPOINT", modify_default_endpoint(ParticipantsClient)) -@mock.patch.object(ParticipantsAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(ParticipantsAsyncClient)) -def test_participants_client_get_mtls_endpoint_and_cert_source(client_class): - mock_client_cert_source = mock.Mock() - - # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "true". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - mock_api_endpoint = "foo" - options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) - assert api_endpoint == mock_api_endpoint - assert cert_source == mock_client_cert_source - - # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "false". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): - mock_client_cert_source = mock.Mock() - mock_api_endpoint = "foo" - options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) - assert api_endpoint == mock_api_endpoint - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "never". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_ENDPOINT - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "always". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert doesn't exist. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=False): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_ENDPOINT - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert exists. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - 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=mock_client_cert_source): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT - assert cert_source == mock_client_cert_source - - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (ParticipantsClient, transports.ParticipantsGrpcTransport, "grpc"), - (ParticipantsAsyncClient, transports.ParticipantsGrpcAsyncIOTransport, "grpc_asyncio"), - (ParticipantsClient, transports.ParticipantsRestTransport, "rest"), -]) -def test_participants_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, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=["1", "2"], - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - -@pytest.mark.parametrize("client_class,transport_class,transport_name,grpc_helpers", [ - (ParticipantsClient, transports.ParticipantsGrpcTransport, "grpc", grpc_helpers), - (ParticipantsAsyncClient, transports.ParticipantsGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), - (ParticipantsClient, transports.ParticipantsRestTransport, "rest", None), -]) -def test_participants_client_client_options_credentials_file(client_class, transport_class, transport_name, grpc_helpers): - # 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, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file="credentials.json", - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - -def test_participants_client_client_options_from_dict(): - with mock.patch('google.cloud.dialogflow_v2beta1.services.participants.transports.ParticipantsGrpcTransport.__init__') as grpc_transport: - grpc_transport.return_value = None - client = ParticipantsClient( - client_options={'api_endpoint': 'squid.clam.whelk'} - ) - grpc_transport.assert_called_once_with( - credentials=None, - credentials_file=None, - host="squid.clam.whelk", - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - -@pytest.mark.parametrize("client_class,transport_class,transport_name,grpc_helpers", [ - (ParticipantsClient, transports.ParticipantsGrpcTransport, "grpc", grpc_helpers), - (ParticipantsAsyncClient, transports.ParticipantsGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), -]) -def test_participants_client_create_channel_credentials_file(client_class, transport_class, transport_name, grpc_helpers): - # 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, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file="credentials.json", - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # test that the credentials from file are saved and used as the credentials. - with mock.patch.object( - google.auth, "load_credentials_from_file", autospec=True - ) as load_creds, mock.patch.object( - google.auth, "default", autospec=True - ) as adc, mock.patch.object( - grpc_helpers, "create_channel" - ) as create_channel: - creds = ga_credentials.AnonymousCredentials() - file_creds = ga_credentials.AnonymousCredentials() - load_creds.return_value = (file_creds, None) - adc.return_value = (creds, None) - client = client_class(client_options=options, transport=transport_name) - create_channel.assert_called_with( - "dialogflow.googleapis.com:443", - credentials=file_creds, - credentials_file=None, - quota_project_id=None, - default_scopes=( - 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/dialogflow', -), - scopes=None, - default_host="dialogflow.googleapis.com", - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - -@pytest.mark.parametrize("request_type", [ - gcd_participant.CreateParticipantRequest, - dict, -]) -def test_create_participant(request_type, transport: str = 'grpc'): - client = ParticipantsClient( - 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_participant), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcd_participant.Participant( - name='name_value', - 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' - - -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=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_participant), - '__call__') as call: - client.create_participant() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == gcd_participant.CreateParticipantRequest() - -@pytest.mark.asyncio -async def test_create_participant_async(transport: str = 'grpc_asyncio', request_type=gcd_participant.CreateParticipantRequest): - client = ParticipantsAsyncClient( - 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_participant), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gcd_participant.Participant( - name='name_value', - role=gcd_participant.Participant.Role.HUMAN_AGENT, - 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' - - -@pytest.mark.asyncio -async def test_create_participant_async_from_dict(): - await test_create_participant_async(request_type=dict) - - -def test_create_participant_field_headers(): - 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. - with mock.patch.object( - 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. - 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_participant_field_headers_async(): - 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. - with mock.patch.object( - type(client.transport.create_participant), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcd_participant.Participant()) - 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] == 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_participant_flattened(): - 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.create_participant), - '__call__') 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( - parent='parent_value', - participant=gcd_participant.Participant(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] - arg = args[0].parent - mock_val = 'parent_value' - assert arg == mock_val - arg = args[0].participant - mock_val = gcd_participant.Participant(name='name_value') - assert arg == mock_val - - -def test_create_participant_flattened_error(): - client = ParticipantsClient( - 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_participant( - gcd_participant.CreateParticipantRequest(), - parent='parent_value', - participant=gcd_participant.Participant(name='name_value'), - ) - -@pytest.mark.asyncio -async def test_create_participant_flattened_async(): - 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.create_participant), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcd_participant.Participant() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcd_participant.Participant()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.create_participant( - parent='parent_value', - participant=gcd_participant.Participant(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] - arg = args[0].parent - mock_val = 'parent_value' - assert arg == mock_val - arg = args[0].participant - mock_val = gcd_participant.Participant(name='name_value') - assert arg == mock_val - -@pytest.mark.asyncio -async def test_create_participant_flattened_error_async(): - client = ParticipantsAsyncClient( - 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_participant( - gcd_participant.CreateParticipantRequest(), - parent='parent_value', - participant=gcd_participant.Participant(name='name_value'), - ) - - -@pytest.mark.parametrize("request_type", [ - participant.GetParticipantRequest, - dict, -]) -def test_get_participant(request_type, transport: str = 'grpc'): - client = ParticipantsClient( - 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_participant), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = participant.Participant( - name='name_value', - 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' - - -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=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_participant), - '__call__') as call: - client.get_participant() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == participant.GetParticipantRequest() - -@pytest.mark.asyncio -async def test_get_participant_async(transport: str = 'grpc_asyncio', request_type=participant.GetParticipantRequest): - client = ParticipantsAsyncClient( - 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_participant), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(participant.Participant( - name='name_value', - role=participant.Participant.Role.HUMAN_AGENT, - 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' - - -@pytest.mark.asyncio -async def test_get_participant_async_from_dict(): - await test_get_participant_async(request_type=dict) - - -def test_get_participant_field_headers(): - 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. - 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_participant_field_headers_async(): - 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. - with mock.patch.object( - type(client.transport.get_participant), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(participant.Participant()) - 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] == 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_participant_flattened(): - 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', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - arg = args[0].name - mock_val = 'name_value' - assert arg == mock_val - - -def test_get_participant_flattened_error(): - client = ParticipantsClient( - 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_participant( - participant.GetParticipantRequest(), - name='name_value', - ) - -@pytest.mark.asyncio -async def test_get_participant_flattened_async(): - 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: - # Designate an appropriate return value for the call. - call.return_value = participant.Participant() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(participant.Participant()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.get_participant( - 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] - arg = args[0].name - mock_val = 'name_value' - assert arg == mock_val - -@pytest.mark.asyncio -async def test_get_participant_flattened_error_async(): - client = ParticipantsAsyncClient( - 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_participant( - participant.GetParticipantRequest(), - name='name_value', - ) - - -@pytest.mark.parametrize("request_type", [ - participant.ListParticipantsRequest, - dict, -]) -def test_list_participants(request_type, transport: str = 'grpc'): - client = ParticipantsClient( - 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_participants), - '__call__') as call: - # Designate an appropriate return value for the call. - 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' - - -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=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_participants), - '__call__') as call: - client.list_participants() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == participant.ListParticipantsRequest() - -@pytest.mark.asyncio -async def test_list_participants_async(transport: str = 'grpc_asyncio', request_type=participant.ListParticipantsRequest): - client = ParticipantsAsyncClient( - 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_participants), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(participant.ListParticipantsResponse( - 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' - - -@pytest.mark.asyncio -async def test_list_participants_async_from_dict(): - await test_list_participants_async(request_type=dict) - - -def test_list_participants_field_headers(): - 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. - with mock.patch.object( - 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. - 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_participants_field_headers_async(): - 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. - with mock.patch.object( - type(client.transport.list_participants), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(participant.ListParticipantsResponse()) - 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] == 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_participants_flattened(): - 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_participants), - '__call__') 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', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - arg = args[0].parent - mock_val = 'parent_value' - assert arg == mock_val - - -def test_list_participants_flattened_error(): - client = ParticipantsClient( - 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_participants( - participant.ListParticipantsRequest(), - parent='parent_value', - ) - -@pytest.mark.asyncio -async def test_list_participants_flattened_async(): - 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.list_participants), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = participant.ListParticipantsResponse() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(participant.ListParticipantsResponse()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.list_participants( - 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] - arg = args[0].parent - mock_val = 'parent_value' - assert arg == mock_val - -@pytest.mark.asyncio -async def test_list_participants_flattened_error_async(): - client = ParticipantsAsyncClient( - 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_participants( - participant.ListParticipantsRequest(), - parent='parent_value', - ) - - -def test_list_participants_pager(transport_name: str = "grpc"): - client = ParticipantsClient( - credentials=ga_credentials.AnonymousCredentials, - transport=transport_name, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_participants), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - participant.ListParticipantsResponse( - participants=[ - participant.Participant(), - participant.Participant(), - participant.Participant(), - ], - next_page_token='abc', - ), - participant.ListParticipantsResponse( - participants=[], - next_page_token='def', - ), - participant.ListParticipantsResponse( - participants=[ - participant.Participant(), - ], - next_page_token='ghi', - ), - participant.ListParticipantsResponse( - participants=[ - participant.Participant(), - participant.Participant(), - ], - ), - RuntimeError, - ) - - metadata = () - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ('parent', ''), - )), - ) - pager = client.list_participants(request={}) - - assert pager._metadata == metadata - - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, participant.Participant) - for i in results) -def test_list_participants_pages(transport_name: str = "grpc"): - client = ParticipantsClient( - credentials=ga_credentials.AnonymousCredentials, - transport=transport_name, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_participants), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - participant.ListParticipantsResponse( - participants=[ - participant.Participant(), - participant.Participant(), - participant.Participant(), - ], - next_page_token='abc', - ), - participant.ListParticipantsResponse( - participants=[], - next_page_token='def', - ), - participant.ListParticipantsResponse( - participants=[ - participant.Participant(), - ], - next_page_token='ghi', - ), - participant.ListParticipantsResponse( - participants=[ - participant.Participant(), - participant.Participant(), - ], - ), - RuntimeError, - ) - pages = list(client.list_participants(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_participants_async_pager(): - 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.list_participants), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - participant.ListParticipantsResponse( - participants=[ - participant.Participant(), - participant.Participant(), - participant.Participant(), - ], - next_page_token='abc', - ), - participant.ListParticipantsResponse( - participants=[], - next_page_token='def', - ), - participant.ListParticipantsResponse( - participants=[ - participant.Participant(), - ], - next_page_token='ghi', - ), - participant.ListParticipantsResponse( - participants=[ - participant.Participant(), - participant.Participant(), - ], - ), - RuntimeError, - ) - async_pager = await client.list_participants(request={},) - assert async_pager.next_page_token == 'abc' - responses = [] - async for response in async_pager: # pragma: no branch - responses.append(response) - - assert len(responses) == 6 - assert all(isinstance(i, participant.Participant) - for i in responses) - - -@pytest.mark.asyncio -async def test_list_participants_async_pages(): - 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.list_participants), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - participant.ListParticipantsResponse( - participants=[ - participant.Participant(), - participant.Participant(), - participant.Participant(), - ], - next_page_token='abc', - ), - participant.ListParticipantsResponse( - participants=[], - next_page_token='def', - ), - participant.ListParticipantsResponse( - participants=[ - participant.Participant(), - ], - next_page_token='ghi', - ), - participant.ListParticipantsResponse( - participants=[ - participant.Participant(), - participant.Participant(), - ], - ), - RuntimeError, - ) - pages = [] - async for page_ in (await client.list_participants(request={})).pages: # pragma: no branch - pages.append(page_) - for page_, token in zip(pages, ['abc','def','ghi', '']): - assert page_.raw_page.next_page_token == token - -@pytest.mark.parametrize("request_type", [ - gcd_participant.UpdateParticipantRequest, - dict, -]) -def test_update_participant(request_type, transport: str = 'grpc'): - client = ParticipantsClient( - 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_participant), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcd_participant.Participant( - name='name_value', - 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' - - -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=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_participant), - '__call__') as call: - client.update_participant() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == gcd_participant.UpdateParticipantRequest() - -@pytest.mark.asyncio -async def test_update_participant_async(transport: str = 'grpc_asyncio', request_type=gcd_participant.UpdateParticipantRequest): - client = ParticipantsAsyncClient( - 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_participant), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gcd_participant.Participant( - name='name_value', - role=gcd_participant.Participant.Role.HUMAN_AGENT, - 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' - - -@pytest.mark.asyncio -async def test_update_participant_async_from_dict(): - await test_update_participant_async(request_type=dict) - - -def test_update_participant_field_headers(): - 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 = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - 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. - 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', - 'participant.name=name_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_update_participant_field_headers_async(): - 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 = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_participant), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcd_participant.Participant()) - 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] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'participant.name=name_value', - ) in kw['metadata'] - - -def test_update_participant_flattened(): - 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.update_participant), - '__call__') 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_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] - arg = args[0].participant - mock_val = gcd_participant.Participant(name='name_value') - assert arg == mock_val - arg = args[0].update_mask - mock_val = field_mask_pb2.FieldMask(paths=['paths_value']) - assert arg == mock_val - - -def test_update_participant_flattened_error(): - client = ParticipantsClient( - 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_participant( - gcd_participant.UpdateParticipantRequest(), - participant=gcd_participant.Participant(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - -@pytest.mark.asyncio -async def test_update_participant_flattened_async(): - 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.update_participant), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcd_participant.Participant() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcd_participant.Participant()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.update_participant( - participant=gcd_participant.Participant(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] - arg = args[0].participant - mock_val = gcd_participant.Participant(name='name_value') - assert arg == mock_val - arg = args[0].update_mask - mock_val = field_mask_pb2.FieldMask(paths=['paths_value']) - assert arg == mock_val - -@pytest.mark.asyncio -async def test_update_participant_flattened_error_async(): - client = ParticipantsAsyncClient( - 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_participant( - gcd_participant.UpdateParticipantRequest(), - participant=gcd_participant.Participant(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - - -@pytest.mark.parametrize("request_type", [ - gcd_participant.AnalyzeContentRequest, - dict, -]) -def test_analyze_content(request_type, transport: str = 'grpc'): - client = ParticipantsClient( - 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.analyze_content), - '__call__') as call: - # Designate an appropriate return value for the call. - 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' - - -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=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.analyze_content), - '__call__') as call: - client.analyze_content() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == gcd_participant.AnalyzeContentRequest() - -@pytest.mark.asyncio -async def test_analyze_content_async(transport: str = 'grpc_asyncio', request_type=gcd_participant.AnalyzeContentRequest): - client = ParticipantsAsyncClient( - 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.analyze_content), - '__call__') as call: - # Designate an appropriate return value for the call. - 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' - - -@pytest.mark.asyncio -async def test_analyze_content_async_from_dict(): - await test_analyze_content_async(request_type=dict) - - -def test_analyze_content_field_headers(): - 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. - 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', - 'participant=participant_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_analyze_content_field_headers_async(): - 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. - with mock.patch.object( - type(client.transport.analyze_content), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcd_participant.AnalyzeContentResponse()) - 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] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'participant=participant_value', - ) in kw['metadata'] - - -def test_analyze_content_flattened(): - 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( - participant='participant_value', - text_input=session.TextInput(text='text_value'), - audio_input=gcd_participant.AudioInput(config=audio_config.InputAudioConfig(audio_encoding=audio_config.AudioEncoding.AUDIO_ENCODING_LINEAR_16)), - event_input=session.EventInput(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] - arg = args[0].participant - mock_val = 'participant_value' - assert arg == mock_val - assert args[0].event_input == session.EventInput(name='name_value') - - -def test_analyze_content_flattened_error(): - client = ParticipantsClient( - 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.analyze_content( - gcd_participant.AnalyzeContentRequest(), - participant='participant_value', - text_input=session.TextInput(text='text_value'), - audio_input=gcd_participant.AudioInput(config=audio_config.InputAudioConfig(audio_encoding=audio_config.AudioEncoding.AUDIO_ENCODING_LINEAR_16)), - event_input=session.EventInput(name='name_value'), - ) - -@pytest.mark.asyncio -async def test_analyze_content_flattened_async(): - 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: - # Designate an appropriate return value for the call. - call.return_value = gcd_participant.AnalyzeContentResponse() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcd_participant.AnalyzeContentResponse()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.analyze_content( - participant='participant_value', - text_input=session.TextInput(text='text_value'), - audio_input=gcd_participant.AudioInput(config=audio_config.InputAudioConfig(audio_encoding=audio_config.AudioEncoding.AUDIO_ENCODING_LINEAR_16)), - event_input=session.EventInput(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] - arg = args[0].participant - mock_val = 'participant_value' - assert arg == mock_val - assert args[0].event_input == session.EventInput(name='name_value') - -@pytest.mark.asyncio -async def test_analyze_content_flattened_error_async(): - client = ParticipantsAsyncClient( - 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.analyze_content( - gcd_participant.AnalyzeContentRequest(), - participant='participant_value', - text_input=session.TextInput(text='text_value'), - audio_input=gcd_participant.AudioInput(config=audio_config.InputAudioConfig(audio_encoding=audio_config.AudioEncoding.AUDIO_ENCODING_LINEAR_16)), - event_input=session.EventInput(name='name_value'), - ) - - -@pytest.mark.parametrize("request_type", [ - participant.StreamingAnalyzeContentRequest, - dict, -]) -def test_streaming_analyze_content(request_type, transport: str = 'grpc'): - client = ParticipantsClient( - 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. - with mock.patch.object( - type(client.transport.streaming_analyze_content), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = iter([participant.StreamingAnalyzeContentResponse()]) - response = client.streaming_analyze_content(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. - for message in response: - assert isinstance(message, participant.StreamingAnalyzeContentResponse) - - -@pytest.mark.asyncio -async def test_streaming_analyze_content_async(transport: str = 'grpc_asyncio', request_type=participant.StreamingAnalyzeContentRequest): - client = ParticipantsAsyncClient( - 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. - with mock.patch.object( - type(client.transport.streaming_analyze_content), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = mock.Mock(aio.StreamStreamCall, autospec=True) - call.return_value.read = mock.AsyncMock(side_effect=[participant.StreamingAnalyzeContentResponse()]) - response = await client.streaming_analyze_content(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. - message = await response.read() - assert isinstance(message, participant.StreamingAnalyzeContentResponse) - - -@pytest.mark.asyncio -async def test_streaming_analyze_content_async_from_dict(): - await test_streaming_analyze_content_async(request_type=dict) - - -@pytest.mark.parametrize("request_type", [ - participant.SuggestArticlesRequest, - dict, -]) -def test_suggest_articles(request_type, transport: str = 'grpc'): - client = ParticipantsClient( - 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.suggest_articles), - '__call__') as call: - # Designate an appropriate return value for the call. - 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 - - -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=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.suggest_articles), - '__call__') as call: - client.suggest_articles() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == participant.SuggestArticlesRequest() - -@pytest.mark.asyncio -async def test_suggest_articles_async(transport: str = 'grpc_asyncio', request_type=participant.SuggestArticlesRequest): - client = ParticipantsAsyncClient( - 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.suggest_articles), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(participant.SuggestArticlesResponse( - 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 - - -@pytest.mark.asyncio -async def test_suggest_articles_async_from_dict(): - await test_suggest_articles_async(request_type=dict) - - -def test_suggest_articles_field_headers(): - 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. - 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_suggest_articles_field_headers_async(): - 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. - with mock.patch.object( - type(client.transport.suggest_articles), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(participant.SuggestArticlesResponse()) - 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] == 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_suggest_articles_flattened(): - 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', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - arg = args[0].parent - mock_val = 'parent_value' - assert arg == mock_val - - -def test_suggest_articles_flattened_error(): - client = ParticipantsClient( - 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.suggest_articles( - participant.SuggestArticlesRequest(), - parent='parent_value', - ) - -@pytest.mark.asyncio -async def test_suggest_articles_flattened_async(): - 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: - # Designate an appropriate return value for the call. - call.return_value = participant.SuggestArticlesResponse() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(participant.SuggestArticlesResponse()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.suggest_articles( - 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] - arg = args[0].parent - mock_val = 'parent_value' - assert arg == mock_val - -@pytest.mark.asyncio -async def test_suggest_articles_flattened_error_async(): - client = ParticipantsAsyncClient( - 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.suggest_articles( - participant.SuggestArticlesRequest(), - parent='parent_value', - ) - - -@pytest.mark.parametrize("request_type", [ - participant.SuggestFaqAnswersRequest, - dict, -]) -def test_suggest_faq_answers(request_type, transport: str = 'grpc'): - client = ParticipantsClient( - 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.suggest_faq_answers), - '__call__') as call: - # Designate an appropriate return value for the call. - 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 - - -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=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.suggest_faq_answers), - '__call__') as call: - client.suggest_faq_answers() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == participant.SuggestFaqAnswersRequest() - -@pytest.mark.asyncio -async def test_suggest_faq_answers_async(transport: str = 'grpc_asyncio', request_type=participant.SuggestFaqAnswersRequest): - client = ParticipantsAsyncClient( - 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.suggest_faq_answers), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(participant.SuggestFaqAnswersResponse( - 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 - - -@pytest.mark.asyncio -async def test_suggest_faq_answers_async_from_dict(): - await test_suggest_faq_answers_async(request_type=dict) - - -def test_suggest_faq_answers_field_headers(): - 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. - with mock.patch.object( - 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. - 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_suggest_faq_answers_field_headers_async(): - 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. - with mock.patch.object( - type(client.transport.suggest_faq_answers), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(participant.SuggestFaqAnswersResponse()) - 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] == 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_suggest_faq_answers_flattened(): - 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_faq_answers), - '__call__') 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', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - arg = args[0].parent - mock_val = 'parent_value' - assert arg == mock_val - - -def test_suggest_faq_answers_flattened_error(): - client = ParticipantsClient( - 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.suggest_faq_answers( - participant.SuggestFaqAnswersRequest(), - parent='parent_value', - ) - -@pytest.mark.asyncio -async def test_suggest_faq_answers_flattened_async(): - 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_faq_answers), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = participant.SuggestFaqAnswersResponse() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(participant.SuggestFaqAnswersResponse()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.suggest_faq_answers( - 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] - arg = args[0].parent - mock_val = 'parent_value' - assert arg == mock_val - -@pytest.mark.asyncio -async def test_suggest_faq_answers_flattened_error_async(): - client = ParticipantsAsyncClient( - 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.suggest_faq_answers( - participant.SuggestFaqAnswersRequest(), - parent='parent_value', - ) - - -@pytest.mark.parametrize("request_type", [ - participant.SuggestSmartRepliesRequest, - dict, -]) -def test_suggest_smart_replies(request_type, transport: str = 'grpc'): - client = ParticipantsClient( - 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.suggest_smart_replies), - '__call__') as call: - # Designate an appropriate return value for the call. - 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 - - -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=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.suggest_smart_replies), - '__call__') as call: - client.suggest_smart_replies() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == participant.SuggestSmartRepliesRequest() - -@pytest.mark.asyncio -async def test_suggest_smart_replies_async(transport: str = 'grpc_asyncio', request_type=participant.SuggestSmartRepliesRequest): - client = ParticipantsAsyncClient( - 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.suggest_smart_replies), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(participant.SuggestSmartRepliesResponse( - 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 - - -@pytest.mark.asyncio -async def test_suggest_smart_replies_async_from_dict(): - await test_suggest_smart_replies_async(request_type=dict) - - -def test_suggest_smart_replies_field_headers(): - 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. - with mock.patch.object( - 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. - 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_suggest_smart_replies_field_headers_async(): - 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. - with mock.patch.object( - type(client.transport.suggest_smart_replies), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(participant.SuggestSmartRepliesResponse()) - 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] == 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_suggest_smart_replies_flattened(): - 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_smart_replies), - '__call__') 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', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - arg = args[0].parent - mock_val = 'parent_value' - assert arg == mock_val - - -def test_suggest_smart_replies_flattened_error(): - client = ParticipantsClient( - 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.suggest_smart_replies( - participant.SuggestSmartRepliesRequest(), - parent='parent_value', - ) - -@pytest.mark.asyncio -async def test_suggest_smart_replies_flattened_async(): - 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_smart_replies), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = participant.SuggestSmartRepliesResponse() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(participant.SuggestSmartRepliesResponse()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.suggest_smart_replies( - 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] - arg = args[0].parent - mock_val = 'parent_value' - assert arg == mock_val - -@pytest.mark.asyncio -async def test_suggest_smart_replies_flattened_error_async(): - client = ParticipantsAsyncClient( - 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.suggest_smart_replies( - participant.SuggestSmartRepliesRequest(), - parent='parent_value', - ) - - -@pytest.mark.parametrize("request_type", [ - participant.ListSuggestionsRequest, - dict, -]) -def test_list_suggestions(request_type, transport: str = 'grpc'): - client = ParticipantsClient( - 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_suggestions), - '__call__') as call: - # Designate an appropriate return value for the call. - 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' - - -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=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_suggestions), - '__call__') as call: - client.list_suggestions() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == participant.ListSuggestionsRequest() - -@pytest.mark.asyncio -async def test_list_suggestions_async(transport: str = 'grpc_asyncio', request_type=participant.ListSuggestionsRequest): - client = ParticipantsAsyncClient( - 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_suggestions), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(participant.ListSuggestionsResponse( - 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' - - -@pytest.mark.asyncio -async def test_list_suggestions_async_from_dict(): - await test_list_suggestions_async(request_type=dict) - - -def test_list_suggestions_field_headers(): - 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. - 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_suggestions_field_headers_async(): - 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. - with mock.patch.object( - type(client.transport.list_suggestions), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(participant.ListSuggestionsResponse()) - 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] == 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_suggestions_pager(transport_name: str = "grpc"): - client = ParticipantsClient( - credentials=ga_credentials.AnonymousCredentials, - transport=transport_name, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_suggestions), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - participant.ListSuggestionsResponse( - suggestions=[ - participant.Suggestion(), - participant.Suggestion(), - participant.Suggestion(), - ], - next_page_token='abc', - ), - participant.ListSuggestionsResponse( - suggestions=[], - next_page_token='def', - ), - participant.ListSuggestionsResponse( - suggestions=[ - participant.Suggestion(), - ], - next_page_token='ghi', - ), - participant.ListSuggestionsResponse( - suggestions=[ - participant.Suggestion(), - participant.Suggestion(), - ], - ), - RuntimeError, - ) - - metadata = () - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ('parent', ''), - )), - ) - pager = client.list_suggestions(request={}) - - assert pager._metadata == metadata - - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, participant.Suggestion) - for i in results) -def test_list_suggestions_pages(transport_name: str = "grpc"): - client = ParticipantsClient( - credentials=ga_credentials.AnonymousCredentials, - transport=transport_name, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_suggestions), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - participant.ListSuggestionsResponse( - suggestions=[ - participant.Suggestion(), - participant.Suggestion(), - participant.Suggestion(), - ], - next_page_token='abc', - ), - participant.ListSuggestionsResponse( - suggestions=[], - next_page_token='def', - ), - participant.ListSuggestionsResponse( - suggestions=[ - participant.Suggestion(), - ], - next_page_token='ghi', - ), - participant.ListSuggestionsResponse( - suggestions=[ - participant.Suggestion(), - participant.Suggestion(), - ], - ), - RuntimeError, - ) - pages = list(client.list_suggestions(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_suggestions_async_pager(): - 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.list_suggestions), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - participant.ListSuggestionsResponse( - suggestions=[ - participant.Suggestion(), - participant.Suggestion(), - participant.Suggestion(), - ], - next_page_token='abc', - ), - participant.ListSuggestionsResponse( - suggestions=[], - next_page_token='def', - ), - participant.ListSuggestionsResponse( - suggestions=[ - participant.Suggestion(), - ], - next_page_token='ghi', - ), - participant.ListSuggestionsResponse( - suggestions=[ - participant.Suggestion(), - participant.Suggestion(), - ], - ), - RuntimeError, - ) - async_pager = await client.list_suggestions(request={},) - assert async_pager.next_page_token == 'abc' - responses = [] - async for response in async_pager: # pragma: no branch - responses.append(response) - - assert len(responses) == 6 - assert all(isinstance(i, participant.Suggestion) - for i in responses) - - -@pytest.mark.asyncio -async def test_list_suggestions_async_pages(): - 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.list_suggestions), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - participant.ListSuggestionsResponse( - suggestions=[ - participant.Suggestion(), - participant.Suggestion(), - participant.Suggestion(), - ], - next_page_token='abc', - ), - participant.ListSuggestionsResponse( - suggestions=[], - next_page_token='def', - ), - participant.ListSuggestionsResponse( - suggestions=[ - participant.Suggestion(), - ], - next_page_token='ghi', - ), - participant.ListSuggestionsResponse( - suggestions=[ - participant.Suggestion(), - participant.Suggestion(), - ], - ), - RuntimeError, - ) - pages = [] - async for page_ in (await client.list_suggestions(request={})).pages: # pragma: no branch - pages.append(page_) - for page_, token in zip(pages, ['abc','def','ghi', '']): - assert page_.raw_page.next_page_token == token - -@pytest.mark.parametrize("request_type", [ - participant.CompileSuggestionRequest, - dict, -]) -def test_compile_suggestion(request_type, transport: str = 'grpc'): - client = ParticipantsClient( - 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.compile_suggestion), - '__call__') as call: - # Designate an appropriate return value for the call. - 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 - - -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=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.compile_suggestion), - '__call__') as call: - client.compile_suggestion() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == participant.CompileSuggestionRequest() - -@pytest.mark.asyncio -async def test_compile_suggestion_async(transport: str = 'grpc_asyncio', request_type=participant.CompileSuggestionRequest): - client = ParticipantsAsyncClient( - 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.compile_suggestion), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(participant.CompileSuggestionResponse( - 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 - - -@pytest.mark.asyncio -async def test_compile_suggestion_async_from_dict(): - await test_compile_suggestion_async(request_type=dict) - - -def test_compile_suggestion_field_headers(): - 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. - with mock.patch.object( - 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. - 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_compile_suggestion_field_headers_async(): - 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. - with mock.patch.object( - type(client.transport.compile_suggestion), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(participant.CompileSuggestionResponse()) - 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] == 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.parametrize("request_type", [ - gcd_participant.CreateParticipantRequest, - dict, -]) -def test_create_participant_rest(request_type): - client = ParticipantsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1/conversations/sample2'} - request_init["participant"] = {'name': 'name_value', 'role': 1, 'obfuscated_external_user_id': 'obfuscated_external_user_id_value', 'documents_metadata_filters': {}} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = gcd_participant.Participant( - name='name_value', - role=gcd_participant.Participant.Role.HUMAN_AGENT, - obfuscated_external_user_id='obfuscated_external_user_id_value', - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - pb_return_value = gcd_participant.Participant.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.create_participant(request) - - # 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' - - -def test_create_participant_rest_required_fields(request_type=gcd_participant.CreateParticipantRequest): - transport_class = transports.ParticipantsRestTransport - - request_init = {} - request_init["parent"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - including_default_value_fields=False, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_participant._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["parent"] = 'parent_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_participant._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "parent" in jsonified_request - assert jsonified_request["parent"] == 'parent_value' - - client = ParticipantsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = gcd_participant.Participant() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "post", - 'query_params': pb_request, - } - transcode_result['body'] = pb_request - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - - pb_return_value = gcd_participant.Participant.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.create_participant(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_create_participant_rest_unset_required_fields(): - transport = transports.ParticipantsRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.create_participant._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("parent", "participant", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_create_participant_rest_interceptors(null_interceptor): - transport = transports.ParticipantsRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.ParticipantsRestInterceptor(), - ) - client = ParticipantsClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.ParticipantsRestInterceptor, "post_create_participant") as post, \ - mock.patch.object(transports.ParticipantsRestInterceptor, "pre_create_participant") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = gcd_participant.CreateParticipantRequest.pb(gcd_participant.CreateParticipantRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = gcd_participant.Participant.to_json(gcd_participant.Participant()) - - request = gcd_participant.CreateParticipantRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = gcd_participant.Participant() - - client.create_participant(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_create_participant_rest_bad_request(transport: str = 'rest', request_type=gcd_participant.CreateParticipantRequest): - client = ParticipantsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1/conversations/sample2'} - request_init["participant"] = {'name': 'name_value', 'role': 1, 'obfuscated_external_user_id': 'obfuscated_external_user_id_value', 'documents_metadata_filters': {}} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.create_participant(request) - - -def test_create_participant_rest_flattened(): - client = ParticipantsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = gcd_participant.Participant() - - # get arguments that satisfy an http rule for this method - sample_request = {'parent': 'projects/sample1/conversations/sample2'} - - # get truthy value for each flattened field - mock_args = dict( - parent='parent_value', - participant=gcd_participant.Participant(name='name_value'), - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - pb_return_value = gcd_participant.Participant.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.create_participant(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v2beta1/{parent=projects/*/conversations/*}/participants" % client.transport._host, args[1]) - - -def test_create_participant_rest_flattened_error(transport: str = 'rest'): - client = ParticipantsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.create_participant( - gcd_participant.CreateParticipantRequest(), - parent='parent_value', - participant=gcd_participant.Participant(name='name_value'), - ) - - -def test_create_participant_rest_error(): - client = ParticipantsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - participant.GetParticipantRequest, - dict, -]) -def test_get_participant_rest(request_type): - client = ParticipantsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/conversations/sample2/participants/sample3'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = participant.Participant( - name='name_value', - role=participant.Participant.Role.HUMAN_AGENT, - obfuscated_external_user_id='obfuscated_external_user_id_value', - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - pb_return_value = participant.Participant.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.get_participant(request) - - # 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' - - -def test_get_participant_rest_required_fields(request_type=participant.GetParticipantRequest): - transport_class = transports.ParticipantsRestTransport - - request_init = {} - request_init["name"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - including_default_value_fields=False, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_participant._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["name"] = 'name_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_participant._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "name" in jsonified_request - assert jsonified_request["name"] == 'name_value' - - client = ParticipantsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = participant.Participant() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "get", - 'query_params': pb_request, - } - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - - pb_return_value = participant.Participant.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.get_participant(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_get_participant_rest_unset_required_fields(): - transport = transports.ParticipantsRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.get_participant._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_get_participant_rest_interceptors(null_interceptor): - transport = transports.ParticipantsRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.ParticipantsRestInterceptor(), - ) - client = ParticipantsClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.ParticipantsRestInterceptor, "post_get_participant") as post, \ - mock.patch.object(transports.ParticipantsRestInterceptor, "pre_get_participant") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = participant.GetParticipantRequest.pb(participant.GetParticipantRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = participant.Participant.to_json(participant.Participant()) - - request = participant.GetParticipantRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = participant.Participant() - - client.get_participant(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_get_participant_rest_bad_request(transport: str = 'rest', request_type=participant.GetParticipantRequest): - client = ParticipantsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/conversations/sample2/participants/sample3'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.get_participant(request) - - -def test_get_participant_rest_flattened(): - client = ParticipantsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = participant.Participant() - - # get arguments that satisfy an http rule for this method - sample_request = {'name': 'projects/sample1/conversations/sample2/participants/sample3'} - - # get truthy value for each flattened field - mock_args = dict( - name='name_value', - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - pb_return_value = participant.Participant.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.get_participant(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v2beta1/{name=projects/*/conversations/*/participants/*}" % client.transport._host, args[1]) - - -def test_get_participant_rest_flattened_error(transport: str = 'rest'): - client = ParticipantsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.get_participant( - participant.GetParticipantRequest(), - name='name_value', - ) - - -def test_get_participant_rest_error(): - client = ParticipantsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - participant.ListParticipantsRequest, - dict, -]) -def test_list_participants_rest(request_type): - client = ParticipantsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1/conversations/sample2'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = participant.ListParticipantsResponse( - next_page_token='next_page_token_value', - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - pb_return_value = participant.ListParticipantsResponse.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.list_participants(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListParticipantsPager) - assert response.next_page_token == 'next_page_token_value' - - -def test_list_participants_rest_required_fields(request_type=participant.ListParticipantsRequest): - transport_class = transports.ParticipantsRestTransport - - request_init = {} - request_init["parent"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - including_default_value_fields=False, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).list_participants._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["parent"] = 'parent_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).list_participants._get_unset_required_fields(jsonified_request) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("page_size", "page_token", )) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "parent" in jsonified_request - assert jsonified_request["parent"] == 'parent_value' - - client = ParticipantsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = participant.ListParticipantsResponse() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "get", - 'query_params': pb_request, - } - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - - pb_return_value = participant.ListParticipantsResponse.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.list_participants(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_list_participants_rest_unset_required_fields(): - transport = transports.ParticipantsRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.list_participants._get_unset_required_fields({}) - assert set(unset_fields) == (set(("pageSize", "pageToken", )) & set(("parent", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_list_participants_rest_interceptors(null_interceptor): - transport = transports.ParticipantsRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.ParticipantsRestInterceptor(), - ) - client = ParticipantsClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.ParticipantsRestInterceptor, "post_list_participants") as post, \ - mock.patch.object(transports.ParticipantsRestInterceptor, "pre_list_participants") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = participant.ListParticipantsRequest.pb(participant.ListParticipantsRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = participant.ListParticipantsResponse.to_json(participant.ListParticipantsResponse()) - - request = participant.ListParticipantsRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = participant.ListParticipantsResponse() - - client.list_participants(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_list_participants_rest_bad_request(transport: str = 'rest', request_type=participant.ListParticipantsRequest): - client = ParticipantsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1/conversations/sample2'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.list_participants(request) - - -def test_list_participants_rest_flattened(): - client = ParticipantsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = participant.ListParticipantsResponse() - - # get arguments that satisfy an http rule for this method - sample_request = {'parent': 'projects/sample1/conversations/sample2'} - - # get truthy value for each flattened field - mock_args = dict( - parent='parent_value', - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - pb_return_value = participant.ListParticipantsResponse.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.list_participants(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v2beta1/{parent=projects/*/conversations/*}/participants" % client.transport._host, args[1]) - - -def test_list_participants_rest_flattened_error(transport: str = 'rest'): - client = ParticipantsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.list_participants( - participant.ListParticipantsRequest(), - parent='parent_value', - ) - - -def test_list_participants_rest_pager(transport: str = 'rest'): - client = ParticipantsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # TODO(kbandes): remove this mock unless there's a good reason for it. - #with mock.patch.object(path_template, 'transcode') as transcode: - # Set the response as a series of pages - response = ( - participant.ListParticipantsResponse( - participants=[ - participant.Participant(), - participant.Participant(), - participant.Participant(), - ], - next_page_token='abc', - ), - participant.ListParticipantsResponse( - participants=[], - next_page_token='def', - ), - participant.ListParticipantsResponse( - participants=[ - participant.Participant(), - ], - next_page_token='ghi', - ), - participant.ListParticipantsResponse( - participants=[ - participant.Participant(), - participant.Participant(), - ], - ), - ) - # Two responses for two calls - response = response + response - - # Wrap the values into proper Response objs - response = tuple(participant.ListParticipantsResponse.to_json(x) for x in response) - return_values = tuple(Response() for i in response) - for return_val, response_val in zip(return_values, response): - return_val._content = response_val.encode('UTF-8') - return_val.status_code = 200 - req.side_effect = return_values - - sample_request = {'parent': 'projects/sample1/conversations/sample2'} - - pager = client.list_participants(request=sample_request) - - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, participant.Participant) - for i in results) - - pages = list(client.list_participants(request=sample_request).pages) - for page_, token in zip(pages, ['abc','def','ghi', '']): - assert page_.raw_page.next_page_token == token - - -@pytest.mark.parametrize("request_type", [ - gcd_participant.UpdateParticipantRequest, - dict, -]) -def test_update_participant_rest(request_type): - client = ParticipantsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'participant': {'name': 'projects/sample1/conversations/sample2/participants/sample3'}} - request_init["participant"] = {'name': 'projects/sample1/conversations/sample2/participants/sample3', 'role': 1, 'obfuscated_external_user_id': 'obfuscated_external_user_id_value', 'documents_metadata_filters': {}} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = gcd_participant.Participant( - name='name_value', - role=gcd_participant.Participant.Role.HUMAN_AGENT, - obfuscated_external_user_id='obfuscated_external_user_id_value', - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - pb_return_value = gcd_participant.Participant.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.update_participant(request) - - # 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' - - -def test_update_participant_rest_required_fields(request_type=gcd_participant.UpdateParticipantRequest): - transport_class = transports.ParticipantsRestTransport - - request_init = {} - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - including_default_value_fields=False, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).update_participant._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).update_participant._get_unset_required_fields(jsonified_request) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("update_mask", )) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - - client = ParticipantsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = gcd_participant.Participant() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "patch", - 'query_params': pb_request, - } - transcode_result['body'] = pb_request - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - - pb_return_value = gcd_participant.Participant.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.update_participant(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_update_participant_rest_unset_required_fields(): - transport = transports.ParticipantsRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.update_participant._get_unset_required_fields({}) - assert set(unset_fields) == (set(("updateMask", )) & set(("participant", "updateMask", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_update_participant_rest_interceptors(null_interceptor): - transport = transports.ParticipantsRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.ParticipantsRestInterceptor(), - ) - client = ParticipantsClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.ParticipantsRestInterceptor, "post_update_participant") as post, \ - mock.patch.object(transports.ParticipantsRestInterceptor, "pre_update_participant") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = gcd_participant.UpdateParticipantRequest.pb(gcd_participant.UpdateParticipantRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = gcd_participant.Participant.to_json(gcd_participant.Participant()) - - request = gcd_participant.UpdateParticipantRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = gcd_participant.Participant() - - client.update_participant(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_update_participant_rest_bad_request(transport: str = 'rest', request_type=gcd_participant.UpdateParticipantRequest): - client = ParticipantsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'participant': {'name': 'projects/sample1/conversations/sample2/participants/sample3'}} - request_init["participant"] = {'name': 'projects/sample1/conversations/sample2/participants/sample3', 'role': 1, 'obfuscated_external_user_id': 'obfuscated_external_user_id_value', 'documents_metadata_filters': {}} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.update_participant(request) - - -def test_update_participant_rest_flattened(): - client = ParticipantsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = gcd_participant.Participant() - - # get arguments that satisfy an http rule for this method - sample_request = {'participant': {'name': 'projects/sample1/conversations/sample2/participants/sample3'}} - - # get truthy value for each flattened field - mock_args = dict( - participant=gcd_participant.Participant(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - pb_return_value = gcd_participant.Participant.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.update_participant(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v2beta1/{participant.name=projects/*/conversations/*/participants/*}" % client.transport._host, args[1]) - - -def test_update_participant_rest_flattened_error(transport: str = 'rest'): - client = ParticipantsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.update_participant( - gcd_participant.UpdateParticipantRequest(), - participant=gcd_participant.Participant(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - - -def test_update_participant_rest_error(): - client = ParticipantsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - gcd_participant.AnalyzeContentRequest, - dict, -]) -def test_analyze_content_rest(request_type): - client = ParticipantsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'participant': 'projects/sample1/conversations/sample2/participants/sample3'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = gcd_participant.AnalyzeContentResponse( - reply_text='reply_text_value', - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - pb_return_value = gcd_participant.AnalyzeContentResponse.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.analyze_content(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, gcd_participant.AnalyzeContentResponse) - assert response.reply_text == 'reply_text_value' - - -def test_analyze_content_rest_required_fields(request_type=gcd_participant.AnalyzeContentRequest): - transport_class = transports.ParticipantsRestTransport - - request_init = {} - request_init["participant"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - including_default_value_fields=False, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).analyze_content._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["participant"] = 'participant_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).analyze_content._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "participant" in jsonified_request - assert jsonified_request["participant"] == 'participant_value' - - client = ParticipantsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = gcd_participant.AnalyzeContentResponse() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "post", - 'query_params': pb_request, - } - transcode_result['body'] = pb_request - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - - pb_return_value = gcd_participant.AnalyzeContentResponse.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.analyze_content(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_analyze_content_rest_unset_required_fields(): - transport = transports.ParticipantsRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.analyze_content._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("participant", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_analyze_content_rest_interceptors(null_interceptor): - transport = transports.ParticipantsRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.ParticipantsRestInterceptor(), - ) - client = ParticipantsClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.ParticipantsRestInterceptor, "post_analyze_content") as post, \ - mock.patch.object(transports.ParticipantsRestInterceptor, "pre_analyze_content") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = gcd_participant.AnalyzeContentRequest.pb(gcd_participant.AnalyzeContentRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = gcd_participant.AnalyzeContentResponse.to_json(gcd_participant.AnalyzeContentResponse()) - - request = gcd_participant.AnalyzeContentRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = gcd_participant.AnalyzeContentResponse() - - client.analyze_content(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_analyze_content_rest_bad_request(transport: str = 'rest', request_type=gcd_participant.AnalyzeContentRequest): - client = ParticipantsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'participant': 'projects/sample1/conversations/sample2/participants/sample3'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.analyze_content(request) - - -def test_analyze_content_rest_flattened(): - client = ParticipantsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = gcd_participant.AnalyzeContentResponse() - - # get arguments that satisfy an http rule for this method - sample_request = {'participant': 'projects/sample1/conversations/sample2/participants/sample3'} - - # get truthy value for each flattened field - mock_args = dict( - participant='participant_value', - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - pb_return_value = gcd_participant.AnalyzeContentResponse.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.analyze_content(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v2beta1/{participant=projects/*/conversations/*/participants/*}:analyzeContent" % client.transport._host, args[1]) - - -def test_analyze_content_rest_flattened_error(transport: str = 'rest'): - client = ParticipantsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.analyze_content( - gcd_participant.AnalyzeContentRequest(), - participant='participant_value', - text_input=session.TextInput(text='text_value'), - audio_input=gcd_participant.AudioInput(config=audio_config.InputAudioConfig(audio_encoding=audio_config.AudioEncoding.AUDIO_ENCODING_LINEAR_16)), - event_input=session.EventInput(name='name_value'), - ) - - -def test_analyze_content_rest_error(): - client = ParticipantsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -def test_streaming_analyze_content_rest_no_http_options(): - client = ParticipantsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request = participant.StreamingAnalyzeContentRequest() - requests = [request] - with pytest.raises(RuntimeError): - client.streaming_analyze_content(requests) - - -@pytest.mark.parametrize("request_type", [ - participant.SuggestArticlesRequest, - dict, -]) -def test_suggest_articles_rest(request_type): - client = ParticipantsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1/conversations/sample2/participants/sample3'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = participant.SuggestArticlesResponse( - latest_message='latest_message_value', - context_size=1311, - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - pb_return_value = participant.SuggestArticlesResponse.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.suggest_articles(request) - - # 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 - - -def test_suggest_articles_rest_required_fields(request_type=participant.SuggestArticlesRequest): - transport_class = transports.ParticipantsRestTransport - - request_init = {} - request_init["parent"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - including_default_value_fields=False, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).suggest_articles._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["parent"] = 'parent_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).suggest_articles._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "parent" in jsonified_request - assert jsonified_request["parent"] == 'parent_value' - - client = ParticipantsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = participant.SuggestArticlesResponse() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "post", - 'query_params': pb_request, - } - transcode_result['body'] = pb_request - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - - pb_return_value = participant.SuggestArticlesResponse.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.suggest_articles(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_suggest_articles_rest_unset_required_fields(): - transport = transports.ParticipantsRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.suggest_articles._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("parent", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_suggest_articles_rest_interceptors(null_interceptor): - transport = transports.ParticipantsRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.ParticipantsRestInterceptor(), - ) - client = ParticipantsClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.ParticipantsRestInterceptor, "post_suggest_articles") as post, \ - mock.patch.object(transports.ParticipantsRestInterceptor, "pre_suggest_articles") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = participant.SuggestArticlesRequest.pb(participant.SuggestArticlesRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = participant.SuggestArticlesResponse.to_json(participant.SuggestArticlesResponse()) - - request = participant.SuggestArticlesRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = participant.SuggestArticlesResponse() - - client.suggest_articles(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_suggest_articles_rest_bad_request(transport: str = 'rest', request_type=participant.SuggestArticlesRequest): - client = ParticipantsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1/conversations/sample2/participants/sample3'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.suggest_articles(request) - - -def test_suggest_articles_rest_flattened(): - client = ParticipantsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = participant.SuggestArticlesResponse() - - # get arguments that satisfy an http rule for this method - sample_request = {'parent': 'projects/sample1/conversations/sample2/participants/sample3'} - - # get truthy value for each flattened field - mock_args = dict( - parent='parent_value', - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - pb_return_value = participant.SuggestArticlesResponse.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.suggest_articles(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v2beta1/{parent=projects/*/conversations/*/participants/*}/suggestions:suggestArticles" % client.transport._host, args[1]) - - -def test_suggest_articles_rest_flattened_error(transport: str = 'rest'): - client = ParticipantsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.suggest_articles( - participant.SuggestArticlesRequest(), - parent='parent_value', - ) - - -def test_suggest_articles_rest_error(): - client = ParticipantsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - participant.SuggestFaqAnswersRequest, - dict, -]) -def test_suggest_faq_answers_rest(request_type): - client = ParticipantsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1/conversations/sample2/participants/sample3'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = participant.SuggestFaqAnswersResponse( - latest_message='latest_message_value', - context_size=1311, - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - pb_return_value = participant.SuggestFaqAnswersResponse.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.suggest_faq_answers(request) - - # 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 - - -def test_suggest_faq_answers_rest_required_fields(request_type=participant.SuggestFaqAnswersRequest): - transport_class = transports.ParticipantsRestTransport - - request_init = {} - request_init["parent"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - including_default_value_fields=False, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).suggest_faq_answers._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["parent"] = 'parent_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).suggest_faq_answers._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "parent" in jsonified_request - assert jsonified_request["parent"] == 'parent_value' - - client = ParticipantsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = participant.SuggestFaqAnswersResponse() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "post", - 'query_params': pb_request, - } - transcode_result['body'] = pb_request - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - - pb_return_value = participant.SuggestFaqAnswersResponse.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.suggest_faq_answers(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_suggest_faq_answers_rest_unset_required_fields(): - transport = transports.ParticipantsRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.suggest_faq_answers._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("parent", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_suggest_faq_answers_rest_interceptors(null_interceptor): - transport = transports.ParticipantsRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.ParticipantsRestInterceptor(), - ) - client = ParticipantsClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.ParticipantsRestInterceptor, "post_suggest_faq_answers") as post, \ - mock.patch.object(transports.ParticipantsRestInterceptor, "pre_suggest_faq_answers") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = participant.SuggestFaqAnswersRequest.pb(participant.SuggestFaqAnswersRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = participant.SuggestFaqAnswersResponse.to_json(participant.SuggestFaqAnswersResponse()) - - request = participant.SuggestFaqAnswersRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = participant.SuggestFaqAnswersResponse() - - client.suggest_faq_answers(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_suggest_faq_answers_rest_bad_request(transport: str = 'rest', request_type=participant.SuggestFaqAnswersRequest): - client = ParticipantsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1/conversations/sample2/participants/sample3'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.suggest_faq_answers(request) - - -def test_suggest_faq_answers_rest_flattened(): - client = ParticipantsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = participant.SuggestFaqAnswersResponse() - - # get arguments that satisfy an http rule for this method - sample_request = {'parent': 'projects/sample1/conversations/sample2/participants/sample3'} - - # get truthy value for each flattened field - mock_args = dict( - parent='parent_value', - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - pb_return_value = participant.SuggestFaqAnswersResponse.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.suggest_faq_answers(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v2beta1/{parent=projects/*/conversations/*/participants/*}/suggestions:suggestFaqAnswers" % client.transport._host, args[1]) - - -def test_suggest_faq_answers_rest_flattened_error(transport: str = 'rest'): - client = ParticipantsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.suggest_faq_answers( - participant.SuggestFaqAnswersRequest(), - parent='parent_value', - ) - - -def test_suggest_faq_answers_rest_error(): - client = ParticipantsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - participant.SuggestSmartRepliesRequest, - dict, -]) -def test_suggest_smart_replies_rest(request_type): - client = ParticipantsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1/conversations/sample2/participants/sample3'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = participant.SuggestSmartRepliesResponse( - latest_message='latest_message_value', - context_size=1311, - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - pb_return_value = participant.SuggestSmartRepliesResponse.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.suggest_smart_replies(request) - - # 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 - - -def test_suggest_smart_replies_rest_required_fields(request_type=participant.SuggestSmartRepliesRequest): - transport_class = transports.ParticipantsRestTransport - - request_init = {} - request_init["parent"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - including_default_value_fields=False, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).suggest_smart_replies._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["parent"] = 'parent_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).suggest_smart_replies._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "parent" in jsonified_request - assert jsonified_request["parent"] == 'parent_value' - - client = ParticipantsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = participant.SuggestSmartRepliesResponse() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "post", - 'query_params': pb_request, - } - transcode_result['body'] = pb_request - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - - pb_return_value = participant.SuggestSmartRepliesResponse.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.suggest_smart_replies(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_suggest_smart_replies_rest_unset_required_fields(): - transport = transports.ParticipantsRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.suggest_smart_replies._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("parent", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_suggest_smart_replies_rest_interceptors(null_interceptor): - transport = transports.ParticipantsRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.ParticipantsRestInterceptor(), - ) - client = ParticipantsClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.ParticipantsRestInterceptor, "post_suggest_smart_replies") as post, \ - mock.patch.object(transports.ParticipantsRestInterceptor, "pre_suggest_smart_replies") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = participant.SuggestSmartRepliesRequest.pb(participant.SuggestSmartRepliesRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = participant.SuggestSmartRepliesResponse.to_json(participant.SuggestSmartRepliesResponse()) - - request = participant.SuggestSmartRepliesRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = participant.SuggestSmartRepliesResponse() - - client.suggest_smart_replies(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_suggest_smart_replies_rest_bad_request(transport: str = 'rest', request_type=participant.SuggestSmartRepliesRequest): - client = ParticipantsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1/conversations/sample2/participants/sample3'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.suggest_smart_replies(request) - - -def test_suggest_smart_replies_rest_flattened(): - client = ParticipantsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = participant.SuggestSmartRepliesResponse() - - # get arguments that satisfy an http rule for this method - sample_request = {'parent': 'projects/sample1/conversations/sample2/participants/sample3'} - - # get truthy value for each flattened field - mock_args = dict( - parent='parent_value', - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - pb_return_value = participant.SuggestSmartRepliesResponse.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.suggest_smart_replies(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v2beta1/{parent=projects/*/conversations/*/participants/*}/suggestions:suggestSmartReplies" % client.transport._host, args[1]) - - -def test_suggest_smart_replies_rest_flattened_error(transport: str = 'rest'): - client = ParticipantsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.suggest_smart_replies( - participant.SuggestSmartRepliesRequest(), - parent='parent_value', - ) - - -def test_suggest_smart_replies_rest_error(): - client = ParticipantsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - participant.ListSuggestionsRequest, - dict, -]) -def test_list_suggestions_rest(request_type): - client = ParticipantsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1/conversations/sample2/participants/sample3'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = participant.ListSuggestionsResponse( - next_page_token='next_page_token_value', - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - pb_return_value = participant.ListSuggestionsResponse.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.list_suggestions(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListSuggestionsPager) - assert response.next_page_token == 'next_page_token_value' - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_list_suggestions_rest_interceptors(null_interceptor): - transport = transports.ParticipantsRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.ParticipantsRestInterceptor(), - ) - client = ParticipantsClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.ParticipantsRestInterceptor, "post_list_suggestions") as post, \ - mock.patch.object(transports.ParticipantsRestInterceptor, "pre_list_suggestions") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = participant.ListSuggestionsRequest.pb(participant.ListSuggestionsRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = participant.ListSuggestionsResponse.to_json(participant.ListSuggestionsResponse()) - - request = participant.ListSuggestionsRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = participant.ListSuggestionsResponse() - - client.list_suggestions(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_list_suggestions_rest_bad_request(transport: str = 'rest', request_type=participant.ListSuggestionsRequest): - client = ParticipantsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1/conversations/sample2/participants/sample3'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.list_suggestions(request) - - -def test_list_suggestions_rest_pager(transport: str = 'rest'): - client = ParticipantsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # TODO(kbandes): remove this mock unless there's a good reason for it. - #with mock.patch.object(path_template, 'transcode') as transcode: - # Set the response as a series of pages - response = ( - participant.ListSuggestionsResponse( - suggestions=[ - participant.Suggestion(), - participant.Suggestion(), - participant.Suggestion(), - ], - next_page_token='abc', - ), - participant.ListSuggestionsResponse( - suggestions=[], - next_page_token='def', - ), - participant.ListSuggestionsResponse( - suggestions=[ - participant.Suggestion(), - ], - next_page_token='ghi', - ), - participant.ListSuggestionsResponse( - suggestions=[ - participant.Suggestion(), - participant.Suggestion(), - ], - ), - ) - # Two responses for two calls - response = response + response - - # Wrap the values into proper Response objs - response = tuple(participant.ListSuggestionsResponse.to_json(x) for x in response) - return_values = tuple(Response() for i in response) - for return_val, response_val in zip(return_values, response): - return_val._content = response_val.encode('UTF-8') - return_val.status_code = 200 - req.side_effect = return_values - - sample_request = {'parent': 'projects/sample1/conversations/sample2/participants/sample3'} - - pager = client.list_suggestions(request=sample_request) - - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, participant.Suggestion) - for i in results) - - pages = list(client.list_suggestions(request=sample_request).pages) - for page_, token in zip(pages, ['abc','def','ghi', '']): - assert page_.raw_page.next_page_token == token - - -@pytest.mark.parametrize("request_type", [ - participant.CompileSuggestionRequest, - dict, -]) -def test_compile_suggestion_rest(request_type): - client = ParticipantsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1/conversations/sample2/participants/sample3'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = participant.CompileSuggestionResponse( - latest_message='latest_message_value', - context_size=1311, - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - pb_return_value = participant.CompileSuggestionResponse.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.compile_suggestion(request) - - # 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 - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_compile_suggestion_rest_interceptors(null_interceptor): - transport = transports.ParticipantsRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.ParticipantsRestInterceptor(), - ) - client = ParticipantsClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.ParticipantsRestInterceptor, "post_compile_suggestion") as post, \ - mock.patch.object(transports.ParticipantsRestInterceptor, "pre_compile_suggestion") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = participant.CompileSuggestionRequest.pb(participant.CompileSuggestionRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = participant.CompileSuggestionResponse.to_json(participant.CompileSuggestionResponse()) - - request = participant.CompileSuggestionRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = participant.CompileSuggestionResponse() - - client.compile_suggestion(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_compile_suggestion_rest_bad_request(transport: str = 'rest', request_type=participant.CompileSuggestionRequest): - client = ParticipantsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1/conversations/sample2/participants/sample3'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.compile_suggestion(request) - - -def test_compile_suggestion_rest_error(): - client = ParticipantsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -def test_streaming_analyze_content_rest_error(): - client = ParticipantsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - # Since a `google.api.http` annotation is required for using a rest transport - # method, this should error. - with pytest.raises(NotImplementedError) as not_implemented_error: - client.streaming_analyze_content({}) - assert ( - "Method StreamingAnalyzeContent is not available over REST transport" - in str(not_implemented_error.value) - ) - - -def test_credentials_transport_error(): - # It is an error to provide credentials and a transport instance. - transport = transports.ParticipantsGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = ParticipantsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # It is an error to provide a credentials file and a transport instance. - transport = transports.ParticipantsGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = ParticipantsClient( - client_options={"credentials_file": "credentials.json"}, - transport=transport, - ) - - # It is an error to provide an api_key and a transport instance. - transport = transports.ParticipantsGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - options = client_options.ClientOptions() - options.api_key = "api_key" - with pytest.raises(ValueError): - client = ParticipantsClient( - client_options=options, - transport=transport, - ) - - # It is an error to provide an api_key and a credential. - options = mock.Mock() - options.api_key = "api_key" - with pytest.raises(ValueError): - client = ParticipantsClient( - client_options=options, - credentials=ga_credentials.AnonymousCredentials() - ) - - # It is an error to provide scopes and a transport instance. - transport = transports.ParticipantsGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = ParticipantsClient( - client_options={"scopes": ["1", "2"]}, - transport=transport, - ) - - -def test_transport_instance(): - # A client may be instantiated with a custom transport instance. - transport = transports.ParticipantsGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - client = ParticipantsClient(transport=transport) - assert client.transport is transport - -def test_transport_get_channel(): - # A client may be instantiated with a custom transport instance. - transport = transports.ParticipantsGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - - transport = transports.ParticipantsGrpcAsyncIOTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - -@pytest.mark.parametrize("transport_class", [ - transports.ParticipantsGrpcTransport, - transports.ParticipantsGrpcAsyncIOTransport, - transports.ParticipantsRestTransport, -]) -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() - -@pytest.mark.parametrize("transport_name", [ - "grpc", - "rest", -]) -def test_transport_kind(transport_name): - transport = ParticipantsClient.get_transport_class(transport_name)( - credentials=ga_credentials.AnonymousCredentials(), - ) - assert transport.kind == transport_name - -def test_transport_grpc_default(): - # A client should use the gRPC transport by default. - 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(core_exceptions.DuplicateCredentialArgs): - transport = transports.ParticipantsTransport( - credentials=ga_credentials.AnonymousCredentials(), - credentials_file="credentials.json" - ) - - -def test_participants_base_transport(): - # Instantiate the base transport. - with mock.patch('google.cloud.dialogflow_v2beta1.services.participants.transports.ParticipantsTransport.__init__') as Transport: - Transport.return_value = None - transport = transports.ParticipantsTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Every method on the transport should just blindly - # raise NotImplementedError. - methods = ( - 'create_participant', - 'get_participant', - 'list_participants', - 'update_participant', - 'analyze_content', - 'streaming_analyze_content', - 'suggest_articles', - 'suggest_faq_answers', - 'suggest_smart_replies', - 'list_suggestions', - 'compile_suggestion', - 'get_location', - 'list_locations', - 'get_operation', - 'cancel_operation', - 'list_operations', - ) - for method in methods: - with pytest.raises(NotImplementedError): - getattr(transport, method)(request=object()) - - with pytest.raises(NotImplementedError): - transport.close() - - # Catch all for all remaining methods and properties - remainder = [ - 'kind', - ] - for r in remainder: - with pytest.raises(NotImplementedError): - getattr(transport, r)() - - -def test_participants_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.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", - ) - - -def test_participants_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.participants.transports.ParticipantsTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.ParticipantsTransport() - adc.assert_called_once() - - -def test_participants_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) - 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, - ) - - -@pytest.mark.parametrize( - "transport_class", - [ - transports.ParticipantsGrpcTransport, - transports.ParticipantsGrpcAsyncIOTransport, - ], -) -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(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, - transports.ParticipantsRestTransport, - ], -) -def test_participants_transport_auth_gdch_credentials(transport_class): - host = 'https://language.com' - api_audience_tests = [None, 'https://language2.com'] - api_audience_expect = [host, 'https://language2.com'] - for t, e in zip(api_audience_tests, api_audience_expect): - with mock.patch.object(google.auth, 'default', autospec=True) as adc: - gdch_mock = mock.MagicMock() - type(gdch_mock).with_gdch_audience = mock.PropertyMock(return_value=gdch_mock) - adc.return_value = (gdch_mock, None) - transport_class(host=host, api_audience=t) - gdch_mock.with_gdch_audience.assert_called_once_with( - e - ) - - -@pytest.mark.parametrize( - "transport_class,grpc_helpers", - [ - (transports.ParticipantsGrpcTransport, grpc_helpers), - (transports.ParticipantsGrpcAsyncIOTransport, grpc_helpers_async) - ], -) -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", [transports.ParticipantsGrpcTransport, transports.ParticipantsGrpcAsyncIOTransport]) -def test_participants_grpc_transport_client_cert_source_for_mtls( - transport_class -): - cred = ga_credentials.AnonymousCredentials() - - # Check ssl_channel_credentials is used if provided. - with mock.patch.object(transport_class, "create_channel") as mock_create_channel: - mock_ssl_channel_creds = mock.Mock() - transport_class( - host="squid.clam.whelk", - credentials=cred, - ssl_channel_credentials=mock_ssl_channel_creds - ) - mock_create_channel.assert_called_once_with( - "squid.clam.whelk:443", - credentials=cred, - credentials_file=None, - scopes=None, - ssl_credentials=mock_ssl_channel_creds, - quota_project_id=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - # Check if ssl_channel_credentials is not provided, then client_cert_source_for_mtls - # is used. - with mock.patch.object(transport_class, "create_channel", return_value=mock.Mock()): - with mock.patch("grpc.ssl_channel_credentials") as mock_ssl_cred: - transport_class( - credentials=cred, - client_cert_source_for_mtls=client_cert_source_callback - ) - expected_cert, expected_key = client_cert_source_callback() - mock_ssl_cred.assert_called_once_with( - certificate_chain=expected_cert, - private_key=expected_key - ) - -def test_participants_http_transport_client_cert_source_for_mtls(): - cred = ga_credentials.AnonymousCredentials() - with mock.patch("google.auth.transport.requests.AuthorizedSession.configure_mtls_channel") as mock_configure_mtls_channel: - transports.ParticipantsRestTransport ( - credentials=cred, - client_cert_source_for_mtls=client_cert_source_callback - ) - mock_configure_mtls_channel.assert_called_once_with(client_cert_source_callback) - - -@pytest.mark.parametrize("transport_name", [ - "grpc", - "grpc_asyncio", - "rest", -]) -def test_participants_host_no_port(transport_name): - client = ParticipantsClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='dialogflow.googleapis.com'), - transport=transport_name, - ) - assert client.transport._host == ( - 'dialogflow.googleapis.com:443' - if transport_name in ['grpc', 'grpc_asyncio'] - else 'https://dialogflow.googleapis.com' - ) - -@pytest.mark.parametrize("transport_name", [ - "grpc", - "grpc_asyncio", - "rest", -]) -def test_participants_host_with_port(transport_name): - client = ParticipantsClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='dialogflow.googleapis.com:8000'), - transport=transport_name, - ) - assert client.transport._host == ( - 'dialogflow.googleapis.com:8000' - if transport_name in ['grpc', 'grpc_asyncio'] - else 'https://dialogflow.googleapis.com:8000' - ) - -@pytest.mark.parametrize("transport_name", [ - "rest", -]) -def test_participants_client_transport_session_collision(transport_name): - creds1 = ga_credentials.AnonymousCredentials() - creds2 = ga_credentials.AnonymousCredentials() - client1 = ParticipantsClient( - credentials=creds1, - transport=transport_name, - ) - client2 = ParticipantsClient( - credentials=creds2, - transport=transport_name, - ) - session1 = client1.transport.create_participant._session - session2 = client2.transport.create_participant._session - assert session1 != session2 - session1 = client1.transport.get_participant._session - session2 = client2.transport.get_participant._session - assert session1 != session2 - session1 = client1.transport.list_participants._session - session2 = client2.transport.list_participants._session - assert session1 != session2 - session1 = client1.transport.update_participant._session - session2 = client2.transport.update_participant._session - assert session1 != session2 - session1 = client1.transport.analyze_content._session - session2 = client2.transport.analyze_content._session - assert session1 != session2 - session1 = client1.transport.streaming_analyze_content._session - session2 = client2.transport.streaming_analyze_content._session - assert session1 != session2 - session1 = client1.transport.suggest_articles._session - session2 = client2.transport.suggest_articles._session - assert session1 != session2 - session1 = client1.transport.suggest_faq_answers._session - session2 = client2.transport.suggest_faq_answers._session - assert session1 != session2 - session1 = client1.transport.suggest_smart_replies._session - session2 = client2.transport.suggest_smart_replies._session - assert session1 != session2 - session1 = client1.transport.list_suggestions._session - session2 = client2.transport.list_suggestions._session - assert session1 != session2 - session1 = client1.transport.compile_suggestion._session - session2 = client2.transport.compile_suggestion._session - assert session1 != session2 -def test_participants_grpc_transport_channel(): - channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.ParticipantsGrpcTransport( - 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_participants_grpc_asyncio_transport_channel(): - channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.ParticipantsGrpcAsyncIOTransport( - 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.ParticipantsGrpcTransport, transports.ParticipantsGrpcAsyncIOTransport]) -def test_participants_transport_channel_mtls_with_client_cert_source( - transport_class -): - with mock.patch("grpc.ssl_channel_credentials", autospec=True) as grpc_ssl_channel_cred: - with mock.patch.object(transport_class, "create_channel") as grpc_create_channel: - mock_ssl_cred = mock.Mock() - grpc_ssl_channel_cred.return_value = mock_ssl_cred - - mock_grpc_channel = mock.Mock() - grpc_create_channel.return_value = mock_grpc_channel - - cred = ga_credentials.AnonymousCredentials() - with pytest.warns(DeprecationWarning): - with mock.patch.object(google.auth, 'default') as adc: - adc.return_value = (cred, None) - transport = transport_class( - host="squid.clam.whelk", - api_mtls_endpoint="mtls.squid.clam.whelk", - client_cert_source=client_cert_source_callback, - ) - adc.assert_called_once() - - grpc_ssl_channel_cred.assert_called_once_with( - certificate_chain=b"cert bytes", private_key=b"key bytes" - ) - grpc_create_channel.assert_called_once_with( - "mtls.squid.clam.whelk:443", - credentials=cred, - credentials_file=None, - scopes=None, - ssl_credentials=mock_ssl_cred, - quota_project_id=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - assert transport.grpc_channel == mock_grpc_channel - assert transport._ssl_channel_credentials == mock_ssl_cred - - -# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are -# removed from grpc/grpc_asyncio transport constructor. -@pytest.mark.parametrize("transport_class", [transports.ParticipantsGrpcTransport, transports.ParticipantsGrpcAsyncIOTransport]) -def test_participants_transport_channel_mtls_with_adc( - transport_class -): - mock_ssl_cred = mock.Mock() - with mock.patch.multiple( - "google.auth.transport.grpc.SslCredentials", - __init__=mock.Mock(return_value=None), - ssl_credentials=mock.PropertyMock(return_value=mock_ssl_cred), - ): - with mock.patch.object(transport_class, "create_channel") as grpc_create_channel: - mock_grpc_channel = mock.Mock() - grpc_create_channel.return_value = mock_grpc_channel - mock_cred = mock.Mock() - - with pytest.warns(DeprecationWarning): - transport = transport_class( - host="squid.clam.whelk", - credentials=mock_cred, - api_mtls_endpoint="mtls.squid.clam.whelk", - client_cert_source=None, - ) - - grpc_create_channel.assert_called_once_with( - "mtls.squid.clam.whelk:443", - credentials=mock_cred, - credentials_file=None, - scopes=None, - ssl_credentials=mock_ssl_cred, - quota_project_id=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - assert transport.grpc_channel == mock_grpc_channel - - -def test_answer_record_path(): - project = "squid" - answer_record = "clam" - expected = "projects/{project}/answerRecords/{answer_record}".format(project=project, answer_record=answer_record, ) - actual = ParticipantsClient.answer_record_path(project, answer_record) - assert expected == actual - - -def test_parse_answer_record_path(): - expected = { - "project": "whelk", - "answer_record": "octopus", - } - path = ParticipantsClient.answer_record_path(**expected) - - # Check that the path construction is reversible. - actual = ParticipantsClient.parse_answer_record_path(path) - assert expected == actual - -def test_context_path(): - project = "oyster" - session = "nudibranch" - context = "cuttlefish" - expected = "projects/{project}/agent/sessions/{session}/contexts/{context}".format(project=project, session=session, context=context, ) - actual = ParticipantsClient.context_path(project, session, context) - assert expected == actual - - -def test_parse_context_path(): - expected = { - "project": "mussel", - "session": "winkle", - "context": "nautilus", - } - path = ParticipantsClient.context_path(**expected) - - # Check that the path construction is reversible. - actual = ParticipantsClient.parse_context_path(path) - assert expected == actual - -def test_document_path(): - project = "scallop" - knowledge_base = "abalone" - document = "squid" - expected = "projects/{project}/knowledgeBases/{knowledge_base}/documents/{document}".format(project=project, knowledge_base=knowledge_base, document=document, ) - actual = ParticipantsClient.document_path(project, knowledge_base, document) - assert expected == actual - - -def test_parse_document_path(): - expected = { - "project": "clam", - "knowledge_base": "whelk", - "document": "octopus", - } - path = ParticipantsClient.document_path(**expected) - - # Check that the path construction is reversible. - actual = ParticipantsClient.parse_document_path(path) - assert expected == actual - -def test_intent_path(): - project = "oyster" - intent = "nudibranch" - expected = "projects/{project}/agent/intents/{intent}".format(project=project, intent=intent, ) - actual = ParticipantsClient.intent_path(project, intent) - assert expected == actual - - -def test_parse_intent_path(): - expected = { - "project": "cuttlefish", - "intent": "mussel", - } - path = ParticipantsClient.intent_path(**expected) - - # Check that the path construction is reversible. - actual = ParticipantsClient.parse_intent_path(path) - assert expected == actual - -def test_message_path(): - project = "winkle" - conversation = "nautilus" - message = "scallop" - expected = "projects/{project}/conversations/{conversation}/messages/{message}".format(project=project, conversation=conversation, message=message, ) - actual = ParticipantsClient.message_path(project, conversation, message) - assert expected == actual - - -def test_parse_message_path(): - expected = { - "project": "abalone", - "conversation": "squid", - "message": "clam", - } - path = ParticipantsClient.message_path(**expected) - - # Check that the path construction is reversible. - actual = ParticipantsClient.parse_message_path(path) - assert expected == actual - -def test_participant_path(): - project = "whelk" - conversation = "octopus" - participant = "oyster" - expected = "projects/{project}/conversations/{conversation}/participants/{participant}".format(project=project, conversation=conversation, participant=participant, ) - actual = ParticipantsClient.participant_path(project, conversation, participant) - assert expected == actual - - -def test_parse_participant_path(): - expected = { - "project": "nudibranch", - "conversation": "cuttlefish", - "participant": "mussel", - } - path = ParticipantsClient.participant_path(**expected) - - # Check that the path construction is reversible. - actual = ParticipantsClient.parse_participant_path(path) - assert expected == actual - -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, ) - actual = ParticipantsClient.session_entity_type_path(project, session, entity_type) - assert expected == actual - - -def test_parse_session_entity_type_path(): - expected = { - "project": "abalone", - "session": "squid", - "entity_type": "clam", - } - path = ParticipantsClient.session_entity_type_path(**expected) - - # Check that the path construction is reversible. - actual = ParticipantsClient.parse_session_entity_type_path(path) - assert expected == actual - -def test_common_billing_account_path(): - billing_account = "whelk" - expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) - actual = ParticipantsClient.common_billing_account_path(billing_account) - assert expected == actual - - -def test_parse_common_billing_account_path(): - expected = { - "billing_account": "octopus", - } - path = ParticipantsClient.common_billing_account_path(**expected) - - # Check that the path construction is reversible. - actual = ParticipantsClient.parse_common_billing_account_path(path) - assert expected == actual - -def test_common_folder_path(): - folder = "oyster" - expected = "folders/{folder}".format(folder=folder, ) - actual = ParticipantsClient.common_folder_path(folder) - assert expected == actual - - -def test_parse_common_folder_path(): - expected = { - "folder": "nudibranch", - } - path = ParticipantsClient.common_folder_path(**expected) - - # Check that the path construction is reversible. - actual = ParticipantsClient.parse_common_folder_path(path) - assert expected == actual - -def test_common_organization_path(): - organization = "cuttlefish" - expected = "organizations/{organization}".format(organization=organization, ) - actual = ParticipantsClient.common_organization_path(organization) - assert expected == actual - - -def test_parse_common_organization_path(): - expected = { - "organization": "mussel", - } - path = ParticipantsClient.common_organization_path(**expected) - - # Check that the path construction is reversible. - actual = ParticipantsClient.parse_common_organization_path(path) - assert expected == actual - -def test_common_project_path(): - project = "winkle" - expected = "projects/{project}".format(project=project, ) - actual = ParticipantsClient.common_project_path(project) - assert expected == actual - - -def test_parse_common_project_path(): - expected = { - "project": "nautilus", - } - path = ParticipantsClient.common_project_path(**expected) - - # Check that the path construction is reversible. - actual = ParticipantsClient.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 = ParticipantsClient.common_location_path(project, location) - assert expected == actual - - -def test_parse_common_location_path(): - expected = { - "project": "squid", - "location": "clam", - } - path = ParticipantsClient.common_location_path(**expected) - - # Check that the path construction is reversible. - actual = ParticipantsClient.parse_common_location_path(path) - assert expected == actual - - -def test_client_with_default_client_info(): - client_info = gapic_v1.client_info.ClientInfo() - - with mock.patch.object(transports.ParticipantsTransport, '_prep_wrapped_messages') as prep: - client = ParticipantsClient( - credentials=ga_credentials.AnonymousCredentials(), - client_info=client_info, - ) - prep.assert_called_once_with(client_info) - - with mock.patch.object(transports.ParticipantsTransport, '_prep_wrapped_messages') as prep: - transport_class = ParticipantsClient.get_transport_class() - transport = transport_class( - credentials=ga_credentials.AnonymousCredentials(), - client_info=client_info, - ) - prep.assert_called_once_with(client_info) - -@pytest.mark.asyncio -async def test_transport_close_async(): - client = ParticipantsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - with mock.patch.object(type(getattr(client.transport, "grpc_channel")), "close") as close: - async with client: - close.assert_not_called() - close.assert_called_once() - - -def test_get_location_rest_bad_request(transport: str = 'rest', request_type=locations_pb2.GetLocationRequest): - client = ParticipantsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - request = request_type() - request = json_format.ParseDict({'name': 'projects/sample1/locations/sample2'}, request) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.get_location(request) - -@pytest.mark.parametrize("request_type", [ - locations_pb2.GetLocationRequest, - dict, -]) -def test_get_location_rest(request_type): - client = ParticipantsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request_init = {'name': 'projects/sample1/locations/sample2'} - request = request_type(**request_init) - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = locations_pb2.Location() - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.get_location(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, locations_pb2.Location) - -def test_list_locations_rest_bad_request(transport: str = 'rest', request_type=locations_pb2.ListLocationsRequest): - client = ParticipantsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - request = request_type() - request = json_format.ParseDict({'name': 'projects/sample1'}, request) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.list_locations(request) - -@pytest.mark.parametrize("request_type", [ - locations_pb2.ListLocationsRequest, - dict, -]) -def test_list_locations_rest(request_type): - client = ParticipantsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request_init = {'name': 'projects/sample1'} - request = request_type(**request_init) - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = locations_pb2.ListLocationsResponse() - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.list_locations(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, locations_pb2.ListLocationsResponse) - -def test_cancel_operation_rest_bad_request(transport: str = 'rest', request_type=operations_pb2.CancelOperationRequest): - client = ParticipantsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - request = request_type() - request = json_format.ParseDict({'name': 'projects/sample1/operations/sample2'}, request) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.cancel_operation(request) - -@pytest.mark.parametrize("request_type", [ - operations_pb2.CancelOperationRequest, - dict, -]) -def test_cancel_operation_rest(request_type): - client = ParticipantsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request_init = {'name': 'projects/sample1/operations/sample2'} - request = request_type(**request_init) - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = None - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = '{}' - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.cancel_operation(request) - - # Establish that the response is the type that we expect. - assert response is None - -def test_get_operation_rest_bad_request(transport: str = 'rest', request_type=operations_pb2.GetOperationRequest): - client = ParticipantsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - request = request_type() - request = json_format.ParseDict({'name': 'projects/sample1/operations/sample2'}, request) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.get_operation(request) - -@pytest.mark.parametrize("request_type", [ - operations_pb2.GetOperationRequest, - dict, -]) -def test_get_operation_rest(request_type): - client = ParticipantsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request_init = {'name': 'projects/sample1/operations/sample2'} - request = request_type(**request_init) - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation() - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.get_operation(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, operations_pb2.Operation) - -def test_list_operations_rest_bad_request(transport: str = 'rest', request_type=operations_pb2.ListOperationsRequest): - client = ParticipantsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - request = request_type() - request = json_format.ParseDict({'name': 'projects/sample1'}, request) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.list_operations(request) - -@pytest.mark.parametrize("request_type", [ - operations_pb2.ListOperationsRequest, - dict, -]) -def test_list_operations_rest(request_type): - client = ParticipantsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request_init = {'name': 'projects/sample1'} - request = request_type(**request_init) - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = operations_pb2.ListOperationsResponse() - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.list_operations(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, operations_pb2.ListOperationsResponse) - - -def test_cancel_operation(transport: str = "grpc"): - client = ParticipantsClient( - 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 = operations_pb2.CancelOperationRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = None - response = client.cancel_operation(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 response is the type that we expect. - assert response is None -@pytest.mark.asyncio -async def test_cancel_operation_async(transport: str = "grpc"): - client = ParticipantsAsyncClient( - 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 = operations_pb2.CancelOperationRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - None - ) - response = await client.cancel_operation(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 response is the type that we expect. - assert response is None - -def test_cancel_operation_field_headers(): - 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 = operations_pb2.CancelOperationRequest() - request.name = "locations" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call: - call.return_value = None - - client.cancel_operation(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=locations",) in kw["metadata"] -@pytest.mark.asyncio -async def test_cancel_operation_field_headers_async(): - 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 = operations_pb2.CancelOperationRequest() - request.name = "locations" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - None - ) - await client.cancel_operation(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=locations",) in kw["metadata"] - -def test_cancel_operation_from_dict(): - 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.cancel_operation), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = None - - response = client.cancel_operation( - request={ - "name": "locations", - } - ) - call.assert_called() -@pytest.mark.asyncio -async def test_cancel_operation_from_dict_async(): - 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.cancel_operation), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - None - ) - response = await client.cancel_operation( - request={ - "name": "locations", - } - ) - call.assert_called() - - -def test_get_operation(transport: str = "grpc"): - client = ParticipantsClient( - 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 = operations_pb2.GetOperationRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_operation), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation() - response = client.get_operation(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 response is the type that we expect. - assert isinstance(response, operations_pb2.Operation) -@pytest.mark.asyncio -async def test_get_operation_async(transport: str = "grpc"): - client = ParticipantsAsyncClient( - 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 = operations_pb2.GetOperationRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_operation), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation() - ) - response = await client.get_operation(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 response is the type that we expect. - assert isinstance(response, operations_pb2.Operation) - -def test_get_operation_field_headers(): - 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 = operations_pb2.GetOperationRequest() - request.name = "locations" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_operation), "__call__") as call: - call.return_value = operations_pb2.Operation() - - client.get_operation(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=locations",) in kw["metadata"] -@pytest.mark.asyncio -async def test_get_operation_field_headers_async(): - 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 = operations_pb2.GetOperationRequest() - request.name = "locations" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_operation), "__call__") as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation() - ) - await client.get_operation(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=locations",) in kw["metadata"] - -def test_get_operation_from_dict(): - 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_operation), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation() - - response = client.get_operation( - request={ - "name": "locations", - } - ) - call.assert_called() -@pytest.mark.asyncio -async def test_get_operation_from_dict_async(): - 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_operation), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation() - ) - response = await client.get_operation( - request={ - "name": "locations", - } - ) - call.assert_called() - - -def test_list_operations(transport: str = "grpc"): - client = ParticipantsClient( - 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 = operations_pb2.ListOperationsRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_operations), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.ListOperationsResponse() - response = client.list_operations(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 response is the type that we expect. - assert isinstance(response, operations_pb2.ListOperationsResponse) -@pytest.mark.asyncio -async def test_list_operations_async(transport: str = "grpc"): - client = ParticipantsAsyncClient( - 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 = operations_pb2.ListOperationsRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_operations), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.ListOperationsResponse() - ) - response = await client.list_operations(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 response is the type that we expect. - assert isinstance(response, operations_pb2.ListOperationsResponse) - -def test_list_operations_field_headers(): - 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 = operations_pb2.ListOperationsRequest() - request.name = "locations" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_operations), "__call__") as call: - call.return_value = operations_pb2.ListOperationsResponse() - - client.list_operations(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=locations",) in kw["metadata"] -@pytest.mark.asyncio -async def test_list_operations_field_headers_async(): - 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 = operations_pb2.ListOperationsRequest() - request.name = "locations" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_operations), "__call__") as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.ListOperationsResponse() - ) - await client.list_operations(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=locations",) in kw["metadata"] - -def test_list_operations_from_dict(): - 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_operations), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.ListOperationsResponse() - - response = client.list_operations( - request={ - "name": "locations", - } - ) - call.assert_called() -@pytest.mark.asyncio -async def test_list_operations_from_dict_async(): - 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.list_operations), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.ListOperationsResponse() - ) - response = await client.list_operations( - request={ - "name": "locations", - } - ) - call.assert_called() - - -def test_list_locations(transport: str = "grpc"): - client = ParticipantsClient( - 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 = locations_pb2.ListLocationsRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_locations), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = locations_pb2.ListLocationsResponse() - response = client.list_locations(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 response is the type that we expect. - assert isinstance(response, locations_pb2.ListLocationsResponse) -@pytest.mark.asyncio -async def test_list_locations_async(transport: str = "grpc"): - client = ParticipantsAsyncClient( - 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 = locations_pb2.ListLocationsRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_locations), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - locations_pb2.ListLocationsResponse() - ) - response = await client.list_locations(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 response is the type that we expect. - assert isinstance(response, locations_pb2.ListLocationsResponse) - -def test_list_locations_field_headers(): - 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 = locations_pb2.ListLocationsRequest() - request.name = "locations" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_locations), "__call__") as call: - call.return_value = locations_pb2.ListLocationsResponse() - - client.list_locations(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=locations",) in kw["metadata"] -@pytest.mark.asyncio -async def test_list_locations_field_headers_async(): - 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 = locations_pb2.ListLocationsRequest() - request.name = "locations" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_locations), "__call__") as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - locations_pb2.ListLocationsResponse() - ) - await client.list_locations(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=locations",) in kw["metadata"] - -def test_list_locations_from_dict(): - 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_locations), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = locations_pb2.ListLocationsResponse() - - response = client.list_locations( - request={ - "name": "locations", - } - ) - call.assert_called() -@pytest.mark.asyncio -async def test_list_locations_from_dict_async(): - 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.list_locations), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - locations_pb2.ListLocationsResponse() - ) - response = await client.list_locations( - request={ - "name": "locations", - } - ) - call.assert_called() - - -def test_get_location(transport: str = "grpc"): - client = ParticipantsClient( - 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 = locations_pb2.GetLocationRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_location), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = locations_pb2.Location() - response = client.get_location(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 response is the type that we expect. - assert isinstance(response, locations_pb2.Location) -@pytest.mark.asyncio -async def test_get_location_async(transport: str = "grpc_asyncio"): - client = ParticipantsAsyncClient( - 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 = locations_pb2.GetLocationRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_location), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - locations_pb2.Location() - ) - response = await client.get_location(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 response is the type that we expect. - assert isinstance(response, locations_pb2.Location) - -def test_get_location_field_headers(): - 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 = locations_pb2.GetLocationRequest() - request.name = "locations/abc" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_location), "__call__") as call: - call.return_value = locations_pb2.Location() - - client.get_location(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=locations/abc",) in kw["metadata"] -@pytest.mark.asyncio -async def test_get_location_field_headers_async(): - 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 = locations_pb2.GetLocationRequest() - request.name = "locations/abc" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_location), "__call__") as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - locations_pb2.Location() - ) - await client.get_location(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=locations/abc",) in kw["metadata"] - -def test_get_location_from_dict(): - 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_locations), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = locations_pb2.Location() - - response = client.get_location( - request={ - "name": "locations/abc", - } - ) - call.assert_called() -@pytest.mark.asyncio -async def test_get_location_from_dict_async(): - 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.list_locations), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - locations_pb2.Location() - ) - response = await client.get_location( - request={ - "name": "locations", - } - ) - call.assert_called() - - -def test_transport_close(): - transports = { - "rest": "_session", - "grpc": "_grpc_channel", - } - - for transport, close_name in transports.items(): - client = ParticipantsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport - ) - with mock.patch.object(type(getattr(client.transport, close_name)), "close") as close: - with client: - close.assert_not_called() - close.assert_called_once() - -def test_client_ctx(): - transports = [ - 'rest', - 'grpc', - ] - for transport in transports: - client = ParticipantsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport - ) - # Test client calls underlying transport. - with mock.patch.object(type(client.transport), "close") as close: - close.assert_not_called() - with client: - pass - close.assert_called() - -@pytest.mark.parametrize("client_class,transport_class", [ - (ParticipantsClient, transports.ParticipantsGrpcTransport), - (ParticipantsAsyncClient, transports.ParticipantsGrpcAsyncIOTransport), -]) -def test_api_key_credentials(client_class, transport_class): - with mock.patch.object( - google.auth._default, "get_api_key_credentials", create=True - ) as get_api_key_credentials: - mock_cred = mock.Mock() - get_api_key_credentials.return_value = mock_cred - options = client_options.ClientOptions() - options.api_key = "api_key" - 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=mock_cred, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) diff --git a/owl-bot-staging/v2beta1/tests/unit/gapic/dialogflow_v2beta1/test_session_entity_types.py b/owl-bot-staging/v2beta1/tests/unit/gapic/dialogflow_v2beta1/test_session_entity_types.py deleted file mode 100644 index f7c1cdb7e..000000000 --- a/owl-bot-staging/v2beta1/tests/unit/gapic/dialogflow_v2beta1/test_session_entity_types.py +++ /dev/null @@ -1,4725 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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 -# try/except added for compatibility with python < 3.8 -try: - from unittest import mock - from unittest.mock import AsyncMock # pragma: NO COVER -except ImportError: # pragma: NO COVER - import mock - -import grpc -from grpc.experimental import aio -from collections.abc import Iterable -from google.protobuf import json_format -import json -import math -import pytest -from proto.marshal.rules.dates import DurationRule, TimestampRule -from proto.marshal.rules import wrappers -from requests import Response -from requests import Request, PreparedRequest -from requests.sessions import Session -from google.protobuf import json_format - -from google.api_core import client_options -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import grpc_helpers -from google.api_core import grpc_helpers_async -from google.api_core import path_template -from google.auth import credentials as ga_credentials -from google.auth.exceptions import MutualTLSChannelError -from google.cloud.dialogflow_v2beta1.services.session_entity_types import SessionEntityTypesAsyncClient -from google.cloud.dialogflow_v2beta1.services.session_entity_types import SessionEntityTypesClient -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.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.cloud.location import locations_pb2 -from google.longrunning import operations_pb2 -from google.oauth2 import service_account -from google.protobuf import field_mask_pb2 # type: ignore -import google.auth - - -def client_cert_source_callback(): - return b"cert bytes", b"key bytes" - - -# If default endpoint is localhost, then default mtls endpoint will be the same. -# This method modifies the default endpoint so the client can produce a different -# mtls endpoint for endpoint testing purposes. -def modify_default_endpoint(client): - return "foo.googleapis.com" if ("localhost" in client.DEFAULT_ENDPOINT) else client.DEFAULT_ENDPOINT - - -def test__get_default_mtls_endpoint(): - api_endpoint = "example.googleapis.com" - api_mtls_endpoint = "example.mtls.googleapis.com" - sandbox_endpoint = "example.sandbox.googleapis.com" - sandbox_mtls_endpoint = "example.mtls.sandbox.googleapis.com" - non_googleapi = "api.example.com" - - assert SessionEntityTypesClient._get_default_mtls_endpoint(None) is None - assert SessionEntityTypesClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint - assert SessionEntityTypesClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint - assert SessionEntityTypesClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint - assert SessionEntityTypesClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint - assert SessionEntityTypesClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi - - -@pytest.mark.parametrize("client_class,transport_name", [ - (SessionEntityTypesClient, "grpc"), - (SessionEntityTypesAsyncClient, "grpc_asyncio"), - (SessionEntityTypesClient, "rest"), -]) -def test_session_entity_types_client_from_service_account_info(client_class, transport_name): - 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, transport=transport_name) - assert client.transport._credentials == creds - assert isinstance(client, client_class) - - assert client.transport._host == ( - 'dialogflow.googleapis.com:443' - if transport_name in ['grpc', 'grpc_asyncio'] - else - 'https://dialogflow.googleapis.com' - ) - - -@pytest.mark.parametrize("transport_class,transport_name", [ - (transports.SessionEntityTypesGrpcTransport, "grpc"), - (transports.SessionEntityTypesGrpcAsyncIOTransport, "grpc_asyncio"), - (transports.SessionEntityTypesRestTransport, "rest"), -]) -def test_session_entity_types_client_service_account_always_use_jwt(transport_class, transport_name): - with mock.patch.object(service_account.Credentials, 'with_always_use_jwt_access', create=True) as use_jwt: - creds = service_account.Credentials(None, None, None) - transport = transport_class(credentials=creds, always_use_jwt_access=True) - use_jwt.assert_called_once_with(True) - - with mock.patch.object(service_account.Credentials, 'with_always_use_jwt_access', create=True) as use_jwt: - creds = service_account.Credentials(None, None, None) - transport = transport_class(credentials=creds, always_use_jwt_access=False) - use_jwt.assert_not_called() - - -@pytest.mark.parametrize("client_class,transport_name", [ - (SessionEntityTypesClient, "grpc"), - (SessionEntityTypesAsyncClient, "grpc_asyncio"), - (SessionEntityTypesClient, "rest"), -]) -def test_session_entity_types_client_from_service_account_file(client_class, transport_name): - 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", transport=transport_name) - assert client.transport._credentials == creds - assert isinstance(client, client_class) - - client = client_class.from_service_account_json("dummy/file/path.json", transport=transport_name) - assert client.transport._credentials == creds - assert isinstance(client, client_class) - - assert client.transport._host == ( - 'dialogflow.googleapis.com:443' - if transport_name in ['grpc', 'grpc_asyncio'] - else - 'https://dialogflow.googleapis.com' - ) - - -def test_session_entity_types_client_get_transport_class(): - transport = SessionEntityTypesClient.get_transport_class() - available_transports = [ - transports.SessionEntityTypesGrpcTransport, - transports.SessionEntityTypesRestTransport, - ] - assert transport in available_transports - - transport = SessionEntityTypesClient.get_transport_class("grpc") - assert transport == transports.SessionEntityTypesGrpcTransport - - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (SessionEntityTypesClient, transports.SessionEntityTypesGrpcTransport, "grpc"), - (SessionEntityTypesAsyncClient, transports.SessionEntityTypesGrpcAsyncIOTransport, "grpc_asyncio"), - (SessionEntityTypesClient, transports.SessionEntityTypesRestTransport, "rest"), -]) -@mock.patch.object(SessionEntityTypesClient, "DEFAULT_ENDPOINT", modify_default_endpoint(SessionEntityTypesClient)) -@mock.patch.object(SessionEntityTypesAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(SessionEntityTypesAsyncClient)) -def test_session_entity_types_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(SessionEntityTypesClient, '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(SessionEntityTypesClient, 'get_transport_class') as gtc: - client = client_class(transport=transport_name) - gtc.assert_called() - - # Check the case api_endpoint is provided. - options = client_options.ClientOptions(api_endpoint="squid.clam.whelk") - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(transport=transport_name, client_options=options) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host="squid.clam.whelk", - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is - # "never". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is - # "always". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_MTLS_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # 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(transport=transport_name) - - # 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(transport=transport_name) - - # 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, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id="octopus", - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - # Check the case api_endpoint is provided - options = client_options.ClientOptions(api_audience="https://language.googleapis.com") - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience="https://language.googleapis.com" - ) - -@pytest.mark.parametrize("client_class,transport_class,transport_name,use_client_cert_env", [ - (SessionEntityTypesClient, transports.SessionEntityTypesGrpcTransport, "grpc", "true"), - (SessionEntityTypesAsyncClient, transports.SessionEntityTypesGrpcAsyncIOTransport, "grpc_asyncio", "true"), - (SessionEntityTypesClient, transports.SessionEntityTypesGrpcTransport, "grpc", "false"), - (SessionEntityTypesAsyncClient, transports.SessionEntityTypesGrpcAsyncIOTransport, "grpc_asyncio", "false"), - (SessionEntityTypesClient, transports.SessionEntityTypesRestTransport, "rest", "true"), - (SessionEntityTypesClient, transports.SessionEntityTypesRestTransport, "rest", "false"), -]) -@mock.patch.object(SessionEntityTypesClient, "DEFAULT_ENDPOINT", modify_default_endpoint(SessionEntityTypesClient)) -@mock.patch.object(SessionEntityTypesAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(SessionEntityTypesAsyncClient)) -@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) -def test_session_entity_types_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, transport=transport_name) - - if use_client_cert_env == "false": - expected_client_cert_source = None - expected_host = client.DEFAULT_ENDPOINT - else: - expected_client_cert_source = client_cert_source_callback - expected_host = client.DEFAULT_MTLS_ENDPOINT - - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=expected_host, - scopes=None, - client_cert_source_for_mtls=expected_client_cert_source, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case ADC client cert is provided. Whether client cert is used depends on - # GOOGLE_API_USE_CLIENT_CERTIFICATE value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): - with mock.patch.object(transport_class, '__init__') as patched: - with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): - with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=client_cert_source_callback): - if use_client_cert_env == "false": - expected_host = client.DEFAULT_ENDPOINT - expected_client_cert_source = None - else: - expected_host = client.DEFAULT_MTLS_ENDPOINT - expected_client_cert_source = client_cert_source_callback - - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=expected_host, - scopes=None, - client_cert_source_for_mtls=expected_client_cert_source, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case client_cert_source and ADC client cert are not provided. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): - with mock.patch.object(transport_class, '__init__') as patched: - with mock.patch("google.auth.transport.mtls.has_default_client_cert_source", return_value=False): - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - -@pytest.mark.parametrize("client_class", [ - SessionEntityTypesClient, SessionEntityTypesAsyncClient -]) -@mock.patch.object(SessionEntityTypesClient, "DEFAULT_ENDPOINT", modify_default_endpoint(SessionEntityTypesClient)) -@mock.patch.object(SessionEntityTypesAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(SessionEntityTypesAsyncClient)) -def test_session_entity_types_client_get_mtls_endpoint_and_cert_source(client_class): - mock_client_cert_source = mock.Mock() - - # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "true". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - mock_api_endpoint = "foo" - options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) - assert api_endpoint == mock_api_endpoint - assert cert_source == mock_client_cert_source - - # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "false". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): - mock_client_cert_source = mock.Mock() - mock_api_endpoint = "foo" - options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) - assert api_endpoint == mock_api_endpoint - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "never". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_ENDPOINT - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "always". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert doesn't exist. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=False): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_ENDPOINT - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert exists. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - 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=mock_client_cert_source): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT - assert cert_source == mock_client_cert_source - - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (SessionEntityTypesClient, transports.SessionEntityTypesGrpcTransport, "grpc"), - (SessionEntityTypesAsyncClient, transports.SessionEntityTypesGrpcAsyncIOTransport, "grpc_asyncio"), - (SessionEntityTypesClient, transports.SessionEntityTypesRestTransport, "rest"), -]) -def test_session_entity_types_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, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=["1", "2"], - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - -@pytest.mark.parametrize("client_class,transport_class,transport_name,grpc_helpers", [ - (SessionEntityTypesClient, transports.SessionEntityTypesGrpcTransport, "grpc", grpc_helpers), - (SessionEntityTypesAsyncClient, transports.SessionEntityTypesGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), - (SessionEntityTypesClient, transports.SessionEntityTypesRestTransport, "rest", None), -]) -def test_session_entity_types_client_client_options_credentials_file(client_class, transport_class, transport_name, grpc_helpers): - # 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, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file="credentials.json", - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - -def test_session_entity_types_client_client_options_from_dict(): - with mock.patch('google.cloud.dialogflow_v2beta1.services.session_entity_types.transports.SessionEntityTypesGrpcTransport.__init__') as grpc_transport: - grpc_transport.return_value = None - client = SessionEntityTypesClient( - client_options={'api_endpoint': 'squid.clam.whelk'} - ) - grpc_transport.assert_called_once_with( - credentials=None, - credentials_file=None, - host="squid.clam.whelk", - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - -@pytest.mark.parametrize("client_class,transport_class,transport_name,grpc_helpers", [ - (SessionEntityTypesClient, transports.SessionEntityTypesGrpcTransport, "grpc", grpc_helpers), - (SessionEntityTypesAsyncClient, transports.SessionEntityTypesGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), -]) -def test_session_entity_types_client_create_channel_credentials_file(client_class, transport_class, transport_name, grpc_helpers): - # 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, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file="credentials.json", - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # test that the credentials from file are saved and used as the credentials. - with mock.patch.object( - google.auth, "load_credentials_from_file", autospec=True - ) as load_creds, mock.patch.object( - google.auth, "default", autospec=True - ) as adc, mock.patch.object( - grpc_helpers, "create_channel" - ) as create_channel: - creds = ga_credentials.AnonymousCredentials() - file_creds = ga_credentials.AnonymousCredentials() - load_creds.return_value = (file_creds, None) - adc.return_value = (creds, None) - client = client_class(client_options=options, transport=transport_name) - create_channel.assert_called_with( - "dialogflow.googleapis.com:443", - credentials=file_creds, - credentials_file=None, - quota_project_id=None, - default_scopes=( - 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/dialogflow', -), - scopes=None, - default_host="dialogflow.googleapis.com", - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - -@pytest.mark.parametrize("request_type", [ - session_entity_type.ListSessionEntityTypesRequest, - dict, -]) -def test_list_session_entity_types(request_type, transport: str = 'grpc'): - client = SessionEntityTypesClient( - 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_session_entity_types), - '__call__') as call: - # Designate an appropriate return value for the call. - 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' - - -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=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_session_entity_types), - '__call__') as call: - client.list_session_entity_types() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == session_entity_type.ListSessionEntityTypesRequest() - -@pytest.mark.asyncio -async def test_list_session_entity_types_async(transport: str = 'grpc_asyncio', request_type=session_entity_type.ListSessionEntityTypesRequest): - client = SessionEntityTypesAsyncClient( - 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_session_entity_types), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(session_entity_type.ListSessionEntityTypesResponse( - 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' - - -@pytest.mark.asyncio -async def test_list_session_entity_types_async_from_dict(): - await test_list_session_entity_types_async(request_type=dict) - - -def test_list_session_entity_types_field_headers(): - 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. - with mock.patch.object( - 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. - 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_session_entity_types_field_headers_async(): - client = SessionEntityTypesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value 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. - with mock.patch.object( - type(client.transport.list_session_entity_types), - '__call__') as call: - 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. - 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_session_entity_types_flattened(): - client = SessionEntityTypesClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_session_entity_types), - '__call__') 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', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - arg = args[0].parent - mock_val = 'parent_value' - assert arg == mock_val - - -def test_list_session_entity_types_flattened_error(): - client = SessionEntityTypesClient( - 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_session_entity_types( - session_entity_type.ListSessionEntityTypesRequest(), - parent='parent_value', - ) - -@pytest.mark.asyncio -async def test_list_session_entity_types_flattened_async(): - client = SessionEntityTypesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_session_entity_types), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = session_entity_type.ListSessionEntityTypesResponse() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(session_entity_type.ListSessionEntityTypesResponse()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.list_session_entity_types( - 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] - arg = args[0].parent - mock_val = 'parent_value' - assert arg == mock_val - -@pytest.mark.asyncio -async def test_list_session_entity_types_flattened_error_async(): - client = SessionEntityTypesAsyncClient( - 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_session_entity_types( - session_entity_type.ListSessionEntityTypesRequest(), - parent='parent_value', - ) - - -def test_list_session_entity_types_pager(transport_name: str = "grpc"): - client = SessionEntityTypesClient( - credentials=ga_credentials.AnonymousCredentials, - transport=transport_name, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_session_entity_types), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - session_entity_type.ListSessionEntityTypesResponse( - session_entity_types=[ - session_entity_type.SessionEntityType(), - session_entity_type.SessionEntityType(), - session_entity_type.SessionEntityType(), - ], - next_page_token='abc', - ), - session_entity_type.ListSessionEntityTypesResponse( - session_entity_types=[], - next_page_token='def', - ), - session_entity_type.ListSessionEntityTypesResponse( - session_entity_types=[ - session_entity_type.SessionEntityType(), - ], - next_page_token='ghi', - ), - session_entity_type.ListSessionEntityTypesResponse( - session_entity_types=[ - session_entity_type.SessionEntityType(), - session_entity_type.SessionEntityType(), - ], - ), - RuntimeError, - ) - - metadata = () - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ('parent', ''), - )), - ) - pager = client.list_session_entity_types(request={}) - - assert pager._metadata == metadata - - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, session_entity_type.SessionEntityType) - for i in results) -def test_list_session_entity_types_pages(transport_name: str = "grpc"): - client = SessionEntityTypesClient( - credentials=ga_credentials.AnonymousCredentials, - transport=transport_name, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_session_entity_types), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - session_entity_type.ListSessionEntityTypesResponse( - session_entity_types=[ - session_entity_type.SessionEntityType(), - session_entity_type.SessionEntityType(), - session_entity_type.SessionEntityType(), - ], - next_page_token='abc', - ), - session_entity_type.ListSessionEntityTypesResponse( - session_entity_types=[], - next_page_token='def', - ), - session_entity_type.ListSessionEntityTypesResponse( - session_entity_types=[ - session_entity_type.SessionEntityType(), - ], - next_page_token='ghi', - ), - session_entity_type.ListSessionEntityTypesResponse( - session_entity_types=[ - session_entity_type.SessionEntityType(), - session_entity_type.SessionEntityType(), - ], - ), - RuntimeError, - ) - pages = list(client.list_session_entity_types(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_session_entity_types_async_pager(): - client = SessionEntityTypesAsyncClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_session_entity_types), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - session_entity_type.ListSessionEntityTypesResponse( - session_entity_types=[ - session_entity_type.SessionEntityType(), - session_entity_type.SessionEntityType(), - session_entity_type.SessionEntityType(), - ], - next_page_token='abc', - ), - session_entity_type.ListSessionEntityTypesResponse( - session_entity_types=[], - next_page_token='def', - ), - session_entity_type.ListSessionEntityTypesResponse( - session_entity_types=[ - session_entity_type.SessionEntityType(), - ], - next_page_token='ghi', - ), - session_entity_type.ListSessionEntityTypesResponse( - session_entity_types=[ - session_entity_type.SessionEntityType(), - session_entity_type.SessionEntityType(), - ], - ), - RuntimeError, - ) - async_pager = await client.list_session_entity_types(request={},) - assert async_pager.next_page_token == 'abc' - responses = [] - async for response in async_pager: # pragma: no branch - responses.append(response) - - assert len(responses) == 6 - assert all(isinstance(i, session_entity_type.SessionEntityType) - for i in responses) - - -@pytest.mark.asyncio -async def test_list_session_entity_types_async_pages(): - client = SessionEntityTypesAsyncClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_session_entity_types), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - session_entity_type.ListSessionEntityTypesResponse( - session_entity_types=[ - session_entity_type.SessionEntityType(), - session_entity_type.SessionEntityType(), - session_entity_type.SessionEntityType(), - ], - next_page_token='abc', - ), - session_entity_type.ListSessionEntityTypesResponse( - session_entity_types=[], - next_page_token='def', - ), - session_entity_type.ListSessionEntityTypesResponse( - session_entity_types=[ - session_entity_type.SessionEntityType(), - ], - next_page_token='ghi', - ), - session_entity_type.ListSessionEntityTypesResponse( - session_entity_types=[ - session_entity_type.SessionEntityType(), - session_entity_type.SessionEntityType(), - ], - ), - RuntimeError, - ) - pages = [] - async for page_ in (await client.list_session_entity_types(request={})).pages: # pragma: no branch - pages.append(page_) - for page_, token in zip(pages, ['abc','def','ghi', '']): - assert page_.raw_page.next_page_token == token - -@pytest.mark.parametrize("request_type", [ - session_entity_type.GetSessionEntityTypeRequest, - dict, -]) -def test_get_session_entity_type(request_type, transport: str = 'grpc'): - client = SessionEntityTypesClient( - 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_session_entity_type), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = session_entity_type.SessionEntityType( - 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 - - -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=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_session_entity_type), - '__call__') as call: - client.get_session_entity_type() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == session_entity_type.GetSessionEntityTypeRequest() - -@pytest.mark.asyncio -async def test_get_session_entity_type_async(transport: str = 'grpc_asyncio', request_type=session_entity_type.GetSessionEntityTypeRequest): - client = SessionEntityTypesAsyncClient( - 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_session_entity_type), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(session_entity_type.SessionEntityType( - name='name_value', - 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 - - -@pytest.mark.asyncio -async def test_get_session_entity_type_async_from_dict(): - await test_get_session_entity_type_async(request_type=dict) - - -def test_get_session_entity_type_field_headers(): - 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. - with mock.patch.object( - 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. - 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_session_entity_type_field_headers_async(): - client = SessionEntityTypesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value 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. - with mock.patch.object( - type(client.transport.get_session_entity_type), - '__call__') as call: - 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. - 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_session_entity_type_flattened(): - client = SessionEntityTypesClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_session_entity_type), - '__call__') 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', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - arg = args[0].name - mock_val = 'name_value' - assert arg == mock_val - - -def test_get_session_entity_type_flattened_error(): - client = SessionEntityTypesClient( - 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_session_entity_type( - session_entity_type.GetSessionEntityTypeRequest(), - name='name_value', - ) - -@pytest.mark.asyncio -async def test_get_session_entity_type_flattened_async(): - client = SessionEntityTypesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_session_entity_type), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = session_entity_type.SessionEntityType() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(session_entity_type.SessionEntityType()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.get_session_entity_type( - 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] - arg = args[0].name - mock_val = 'name_value' - assert arg == mock_val - -@pytest.mark.asyncio -async def test_get_session_entity_type_flattened_error_async(): - client = SessionEntityTypesAsyncClient( - 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_session_entity_type( - session_entity_type.GetSessionEntityTypeRequest(), - name='name_value', - ) - - -@pytest.mark.parametrize("request_type", [ - gcd_session_entity_type.CreateSessionEntityTypeRequest, - dict, -]) -def test_create_session_entity_type(request_type, transport: str = 'grpc'): - client = SessionEntityTypesClient( - 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_session_entity_type), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcd_session_entity_type.SessionEntityType( - 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 - - -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=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_session_entity_type), - '__call__') as call: - client.create_session_entity_type() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == gcd_session_entity_type.CreateSessionEntityTypeRequest() - -@pytest.mark.asyncio -async def test_create_session_entity_type_async(transport: str = 'grpc_asyncio', request_type=gcd_session_entity_type.CreateSessionEntityTypeRequest): - client = SessionEntityTypesAsyncClient( - 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_session_entity_type), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gcd_session_entity_type.SessionEntityType( - name='name_value', - 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 - - -@pytest.mark.asyncio -async def test_create_session_entity_type_async_from_dict(): - await test_create_session_entity_type_async(request_type=dict) - - -def test_create_session_entity_type_field_headers(): - 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. - with mock.patch.object( - 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. - 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_session_entity_type_field_headers_async(): - client = SessionEntityTypesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value 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. - with mock.patch.object( - type(client.transport.create_session_entity_type), - '__call__') as call: - 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. - 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_session_entity_type_flattened(): - client = SessionEntityTypesClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_session_entity_type), - '__call__') 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( - parent='parent_value', - session_entity_type=gcd_session_entity_type.SessionEntityType(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] - arg = args[0].parent - mock_val = 'parent_value' - assert arg == mock_val - arg = args[0].session_entity_type - mock_val = gcd_session_entity_type.SessionEntityType(name='name_value') - assert arg == mock_val - - -def test_create_session_entity_type_flattened_error(): - client = SessionEntityTypesClient( - 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_session_entity_type( - gcd_session_entity_type.CreateSessionEntityTypeRequest(), - parent='parent_value', - session_entity_type=gcd_session_entity_type.SessionEntityType(name='name_value'), - ) - -@pytest.mark.asyncio -async def test_create_session_entity_type_flattened_async(): - client = SessionEntityTypesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_session_entity_type), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcd_session_entity_type.SessionEntityType() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcd_session_entity_type.SessionEntityType()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.create_session_entity_type( - parent='parent_value', - session_entity_type=gcd_session_entity_type.SessionEntityType(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] - arg = args[0].parent - mock_val = 'parent_value' - assert arg == mock_val - arg = args[0].session_entity_type - mock_val = gcd_session_entity_type.SessionEntityType(name='name_value') - assert arg == mock_val - -@pytest.mark.asyncio -async def test_create_session_entity_type_flattened_error_async(): - client = SessionEntityTypesAsyncClient( - 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_session_entity_type( - gcd_session_entity_type.CreateSessionEntityTypeRequest(), - parent='parent_value', - session_entity_type=gcd_session_entity_type.SessionEntityType(name='name_value'), - ) - - -@pytest.mark.parametrize("request_type", [ - gcd_session_entity_type.UpdateSessionEntityTypeRequest, - dict, -]) -def test_update_session_entity_type(request_type, transport: str = 'grpc'): - client = SessionEntityTypesClient( - 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_session_entity_type), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcd_session_entity_type.SessionEntityType( - 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 - - -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=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_session_entity_type), - '__call__') as call: - client.update_session_entity_type() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == gcd_session_entity_type.UpdateSessionEntityTypeRequest() - -@pytest.mark.asyncio -async def test_update_session_entity_type_async(transport: str = 'grpc_asyncio', request_type=gcd_session_entity_type.UpdateSessionEntityTypeRequest): - client = SessionEntityTypesAsyncClient( - 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_session_entity_type), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gcd_session_entity_type.SessionEntityType( - name='name_value', - 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 - - -@pytest.mark.asyncio -async def test_update_session_entity_type_async_from_dict(): - await test_update_session_entity_type_async(request_type=dict) - - -def test_update_session_entity_type_field_headers(): - 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 = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - 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. - 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', - 'session_entity_type.name=name_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_update_session_entity_type_field_headers_async(): - client = SessionEntityTypesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value 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 = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_session_entity_type), - '__call__') as call: - 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. - 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', - 'session_entity_type.name=name_value', - ) in kw['metadata'] - - -def test_update_session_entity_type_flattened(): - client = SessionEntityTypesClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_session_entity_type), - '__call__') 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_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] - arg = args[0].session_entity_type - mock_val = gcd_session_entity_type.SessionEntityType(name='name_value') - assert arg == mock_val - arg = args[0].update_mask - mock_val = field_mask_pb2.FieldMask(paths=['paths_value']) - assert arg == mock_val - - -def test_update_session_entity_type_flattened_error(): - client = SessionEntityTypesClient( - 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_session_entity_type( - gcd_session_entity_type.UpdateSessionEntityTypeRequest(), - session_entity_type=gcd_session_entity_type.SessionEntityType(name='name_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=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_session_entity_type), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcd_session_entity_type.SessionEntityType() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcd_session_entity_type.SessionEntityType()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.update_session_entity_type( - session_entity_type=gcd_session_entity_type.SessionEntityType(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] - arg = args[0].session_entity_type - mock_val = gcd_session_entity_type.SessionEntityType(name='name_value') - assert arg == mock_val - arg = args[0].update_mask - mock_val = field_mask_pb2.FieldMask(paths=['paths_value']) - assert arg == mock_val - -@pytest.mark.asyncio -async def test_update_session_entity_type_flattened_error_async(): - client = SessionEntityTypesAsyncClient( - 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_session_entity_type( - gcd_session_entity_type.UpdateSessionEntityTypeRequest(), - session_entity_type=gcd_session_entity_type.SessionEntityType(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - - -@pytest.mark.parametrize("request_type", [ - session_entity_type.DeleteSessionEntityTypeRequest, - dict, -]) -def test_delete_session_entity_type(request_type, transport: str = 'grpc'): - client = SessionEntityTypesClient( - 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_session_entity_type), - '__call__') 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. - assert response is None - - -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=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_session_entity_type), - '__call__') as call: - client.delete_session_entity_type() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == session_entity_type.DeleteSessionEntityTypeRequest() - -@pytest.mark.asyncio -async def test_delete_session_entity_type_async(transport: str = 'grpc_asyncio', request_type=session_entity_type.DeleteSessionEntityTypeRequest): - client = SessionEntityTypesAsyncClient( - 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_session_entity_type), - '__call__') 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. - assert response is None - - -@pytest.mark.asyncio -async def test_delete_session_entity_type_async_from_dict(): - await test_delete_session_entity_type_async(request_type=dict) - - -def test_delete_session_entity_type_field_headers(): - 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. - with mock.patch.object( - 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. - 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_session_entity_type_field_headers_async(): - client = SessionEntityTypesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value 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. - with mock.patch.object( - 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. - 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_session_entity_type_flattened(): - client = SessionEntityTypesClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_session_entity_type), - '__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_session_entity_type( - 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] - arg = args[0].name - mock_val = 'name_value' - assert arg == mock_val - - -def test_delete_session_entity_type_flattened_error(): - client = SessionEntityTypesClient( - 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_session_entity_type( - session_entity_type.DeleteSessionEntityTypeRequest(), - name='name_value', - ) - -@pytest.mark.asyncio -async def test_delete_session_entity_type_flattened_async(): - client = SessionEntityTypesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_session_entity_type), - '__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_session_entity_type( - 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] - arg = args[0].name - mock_val = 'name_value' - assert arg == mock_val - -@pytest.mark.asyncio -async def test_delete_session_entity_type_flattened_error_async(): - client = SessionEntityTypesAsyncClient( - 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_session_entity_type( - session_entity_type.DeleteSessionEntityTypeRequest(), - name='name_value', - ) - - -@pytest.mark.parametrize("request_type", [ - session_entity_type.ListSessionEntityTypesRequest, - dict, -]) -def test_list_session_entity_types_rest(request_type): - client = SessionEntityTypesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1/agent/sessions/sample2'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = session_entity_type.ListSessionEntityTypesResponse( - next_page_token='next_page_token_value', - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - pb_return_value = session_entity_type.ListSessionEntityTypesResponse.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.list_session_entity_types(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListSessionEntityTypesPager) - assert response.next_page_token == 'next_page_token_value' - - -def test_list_session_entity_types_rest_required_fields(request_type=session_entity_type.ListSessionEntityTypesRequest): - transport_class = transports.SessionEntityTypesRestTransport - - request_init = {} - request_init["parent"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - including_default_value_fields=False, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).list_session_entity_types._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["parent"] = 'parent_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).list_session_entity_types._get_unset_required_fields(jsonified_request) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("page_size", "page_token", )) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "parent" in jsonified_request - assert jsonified_request["parent"] == 'parent_value' - - client = SessionEntityTypesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = session_entity_type.ListSessionEntityTypesResponse() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "get", - 'query_params': pb_request, - } - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - - pb_return_value = session_entity_type.ListSessionEntityTypesResponse.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.list_session_entity_types(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_list_session_entity_types_rest_unset_required_fields(): - transport = transports.SessionEntityTypesRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.list_session_entity_types._get_unset_required_fields({}) - assert set(unset_fields) == (set(("pageSize", "pageToken", )) & set(("parent", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_list_session_entity_types_rest_interceptors(null_interceptor): - transport = transports.SessionEntityTypesRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.SessionEntityTypesRestInterceptor(), - ) - client = SessionEntityTypesClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.SessionEntityTypesRestInterceptor, "post_list_session_entity_types") as post, \ - mock.patch.object(transports.SessionEntityTypesRestInterceptor, "pre_list_session_entity_types") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = session_entity_type.ListSessionEntityTypesRequest.pb(session_entity_type.ListSessionEntityTypesRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = session_entity_type.ListSessionEntityTypesResponse.to_json(session_entity_type.ListSessionEntityTypesResponse()) - - request = session_entity_type.ListSessionEntityTypesRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = session_entity_type.ListSessionEntityTypesResponse() - - client.list_session_entity_types(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_list_session_entity_types_rest_bad_request(transport: str = 'rest', request_type=session_entity_type.ListSessionEntityTypesRequest): - client = SessionEntityTypesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1/agent/sessions/sample2'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.list_session_entity_types(request) - - -def test_list_session_entity_types_rest_flattened(): - client = SessionEntityTypesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = session_entity_type.ListSessionEntityTypesResponse() - - # get arguments that satisfy an http rule for this method - sample_request = {'parent': 'projects/sample1/agent/sessions/sample2'} - - # get truthy value for each flattened field - mock_args = dict( - parent='parent_value', - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - pb_return_value = session_entity_type.ListSessionEntityTypesResponse.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.list_session_entity_types(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v2beta1/{parent=projects/*/agent/sessions/*}/entityTypes" % client.transport._host, args[1]) - - -def test_list_session_entity_types_rest_flattened_error(transport: str = 'rest'): - client = SessionEntityTypesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.list_session_entity_types( - session_entity_type.ListSessionEntityTypesRequest(), - parent='parent_value', - ) - - -def test_list_session_entity_types_rest_pager(transport: str = 'rest'): - client = SessionEntityTypesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # TODO(kbandes): remove this mock unless there's a good reason for it. - #with mock.patch.object(path_template, 'transcode') as transcode: - # Set the response as a series of pages - response = ( - session_entity_type.ListSessionEntityTypesResponse( - session_entity_types=[ - session_entity_type.SessionEntityType(), - session_entity_type.SessionEntityType(), - session_entity_type.SessionEntityType(), - ], - next_page_token='abc', - ), - session_entity_type.ListSessionEntityTypesResponse( - session_entity_types=[], - next_page_token='def', - ), - session_entity_type.ListSessionEntityTypesResponse( - session_entity_types=[ - session_entity_type.SessionEntityType(), - ], - next_page_token='ghi', - ), - session_entity_type.ListSessionEntityTypesResponse( - session_entity_types=[ - session_entity_type.SessionEntityType(), - session_entity_type.SessionEntityType(), - ], - ), - ) - # Two responses for two calls - response = response + response - - # Wrap the values into proper Response objs - response = tuple(session_entity_type.ListSessionEntityTypesResponse.to_json(x) for x in response) - return_values = tuple(Response() for i in response) - for return_val, response_val in zip(return_values, response): - return_val._content = response_val.encode('UTF-8') - return_val.status_code = 200 - req.side_effect = return_values - - sample_request = {'parent': 'projects/sample1/agent/sessions/sample2'} - - pager = client.list_session_entity_types(request=sample_request) - - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, session_entity_type.SessionEntityType) - for i in results) - - pages = list(client.list_session_entity_types(request=sample_request).pages) - for page_, token in zip(pages, ['abc','def','ghi', '']): - assert page_.raw_page.next_page_token == token - - -@pytest.mark.parametrize("request_type", [ - session_entity_type.GetSessionEntityTypeRequest, - dict, -]) -def test_get_session_entity_type_rest(request_type): - client = SessionEntityTypesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/agent/sessions/sample2/entityTypes/sample3'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = session_entity_type.SessionEntityType( - name='name_value', - entity_override_mode=session_entity_type.SessionEntityType.EntityOverrideMode.ENTITY_OVERRIDE_MODE_OVERRIDE, - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - pb_return_value = session_entity_type.SessionEntityType.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.get_session_entity_type(request) - - # 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 - - -def test_get_session_entity_type_rest_required_fields(request_type=session_entity_type.GetSessionEntityTypeRequest): - transport_class = transports.SessionEntityTypesRestTransport - - request_init = {} - request_init["name"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - including_default_value_fields=False, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_session_entity_type._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["name"] = 'name_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_session_entity_type._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "name" in jsonified_request - assert jsonified_request["name"] == 'name_value' - - client = SessionEntityTypesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = session_entity_type.SessionEntityType() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "get", - 'query_params': pb_request, - } - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - - pb_return_value = session_entity_type.SessionEntityType.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.get_session_entity_type(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_get_session_entity_type_rest_unset_required_fields(): - transport = transports.SessionEntityTypesRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.get_session_entity_type._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_get_session_entity_type_rest_interceptors(null_interceptor): - transport = transports.SessionEntityTypesRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.SessionEntityTypesRestInterceptor(), - ) - client = SessionEntityTypesClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.SessionEntityTypesRestInterceptor, "post_get_session_entity_type") as post, \ - mock.patch.object(transports.SessionEntityTypesRestInterceptor, "pre_get_session_entity_type") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = session_entity_type.GetSessionEntityTypeRequest.pb(session_entity_type.GetSessionEntityTypeRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = session_entity_type.SessionEntityType.to_json(session_entity_type.SessionEntityType()) - - request = session_entity_type.GetSessionEntityTypeRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = session_entity_type.SessionEntityType() - - client.get_session_entity_type(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_get_session_entity_type_rest_bad_request(transport: str = 'rest', request_type=session_entity_type.GetSessionEntityTypeRequest): - client = SessionEntityTypesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/agent/sessions/sample2/entityTypes/sample3'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.get_session_entity_type(request) - - -def test_get_session_entity_type_rest_flattened(): - client = SessionEntityTypesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = session_entity_type.SessionEntityType() - - # get arguments that satisfy an http rule for this method - sample_request = {'name': 'projects/sample1/agent/sessions/sample2/entityTypes/sample3'} - - # get truthy value for each flattened field - mock_args = dict( - name='name_value', - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - pb_return_value = session_entity_type.SessionEntityType.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.get_session_entity_type(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v2beta1/{name=projects/*/agent/sessions/*/entityTypes/*}" % client.transport._host, args[1]) - - -def test_get_session_entity_type_rest_flattened_error(transport: str = 'rest'): - client = SessionEntityTypesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.get_session_entity_type( - session_entity_type.GetSessionEntityTypeRequest(), - name='name_value', - ) - - -def test_get_session_entity_type_rest_error(): - client = SessionEntityTypesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - gcd_session_entity_type.CreateSessionEntityTypeRequest, - dict, -]) -def test_create_session_entity_type_rest(request_type): - client = SessionEntityTypesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1/agent/sessions/sample2'} - request_init["session_entity_type"] = {'name': 'name_value', 'entity_override_mode': 1, 'entities': [{'value': 'value_value', 'synonyms': ['synonyms_value1', 'synonyms_value2']}]} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = gcd_session_entity_type.SessionEntityType( - name='name_value', - entity_override_mode=gcd_session_entity_type.SessionEntityType.EntityOverrideMode.ENTITY_OVERRIDE_MODE_OVERRIDE, - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - pb_return_value = gcd_session_entity_type.SessionEntityType.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.create_session_entity_type(request) - - # 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 - - -def test_create_session_entity_type_rest_required_fields(request_type=gcd_session_entity_type.CreateSessionEntityTypeRequest): - transport_class = transports.SessionEntityTypesRestTransport - - request_init = {} - request_init["parent"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - including_default_value_fields=False, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_session_entity_type._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["parent"] = 'parent_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_session_entity_type._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "parent" in jsonified_request - assert jsonified_request["parent"] == 'parent_value' - - client = SessionEntityTypesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = gcd_session_entity_type.SessionEntityType() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "post", - 'query_params': pb_request, - } - transcode_result['body'] = pb_request - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - - pb_return_value = gcd_session_entity_type.SessionEntityType.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.create_session_entity_type(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_create_session_entity_type_rest_unset_required_fields(): - transport = transports.SessionEntityTypesRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.create_session_entity_type._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("parent", "sessionEntityType", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_create_session_entity_type_rest_interceptors(null_interceptor): - transport = transports.SessionEntityTypesRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.SessionEntityTypesRestInterceptor(), - ) - client = SessionEntityTypesClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.SessionEntityTypesRestInterceptor, "post_create_session_entity_type") as post, \ - mock.patch.object(transports.SessionEntityTypesRestInterceptor, "pre_create_session_entity_type") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = gcd_session_entity_type.CreateSessionEntityTypeRequest.pb(gcd_session_entity_type.CreateSessionEntityTypeRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = gcd_session_entity_type.SessionEntityType.to_json(gcd_session_entity_type.SessionEntityType()) - - request = gcd_session_entity_type.CreateSessionEntityTypeRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = gcd_session_entity_type.SessionEntityType() - - client.create_session_entity_type(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_create_session_entity_type_rest_bad_request(transport: str = 'rest', request_type=gcd_session_entity_type.CreateSessionEntityTypeRequest): - client = SessionEntityTypesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1/agent/sessions/sample2'} - request_init["session_entity_type"] = {'name': 'name_value', 'entity_override_mode': 1, 'entities': [{'value': 'value_value', 'synonyms': ['synonyms_value1', 'synonyms_value2']}]} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.create_session_entity_type(request) - - -def test_create_session_entity_type_rest_flattened(): - client = SessionEntityTypesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = gcd_session_entity_type.SessionEntityType() - - # get arguments that satisfy an http rule for this method - sample_request = {'parent': 'projects/sample1/agent/sessions/sample2'} - - # get truthy value for each flattened field - mock_args = dict( - parent='parent_value', - session_entity_type=gcd_session_entity_type.SessionEntityType(name='name_value'), - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - pb_return_value = gcd_session_entity_type.SessionEntityType.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.create_session_entity_type(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v2beta1/{parent=projects/*/agent/sessions/*}/entityTypes" % client.transport._host, args[1]) - - -def test_create_session_entity_type_rest_flattened_error(transport: str = 'rest'): - client = SessionEntityTypesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.create_session_entity_type( - gcd_session_entity_type.CreateSessionEntityTypeRequest(), - parent='parent_value', - session_entity_type=gcd_session_entity_type.SessionEntityType(name='name_value'), - ) - - -def test_create_session_entity_type_rest_error(): - client = SessionEntityTypesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - gcd_session_entity_type.UpdateSessionEntityTypeRequest, - dict, -]) -def test_update_session_entity_type_rest(request_type): - client = SessionEntityTypesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'session_entity_type': {'name': 'projects/sample1/agent/sessions/sample2/entityTypes/sample3'}} - request_init["session_entity_type"] = {'name': 'projects/sample1/agent/sessions/sample2/entityTypes/sample3', 'entity_override_mode': 1, 'entities': [{'value': 'value_value', 'synonyms': ['synonyms_value1', 'synonyms_value2']}]} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = gcd_session_entity_type.SessionEntityType( - name='name_value', - entity_override_mode=gcd_session_entity_type.SessionEntityType.EntityOverrideMode.ENTITY_OVERRIDE_MODE_OVERRIDE, - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - pb_return_value = gcd_session_entity_type.SessionEntityType.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.update_session_entity_type(request) - - # 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 - - -def test_update_session_entity_type_rest_required_fields(request_type=gcd_session_entity_type.UpdateSessionEntityTypeRequest): - transport_class = transports.SessionEntityTypesRestTransport - - request_init = {} - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - including_default_value_fields=False, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).update_session_entity_type._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).update_session_entity_type._get_unset_required_fields(jsonified_request) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("update_mask", )) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - - client = SessionEntityTypesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = gcd_session_entity_type.SessionEntityType() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "patch", - 'query_params': pb_request, - } - transcode_result['body'] = pb_request - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - - pb_return_value = gcd_session_entity_type.SessionEntityType.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.update_session_entity_type(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_update_session_entity_type_rest_unset_required_fields(): - transport = transports.SessionEntityTypesRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.update_session_entity_type._get_unset_required_fields({}) - assert set(unset_fields) == (set(("updateMask", )) & set(("sessionEntityType", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_update_session_entity_type_rest_interceptors(null_interceptor): - transport = transports.SessionEntityTypesRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.SessionEntityTypesRestInterceptor(), - ) - client = SessionEntityTypesClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.SessionEntityTypesRestInterceptor, "post_update_session_entity_type") as post, \ - mock.patch.object(transports.SessionEntityTypesRestInterceptor, "pre_update_session_entity_type") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = gcd_session_entity_type.UpdateSessionEntityTypeRequest.pb(gcd_session_entity_type.UpdateSessionEntityTypeRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = gcd_session_entity_type.SessionEntityType.to_json(gcd_session_entity_type.SessionEntityType()) - - request = gcd_session_entity_type.UpdateSessionEntityTypeRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = gcd_session_entity_type.SessionEntityType() - - client.update_session_entity_type(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_update_session_entity_type_rest_bad_request(transport: str = 'rest', request_type=gcd_session_entity_type.UpdateSessionEntityTypeRequest): - client = SessionEntityTypesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'session_entity_type': {'name': 'projects/sample1/agent/sessions/sample2/entityTypes/sample3'}} - request_init["session_entity_type"] = {'name': 'projects/sample1/agent/sessions/sample2/entityTypes/sample3', 'entity_override_mode': 1, 'entities': [{'value': 'value_value', 'synonyms': ['synonyms_value1', 'synonyms_value2']}]} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.update_session_entity_type(request) - - -def test_update_session_entity_type_rest_flattened(): - client = SessionEntityTypesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = gcd_session_entity_type.SessionEntityType() - - # get arguments that satisfy an http rule for this method - sample_request = {'session_entity_type': {'name': 'projects/sample1/agent/sessions/sample2/entityTypes/sample3'}} - - # get truthy value for each flattened field - mock_args = dict( - session_entity_type=gcd_session_entity_type.SessionEntityType(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - pb_return_value = gcd_session_entity_type.SessionEntityType.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.update_session_entity_type(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v2beta1/{session_entity_type.name=projects/*/agent/sessions/*/entityTypes/*}" % client.transport._host, args[1]) - - -def test_update_session_entity_type_rest_flattened_error(transport: str = 'rest'): - client = SessionEntityTypesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.update_session_entity_type( - gcd_session_entity_type.UpdateSessionEntityTypeRequest(), - session_entity_type=gcd_session_entity_type.SessionEntityType(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - - -def test_update_session_entity_type_rest_error(): - client = SessionEntityTypesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - session_entity_type.DeleteSessionEntityTypeRequest, - dict, -]) -def test_delete_session_entity_type_rest(request_type): - client = SessionEntityTypesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/agent/sessions/sample2/entityTypes/sample3'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = None - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = '' - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.delete_session_entity_type(request) - - # Establish that the response is the type that we expect. - assert response is None - - -def test_delete_session_entity_type_rest_required_fields(request_type=session_entity_type.DeleteSessionEntityTypeRequest): - transport_class = transports.SessionEntityTypesRestTransport - - request_init = {} - request_init["name"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - including_default_value_fields=False, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).delete_session_entity_type._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["name"] = 'name_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).delete_session_entity_type._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "name" in jsonified_request - assert jsonified_request["name"] == 'name_value' - - client = SessionEntityTypesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = None - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "delete", - 'query_params': pb_request, - } - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - json_return_value = '' - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.delete_session_entity_type(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_delete_session_entity_type_rest_unset_required_fields(): - transport = transports.SessionEntityTypesRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.delete_session_entity_type._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_delete_session_entity_type_rest_interceptors(null_interceptor): - transport = transports.SessionEntityTypesRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.SessionEntityTypesRestInterceptor(), - ) - client = SessionEntityTypesClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.SessionEntityTypesRestInterceptor, "pre_delete_session_entity_type") as pre: - pre.assert_not_called() - pb_message = session_entity_type.DeleteSessionEntityTypeRequest.pb(session_entity_type.DeleteSessionEntityTypeRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - - request = session_entity_type.DeleteSessionEntityTypeRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - - client.delete_session_entity_type(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - - -def test_delete_session_entity_type_rest_bad_request(transport: str = 'rest', request_type=session_entity_type.DeleteSessionEntityTypeRequest): - client = SessionEntityTypesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/agent/sessions/sample2/entityTypes/sample3'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.delete_session_entity_type(request) - - -def test_delete_session_entity_type_rest_flattened(): - client = SessionEntityTypesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = None - - # get arguments that satisfy an http rule for this method - sample_request = {'name': 'projects/sample1/agent/sessions/sample2/entityTypes/sample3'} - - # get truthy value for each flattened field - mock_args = dict( - name='name_value', - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = '' - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.delete_session_entity_type(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v2beta1/{name=projects/*/agent/sessions/*/entityTypes/*}" % client.transport._host, args[1]) - - -def test_delete_session_entity_type_rest_flattened_error(transport: str = 'rest'): - client = SessionEntityTypesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.delete_session_entity_type( - session_entity_type.DeleteSessionEntityTypeRequest(), - name='name_value', - ) - - -def test_delete_session_entity_type_rest_error(): - client = SessionEntityTypesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -def test_credentials_transport_error(): - # It is an error to provide credentials and a transport instance. - transport = transports.SessionEntityTypesGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = SessionEntityTypesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # It is an error to provide a credentials file and a transport instance. - transport = transports.SessionEntityTypesGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = SessionEntityTypesClient( - client_options={"credentials_file": "credentials.json"}, - transport=transport, - ) - - # It is an error to provide an api_key and a transport instance. - transport = transports.SessionEntityTypesGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - options = client_options.ClientOptions() - options.api_key = "api_key" - with pytest.raises(ValueError): - client = SessionEntityTypesClient( - client_options=options, - transport=transport, - ) - - # It is an error to provide an api_key and a credential. - options = mock.Mock() - options.api_key = "api_key" - with pytest.raises(ValueError): - client = SessionEntityTypesClient( - client_options=options, - credentials=ga_credentials.AnonymousCredentials() - ) - - # It is an error to provide scopes and a transport instance. - transport = transports.SessionEntityTypesGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = SessionEntityTypesClient( - client_options={"scopes": ["1", "2"]}, - transport=transport, - ) - - -def test_transport_instance(): - # A client may be instantiated with a custom transport instance. - transport = transports.SessionEntityTypesGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - client = SessionEntityTypesClient(transport=transport) - assert client.transport is transport - -def test_transport_get_channel(): - # A client may be instantiated with a custom transport instance. - transport = transports.SessionEntityTypesGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - - transport = transports.SessionEntityTypesGrpcAsyncIOTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - -@pytest.mark.parametrize("transport_class", [ - transports.SessionEntityTypesGrpcTransport, - transports.SessionEntityTypesGrpcAsyncIOTransport, - transports.SessionEntityTypesRestTransport, -]) -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() - -@pytest.mark.parametrize("transport_name", [ - "grpc", - "rest", -]) -def test_transport_kind(transport_name): - transport = SessionEntityTypesClient.get_transport_class(transport_name)( - credentials=ga_credentials.AnonymousCredentials(), - ) - assert transport.kind == transport_name - -def test_transport_grpc_default(): - # A client should use the gRPC transport by default. - 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(core_exceptions.DuplicateCredentialArgs): - transport = transports.SessionEntityTypesTransport( - credentials=ga_credentials.AnonymousCredentials(), - credentials_file="credentials.json" - ) - - -def test_session_entity_types_base_transport(): - # Instantiate the base transport. - with mock.patch('google.cloud.dialogflow_v2beta1.services.session_entity_types.transports.SessionEntityTypesTransport.__init__') as Transport: - Transport.return_value = None - transport = transports.SessionEntityTypesTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Every method on the transport should just blindly - # raise NotImplementedError. - methods = ( - 'list_session_entity_types', - 'get_session_entity_type', - 'create_session_entity_type', - 'update_session_entity_type', - 'delete_session_entity_type', - 'get_location', - 'list_locations', - 'get_operation', - 'cancel_operation', - 'list_operations', - ) - for method in methods: - with pytest.raises(NotImplementedError): - getattr(transport, method)(request=object()) - - with pytest.raises(NotImplementedError): - transport.close() - - # Catch all for all remaining methods and properties - remainder = [ - 'kind', - ] - for r in remainder: - with pytest.raises(NotImplementedError): - getattr(transport, r)() - - -def test_session_entity_types_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.session_entity_types.transports.SessionEntityTypesTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.SessionEntityTypesTransport( - credentials_file="credentials.json", - quota_project_id="octopus", - ) - load_creds.assert_called_once_with("credentials.json", - scopes=None, - default_scopes=( - 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/dialogflow', -), - quota_project_id="octopus", - ) - - -def test_session_entity_types_base_transport_with_adc(): - # Test the default credentials are used if credentials and credentials_file are None. - with mock.patch.object(google.auth, 'default', autospec=True) as adc, mock.patch('google.cloud.dialogflow_v2beta1.services.session_entity_types.transports.SessionEntityTypesTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.SessionEntityTypesTransport() - adc.assert_called_once() - - -def test_session_entity_types_auth_adc(): - # If no credentials are provided, we should use ADC credentials. - with mock.patch.object(google.auth, 'default', autospec=True) as adc: - 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, - ) - - -@pytest.mark.parametrize( - "transport_class", - [ - transports.SessionEntityTypesGrpcTransport, - transports.SessionEntityTypesGrpcAsyncIOTransport, - ], -) -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(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, - transports.SessionEntityTypesRestTransport, - ], -) -def test_session_entity_types_transport_auth_gdch_credentials(transport_class): - host = 'https://language.com' - api_audience_tests = [None, 'https://language2.com'] - api_audience_expect = [host, 'https://language2.com'] - for t, e in zip(api_audience_tests, api_audience_expect): - with mock.patch.object(google.auth, 'default', autospec=True) as adc: - gdch_mock = mock.MagicMock() - type(gdch_mock).with_gdch_audience = mock.PropertyMock(return_value=gdch_mock) - adc.return_value = (gdch_mock, None) - transport_class(host=host, api_audience=t) - gdch_mock.with_gdch_audience.assert_called_once_with( - e - ) - - -@pytest.mark.parametrize( - "transport_class,grpc_helpers", - [ - (transports.SessionEntityTypesGrpcTransport, grpc_helpers), - (transports.SessionEntityTypesGrpcAsyncIOTransport, grpc_helpers_async) - ], -) -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", [transports.SessionEntityTypesGrpcTransport, transports.SessionEntityTypesGrpcAsyncIOTransport]) -def test_session_entity_types_grpc_transport_client_cert_source_for_mtls( - transport_class -): - cred = ga_credentials.AnonymousCredentials() - - # Check ssl_channel_credentials is used if provided. - with mock.patch.object(transport_class, "create_channel") as mock_create_channel: - mock_ssl_channel_creds = mock.Mock() - transport_class( - host="squid.clam.whelk", - credentials=cred, - ssl_channel_credentials=mock_ssl_channel_creds - ) - mock_create_channel.assert_called_once_with( - "squid.clam.whelk:443", - credentials=cred, - credentials_file=None, - scopes=None, - ssl_credentials=mock_ssl_channel_creds, - quota_project_id=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - # Check if ssl_channel_credentials is not provided, then client_cert_source_for_mtls - # is used. - with mock.patch.object(transport_class, "create_channel", return_value=mock.Mock()): - with mock.patch("grpc.ssl_channel_credentials") as mock_ssl_cred: - transport_class( - credentials=cred, - client_cert_source_for_mtls=client_cert_source_callback - ) - expected_cert, expected_key = client_cert_source_callback() - mock_ssl_cred.assert_called_once_with( - certificate_chain=expected_cert, - private_key=expected_key - ) - -def test_session_entity_types_http_transport_client_cert_source_for_mtls(): - cred = ga_credentials.AnonymousCredentials() - with mock.patch("google.auth.transport.requests.AuthorizedSession.configure_mtls_channel") as mock_configure_mtls_channel: - transports.SessionEntityTypesRestTransport ( - credentials=cred, - client_cert_source_for_mtls=client_cert_source_callback - ) - mock_configure_mtls_channel.assert_called_once_with(client_cert_source_callback) - - -@pytest.mark.parametrize("transport_name", [ - "grpc", - "grpc_asyncio", - "rest", -]) -def test_session_entity_types_host_no_port(transport_name): - client = SessionEntityTypesClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='dialogflow.googleapis.com'), - transport=transport_name, - ) - assert client.transport._host == ( - 'dialogflow.googleapis.com:443' - if transport_name in ['grpc', 'grpc_asyncio'] - else 'https://dialogflow.googleapis.com' - ) - -@pytest.mark.parametrize("transport_name", [ - "grpc", - "grpc_asyncio", - "rest", -]) -def test_session_entity_types_host_with_port(transport_name): - client = SessionEntityTypesClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='dialogflow.googleapis.com:8000'), - transport=transport_name, - ) - assert client.transport._host == ( - 'dialogflow.googleapis.com:8000' - if transport_name in ['grpc', 'grpc_asyncio'] - else 'https://dialogflow.googleapis.com:8000' - ) - -@pytest.mark.parametrize("transport_name", [ - "rest", -]) -def test_session_entity_types_client_transport_session_collision(transport_name): - creds1 = ga_credentials.AnonymousCredentials() - creds2 = ga_credentials.AnonymousCredentials() - client1 = SessionEntityTypesClient( - credentials=creds1, - transport=transport_name, - ) - client2 = SessionEntityTypesClient( - credentials=creds2, - transport=transport_name, - ) - session1 = client1.transport.list_session_entity_types._session - session2 = client2.transport.list_session_entity_types._session - assert session1 != session2 - session1 = client1.transport.get_session_entity_type._session - session2 = client2.transport.get_session_entity_type._session - assert session1 != session2 - session1 = client1.transport.create_session_entity_type._session - session2 = client2.transport.create_session_entity_type._session - assert session1 != session2 - session1 = client1.transport.update_session_entity_type._session - session2 = client2.transport.update_session_entity_type._session - assert session1 != session2 - session1 = client1.transport.delete_session_entity_type._session - session2 = client2.transport.delete_session_entity_type._session - assert session1 != session2 -def test_session_entity_types_grpc_transport_channel(): - channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.SessionEntityTypesGrpcTransport( - 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_session_entity_types_grpc_asyncio_transport_channel(): - channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.SessionEntityTypesGrpcAsyncIOTransport( - 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.SessionEntityTypesGrpcTransport, transports.SessionEntityTypesGrpcAsyncIOTransport]) -def test_session_entity_types_transport_channel_mtls_with_client_cert_source( - transport_class -): - with mock.patch("grpc.ssl_channel_credentials", autospec=True) as grpc_ssl_channel_cred: - with mock.patch.object(transport_class, "create_channel") as grpc_create_channel: - mock_ssl_cred = mock.Mock() - grpc_ssl_channel_cred.return_value = mock_ssl_cred - - mock_grpc_channel = mock.Mock() - grpc_create_channel.return_value = mock_grpc_channel - - cred = ga_credentials.AnonymousCredentials() - with pytest.warns(DeprecationWarning): - with mock.patch.object(google.auth, 'default') as adc: - adc.return_value = (cred, None) - transport = transport_class( - host="squid.clam.whelk", - api_mtls_endpoint="mtls.squid.clam.whelk", - client_cert_source=client_cert_source_callback, - ) - adc.assert_called_once() - - grpc_ssl_channel_cred.assert_called_once_with( - certificate_chain=b"cert bytes", private_key=b"key bytes" - ) - grpc_create_channel.assert_called_once_with( - "mtls.squid.clam.whelk:443", - credentials=cred, - credentials_file=None, - scopes=None, - ssl_credentials=mock_ssl_cred, - quota_project_id=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - assert transport.grpc_channel == mock_grpc_channel - assert transport._ssl_channel_credentials == mock_ssl_cred - - -# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are -# removed from grpc/grpc_asyncio transport constructor. -@pytest.mark.parametrize("transport_class", [transports.SessionEntityTypesGrpcTransport, transports.SessionEntityTypesGrpcAsyncIOTransport]) -def test_session_entity_types_transport_channel_mtls_with_adc( - transport_class -): - mock_ssl_cred = mock.Mock() - with mock.patch.multiple( - "google.auth.transport.grpc.SslCredentials", - __init__=mock.Mock(return_value=None), - ssl_credentials=mock.PropertyMock(return_value=mock_ssl_cred), - ): - with mock.patch.object(transport_class, "create_channel") as grpc_create_channel: - mock_grpc_channel = mock.Mock() - grpc_create_channel.return_value = mock_grpc_channel - mock_cred = mock.Mock() - - with pytest.warns(DeprecationWarning): - transport = transport_class( - host="squid.clam.whelk", - credentials=mock_cred, - api_mtls_endpoint="mtls.squid.clam.whelk", - client_cert_source=None, - ) - - grpc_create_channel.assert_called_once_with( - "mtls.squid.clam.whelk:443", - credentials=mock_cred, - credentials_file=None, - scopes=None, - ssl_credentials=mock_ssl_cred, - quota_project_id=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - assert transport.grpc_channel == mock_grpc_channel - - -def test_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, ) - actual = SessionEntityTypesClient.session_entity_type_path(project, session, entity_type) - assert expected == actual - - -def test_parse_session_entity_type_path(): - expected = { - "project": "octopus", - "session": "oyster", - "entity_type": "nudibranch", - } - path = SessionEntityTypesClient.session_entity_type_path(**expected) - - # Check that the path construction is reversible. - actual = SessionEntityTypesClient.parse_session_entity_type_path(path) - assert expected == actual - -def test_common_billing_account_path(): - billing_account = "cuttlefish" - expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) - actual = SessionEntityTypesClient.common_billing_account_path(billing_account) - assert expected == actual - - -def test_parse_common_billing_account_path(): - expected = { - "billing_account": "mussel", - } - path = SessionEntityTypesClient.common_billing_account_path(**expected) - - # Check that the path construction is reversible. - actual = SessionEntityTypesClient.parse_common_billing_account_path(path) - assert expected == actual - -def test_common_folder_path(): - folder = "winkle" - expected = "folders/{folder}".format(folder=folder, ) - actual = SessionEntityTypesClient.common_folder_path(folder) - assert expected == actual - - -def test_parse_common_folder_path(): - expected = { - "folder": "nautilus", - } - path = SessionEntityTypesClient.common_folder_path(**expected) - - # Check that the path construction is reversible. - actual = SessionEntityTypesClient.parse_common_folder_path(path) - assert expected == actual - -def test_common_organization_path(): - organization = "scallop" - expected = "organizations/{organization}".format(organization=organization, ) - actual = SessionEntityTypesClient.common_organization_path(organization) - assert expected == actual - - -def test_parse_common_organization_path(): - expected = { - "organization": "abalone", - } - path = SessionEntityTypesClient.common_organization_path(**expected) - - # Check that the path construction is reversible. - actual = SessionEntityTypesClient.parse_common_organization_path(path) - assert expected == actual - -def test_common_project_path(): - project = "squid" - expected = "projects/{project}".format(project=project, ) - actual = SessionEntityTypesClient.common_project_path(project) - assert expected == actual - - -def test_parse_common_project_path(): - expected = { - "project": "clam", - } - path = SessionEntityTypesClient.common_project_path(**expected) - - # Check that the path construction is reversible. - actual = SessionEntityTypesClient.parse_common_project_path(path) - assert expected == actual - -def test_common_location_path(): - project = "whelk" - location = "octopus" - expected = "projects/{project}/locations/{location}".format(project=project, location=location, ) - actual = SessionEntityTypesClient.common_location_path(project, location) - assert expected == actual - - -def test_parse_common_location_path(): - expected = { - "project": "oyster", - "location": "nudibranch", - } - path = SessionEntityTypesClient.common_location_path(**expected) - - # Check that the path construction is reversible. - actual = SessionEntityTypesClient.parse_common_location_path(path) - assert expected == actual - - -def test_client_with_default_client_info(): - client_info = gapic_v1.client_info.ClientInfo() - - with mock.patch.object(transports.SessionEntityTypesTransport, '_prep_wrapped_messages') as prep: - client = SessionEntityTypesClient( - credentials=ga_credentials.AnonymousCredentials(), - client_info=client_info, - ) - prep.assert_called_once_with(client_info) - - with mock.patch.object(transports.SessionEntityTypesTransport, '_prep_wrapped_messages') as prep: - transport_class = SessionEntityTypesClient.get_transport_class() - transport = transport_class( - credentials=ga_credentials.AnonymousCredentials(), - client_info=client_info, - ) - prep.assert_called_once_with(client_info) - -@pytest.mark.asyncio -async def test_transport_close_async(): - client = SessionEntityTypesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - with mock.patch.object(type(getattr(client.transport, "grpc_channel")), "close") as close: - async with client: - close.assert_not_called() - close.assert_called_once() - - -def test_get_location_rest_bad_request(transport: str = 'rest', request_type=locations_pb2.GetLocationRequest): - client = SessionEntityTypesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - request = request_type() - request = json_format.ParseDict({'name': 'projects/sample1/locations/sample2'}, request) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.get_location(request) - -@pytest.mark.parametrize("request_type", [ - locations_pb2.GetLocationRequest, - dict, -]) -def test_get_location_rest(request_type): - client = SessionEntityTypesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request_init = {'name': 'projects/sample1/locations/sample2'} - request = request_type(**request_init) - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = locations_pb2.Location() - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.get_location(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, locations_pb2.Location) - -def test_list_locations_rest_bad_request(transport: str = 'rest', request_type=locations_pb2.ListLocationsRequest): - client = SessionEntityTypesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - request = request_type() - request = json_format.ParseDict({'name': 'projects/sample1'}, request) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.list_locations(request) - -@pytest.mark.parametrize("request_type", [ - locations_pb2.ListLocationsRequest, - dict, -]) -def test_list_locations_rest(request_type): - client = SessionEntityTypesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request_init = {'name': 'projects/sample1'} - request = request_type(**request_init) - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = locations_pb2.ListLocationsResponse() - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.list_locations(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, locations_pb2.ListLocationsResponse) - -def test_cancel_operation_rest_bad_request(transport: str = 'rest', request_type=operations_pb2.CancelOperationRequest): - client = SessionEntityTypesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - request = request_type() - request = json_format.ParseDict({'name': 'projects/sample1/operations/sample2'}, request) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.cancel_operation(request) - -@pytest.mark.parametrize("request_type", [ - operations_pb2.CancelOperationRequest, - dict, -]) -def test_cancel_operation_rest(request_type): - client = SessionEntityTypesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request_init = {'name': 'projects/sample1/operations/sample2'} - request = request_type(**request_init) - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = None - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = '{}' - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.cancel_operation(request) - - # Establish that the response is the type that we expect. - assert response is None - -def test_get_operation_rest_bad_request(transport: str = 'rest', request_type=operations_pb2.GetOperationRequest): - client = SessionEntityTypesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - request = request_type() - request = json_format.ParseDict({'name': 'projects/sample1/operations/sample2'}, request) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.get_operation(request) - -@pytest.mark.parametrize("request_type", [ - operations_pb2.GetOperationRequest, - dict, -]) -def test_get_operation_rest(request_type): - client = SessionEntityTypesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request_init = {'name': 'projects/sample1/operations/sample2'} - request = request_type(**request_init) - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation() - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.get_operation(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, operations_pb2.Operation) - -def test_list_operations_rest_bad_request(transport: str = 'rest', request_type=operations_pb2.ListOperationsRequest): - client = SessionEntityTypesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - request = request_type() - request = json_format.ParseDict({'name': 'projects/sample1'}, request) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.list_operations(request) - -@pytest.mark.parametrize("request_type", [ - operations_pb2.ListOperationsRequest, - dict, -]) -def test_list_operations_rest(request_type): - client = SessionEntityTypesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request_init = {'name': 'projects/sample1'} - request = request_type(**request_init) - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = operations_pb2.ListOperationsResponse() - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.list_operations(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, operations_pb2.ListOperationsResponse) - - -def test_cancel_operation(transport: str = "grpc"): - client = SessionEntityTypesClient( - 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 = operations_pb2.CancelOperationRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = None - response = client.cancel_operation(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 response is the type that we expect. - assert response is None -@pytest.mark.asyncio -async def test_cancel_operation_async(transport: str = "grpc"): - client = SessionEntityTypesAsyncClient( - 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 = operations_pb2.CancelOperationRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - None - ) - response = await client.cancel_operation(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 response is the type that we expect. - assert response is None - -def test_cancel_operation_field_headers(): - 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 = operations_pb2.CancelOperationRequest() - request.name = "locations" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call: - call.return_value = None - - client.cancel_operation(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=locations",) in kw["metadata"] -@pytest.mark.asyncio -async def test_cancel_operation_field_headers_async(): - client = SessionEntityTypesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = operations_pb2.CancelOperationRequest() - request.name = "locations" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - None - ) - await client.cancel_operation(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=locations",) in kw["metadata"] - -def test_cancel_operation_from_dict(): - client = SessionEntityTypesClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = None - - response = client.cancel_operation( - request={ - "name": "locations", - } - ) - call.assert_called() -@pytest.mark.asyncio -async def test_cancel_operation_from_dict_async(): - client = SessionEntityTypesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - None - ) - response = await client.cancel_operation( - request={ - "name": "locations", - } - ) - call.assert_called() - - -def test_get_operation(transport: str = "grpc"): - client = SessionEntityTypesClient( - 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 = operations_pb2.GetOperationRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_operation), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation() - response = client.get_operation(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 response is the type that we expect. - assert isinstance(response, operations_pb2.Operation) -@pytest.mark.asyncio -async def test_get_operation_async(transport: str = "grpc"): - client = SessionEntityTypesAsyncClient( - 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 = operations_pb2.GetOperationRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_operation), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation() - ) - response = await client.get_operation(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 response is the type that we expect. - assert isinstance(response, operations_pb2.Operation) - -def test_get_operation_field_headers(): - 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 = operations_pb2.GetOperationRequest() - request.name = "locations" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_operation), "__call__") as call: - call.return_value = operations_pb2.Operation() - - client.get_operation(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=locations",) in kw["metadata"] -@pytest.mark.asyncio -async def test_get_operation_field_headers_async(): - client = SessionEntityTypesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = operations_pb2.GetOperationRequest() - request.name = "locations" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_operation), "__call__") as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation() - ) - await client.get_operation(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=locations",) in kw["metadata"] - -def test_get_operation_from_dict(): - client = SessionEntityTypesClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_operation), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation() - - response = client.get_operation( - request={ - "name": "locations", - } - ) - call.assert_called() -@pytest.mark.asyncio -async def test_get_operation_from_dict_async(): - client = SessionEntityTypesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_operation), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation() - ) - response = await client.get_operation( - request={ - "name": "locations", - } - ) - call.assert_called() - - -def test_list_operations(transport: str = "grpc"): - client = SessionEntityTypesClient( - 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 = operations_pb2.ListOperationsRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_operations), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.ListOperationsResponse() - response = client.list_operations(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 response is the type that we expect. - assert isinstance(response, operations_pb2.ListOperationsResponse) -@pytest.mark.asyncio -async def test_list_operations_async(transport: str = "grpc"): - client = SessionEntityTypesAsyncClient( - 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 = operations_pb2.ListOperationsRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_operations), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.ListOperationsResponse() - ) - response = await client.list_operations(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 response is the type that we expect. - assert isinstance(response, operations_pb2.ListOperationsResponse) - -def test_list_operations_field_headers(): - 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 = operations_pb2.ListOperationsRequest() - request.name = "locations" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_operations), "__call__") as call: - call.return_value = operations_pb2.ListOperationsResponse() - - client.list_operations(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=locations",) in kw["metadata"] -@pytest.mark.asyncio -async def test_list_operations_field_headers_async(): - client = SessionEntityTypesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = operations_pb2.ListOperationsRequest() - request.name = "locations" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_operations), "__call__") as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.ListOperationsResponse() - ) - await client.list_operations(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=locations",) in kw["metadata"] - -def test_list_operations_from_dict(): - client = SessionEntityTypesClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_operations), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.ListOperationsResponse() - - response = client.list_operations( - request={ - "name": "locations", - } - ) - call.assert_called() -@pytest.mark.asyncio -async def test_list_operations_from_dict_async(): - client = SessionEntityTypesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_operations), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.ListOperationsResponse() - ) - response = await client.list_operations( - request={ - "name": "locations", - } - ) - call.assert_called() - - -def test_list_locations(transport: str = "grpc"): - client = SessionEntityTypesClient( - 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 = locations_pb2.ListLocationsRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_locations), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = locations_pb2.ListLocationsResponse() - response = client.list_locations(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 response is the type that we expect. - assert isinstance(response, locations_pb2.ListLocationsResponse) -@pytest.mark.asyncio -async def test_list_locations_async(transport: str = "grpc"): - client = SessionEntityTypesAsyncClient( - 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 = locations_pb2.ListLocationsRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_locations), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - locations_pb2.ListLocationsResponse() - ) - response = await client.list_locations(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 response is the type that we expect. - assert isinstance(response, locations_pb2.ListLocationsResponse) - -def test_list_locations_field_headers(): - 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 = locations_pb2.ListLocationsRequest() - request.name = "locations" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_locations), "__call__") as call: - call.return_value = locations_pb2.ListLocationsResponse() - - client.list_locations(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=locations",) in kw["metadata"] -@pytest.mark.asyncio -async def test_list_locations_field_headers_async(): - client = SessionEntityTypesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = locations_pb2.ListLocationsRequest() - request.name = "locations" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_locations), "__call__") as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - locations_pb2.ListLocationsResponse() - ) - await client.list_locations(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=locations",) in kw["metadata"] - -def test_list_locations_from_dict(): - client = SessionEntityTypesClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_locations), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = locations_pb2.ListLocationsResponse() - - response = client.list_locations( - request={ - "name": "locations", - } - ) - call.assert_called() -@pytest.mark.asyncio -async def test_list_locations_from_dict_async(): - client = SessionEntityTypesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_locations), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - locations_pb2.ListLocationsResponse() - ) - response = await client.list_locations( - request={ - "name": "locations", - } - ) - call.assert_called() - - -def test_get_location(transport: str = "grpc"): - client = SessionEntityTypesClient( - 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 = locations_pb2.GetLocationRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_location), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = locations_pb2.Location() - response = client.get_location(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 response is the type that we expect. - assert isinstance(response, locations_pb2.Location) -@pytest.mark.asyncio -async def test_get_location_async(transport: str = "grpc_asyncio"): - client = SessionEntityTypesAsyncClient( - 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 = locations_pb2.GetLocationRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_location), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - locations_pb2.Location() - ) - response = await client.get_location(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 response is the type that we expect. - assert isinstance(response, locations_pb2.Location) - -def test_get_location_field_headers(): - 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 = locations_pb2.GetLocationRequest() - request.name = "locations/abc" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_location), "__call__") as call: - call.return_value = locations_pb2.Location() - - client.get_location(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=locations/abc",) in kw["metadata"] -@pytest.mark.asyncio -async def test_get_location_field_headers_async(): - client = SessionEntityTypesAsyncClient( - credentials=ga_credentials.AnonymousCredentials() - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = locations_pb2.GetLocationRequest() - request.name = "locations/abc" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_location), "__call__") as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - locations_pb2.Location() - ) - await client.get_location(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=locations/abc",) in kw["metadata"] - -def test_get_location_from_dict(): - client = SessionEntityTypesClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_locations), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = locations_pb2.Location() - - response = client.get_location( - request={ - "name": "locations/abc", - } - ) - call.assert_called() -@pytest.mark.asyncio -async def test_get_location_from_dict_async(): - client = SessionEntityTypesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_locations), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - locations_pb2.Location() - ) - response = await client.get_location( - request={ - "name": "locations", - } - ) - call.assert_called() - - -def test_transport_close(): - transports = { - "rest": "_session", - "grpc": "_grpc_channel", - } - - for transport, close_name in transports.items(): - client = SessionEntityTypesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport - ) - with mock.patch.object(type(getattr(client.transport, close_name)), "close") as close: - with client: - close.assert_not_called() - close.assert_called_once() - -def test_client_ctx(): - transports = [ - 'rest', - 'grpc', - ] - for transport in transports: - client = SessionEntityTypesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport - ) - # Test client calls underlying transport. - with mock.patch.object(type(client.transport), "close") as close: - close.assert_not_called() - with client: - pass - close.assert_called() - -@pytest.mark.parametrize("client_class,transport_class", [ - (SessionEntityTypesClient, transports.SessionEntityTypesGrpcTransport), - (SessionEntityTypesAsyncClient, transports.SessionEntityTypesGrpcAsyncIOTransport), -]) -def test_api_key_credentials(client_class, transport_class): - with mock.patch.object( - google.auth._default, "get_api_key_credentials", create=True - ) as get_api_key_credentials: - mock_cred = mock.Mock() - get_api_key_credentials.return_value = mock_cred - options = client_options.ClientOptions() - options.api_key = "api_key" - 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=mock_cred, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) diff --git a/owl-bot-staging/v2beta1/tests/unit/gapic/dialogflow_v2beta1/test_sessions.py b/owl-bot-staging/v2beta1/tests/unit/gapic/dialogflow_v2beta1/test_sessions.py deleted file mode 100644 index 8eb2bc7a0..000000000 --- a/owl-bot-staging/v2beta1/tests/unit/gapic/dialogflow_v2beta1/test_sessions.py +++ /dev/null @@ -1,2782 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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 -# try/except added for compatibility with python < 3.8 -try: - from unittest import mock - from unittest.mock import AsyncMock # pragma: NO COVER -except ImportError: # pragma: NO COVER - import mock - -import grpc -from grpc.experimental import aio -from collections.abc import Iterable -from google.protobuf import json_format -import json -import math -import pytest -from proto.marshal.rules.dates import DurationRule, TimestampRule -from proto.marshal.rules import wrappers -from requests import Response -from requests import Request, PreparedRequest -from requests.sessions import Session -from google.protobuf import json_format - -from google.api_core import client_options -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import grpc_helpers -from google.api_core import grpc_helpers_async -from google.api_core import path_template -from google.auth import credentials as ga_credentials -from google.auth.exceptions import MutualTLSChannelError -from google.cloud.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.types import agent -from google.cloud.dialogflow_v2beta1.types import audio_config -from google.cloud.dialogflow_v2beta1.types import context -from google.cloud.dialogflow_v2beta1.types import entity_type -from google.cloud.dialogflow_v2beta1.types import session -from google.cloud.dialogflow_v2beta1.types import session as gcd_session -from google.cloud.dialogflow_v2beta1.types import session_entity_type -from google.cloud.location import locations_pb2 -from google.longrunning import operations_pb2 -from google.oauth2 import service_account -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 -import google.auth - - -def client_cert_source_callback(): - return b"cert bytes", b"key bytes" - - -# If default endpoint is localhost, then default mtls endpoint will be the same. -# This method modifies the default endpoint so the client can produce a different -# mtls endpoint for endpoint testing purposes. -def modify_default_endpoint(client): - return "foo.googleapis.com" if ("localhost" in client.DEFAULT_ENDPOINT) else client.DEFAULT_ENDPOINT - - -def test__get_default_mtls_endpoint(): - api_endpoint = "example.googleapis.com" - api_mtls_endpoint = "example.mtls.googleapis.com" - sandbox_endpoint = "example.sandbox.googleapis.com" - sandbox_mtls_endpoint = "example.mtls.sandbox.googleapis.com" - non_googleapi = "api.example.com" - - assert SessionsClient._get_default_mtls_endpoint(None) is None - assert SessionsClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint - assert SessionsClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint - assert SessionsClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint - assert SessionsClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint - assert SessionsClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi - - -@pytest.mark.parametrize("client_class,transport_name", [ - (SessionsClient, "grpc"), - (SessionsAsyncClient, "grpc_asyncio"), - (SessionsClient, "rest"), -]) -def test_sessions_client_from_service_account_info(client_class, transport_name): - 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, transport=transport_name) - assert client.transport._credentials == creds - assert isinstance(client, client_class) - - assert client.transport._host == ( - 'dialogflow.googleapis.com:443' - if transport_name in ['grpc', 'grpc_asyncio'] - else - 'https://dialogflow.googleapis.com' - ) - - -@pytest.mark.parametrize("transport_class,transport_name", [ - (transports.SessionsGrpcTransport, "grpc"), - (transports.SessionsGrpcAsyncIOTransport, "grpc_asyncio"), - (transports.SessionsRestTransport, "rest"), -]) -def test_sessions_client_service_account_always_use_jwt(transport_class, transport_name): - with mock.patch.object(service_account.Credentials, 'with_always_use_jwt_access', create=True) as use_jwt: - creds = service_account.Credentials(None, None, None) - transport = transport_class(credentials=creds, always_use_jwt_access=True) - use_jwt.assert_called_once_with(True) - - with mock.patch.object(service_account.Credentials, 'with_always_use_jwt_access', create=True) as use_jwt: - creds = service_account.Credentials(None, None, None) - transport = transport_class(credentials=creds, always_use_jwt_access=False) - use_jwt.assert_not_called() - - -@pytest.mark.parametrize("client_class,transport_name", [ - (SessionsClient, "grpc"), - (SessionsAsyncClient, "grpc_asyncio"), - (SessionsClient, "rest"), -]) -def test_sessions_client_from_service_account_file(client_class, transport_name): - 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", transport=transport_name) - assert client.transport._credentials == creds - assert isinstance(client, client_class) - - client = client_class.from_service_account_json("dummy/file/path.json", transport=transport_name) - assert client.transport._credentials == creds - assert isinstance(client, client_class) - - assert client.transport._host == ( - 'dialogflow.googleapis.com:443' - if transport_name in ['grpc', 'grpc_asyncio'] - else - 'https://dialogflow.googleapis.com' - ) - - -def test_sessions_client_get_transport_class(): - transport = SessionsClient.get_transport_class() - available_transports = [ - transports.SessionsGrpcTransport, - transports.SessionsRestTransport, - ] - assert transport in available_transports - - transport = SessionsClient.get_transport_class("grpc") - assert transport == transports.SessionsGrpcTransport - - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (SessionsClient, transports.SessionsGrpcTransport, "grpc"), - (SessionsAsyncClient, transports.SessionsGrpcAsyncIOTransport, "grpc_asyncio"), - (SessionsClient, transports.SessionsRestTransport, "rest"), -]) -@mock.patch.object(SessionsClient, "DEFAULT_ENDPOINT", modify_default_endpoint(SessionsClient)) -@mock.patch.object(SessionsAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(SessionsAsyncClient)) -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=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(SessionsClient, 'get_transport_class') as gtc: - client = client_class(transport=transport_name) - gtc.assert_called() - - # Check the case api_endpoint is provided. - options = client_options.ClientOptions(api_endpoint="squid.clam.whelk") - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(transport=transport_name, client_options=options) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host="squid.clam.whelk", - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is - # "never". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is - # "always". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_MTLS_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # 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(transport=transport_name) - - # 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(transport=transport_name) - - # 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, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id="octopus", - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - # Check the case api_endpoint is provided - options = client_options.ClientOptions(api_audience="https://language.googleapis.com") - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience="https://language.googleapis.com" - ) - -@pytest.mark.parametrize("client_class,transport_class,transport_name,use_client_cert_env", [ - (SessionsClient, transports.SessionsGrpcTransport, "grpc", "true"), - (SessionsAsyncClient, transports.SessionsGrpcAsyncIOTransport, "grpc_asyncio", "true"), - (SessionsClient, transports.SessionsGrpcTransport, "grpc", "false"), - (SessionsAsyncClient, transports.SessionsGrpcAsyncIOTransport, "grpc_asyncio", "false"), - (SessionsClient, transports.SessionsRestTransport, "rest", "true"), - (SessionsClient, transports.SessionsRestTransport, "rest", "false"), -]) -@mock.patch.object(SessionsClient, "DEFAULT_ENDPOINT", modify_default_endpoint(SessionsClient)) -@mock.patch.object(SessionsAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(SessionsAsyncClient)) -@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) -def test_sessions_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, transport=transport_name) - - if use_client_cert_env == "false": - expected_client_cert_source = None - expected_host = client.DEFAULT_ENDPOINT - else: - expected_client_cert_source = client_cert_source_callback - expected_host = client.DEFAULT_MTLS_ENDPOINT - - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=expected_host, - scopes=None, - client_cert_source_for_mtls=expected_client_cert_source, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case ADC client cert is provided. Whether client cert is used depends on - # GOOGLE_API_USE_CLIENT_CERTIFICATE value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): - with mock.patch.object(transport_class, '__init__') as patched: - with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): - with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=client_cert_source_callback): - if use_client_cert_env == "false": - expected_host = client.DEFAULT_ENDPOINT - expected_client_cert_source = None - else: - expected_host = client.DEFAULT_MTLS_ENDPOINT - expected_client_cert_source = client_cert_source_callback - - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=expected_host, - scopes=None, - client_cert_source_for_mtls=expected_client_cert_source, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case client_cert_source and ADC client cert are not provided. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): - with mock.patch.object(transport_class, '__init__') as patched: - with mock.patch("google.auth.transport.mtls.has_default_client_cert_source", return_value=False): - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - -@pytest.mark.parametrize("client_class", [ - SessionsClient, SessionsAsyncClient -]) -@mock.patch.object(SessionsClient, "DEFAULT_ENDPOINT", modify_default_endpoint(SessionsClient)) -@mock.patch.object(SessionsAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(SessionsAsyncClient)) -def test_sessions_client_get_mtls_endpoint_and_cert_source(client_class): - mock_client_cert_source = mock.Mock() - - # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "true". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - mock_api_endpoint = "foo" - options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) - assert api_endpoint == mock_api_endpoint - assert cert_source == mock_client_cert_source - - # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "false". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): - mock_client_cert_source = mock.Mock() - mock_api_endpoint = "foo" - options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) - assert api_endpoint == mock_api_endpoint - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "never". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_ENDPOINT - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "always". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert doesn't exist. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=False): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_ENDPOINT - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert exists. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - 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=mock_client_cert_source): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT - assert cert_source == mock_client_cert_source - - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (SessionsClient, transports.SessionsGrpcTransport, "grpc"), - (SessionsAsyncClient, transports.SessionsGrpcAsyncIOTransport, "grpc_asyncio"), - (SessionsClient, transports.SessionsRestTransport, "rest"), -]) -def test_sessions_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, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=["1", "2"], - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - -@pytest.mark.parametrize("client_class,transport_class,transport_name,grpc_helpers", [ - (SessionsClient, transports.SessionsGrpcTransport, "grpc", grpc_helpers), - (SessionsAsyncClient, transports.SessionsGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), - (SessionsClient, transports.SessionsRestTransport, "rest", None), -]) -def test_sessions_client_client_options_credentials_file(client_class, transport_class, transport_name, grpc_helpers): - # 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, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file="credentials.json", - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - -def test_sessions_client_client_options_from_dict(): - with mock.patch('google.cloud.dialogflow_v2beta1.services.sessions.transports.SessionsGrpcTransport.__init__') as grpc_transport: - grpc_transport.return_value = None - client = SessionsClient( - client_options={'api_endpoint': 'squid.clam.whelk'} - ) - grpc_transport.assert_called_once_with( - credentials=None, - credentials_file=None, - host="squid.clam.whelk", - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - -@pytest.mark.parametrize("client_class,transport_class,transport_name,grpc_helpers", [ - (SessionsClient, transports.SessionsGrpcTransport, "grpc", grpc_helpers), - (SessionsAsyncClient, transports.SessionsGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), -]) -def test_sessions_client_create_channel_credentials_file(client_class, transport_class, transport_name, grpc_helpers): - # 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, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file="credentials.json", - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # test that the credentials from file are saved and used as the credentials. - with mock.patch.object( - google.auth, "load_credentials_from_file", autospec=True - ) as load_creds, mock.patch.object( - google.auth, "default", autospec=True - ) as adc, mock.patch.object( - grpc_helpers, "create_channel" - ) as create_channel: - creds = ga_credentials.AnonymousCredentials() - file_creds = ga_credentials.AnonymousCredentials() - load_creds.return_value = (file_creds, None) - adc.return_value = (creds, None) - client = client_class(client_options=options, transport=transport_name) - create_channel.assert_called_with( - "dialogflow.googleapis.com:443", - credentials=file_creds, - credentials_file=None, - quota_project_id=None, - default_scopes=( - 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/dialogflow', -), - scopes=None, - default_host="dialogflow.googleapis.com", - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - -@pytest.mark.parametrize("request_type", [ - gcd_session.DetectIntentRequest, - dict, -]) -def test_detect_intent(request_type, transport: str = 'grpc'): - client = SessionsClient( - 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.detect_intent), - '__call__') as call: - # Designate an appropriate return value for the call. - 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' - - -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=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.detect_intent), - '__call__') as call: - client.detect_intent() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == gcd_session.DetectIntentRequest() - -@pytest.mark.asyncio -async def test_detect_intent_async(transport: str = 'grpc_asyncio', request_type=gcd_session.DetectIntentRequest): - client = SessionsAsyncClient( - 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.detect_intent), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gcd_session.DetectIntentResponse( - 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' - - -@pytest.mark.asyncio -async def test_detect_intent_async_from_dict(): - await test_detect_intent_async(request_type=dict) - - -def test_detect_intent_field_headers(): - 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. - 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', - 'session=session_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_detect_intent_field_headers_async(): - 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. - with mock.patch.object( - type(client.transport.detect_intent), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcd_session.DetectIntentResponse()) - 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] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'session=session_value', - ) in kw['metadata'] - - -def test_detect_intent_flattened(): - 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( - session='session_value', - query_input=gcd_session.QueryInput(audio_config=audio_config.InputAudioConfig(audio_encoding=audio_config.AudioEncoding.AUDIO_ENCODING_LINEAR_16)), - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - arg = args[0].session - mock_val = 'session_value' - assert arg == mock_val - arg = args[0].query_input - mock_val = gcd_session.QueryInput(audio_config=audio_config.InputAudioConfig(audio_encoding=audio_config.AudioEncoding.AUDIO_ENCODING_LINEAR_16)) - assert arg == mock_val - - -def test_detect_intent_flattened_error(): - client = SessionsClient( - 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.detect_intent( - gcd_session.DetectIntentRequest(), - session='session_value', - query_input=gcd_session.QueryInput(audio_config=audio_config.InputAudioConfig(audio_encoding=audio_config.AudioEncoding.AUDIO_ENCODING_LINEAR_16)), - ) - -@pytest.mark.asyncio -async def test_detect_intent_flattened_async(): - 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: - # Designate an appropriate return value for the call. - call.return_value = gcd_session.DetectIntentResponse() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcd_session.DetectIntentResponse()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.detect_intent( - session='session_value', - query_input=gcd_session.QueryInput(audio_config=audio_config.InputAudioConfig(audio_encoding=audio_config.AudioEncoding.AUDIO_ENCODING_LINEAR_16)), - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - arg = args[0].session - mock_val = 'session_value' - assert arg == mock_val - arg = args[0].query_input - mock_val = gcd_session.QueryInput(audio_config=audio_config.InputAudioConfig(audio_encoding=audio_config.AudioEncoding.AUDIO_ENCODING_LINEAR_16)) - assert arg == mock_val - -@pytest.mark.asyncio -async def test_detect_intent_flattened_error_async(): - client = SessionsAsyncClient( - 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.detect_intent( - gcd_session.DetectIntentRequest(), - session='session_value', - query_input=gcd_session.QueryInput(audio_config=audio_config.InputAudioConfig(audio_encoding=audio_config.AudioEncoding.AUDIO_ENCODING_LINEAR_16)), - ) - - -@pytest.mark.parametrize("request_type", [ - session.StreamingDetectIntentRequest, - dict, -]) -def test_streaming_detect_intent(request_type, transport: str = 'grpc'): - client = SessionsClient( - 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. - with mock.patch.object( - type(client.transport.streaming_detect_intent), - '__call__') 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. - for message in response: - assert isinstance(message, session.StreamingDetectIntentResponse) - - -@pytest.mark.asyncio -async def test_streaming_detect_intent_async(transport: str = 'grpc_asyncio', request_type=session.StreamingDetectIntentRequest): - client = SessionsAsyncClient( - 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. - with mock.patch.object( - type(client.transport.streaming_detect_intent), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = mock.Mock(aio.StreamStreamCall, autospec=True) - 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. - message = await response.read() - assert isinstance(message, session.StreamingDetectIntentResponse) - - -@pytest.mark.asyncio -async def test_streaming_detect_intent_async_from_dict(): - await test_streaming_detect_intent_async(request_type=dict) - - -@pytest.mark.parametrize("request_type", [ - gcd_session.DetectIntentRequest, - dict, -]) -def test_detect_intent_rest(request_type): - client = SessionsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'session': 'projects/sample1/agent/sessions/sample2'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = gcd_session.DetectIntentResponse( - response_id='response_id_value', - output_audio=b'output_audio_blob', - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - pb_return_value = gcd_session.DetectIntentResponse.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.detect_intent(request) - - # 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' - - -def test_detect_intent_rest_required_fields(request_type=gcd_session.DetectIntentRequest): - transport_class = transports.SessionsRestTransport - - request_init = {} - request_init["session"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - including_default_value_fields=False, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).detect_intent._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["session"] = 'session_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).detect_intent._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "session" in jsonified_request - assert jsonified_request["session"] == 'session_value' - - client = SessionsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = gcd_session.DetectIntentResponse() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "post", - 'query_params': pb_request, - } - transcode_result['body'] = pb_request - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - - pb_return_value = gcd_session.DetectIntentResponse.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.detect_intent(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_detect_intent_rest_unset_required_fields(): - transport = transports.SessionsRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.detect_intent._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("session", "queryInput", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_detect_intent_rest_interceptors(null_interceptor): - transport = transports.SessionsRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.SessionsRestInterceptor(), - ) - client = SessionsClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.SessionsRestInterceptor, "post_detect_intent") as post, \ - mock.patch.object(transports.SessionsRestInterceptor, "pre_detect_intent") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = gcd_session.DetectIntentRequest.pb(gcd_session.DetectIntentRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = gcd_session.DetectIntentResponse.to_json(gcd_session.DetectIntentResponse()) - - request = gcd_session.DetectIntentRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = gcd_session.DetectIntentResponse() - - client.detect_intent(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_detect_intent_rest_bad_request(transport: str = 'rest', request_type=gcd_session.DetectIntentRequest): - client = SessionsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'session': 'projects/sample1/agent/sessions/sample2'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.detect_intent(request) - - -def test_detect_intent_rest_flattened(): - client = SessionsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = gcd_session.DetectIntentResponse() - - # get arguments that satisfy an http rule for this method - sample_request = {'session': 'projects/sample1/agent/sessions/sample2'} - - # get truthy value for each flattened field - mock_args = dict( - session='session_value', - query_input=gcd_session.QueryInput(audio_config=audio_config.InputAudioConfig(audio_encoding=audio_config.AudioEncoding.AUDIO_ENCODING_LINEAR_16)), - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - pb_return_value = gcd_session.DetectIntentResponse.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.detect_intent(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v2beta1/{session=projects/*/agent/sessions/*}:detectIntent" % client.transport._host, args[1]) - - -def test_detect_intent_rest_flattened_error(transport: str = 'rest'): - client = SessionsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.detect_intent( - gcd_session.DetectIntentRequest(), - session='session_value', - query_input=gcd_session.QueryInput(audio_config=audio_config.InputAudioConfig(audio_encoding=audio_config.AudioEncoding.AUDIO_ENCODING_LINEAR_16)), - ) - - -def test_detect_intent_rest_error(): - client = SessionsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -def test_streaming_detect_intent_rest_no_http_options(): - client = SessionsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request = session.StreamingDetectIntentRequest() - requests = [request] - with pytest.raises(RuntimeError): - client.streaming_detect_intent(requests) - - -def test_streaming_detect_intent_rest_error(): - client = SessionsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - # Since a `google.api.http` annotation is required for using a rest transport - # method, this should error. - with pytest.raises(NotImplementedError) as not_implemented_error: - client.streaming_detect_intent({}) - assert ( - "Method StreamingDetectIntent is not available over REST transport" - in str(not_implemented_error.value) - ) - - -def test_credentials_transport_error(): - # It is an error to provide credentials and a transport instance. - transport = transports.SessionsGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = SessionsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # It is an error to provide a credentials file and a transport instance. - transport = transports.SessionsGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = SessionsClient( - client_options={"credentials_file": "credentials.json"}, - transport=transport, - ) - - # It is an error to provide an api_key and a transport instance. - transport = transports.SessionsGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - options = client_options.ClientOptions() - options.api_key = "api_key" - with pytest.raises(ValueError): - client = SessionsClient( - client_options=options, - transport=transport, - ) - - # It is an error to provide an api_key and a credential. - options = mock.Mock() - options.api_key = "api_key" - with pytest.raises(ValueError): - client = SessionsClient( - client_options=options, - credentials=ga_credentials.AnonymousCredentials() - ) - - # It is an error to provide scopes and a transport instance. - transport = transports.SessionsGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = SessionsClient( - client_options={"scopes": ["1", "2"]}, - transport=transport, - ) - - -def test_transport_instance(): - # A client may be instantiated with a custom transport instance. - transport = transports.SessionsGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - client = SessionsClient(transport=transport) - assert client.transport is transport - -def test_transport_get_channel(): - # A client may be instantiated with a custom transport instance. - transport = transports.SessionsGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - - transport = transports.SessionsGrpcAsyncIOTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - -@pytest.mark.parametrize("transport_class", [ - transports.SessionsGrpcTransport, - transports.SessionsGrpcAsyncIOTransport, - transports.SessionsRestTransport, -]) -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() - -@pytest.mark.parametrize("transport_name", [ - "grpc", - "rest", -]) -def test_transport_kind(transport_name): - transport = SessionsClient.get_transport_class(transport_name)( - credentials=ga_credentials.AnonymousCredentials(), - ) - assert transport.kind == transport_name - -def test_transport_grpc_default(): - # A client should use the gRPC transport by default. - 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(core_exceptions.DuplicateCredentialArgs): - transport = transports.SessionsTransport( - credentials=ga_credentials.AnonymousCredentials(), - credentials_file="credentials.json" - ) - - -def test_sessions_base_transport(): - # Instantiate the base transport. - with mock.patch('google.cloud.dialogflow_v2beta1.services.sessions.transports.SessionsTransport.__init__') as Transport: - Transport.return_value = None - transport = transports.SessionsTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Every method on the transport should just blindly - # raise NotImplementedError. - methods = ( - 'detect_intent', - 'streaming_detect_intent', - 'get_location', - 'list_locations', - 'get_operation', - 'cancel_operation', - 'list_operations', - ) - for method in methods: - with pytest.raises(NotImplementedError): - getattr(transport, method)(request=object()) - - with pytest.raises(NotImplementedError): - transport.close() - - # Catch all for all remaining methods and properties - remainder = [ - 'kind', - ] - for r in remainder: - with pytest.raises(NotImplementedError): - getattr(transport, r)() - - -def test_sessions_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.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", - ) - - -def test_sessions_base_transport_with_adc(): - # Test the default credentials are used if credentials and credentials_file are None. - with mock.patch.object(google.auth, 'default', autospec=True) as adc, mock.patch('google.cloud.dialogflow_v2beta1.services.sessions.transports.SessionsTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.SessionsTransport() - adc.assert_called_once() - - -def test_sessions_auth_adc(): - # If no credentials are provided, we should use ADC credentials. - with mock.patch.object(google.auth, 'default', autospec=True) as adc: - 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, - ) - - -@pytest.mark.parametrize( - "transport_class", - [ - transports.SessionsGrpcTransport, - transports.SessionsGrpcAsyncIOTransport, - ], -) -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(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, - transports.SessionsRestTransport, - ], -) -def test_sessions_transport_auth_gdch_credentials(transport_class): - host = 'https://language.com' - api_audience_tests = [None, 'https://language2.com'] - api_audience_expect = [host, 'https://language2.com'] - for t, e in zip(api_audience_tests, api_audience_expect): - with mock.patch.object(google.auth, 'default', autospec=True) as adc: - gdch_mock = mock.MagicMock() - type(gdch_mock).with_gdch_audience = mock.PropertyMock(return_value=gdch_mock) - adc.return_value = (gdch_mock, None) - transport_class(host=host, api_audience=t) - gdch_mock.with_gdch_audience.assert_called_once_with( - e - ) - - -@pytest.mark.parametrize( - "transport_class,grpc_helpers", - [ - (transports.SessionsGrpcTransport, grpc_helpers), - (transports.SessionsGrpcAsyncIOTransport, grpc_helpers_async) - ], -) -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", [transports.SessionsGrpcTransport, transports.SessionsGrpcAsyncIOTransport]) -def test_sessions_grpc_transport_client_cert_source_for_mtls( - transport_class -): - cred = ga_credentials.AnonymousCredentials() - - # Check ssl_channel_credentials is used if provided. - with mock.patch.object(transport_class, "create_channel") as mock_create_channel: - mock_ssl_channel_creds = mock.Mock() - transport_class( - host="squid.clam.whelk", - credentials=cred, - ssl_channel_credentials=mock_ssl_channel_creds - ) - mock_create_channel.assert_called_once_with( - "squid.clam.whelk:443", - credentials=cred, - credentials_file=None, - scopes=None, - ssl_credentials=mock_ssl_channel_creds, - quota_project_id=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - # Check if ssl_channel_credentials is not provided, then client_cert_source_for_mtls - # is used. - with mock.patch.object(transport_class, "create_channel", return_value=mock.Mock()): - with mock.patch("grpc.ssl_channel_credentials") as mock_ssl_cred: - transport_class( - credentials=cred, - client_cert_source_for_mtls=client_cert_source_callback - ) - expected_cert, expected_key = client_cert_source_callback() - mock_ssl_cred.assert_called_once_with( - certificate_chain=expected_cert, - private_key=expected_key - ) - -def test_sessions_http_transport_client_cert_source_for_mtls(): - cred = ga_credentials.AnonymousCredentials() - with mock.patch("google.auth.transport.requests.AuthorizedSession.configure_mtls_channel") as mock_configure_mtls_channel: - transports.SessionsRestTransport ( - credentials=cred, - client_cert_source_for_mtls=client_cert_source_callback - ) - mock_configure_mtls_channel.assert_called_once_with(client_cert_source_callback) - - -@pytest.mark.parametrize("transport_name", [ - "grpc", - "grpc_asyncio", - "rest", -]) -def test_sessions_host_no_port(transport_name): - client = SessionsClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='dialogflow.googleapis.com'), - transport=transport_name, - ) - assert client.transport._host == ( - 'dialogflow.googleapis.com:443' - if transport_name in ['grpc', 'grpc_asyncio'] - else 'https://dialogflow.googleapis.com' - ) - -@pytest.mark.parametrize("transport_name", [ - "grpc", - "grpc_asyncio", - "rest", -]) -def test_sessions_host_with_port(transport_name): - client = SessionsClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='dialogflow.googleapis.com:8000'), - transport=transport_name, - ) - assert client.transport._host == ( - 'dialogflow.googleapis.com:8000' - if transport_name in ['grpc', 'grpc_asyncio'] - else 'https://dialogflow.googleapis.com:8000' - ) - -@pytest.mark.parametrize("transport_name", [ - "rest", -]) -def test_sessions_client_transport_session_collision(transport_name): - creds1 = ga_credentials.AnonymousCredentials() - creds2 = ga_credentials.AnonymousCredentials() - client1 = SessionsClient( - credentials=creds1, - transport=transport_name, - ) - client2 = SessionsClient( - credentials=creds2, - transport=transport_name, - ) - session1 = client1.transport.detect_intent._session - session2 = client2.transport.detect_intent._session - assert session1 != session2 - session1 = client1.transport.streaming_detect_intent._session - session2 = client2.transport.streaming_detect_intent._session - assert session1 != session2 -def test_sessions_grpc_transport_channel(): - channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.SessionsGrpcTransport( - 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_sessions_grpc_asyncio_transport_channel(): - channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.SessionsGrpcAsyncIOTransport( - 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.SessionsGrpcTransport, transports.SessionsGrpcAsyncIOTransport]) -def test_sessions_transport_channel_mtls_with_client_cert_source( - transport_class -): - with mock.patch("grpc.ssl_channel_credentials", autospec=True) as grpc_ssl_channel_cred: - with mock.patch.object(transport_class, "create_channel") as grpc_create_channel: - mock_ssl_cred = mock.Mock() - grpc_ssl_channel_cred.return_value = mock_ssl_cred - - mock_grpc_channel = mock.Mock() - grpc_create_channel.return_value = mock_grpc_channel - - cred = ga_credentials.AnonymousCredentials() - with pytest.warns(DeprecationWarning): - with mock.patch.object(google.auth, 'default') as adc: - adc.return_value = (cred, None) - transport = transport_class( - host="squid.clam.whelk", - api_mtls_endpoint="mtls.squid.clam.whelk", - client_cert_source=client_cert_source_callback, - ) - adc.assert_called_once() - - grpc_ssl_channel_cred.assert_called_once_with( - certificate_chain=b"cert bytes", private_key=b"key bytes" - ) - grpc_create_channel.assert_called_once_with( - "mtls.squid.clam.whelk:443", - credentials=cred, - credentials_file=None, - scopes=None, - ssl_credentials=mock_ssl_cred, - quota_project_id=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - assert transport.grpc_channel == mock_grpc_channel - assert transport._ssl_channel_credentials == mock_ssl_cred - - -# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are -# removed from grpc/grpc_asyncio transport constructor. -@pytest.mark.parametrize("transport_class", [transports.SessionsGrpcTransport, transports.SessionsGrpcAsyncIOTransport]) -def test_sessions_transport_channel_mtls_with_adc( - transport_class -): - mock_ssl_cred = mock.Mock() - with mock.patch.multiple( - "google.auth.transport.grpc.SslCredentials", - __init__=mock.Mock(return_value=None), - ssl_credentials=mock.PropertyMock(return_value=mock_ssl_cred), - ): - with mock.patch.object(transport_class, "create_channel") as grpc_create_channel: - mock_grpc_channel = mock.Mock() - grpc_create_channel.return_value = mock_grpc_channel - mock_cred = mock.Mock() - - with pytest.warns(DeprecationWarning): - transport = transport_class( - host="squid.clam.whelk", - credentials=mock_cred, - api_mtls_endpoint="mtls.squid.clam.whelk", - client_cert_source=None, - ) - - grpc_create_channel.assert_called_once_with( - "mtls.squid.clam.whelk:443", - credentials=mock_cred, - credentials_file=None, - scopes=None, - ssl_credentials=mock_ssl_cred, - quota_project_id=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - assert transport.grpc_channel == mock_grpc_channel - - -def test_context_path(): - project = "squid" - session = "clam" - context = "whelk" - expected = "projects/{project}/agent/sessions/{session}/contexts/{context}".format(project=project, session=session, context=context, ) - actual = SessionsClient.context_path(project, session, context) - assert expected == actual - - -def test_parse_context_path(): - expected = { - "project": "octopus", - "session": "oyster", - "context": "nudibranch", - } - path = SessionsClient.context_path(**expected) - - # Check that the path construction is reversible. - actual = SessionsClient.parse_context_path(path) - assert expected == actual - -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, ) - actual = SessionsClient.document_path(project, knowledge_base, document) - assert expected == actual - - -def test_parse_document_path(): - expected = { - "project": "nautilus", - "knowledge_base": "scallop", - "document": "abalone", - } - path = SessionsClient.document_path(**expected) - - # Check that the path construction is reversible. - actual = SessionsClient.parse_document_path(path) - assert expected == actual - -def test_intent_path(): - project = "squid" - intent = "clam" - expected = "projects/{project}/agent/intents/{intent}".format(project=project, intent=intent, ) - actual = SessionsClient.intent_path(project, intent) - assert expected == actual - - -def test_parse_intent_path(): - expected = { - "project": "whelk", - "intent": "octopus", - } - path = SessionsClient.intent_path(**expected) - - # Check that the path construction is reversible. - actual = SessionsClient.parse_intent_path(path) - assert expected == actual - -def test_session_path(): - project = "oyster" - session = "nudibranch" - expected = "projects/{project}/agent/sessions/{session}".format(project=project, session=session, ) - actual = SessionsClient.session_path(project, session) - assert expected == actual - - -def test_parse_session_path(): - expected = { - "project": "cuttlefish", - "session": "mussel", - } - path = SessionsClient.session_path(**expected) - - # Check that the path construction is reversible. - actual = SessionsClient.parse_session_path(path) - assert expected == actual - -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, ) - actual = SessionsClient.session_entity_type_path(project, session, entity_type) - assert expected == actual - - -def test_parse_session_entity_type_path(): - expected = { - "project": "abalone", - "session": "squid", - "entity_type": "clam", - } - path = SessionsClient.session_entity_type_path(**expected) - - # Check that the path construction is reversible. - actual = SessionsClient.parse_session_entity_type_path(path) - assert expected == actual - -def test_common_billing_account_path(): - billing_account = "whelk" - expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) - actual = SessionsClient.common_billing_account_path(billing_account) - assert expected == actual - - -def test_parse_common_billing_account_path(): - expected = { - "billing_account": "octopus", - } - path = SessionsClient.common_billing_account_path(**expected) - - # Check that the path construction is reversible. - actual = SessionsClient.parse_common_billing_account_path(path) - assert expected == actual - -def test_common_folder_path(): - folder = "oyster" - expected = "folders/{folder}".format(folder=folder, ) - actual = SessionsClient.common_folder_path(folder) - assert expected == actual - - -def test_parse_common_folder_path(): - expected = { - "folder": "nudibranch", - } - path = SessionsClient.common_folder_path(**expected) - - # Check that the path construction is reversible. - actual = SessionsClient.parse_common_folder_path(path) - assert expected == actual - -def test_common_organization_path(): - organization = "cuttlefish" - expected = "organizations/{organization}".format(organization=organization, ) - actual = SessionsClient.common_organization_path(organization) - assert expected == actual - - -def test_parse_common_organization_path(): - expected = { - "organization": "mussel", - } - path = SessionsClient.common_organization_path(**expected) - - # Check that the path construction is reversible. - actual = SessionsClient.parse_common_organization_path(path) - assert expected == actual - -def test_common_project_path(): - project = "winkle" - expected = "projects/{project}".format(project=project, ) - actual = SessionsClient.common_project_path(project) - assert expected == actual - - -def test_parse_common_project_path(): - expected = { - "project": "nautilus", - } - path = SessionsClient.common_project_path(**expected) - - # Check that the path construction is reversible. - actual = SessionsClient.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 = SessionsClient.common_location_path(project, location) - assert expected == actual - - -def test_parse_common_location_path(): - expected = { - "project": "squid", - "location": "clam", - } - path = SessionsClient.common_location_path(**expected) - - # Check that the path construction is reversible. - actual = SessionsClient.parse_common_location_path(path) - assert expected == actual - - -def test_client_with_default_client_info(): - client_info = gapic_v1.client_info.ClientInfo() - - with mock.patch.object(transports.SessionsTransport, '_prep_wrapped_messages') as prep: - client = SessionsClient( - credentials=ga_credentials.AnonymousCredentials(), - client_info=client_info, - ) - prep.assert_called_once_with(client_info) - - with mock.patch.object(transports.SessionsTransport, '_prep_wrapped_messages') as prep: - transport_class = SessionsClient.get_transport_class() - transport = transport_class( - credentials=ga_credentials.AnonymousCredentials(), - client_info=client_info, - ) - prep.assert_called_once_with(client_info) - -@pytest.mark.asyncio -async def test_transport_close_async(): - client = SessionsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - with mock.patch.object(type(getattr(client.transport, "grpc_channel")), "close") as close: - async with client: - close.assert_not_called() - close.assert_called_once() - - -def test_get_location_rest_bad_request(transport: str = 'rest', request_type=locations_pb2.GetLocationRequest): - client = SessionsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - request = request_type() - request = json_format.ParseDict({'name': 'projects/sample1/locations/sample2'}, request) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.get_location(request) - -@pytest.mark.parametrize("request_type", [ - locations_pb2.GetLocationRequest, - dict, -]) -def test_get_location_rest(request_type): - client = SessionsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request_init = {'name': 'projects/sample1/locations/sample2'} - request = request_type(**request_init) - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = locations_pb2.Location() - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.get_location(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, locations_pb2.Location) - -def test_list_locations_rest_bad_request(transport: str = 'rest', request_type=locations_pb2.ListLocationsRequest): - client = SessionsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - request = request_type() - request = json_format.ParseDict({'name': 'projects/sample1'}, request) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.list_locations(request) - -@pytest.mark.parametrize("request_type", [ - locations_pb2.ListLocationsRequest, - dict, -]) -def test_list_locations_rest(request_type): - client = SessionsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request_init = {'name': 'projects/sample1'} - request = request_type(**request_init) - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = locations_pb2.ListLocationsResponse() - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.list_locations(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, locations_pb2.ListLocationsResponse) - -def test_cancel_operation_rest_bad_request(transport: str = 'rest', request_type=operations_pb2.CancelOperationRequest): - client = SessionsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - request = request_type() - request = json_format.ParseDict({'name': 'projects/sample1/operations/sample2'}, request) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.cancel_operation(request) - -@pytest.mark.parametrize("request_type", [ - operations_pb2.CancelOperationRequest, - dict, -]) -def test_cancel_operation_rest(request_type): - client = SessionsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request_init = {'name': 'projects/sample1/operations/sample2'} - request = request_type(**request_init) - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = None - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = '{}' - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.cancel_operation(request) - - # Establish that the response is the type that we expect. - assert response is None - -def test_get_operation_rest_bad_request(transport: str = 'rest', request_type=operations_pb2.GetOperationRequest): - client = SessionsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - request = request_type() - request = json_format.ParseDict({'name': 'projects/sample1/operations/sample2'}, request) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.get_operation(request) - -@pytest.mark.parametrize("request_type", [ - operations_pb2.GetOperationRequest, - dict, -]) -def test_get_operation_rest(request_type): - client = SessionsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request_init = {'name': 'projects/sample1/operations/sample2'} - request = request_type(**request_init) - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation() - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.get_operation(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, operations_pb2.Operation) - -def test_list_operations_rest_bad_request(transport: str = 'rest', request_type=operations_pb2.ListOperationsRequest): - client = SessionsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - request = request_type() - request = json_format.ParseDict({'name': 'projects/sample1'}, request) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.list_operations(request) - -@pytest.mark.parametrize("request_type", [ - operations_pb2.ListOperationsRequest, - dict, -]) -def test_list_operations_rest(request_type): - client = SessionsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request_init = {'name': 'projects/sample1'} - request = request_type(**request_init) - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = operations_pb2.ListOperationsResponse() - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.list_operations(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, operations_pb2.ListOperationsResponse) - - -def test_cancel_operation(transport: str = "grpc"): - client = SessionsClient( - 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 = operations_pb2.CancelOperationRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = None - response = client.cancel_operation(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 response is the type that we expect. - assert response is None -@pytest.mark.asyncio -async def test_cancel_operation_async(transport: str = "grpc"): - client = SessionsAsyncClient( - 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 = operations_pb2.CancelOperationRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - None - ) - response = await client.cancel_operation(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 response is the type that we expect. - assert response is None - -def test_cancel_operation_field_headers(): - 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 = operations_pb2.CancelOperationRequest() - request.name = "locations" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call: - call.return_value = None - - client.cancel_operation(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=locations",) in kw["metadata"] -@pytest.mark.asyncio -async def test_cancel_operation_field_headers_async(): - 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 = operations_pb2.CancelOperationRequest() - request.name = "locations" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - None - ) - await client.cancel_operation(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=locations",) in kw["metadata"] - -def test_cancel_operation_from_dict(): - 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.cancel_operation), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = None - - response = client.cancel_operation( - request={ - "name": "locations", - } - ) - call.assert_called() -@pytest.mark.asyncio -async def test_cancel_operation_from_dict_async(): - 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.cancel_operation), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - None - ) - response = await client.cancel_operation( - request={ - "name": "locations", - } - ) - call.assert_called() - - -def test_get_operation(transport: str = "grpc"): - client = SessionsClient( - 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 = operations_pb2.GetOperationRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_operation), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation() - response = client.get_operation(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 response is the type that we expect. - assert isinstance(response, operations_pb2.Operation) -@pytest.mark.asyncio -async def test_get_operation_async(transport: str = "grpc"): - client = SessionsAsyncClient( - 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 = operations_pb2.GetOperationRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_operation), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation() - ) - response = await client.get_operation(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 response is the type that we expect. - assert isinstance(response, operations_pb2.Operation) - -def test_get_operation_field_headers(): - 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 = operations_pb2.GetOperationRequest() - request.name = "locations" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_operation), "__call__") as call: - call.return_value = operations_pb2.Operation() - - client.get_operation(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=locations",) in kw["metadata"] -@pytest.mark.asyncio -async def test_get_operation_field_headers_async(): - 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 = operations_pb2.GetOperationRequest() - request.name = "locations" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_operation), "__call__") as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation() - ) - await client.get_operation(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=locations",) in kw["metadata"] - -def test_get_operation_from_dict(): - 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.get_operation), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation() - - response = client.get_operation( - request={ - "name": "locations", - } - ) - call.assert_called() -@pytest.mark.asyncio -async def test_get_operation_from_dict_async(): - 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.get_operation), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation() - ) - response = await client.get_operation( - request={ - "name": "locations", - } - ) - call.assert_called() - - -def test_list_operations(transport: str = "grpc"): - client = SessionsClient( - 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 = operations_pb2.ListOperationsRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_operations), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.ListOperationsResponse() - response = client.list_operations(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 response is the type that we expect. - assert isinstance(response, operations_pb2.ListOperationsResponse) -@pytest.mark.asyncio -async def test_list_operations_async(transport: str = "grpc"): - client = SessionsAsyncClient( - 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 = operations_pb2.ListOperationsRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_operations), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.ListOperationsResponse() - ) - response = await client.list_operations(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 response is the type that we expect. - assert isinstance(response, operations_pb2.ListOperationsResponse) - -def test_list_operations_field_headers(): - 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 = operations_pb2.ListOperationsRequest() - request.name = "locations" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_operations), "__call__") as call: - call.return_value = operations_pb2.ListOperationsResponse() - - client.list_operations(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=locations",) in kw["metadata"] -@pytest.mark.asyncio -async def test_list_operations_field_headers_async(): - 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 = operations_pb2.ListOperationsRequest() - request.name = "locations" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_operations), "__call__") as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.ListOperationsResponse() - ) - await client.list_operations(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=locations",) in kw["metadata"] - -def test_list_operations_from_dict(): - 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.list_operations), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.ListOperationsResponse() - - response = client.list_operations( - request={ - "name": "locations", - } - ) - call.assert_called() -@pytest.mark.asyncio -async def test_list_operations_from_dict_async(): - 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.list_operations), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.ListOperationsResponse() - ) - response = await client.list_operations( - request={ - "name": "locations", - } - ) - call.assert_called() - - -def test_list_locations(transport: str = "grpc"): - client = SessionsClient( - 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 = locations_pb2.ListLocationsRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_locations), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = locations_pb2.ListLocationsResponse() - response = client.list_locations(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 response is the type that we expect. - assert isinstance(response, locations_pb2.ListLocationsResponse) -@pytest.mark.asyncio -async def test_list_locations_async(transport: str = "grpc"): - client = SessionsAsyncClient( - 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 = locations_pb2.ListLocationsRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_locations), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - locations_pb2.ListLocationsResponse() - ) - response = await client.list_locations(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 response is the type that we expect. - assert isinstance(response, locations_pb2.ListLocationsResponse) - -def test_list_locations_field_headers(): - 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 = locations_pb2.ListLocationsRequest() - request.name = "locations" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_locations), "__call__") as call: - call.return_value = locations_pb2.ListLocationsResponse() - - client.list_locations(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=locations",) in kw["metadata"] -@pytest.mark.asyncio -async def test_list_locations_field_headers_async(): - 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 = locations_pb2.ListLocationsRequest() - request.name = "locations" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_locations), "__call__") as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - locations_pb2.ListLocationsResponse() - ) - await client.list_locations(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=locations",) in kw["metadata"] - -def test_list_locations_from_dict(): - 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.list_locations), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = locations_pb2.ListLocationsResponse() - - response = client.list_locations( - request={ - "name": "locations", - } - ) - call.assert_called() -@pytest.mark.asyncio -async def test_list_locations_from_dict_async(): - 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.list_locations), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - locations_pb2.ListLocationsResponse() - ) - response = await client.list_locations( - request={ - "name": "locations", - } - ) - call.assert_called() - - -def test_get_location(transport: str = "grpc"): - client = SessionsClient( - 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 = locations_pb2.GetLocationRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_location), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = locations_pb2.Location() - response = client.get_location(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 response is the type that we expect. - assert isinstance(response, locations_pb2.Location) -@pytest.mark.asyncio -async def test_get_location_async(transport: str = "grpc_asyncio"): - client = SessionsAsyncClient( - 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 = locations_pb2.GetLocationRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_location), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - locations_pb2.Location() - ) - response = await client.get_location(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 response is the type that we expect. - assert isinstance(response, locations_pb2.Location) - -def test_get_location_field_headers(): - 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 = locations_pb2.GetLocationRequest() - request.name = "locations/abc" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_location), "__call__") as call: - call.return_value = locations_pb2.Location() - - client.get_location(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=locations/abc",) in kw["metadata"] -@pytest.mark.asyncio -async def test_get_location_field_headers_async(): - 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 = locations_pb2.GetLocationRequest() - request.name = "locations/abc" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_location), "__call__") as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - locations_pb2.Location() - ) - await client.get_location(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=locations/abc",) in kw["metadata"] - -def test_get_location_from_dict(): - 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.list_locations), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = locations_pb2.Location() - - response = client.get_location( - request={ - "name": "locations/abc", - } - ) - call.assert_called() -@pytest.mark.asyncio -async def test_get_location_from_dict_async(): - 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.list_locations), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - locations_pb2.Location() - ) - response = await client.get_location( - request={ - "name": "locations", - } - ) - call.assert_called() - - -def test_transport_close(): - transports = { - "rest": "_session", - "grpc": "_grpc_channel", - } - - for transport, close_name in transports.items(): - client = SessionsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport - ) - with mock.patch.object(type(getattr(client.transport, close_name)), "close") as close: - with client: - close.assert_not_called() - close.assert_called_once() - -def test_client_ctx(): - transports = [ - 'rest', - 'grpc', - ] - for transport in transports: - client = SessionsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport - ) - # Test client calls underlying transport. - with mock.patch.object(type(client.transport), "close") as close: - close.assert_not_called() - with client: - pass - close.assert_called() - -@pytest.mark.parametrize("client_class,transport_class", [ - (SessionsClient, transports.SessionsGrpcTransport), - (SessionsAsyncClient, transports.SessionsGrpcAsyncIOTransport), -]) -def test_api_key_credentials(client_class, transport_class): - with mock.patch.object( - google.auth._default, "get_api_key_credentials", create=True - ) as get_api_key_credentials: - mock_cred = mock.Mock() - get_api_key_credentials.return_value = mock_cred - options = client_options.ClientOptions() - options.api_key = "api_key" - 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=mock_cred, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) diff --git a/owl-bot-staging/v2beta1/tests/unit/gapic/dialogflow_v2beta1/test_versions.py b/owl-bot-staging/v2beta1/tests/unit/gapic/dialogflow_v2beta1/test_versions.py deleted file mode 100644 index a3f800b55..000000000 --- a/owl-bot-staging/v2beta1/tests/unit/gapic/dialogflow_v2beta1/test_versions.py +++ /dev/null @@ -1,4759 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 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 -# try/except added for compatibility with python < 3.8 -try: - from unittest import mock - from unittest.mock import AsyncMock # pragma: NO COVER -except ImportError: # pragma: NO COVER - import mock - -import grpc -from grpc.experimental import aio -from collections.abc import Iterable -from google.protobuf import json_format -import json -import math -import pytest -from proto.marshal.rules.dates import DurationRule, TimestampRule -from proto.marshal.rules import wrappers -from requests import Response -from requests import Request, PreparedRequest -from requests.sessions import Session -from google.protobuf import json_format - -from google.api_core import client_options -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import grpc_helpers -from google.api_core import grpc_helpers_async -from google.api_core import path_template -from google.auth import credentials as ga_credentials -from google.auth.exceptions import MutualTLSChannelError -from google.cloud.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.types import version -from google.cloud.dialogflow_v2beta1.types import version as gcd_version -from google.cloud.location import locations_pb2 -from google.longrunning import operations_pb2 -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 - - -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,transport_name", [ - (VersionsClient, "grpc"), - (VersionsAsyncClient, "grpc_asyncio"), - (VersionsClient, "rest"), -]) -def test_versions_client_from_service_account_info(client_class, transport_name): - 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, transport=transport_name) - assert client.transport._credentials == creds - assert isinstance(client, client_class) - - assert client.transport._host == ( - 'dialogflow.googleapis.com:443' - if transport_name in ['grpc', 'grpc_asyncio'] - else - 'https://dialogflow.googleapis.com' - ) - - -@pytest.mark.parametrize("transport_class,transport_name", [ - (transports.VersionsGrpcTransport, "grpc"), - (transports.VersionsGrpcAsyncIOTransport, "grpc_asyncio"), - (transports.VersionsRestTransport, "rest"), -]) -def test_versions_client_service_account_always_use_jwt(transport_class, transport_name): - with mock.patch.object(service_account.Credentials, 'with_always_use_jwt_access', create=True) as use_jwt: - creds = service_account.Credentials(None, None, None) - transport = transport_class(credentials=creds, always_use_jwt_access=True) - use_jwt.assert_called_once_with(True) - - with mock.patch.object(service_account.Credentials, 'with_always_use_jwt_access', create=True) as use_jwt: - creds = service_account.Credentials(None, None, None) - transport = transport_class(credentials=creds, always_use_jwt_access=False) - use_jwt.assert_not_called() - - -@pytest.mark.parametrize("client_class,transport_name", [ - (VersionsClient, "grpc"), - (VersionsAsyncClient, "grpc_asyncio"), - (VersionsClient, "rest"), -]) -def test_versions_client_from_service_account_file(client_class, transport_name): - 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", transport=transport_name) - assert client.transport._credentials == creds - assert isinstance(client, client_class) - - client = client_class.from_service_account_json("dummy/file/path.json", transport=transport_name) - assert client.transport._credentials == creds - assert isinstance(client, client_class) - - assert client.transport._host == ( - 'dialogflow.googleapis.com:443' - if transport_name in ['grpc', 'grpc_asyncio'] - else - 'https://dialogflow.googleapis.com' - ) - - -def test_versions_client_get_transport_class(): - transport = VersionsClient.get_transport_class() - available_transports = [ - transports.VersionsGrpcTransport, - transports.VersionsRestTransport, - ] - 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"), - (VersionsClient, transports.VersionsRestTransport, "rest"), -]) -@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(transport=transport_name, client_options=options) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host="squid.clam.whelk", - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is - # "never". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is - # "always". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_MTLS_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # 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(transport=transport_name) - - # 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(transport=transport_name) - - # 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, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id="octopus", - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - # Check the case api_endpoint is provided - options = client_options.ClientOptions(api_audience="https://language.googleapis.com") - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience="https://language.googleapis.com" - ) - -@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"), - (VersionsClient, transports.VersionsRestTransport, "rest", "true"), - (VersionsClient, transports.VersionsRestTransport, "rest", "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, transport=transport_name) - - if use_client_cert_env == "false": - expected_client_cert_source = None - expected_host = client.DEFAULT_ENDPOINT - else: - expected_client_cert_source = client_cert_source_callback - expected_host = client.DEFAULT_MTLS_ENDPOINT - - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=expected_host, - scopes=None, - client_cert_source_for_mtls=expected_client_cert_source, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case ADC client cert is provided. Whether client cert is used depends on - # GOOGLE_API_USE_CLIENT_CERTIFICATE value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): - with mock.patch.object(transport_class, '__init__') as patched: - with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): - with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=client_cert_source_callback): - if use_client_cert_env == "false": - expected_host = client.DEFAULT_ENDPOINT - expected_client_cert_source = None - else: - expected_host = client.DEFAULT_MTLS_ENDPOINT - expected_client_cert_source = client_cert_source_callback - - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=expected_host, - scopes=None, - client_cert_source_for_mtls=expected_client_cert_source, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case client_cert_source and ADC client cert are not provided. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): - with mock.patch.object(transport_class, '__init__') as patched: - with mock.patch("google.auth.transport.mtls.has_default_client_cert_source", return_value=False): - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - -@pytest.mark.parametrize("client_class", [ - VersionsClient, VersionsAsyncClient -]) -@mock.patch.object(VersionsClient, "DEFAULT_ENDPOINT", modify_default_endpoint(VersionsClient)) -@mock.patch.object(VersionsAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(VersionsAsyncClient)) -def test_versions_client_get_mtls_endpoint_and_cert_source(client_class): - mock_client_cert_source = mock.Mock() - - # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "true". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - mock_api_endpoint = "foo" - options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) - assert api_endpoint == mock_api_endpoint - assert cert_source == mock_client_cert_source - - # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "false". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): - mock_client_cert_source = mock.Mock() - mock_api_endpoint = "foo" - options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) - assert api_endpoint == mock_api_endpoint - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "never". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_ENDPOINT - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "always". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert doesn't exist. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=False): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_ENDPOINT - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert exists. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - 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=mock_client_cert_source): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT - assert cert_source == mock_client_cert_source - - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (VersionsClient, transports.VersionsGrpcTransport, "grpc"), - (VersionsAsyncClient, transports.VersionsGrpcAsyncIOTransport, "grpc_asyncio"), - (VersionsClient, transports.VersionsRestTransport, "rest"), -]) -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, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=["1", "2"], - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - -@pytest.mark.parametrize("client_class,transport_class,transport_name,grpc_helpers", [ - (VersionsClient, transports.VersionsGrpcTransport, "grpc", grpc_helpers), - (VersionsAsyncClient, transports.VersionsGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), - (VersionsClient, transports.VersionsRestTransport, "rest", None), -]) -def test_versions_client_client_options_credentials_file(client_class, transport_class, transport_name, grpc_helpers): - # 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, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file="credentials.json", - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - -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, - always_use_jwt_access=True, - api_audience=None, - ) - - -@pytest.mark.parametrize("client_class,transport_class,transport_name,grpc_helpers", [ - (VersionsClient, transports.VersionsGrpcTransport, "grpc", grpc_helpers), - (VersionsAsyncClient, transports.VersionsGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), -]) -def test_versions_client_create_channel_credentials_file(client_class, transport_class, transport_name, grpc_helpers): - # 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, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file="credentials.json", - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # test that the credentials from file are saved and used as the credentials. - with mock.patch.object( - google.auth, "load_credentials_from_file", autospec=True - ) as load_creds, mock.patch.object( - google.auth, "default", autospec=True - ) as adc, mock.patch.object( - grpc_helpers, "create_channel" - ) as create_channel: - creds = ga_credentials.AnonymousCredentials() - file_creds = ga_credentials.AnonymousCredentials() - load_creds.return_value = (file_creds, None) - adc.return_value = (creds, None) - client = client_class(client_options=options, transport=transport_name) - create_channel.assert_called_with( - "dialogflow.googleapis.com:443", - credentials=file_creds, - credentials_file=None, - quota_project_id=None, - default_scopes=( - 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/dialogflow', -), - scopes=None, - default_host="dialogflow.googleapis.com", - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - -@pytest.mark.parametrize("request_type", [ - version.ListVersionsRequest, - dict, -]) -def test_list_versions(request_type, transport: str = 'grpc'): - 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_empty_call(): - # 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] - arg = args[0].parent - mock_val = 'parent_value' - assert arg == mock_val - - -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] - arg = args[0].parent - mock_val = 'parent_value' - assert arg == mock_val - -@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(transport_name: str = "grpc"): - client = VersionsClient( - credentials=ga_credentials.AnonymousCredentials, - transport=transport_name, - ) - - # 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 = list(pager) - assert len(results) == 6 - assert all(isinstance(i, version.Version) - for i in results) -def test_list_versions_pages(transport_name: str = "grpc"): - client = VersionsClient( - credentials=ga_credentials.AnonymousCredentials, - transport=transport_name, - ) - - # 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: # pragma: no branch - 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: # pragma: no branch - pages.append(page_) - for page_, token in zip(pages, ['abc','def','ghi', '']): - assert page_.raw_page.next_page_token == token - -@pytest.mark.parametrize("request_type", [ - version.GetVersionRequest, - dict, -]) -def test_get_version(request_type, transport: str = 'grpc'): - 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_empty_call(): - # 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] - arg = args[0].name - mock_val = 'name_value' - assert arg == mock_val - - -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] - arg = args[0].name - mock_val = 'name_value' - assert arg == mock_val - -@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', - ) - - -@pytest.mark.parametrize("request_type", [ - gcd_version.CreateVersionRequest, - dict, -]) -def test_create_version(request_type, transport: str = 'grpc'): - 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_empty_call(): - # 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] - arg = args[0].parent - mock_val = 'parent_value' - assert arg == mock_val - arg = args[0].version - mock_val = gcd_version.Version(name='name_value') - assert arg == mock_val - - -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] - arg = args[0].parent - mock_val = 'parent_value' - assert arg == mock_val - arg = args[0].version - mock_val = gcd_version.Version(name='name_value') - assert arg == mock_val - -@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'), - ) - - -@pytest.mark.parametrize("request_type", [ - gcd_version.UpdateVersionRequest, - dict, -]) -def test_update_version(request_type, transport: str = 'grpc'): - 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_empty_call(): - # 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 = '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=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 = '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=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] - arg = args[0].version - mock_val = gcd_version.Version(name='name_value') - assert arg == mock_val - arg = args[0].update_mask - mock_val = field_mask_pb2.FieldMask(paths=['paths_value']) - assert arg == mock_val - - -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] - arg = args[0].version - mock_val = gcd_version.Version(name='name_value') - assert arg == mock_val - arg = args[0].update_mask - mock_val = field_mask_pb2.FieldMask(paths=['paths_value']) - assert arg == mock_val - -@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']), - ) - - -@pytest.mark.parametrize("request_type", [ - version.DeleteVersionRequest, - dict, -]) -def test_delete_version(request_type, transport: str = 'grpc'): - 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_empty_call(): - # 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] - arg = args[0].name - mock_val = 'name_value' - assert arg == mock_val - - -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] - arg = args[0].name - mock_val = 'name_value' - assert arg == mock_val - -@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', - ) - - -@pytest.mark.parametrize("request_type", [ - version.ListVersionsRequest, - dict, -]) -def test_list_versions_rest(request_type): - client = VersionsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1/agent'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = version.ListVersionsResponse( - next_page_token='next_page_token_value', - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - pb_return_value = version.ListVersionsResponse.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.list_versions(request) - - # 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_rest_required_fields(request_type=version.ListVersionsRequest): - transport_class = transports.VersionsRestTransport - - request_init = {} - request_init["parent"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - including_default_value_fields=False, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).list_versions._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["parent"] = 'parent_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).list_versions._get_unset_required_fields(jsonified_request) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("page_size", "page_token", )) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "parent" in jsonified_request - assert jsonified_request["parent"] == 'parent_value' - - client = VersionsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = version.ListVersionsResponse() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "get", - 'query_params': pb_request, - } - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - - pb_return_value = version.ListVersionsResponse.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.list_versions(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_list_versions_rest_unset_required_fields(): - transport = transports.VersionsRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.list_versions._get_unset_required_fields({}) - assert set(unset_fields) == (set(("pageSize", "pageToken", )) & set(("parent", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_list_versions_rest_interceptors(null_interceptor): - transport = transports.VersionsRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.VersionsRestInterceptor(), - ) - client = VersionsClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.VersionsRestInterceptor, "post_list_versions") as post, \ - mock.patch.object(transports.VersionsRestInterceptor, "pre_list_versions") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = version.ListVersionsRequest.pb(version.ListVersionsRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = version.ListVersionsResponse.to_json(version.ListVersionsResponse()) - - request = version.ListVersionsRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = version.ListVersionsResponse() - - client.list_versions(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_list_versions_rest_bad_request(transport: str = 'rest', request_type=version.ListVersionsRequest): - client = VersionsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1/agent'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.list_versions(request) - - -def test_list_versions_rest_flattened(): - client = VersionsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = version.ListVersionsResponse() - - # get arguments that satisfy an http rule for this method - sample_request = {'parent': 'projects/sample1/agent'} - - # get truthy value for each flattened field - mock_args = dict( - parent='parent_value', - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - pb_return_value = version.ListVersionsResponse.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.list_versions(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v2beta1/{parent=projects/*/agent}/versions" % client.transport._host, args[1]) - - -def test_list_versions_rest_flattened_error(transport: str = 'rest'): - client = VersionsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # 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', - ) - - -def test_list_versions_rest_pager(transport: str = 'rest'): - client = VersionsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # TODO(kbandes): remove this mock unless there's a good reason for it. - #with mock.patch.object(path_template, 'transcode') as transcode: - # Set the response as a series of pages - response = ( - 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(), - ], - ), - ) - # Two responses for two calls - response = response + response - - # Wrap the values into proper Response objs - response = tuple(version.ListVersionsResponse.to_json(x) for x in response) - return_values = tuple(Response() for i in response) - for return_val, response_val in zip(return_values, response): - return_val._content = response_val.encode('UTF-8') - return_val.status_code = 200 - req.side_effect = return_values - - sample_request = {'parent': 'projects/sample1/agent'} - - pager = client.list_versions(request=sample_request) - - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, version.Version) - for i in results) - - pages = list(client.list_versions(request=sample_request).pages) - for page_, token in zip(pages, ['abc','def','ghi', '']): - assert page_.raw_page.next_page_token == token - - -@pytest.mark.parametrize("request_type", [ - version.GetVersionRequest, - dict, -]) -def test_get_version_rest(request_type): - client = VersionsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/agent/versions/sample2'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = version.Version( - name='name_value', - description='description_value', - version_number=1518, - status=version.Version.VersionStatus.IN_PROGRESS, - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - pb_return_value = version.Version.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.get_version(request) - - # 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_rest_required_fields(request_type=version.GetVersionRequest): - transport_class = transports.VersionsRestTransport - - request_init = {} - request_init["name"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - including_default_value_fields=False, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_version._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["name"] = 'name_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_version._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "name" in jsonified_request - assert jsonified_request["name"] == 'name_value' - - client = VersionsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = version.Version() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "get", - 'query_params': pb_request, - } - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - - pb_return_value = version.Version.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.get_version(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_get_version_rest_unset_required_fields(): - transport = transports.VersionsRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.get_version._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_get_version_rest_interceptors(null_interceptor): - transport = transports.VersionsRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.VersionsRestInterceptor(), - ) - client = VersionsClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.VersionsRestInterceptor, "post_get_version") as post, \ - mock.patch.object(transports.VersionsRestInterceptor, "pre_get_version") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = version.GetVersionRequest.pb(version.GetVersionRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = version.Version.to_json(version.Version()) - - request = version.GetVersionRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = version.Version() - - client.get_version(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_get_version_rest_bad_request(transport: str = 'rest', request_type=version.GetVersionRequest): - client = VersionsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/agent/versions/sample2'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.get_version(request) - - -def test_get_version_rest_flattened(): - client = VersionsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = version.Version() - - # get arguments that satisfy an http rule for this method - sample_request = {'name': 'projects/sample1/agent/versions/sample2'} - - # get truthy value for each flattened field - mock_args = dict( - name='name_value', - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - pb_return_value = version.Version.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.get_version(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v2beta1/{name=projects/*/agent/versions/*}" % client.transport._host, args[1]) - - -def test_get_version_rest_flattened_error(transport: str = 'rest'): - client = VersionsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # 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', - ) - - -def test_get_version_rest_error(): - client = VersionsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - gcd_version.CreateVersionRequest, - dict, -]) -def test_create_version_rest(request_type): - client = VersionsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1/agent'} - request_init["version"] = {'name': 'name_value', 'description': 'description_value', 'version_number': 1518, 'create_time': {'seconds': 751, 'nanos': 543}, 'status': 1} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = gcd_version.Version( - name='name_value', - description='description_value', - version_number=1518, - status=gcd_version.Version.VersionStatus.IN_PROGRESS, - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - pb_return_value = gcd_version.Version.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.create_version(request) - - # 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_rest_required_fields(request_type=gcd_version.CreateVersionRequest): - transport_class = transports.VersionsRestTransport - - request_init = {} - request_init["parent"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - including_default_value_fields=False, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_version._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["parent"] = 'parent_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_version._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "parent" in jsonified_request - assert jsonified_request["parent"] == 'parent_value' - - client = VersionsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = gcd_version.Version() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "post", - 'query_params': pb_request, - } - transcode_result['body'] = pb_request - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - - pb_return_value = gcd_version.Version.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.create_version(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_create_version_rest_unset_required_fields(): - transport = transports.VersionsRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.create_version._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("parent", "version", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_create_version_rest_interceptors(null_interceptor): - transport = transports.VersionsRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.VersionsRestInterceptor(), - ) - client = VersionsClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.VersionsRestInterceptor, "post_create_version") as post, \ - mock.patch.object(transports.VersionsRestInterceptor, "pre_create_version") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = gcd_version.CreateVersionRequest.pb(gcd_version.CreateVersionRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = gcd_version.Version.to_json(gcd_version.Version()) - - request = gcd_version.CreateVersionRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = gcd_version.Version() - - client.create_version(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_create_version_rest_bad_request(transport: str = 'rest', request_type=gcd_version.CreateVersionRequest): - client = VersionsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1/agent'} - request_init["version"] = {'name': 'name_value', 'description': 'description_value', 'version_number': 1518, 'create_time': {'seconds': 751, 'nanos': 543}, 'status': 1} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.create_version(request) - - -def test_create_version_rest_flattened(): - client = VersionsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = gcd_version.Version() - - # get arguments that satisfy an http rule for this method - sample_request = {'parent': 'projects/sample1/agent'} - - # get truthy value for each flattened field - mock_args = dict( - parent='parent_value', - version=gcd_version.Version(name='name_value'), - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - pb_return_value = gcd_version.Version.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.create_version(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v2beta1/{parent=projects/*/agent}/versions" % client.transport._host, args[1]) - - -def test_create_version_rest_flattened_error(transport: str = 'rest'): - client = VersionsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # 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'), - ) - - -def test_create_version_rest_error(): - client = VersionsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - gcd_version.UpdateVersionRequest, - dict, -]) -def test_update_version_rest(request_type): - client = VersionsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'version': {'name': 'projects/sample1/agent/versions/sample2'}} - request_init["version"] = {'name': 'projects/sample1/agent/versions/sample2', 'description': 'description_value', 'version_number': 1518, 'create_time': {'seconds': 751, 'nanos': 543}, 'status': 1} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = gcd_version.Version( - name='name_value', - description='description_value', - version_number=1518, - status=gcd_version.Version.VersionStatus.IN_PROGRESS, - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - pb_return_value = gcd_version.Version.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.update_version(request) - - # 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_rest_required_fields(request_type=gcd_version.UpdateVersionRequest): - transport_class = transports.VersionsRestTransport - - request_init = {} - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - including_default_value_fields=False, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).update_version._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).update_version._get_unset_required_fields(jsonified_request) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("update_mask", )) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - - client = VersionsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = gcd_version.Version() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "patch", - 'query_params': pb_request, - } - transcode_result['body'] = pb_request - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - - pb_return_value = gcd_version.Version.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.update_version(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_update_version_rest_unset_required_fields(): - transport = transports.VersionsRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.update_version._get_unset_required_fields({}) - assert set(unset_fields) == (set(("updateMask", )) & set(("version", "updateMask", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_update_version_rest_interceptors(null_interceptor): - transport = transports.VersionsRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.VersionsRestInterceptor(), - ) - client = VersionsClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.VersionsRestInterceptor, "post_update_version") as post, \ - mock.patch.object(transports.VersionsRestInterceptor, "pre_update_version") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = gcd_version.UpdateVersionRequest.pb(gcd_version.UpdateVersionRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = gcd_version.Version.to_json(gcd_version.Version()) - - request = gcd_version.UpdateVersionRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = gcd_version.Version() - - client.update_version(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_update_version_rest_bad_request(transport: str = 'rest', request_type=gcd_version.UpdateVersionRequest): - client = VersionsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'version': {'name': 'projects/sample1/agent/versions/sample2'}} - request_init["version"] = {'name': 'projects/sample1/agent/versions/sample2', 'description': 'description_value', 'version_number': 1518, 'create_time': {'seconds': 751, 'nanos': 543}, 'status': 1} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.update_version(request) - - -def test_update_version_rest_flattened(): - client = VersionsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = gcd_version.Version() - - # get arguments that satisfy an http rule for this method - sample_request = {'version': {'name': 'projects/sample1/agent/versions/sample2'}} - - # get truthy value for each flattened field - mock_args = dict( - version=gcd_version.Version(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - pb_return_value = gcd_version.Version.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.update_version(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v2beta1/{version.name=projects/*/agent/versions/*}" % client.transport._host, args[1]) - - -def test_update_version_rest_flattened_error(transport: str = 'rest'): - client = VersionsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # 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']), - ) - - -def test_update_version_rest_error(): - client = VersionsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - version.DeleteVersionRequest, - dict, -]) -def test_delete_version_rest(request_type): - client = VersionsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/agent/versions/sample2'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = None - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = '' - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.delete_version(request) - - # Establish that the response is the type that we expect. - assert response is None - - -def test_delete_version_rest_required_fields(request_type=version.DeleteVersionRequest): - transport_class = transports.VersionsRestTransport - - request_init = {} - request_init["name"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - including_default_value_fields=False, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).delete_version._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["name"] = 'name_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).delete_version._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "name" in jsonified_request - assert jsonified_request["name"] == 'name_value' - - client = VersionsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = None - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "delete", - 'query_params': pb_request, - } - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - json_return_value = '' - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.delete_version(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_delete_version_rest_unset_required_fields(): - transport = transports.VersionsRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.delete_version._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_delete_version_rest_interceptors(null_interceptor): - transport = transports.VersionsRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.VersionsRestInterceptor(), - ) - client = VersionsClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.VersionsRestInterceptor, "pre_delete_version") as pre: - pre.assert_not_called() - pb_message = version.DeleteVersionRequest.pb(version.DeleteVersionRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - - request = version.DeleteVersionRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - - client.delete_version(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - - -def test_delete_version_rest_bad_request(transport: str = 'rest', request_type=version.DeleteVersionRequest): - client = VersionsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/agent/versions/sample2'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.delete_version(request) - - -def test_delete_version_rest_flattened(): - client = VersionsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = None - - # get arguments that satisfy an http rule for this method - sample_request = {'name': 'projects/sample1/agent/versions/sample2'} - - # get truthy value for each flattened field - mock_args = dict( - name='name_value', - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = '' - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.delete_version(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v2beta1/{name=projects/*/agent/versions/*}" % client.transport._host, args[1]) - - -def test_delete_version_rest_flattened_error(transport: str = 'rest'): - client = VersionsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # 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', - ) - - -def test_delete_version_rest_error(): - client = VersionsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -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 an api_key and a transport instance. - transport = transports.VersionsGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - options = client_options.ClientOptions() - options.api_key = "api_key" - with pytest.raises(ValueError): - client = VersionsClient( - client_options=options, - transport=transport, - ) - - # It is an error to provide an api_key and a credential. - options = mock.Mock() - options.api_key = "api_key" - with pytest.raises(ValueError): - client = VersionsClient( - client_options=options, - credentials=ga_credentials.AnonymousCredentials() - ) - - # 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, - transports.VersionsRestTransport, -]) -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() - -@pytest.mark.parametrize("transport_name", [ - "grpc", - "rest", -]) -def test_transport_kind(transport_name): - transport = VersionsClient.get_transport_class(transport_name)( - credentials=ga_credentials.AnonymousCredentials(), - ) - assert transport.kind == transport_name - -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', - 'get_location', - 'list_locations', - 'get_operation', - 'cancel_operation', - 'list_operations', - ) - for method in methods: - with pytest.raises(NotImplementedError): - getattr(transport, method)(request=object()) - - with pytest.raises(NotImplementedError): - transport.close() - - # Catch all for all remaining methods and properties - remainder = [ - 'kind', - ] - for r in remainder: - with pytest.raises(NotImplementedError): - getattr(transport, r)() - - -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", - ) - - -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() - - -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, - ) - - -@pytest.mark.parametrize( - "transport_class", - [ - transports.VersionsGrpcTransport, - transports.VersionsGrpcAsyncIOTransport, - ], -) -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, - transports.VersionsRestTransport, - ], -) -def test_versions_transport_auth_gdch_credentials(transport_class): - host = 'https://language.com' - api_audience_tests = [None, 'https://language2.com'] - api_audience_expect = [host, 'https://language2.com'] - for t, e in zip(api_audience_tests, api_audience_expect): - with mock.patch.object(google.auth, 'default', autospec=True) as adc: - gdch_mock = mock.MagicMock() - type(gdch_mock).with_gdch_audience = mock.PropertyMock(return_value=gdch_mock) - adc.return_value = (gdch_mock, None) - transport_class(host=host, api_audience=t) - gdch_mock.with_gdch_audience.assert_called_once_with( - e - ) - - -@pytest.mark.parametrize( - "transport_class,grpc_helpers", - [ - (transports.VersionsGrpcTransport, grpc_helpers), - (transports.VersionsGrpcAsyncIOTransport, grpc_helpers_async) - ], -) -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", [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=None, - ssl_credentials=mock_ssl_channel_creds, - quota_project_id=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - # Check if ssl_channel_credentials is not provided, then client_cert_source_for_mtls - # is used. - with mock.patch.object(transport_class, "create_channel", return_value=mock.Mock()): - with mock.patch("grpc.ssl_channel_credentials") as mock_ssl_cred: - transport_class( - credentials=cred, - client_cert_source_for_mtls=client_cert_source_callback - ) - expected_cert, expected_key = client_cert_source_callback() - mock_ssl_cred.assert_called_once_with( - certificate_chain=expected_cert, - private_key=expected_key - ) - -def test_versions_http_transport_client_cert_source_for_mtls(): - cred = ga_credentials.AnonymousCredentials() - with mock.patch("google.auth.transport.requests.AuthorizedSession.configure_mtls_channel") as mock_configure_mtls_channel: - transports.VersionsRestTransport ( - credentials=cred, - client_cert_source_for_mtls=client_cert_source_callback - ) - mock_configure_mtls_channel.assert_called_once_with(client_cert_source_callback) - - -@pytest.mark.parametrize("transport_name", [ - "grpc", - "grpc_asyncio", - "rest", -]) -def test_versions_host_no_port(transport_name): - client = VersionsClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='dialogflow.googleapis.com'), - transport=transport_name, - ) - assert client.transport._host == ( - 'dialogflow.googleapis.com:443' - if transport_name in ['grpc', 'grpc_asyncio'] - else 'https://dialogflow.googleapis.com' - ) - -@pytest.mark.parametrize("transport_name", [ - "grpc", - "grpc_asyncio", - "rest", -]) -def test_versions_host_with_port(transport_name): - client = VersionsClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='dialogflow.googleapis.com:8000'), - transport=transport_name, - ) - assert client.transport._host == ( - 'dialogflow.googleapis.com:8000' - if transport_name in ['grpc', 'grpc_asyncio'] - else 'https://dialogflow.googleapis.com:8000' - ) - -@pytest.mark.parametrize("transport_name", [ - "rest", -]) -def test_versions_client_transport_session_collision(transport_name): - creds1 = ga_credentials.AnonymousCredentials() - creds2 = ga_credentials.AnonymousCredentials() - client1 = VersionsClient( - credentials=creds1, - transport=transport_name, - ) - client2 = VersionsClient( - credentials=creds2, - transport=transport_name, - ) - session1 = client1.transport.list_versions._session - session2 = client2.transport.list_versions._session - assert session1 != session2 - session1 = client1.transport.get_version._session - session2 = client2.transport.get_version._session - assert session1 != session2 - session1 = client1.transport.create_version._session - session2 = client2.transport.create_version._session - assert session1 != session2 - session1 = client1.transport.update_version._session - session2 = client2.transport.update_version._session - assert session1 != session2 - session1 = client1.transport.delete_version._session - session2 = client2.transport.delete_version._session - assert session1 != session2 -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=None, - ssl_credentials=mock_ssl_cred, - quota_project_id=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - assert transport.grpc_channel == mock_grpc_channel - assert transport._ssl_channel_credentials == mock_ssl_cred - - -# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are -# removed from grpc/grpc_asyncio transport constructor. -@pytest.mark.parametrize("transport_class", [transports.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=None, - ssl_credentials=mock_ssl_cred, - quota_project_id=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - assert transport.grpc_channel == mock_grpc_channel - - -def test_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_with_default_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) - -@pytest.mark.asyncio -async def test_transport_close_async(): - client = VersionsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - with mock.patch.object(type(getattr(client.transport, "grpc_channel")), "close") as close: - async with client: - close.assert_not_called() - close.assert_called_once() - - -def test_get_location_rest_bad_request(transport: str = 'rest', request_type=locations_pb2.GetLocationRequest): - client = VersionsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - request = request_type() - request = json_format.ParseDict({'name': 'projects/sample1/locations/sample2'}, request) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.get_location(request) - -@pytest.mark.parametrize("request_type", [ - locations_pb2.GetLocationRequest, - dict, -]) -def test_get_location_rest(request_type): - client = VersionsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request_init = {'name': 'projects/sample1/locations/sample2'} - request = request_type(**request_init) - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = locations_pb2.Location() - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.get_location(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, locations_pb2.Location) - -def test_list_locations_rest_bad_request(transport: str = 'rest', request_type=locations_pb2.ListLocationsRequest): - client = VersionsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - request = request_type() - request = json_format.ParseDict({'name': 'projects/sample1'}, request) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.list_locations(request) - -@pytest.mark.parametrize("request_type", [ - locations_pb2.ListLocationsRequest, - dict, -]) -def test_list_locations_rest(request_type): - client = VersionsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request_init = {'name': 'projects/sample1'} - request = request_type(**request_init) - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = locations_pb2.ListLocationsResponse() - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.list_locations(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, locations_pb2.ListLocationsResponse) - -def test_cancel_operation_rest_bad_request(transport: str = 'rest', request_type=operations_pb2.CancelOperationRequest): - client = VersionsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - request = request_type() - request = json_format.ParseDict({'name': 'projects/sample1/operations/sample2'}, request) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.cancel_operation(request) - -@pytest.mark.parametrize("request_type", [ - operations_pb2.CancelOperationRequest, - dict, -]) -def test_cancel_operation_rest(request_type): - client = VersionsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request_init = {'name': 'projects/sample1/operations/sample2'} - request = request_type(**request_init) - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = None - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = '{}' - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.cancel_operation(request) - - # Establish that the response is the type that we expect. - assert response is None - -def test_get_operation_rest_bad_request(transport: str = 'rest', request_type=operations_pb2.GetOperationRequest): - client = VersionsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - request = request_type() - request = json_format.ParseDict({'name': 'projects/sample1/operations/sample2'}, request) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.get_operation(request) - -@pytest.mark.parametrize("request_type", [ - operations_pb2.GetOperationRequest, - dict, -]) -def test_get_operation_rest(request_type): - client = VersionsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request_init = {'name': 'projects/sample1/operations/sample2'} - request = request_type(**request_init) - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation() - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.get_operation(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, operations_pb2.Operation) - -def test_list_operations_rest_bad_request(transport: str = 'rest', request_type=operations_pb2.ListOperationsRequest): - client = VersionsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - request = request_type() - request = json_format.ParseDict({'name': 'projects/sample1'}, request) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.list_operations(request) - -@pytest.mark.parametrize("request_type", [ - operations_pb2.ListOperationsRequest, - dict, -]) -def test_list_operations_rest(request_type): - client = VersionsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request_init = {'name': 'projects/sample1'} - request = request_type(**request_init) - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = operations_pb2.ListOperationsResponse() - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.list_operations(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, operations_pb2.ListOperationsResponse) - - -def test_cancel_operation(transport: str = "grpc"): - 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 = operations_pb2.CancelOperationRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = None - response = client.cancel_operation(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 response is the type that we expect. - assert response is None -@pytest.mark.asyncio -async def test_cancel_operation_async(transport: str = "grpc"): - 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 = operations_pb2.CancelOperationRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - None - ) - response = await client.cancel_operation(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 response is the type that we expect. - assert response is None - -def test_cancel_operation_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 = operations_pb2.CancelOperationRequest() - request.name = "locations" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call: - call.return_value = None - - client.cancel_operation(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=locations",) in kw["metadata"] -@pytest.mark.asyncio -async def test_cancel_operation_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 = operations_pb2.CancelOperationRequest() - request.name = "locations" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - None - ) - await client.cancel_operation(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=locations",) in kw["metadata"] - -def test_cancel_operation_from_dict(): - 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.cancel_operation), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = None - - response = client.cancel_operation( - request={ - "name": "locations", - } - ) - call.assert_called() -@pytest.mark.asyncio -async def test_cancel_operation_from_dict_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.cancel_operation), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - None - ) - response = await client.cancel_operation( - request={ - "name": "locations", - } - ) - call.assert_called() - - -def test_get_operation(transport: str = "grpc"): - 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 = operations_pb2.GetOperationRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_operation), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation() - response = client.get_operation(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 response is the type that we expect. - assert isinstance(response, operations_pb2.Operation) -@pytest.mark.asyncio -async def test_get_operation_async(transport: str = "grpc"): - 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 = operations_pb2.GetOperationRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_operation), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation() - ) - response = await client.get_operation(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 response is the type that we expect. - assert isinstance(response, operations_pb2.Operation) - -def test_get_operation_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 = operations_pb2.GetOperationRequest() - request.name = "locations" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_operation), "__call__") as call: - call.return_value = operations_pb2.Operation() - - client.get_operation(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=locations",) in kw["metadata"] -@pytest.mark.asyncio -async def test_get_operation_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 = operations_pb2.GetOperationRequest() - request.name = "locations" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_operation), "__call__") as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation() - ) - await client.get_operation(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=locations",) in kw["metadata"] - -def test_get_operation_from_dict(): - 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_operation), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation() - - response = client.get_operation( - request={ - "name": "locations", - } - ) - call.assert_called() -@pytest.mark.asyncio -async def test_get_operation_from_dict_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_operation), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation() - ) - response = await client.get_operation( - request={ - "name": "locations", - } - ) - call.assert_called() - - -def test_list_operations(transport: str = "grpc"): - 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 = operations_pb2.ListOperationsRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_operations), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.ListOperationsResponse() - response = client.list_operations(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 response is the type that we expect. - assert isinstance(response, operations_pb2.ListOperationsResponse) -@pytest.mark.asyncio -async def test_list_operations_async(transport: str = "grpc"): - 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 = operations_pb2.ListOperationsRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_operations), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.ListOperationsResponse() - ) - response = await client.list_operations(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 response is the type that we expect. - assert isinstance(response, operations_pb2.ListOperationsResponse) - -def test_list_operations_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 = operations_pb2.ListOperationsRequest() - request.name = "locations" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_operations), "__call__") as call: - call.return_value = operations_pb2.ListOperationsResponse() - - client.list_operations(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=locations",) in kw["metadata"] -@pytest.mark.asyncio -async def test_list_operations_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 = operations_pb2.ListOperationsRequest() - request.name = "locations" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_operations), "__call__") as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.ListOperationsResponse() - ) - await client.list_operations(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=locations",) in kw["metadata"] - -def test_list_operations_from_dict(): - 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_operations), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.ListOperationsResponse() - - response = client.list_operations( - request={ - "name": "locations", - } - ) - call.assert_called() -@pytest.mark.asyncio -async def test_list_operations_from_dict_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_operations), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.ListOperationsResponse() - ) - response = await client.list_operations( - request={ - "name": "locations", - } - ) - call.assert_called() - - -def test_list_locations(transport: str = "grpc"): - 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 = locations_pb2.ListLocationsRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_locations), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = locations_pb2.ListLocationsResponse() - response = client.list_locations(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 response is the type that we expect. - assert isinstance(response, locations_pb2.ListLocationsResponse) -@pytest.mark.asyncio -async def test_list_locations_async(transport: str = "grpc"): - 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 = locations_pb2.ListLocationsRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_locations), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - locations_pb2.ListLocationsResponse() - ) - response = await client.list_locations(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 response is the type that we expect. - assert isinstance(response, locations_pb2.ListLocationsResponse) - -def test_list_locations_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 = locations_pb2.ListLocationsRequest() - request.name = "locations" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_locations), "__call__") as call: - call.return_value = locations_pb2.ListLocationsResponse() - - client.list_locations(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=locations",) in kw["metadata"] -@pytest.mark.asyncio -async def test_list_locations_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 = locations_pb2.ListLocationsRequest() - request.name = "locations" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_locations), "__call__") as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - locations_pb2.ListLocationsResponse() - ) - await client.list_locations(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=locations",) in kw["metadata"] - -def test_list_locations_from_dict(): - 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_locations), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = locations_pb2.ListLocationsResponse() - - response = client.list_locations( - request={ - "name": "locations", - } - ) - call.assert_called() -@pytest.mark.asyncio -async def test_list_locations_from_dict_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_locations), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - locations_pb2.ListLocationsResponse() - ) - response = await client.list_locations( - request={ - "name": "locations", - } - ) - call.assert_called() - - -def test_get_location(transport: str = "grpc"): - 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 = locations_pb2.GetLocationRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_location), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = locations_pb2.Location() - response = client.get_location(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 response is the type that we expect. - assert isinstance(response, locations_pb2.Location) -@pytest.mark.asyncio -async def test_get_location_async(transport: str = "grpc_asyncio"): - 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 = locations_pb2.GetLocationRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_location), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - locations_pb2.Location() - ) - response = await client.get_location(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 response is the type that we expect. - assert isinstance(response, locations_pb2.Location) - -def test_get_location_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 = locations_pb2.GetLocationRequest() - request.name = "locations/abc" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_location), "__call__") as call: - call.return_value = locations_pb2.Location() - - client.get_location(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=locations/abc",) in kw["metadata"] -@pytest.mark.asyncio -async def test_get_location_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 = locations_pb2.GetLocationRequest() - request.name = "locations/abc" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_location), "__call__") as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - locations_pb2.Location() - ) - await client.get_location(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=locations/abc",) in kw["metadata"] - -def test_get_location_from_dict(): - 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_locations), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = locations_pb2.Location() - - response = client.get_location( - request={ - "name": "locations/abc", - } - ) - call.assert_called() -@pytest.mark.asyncio -async def test_get_location_from_dict_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_locations), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - locations_pb2.Location() - ) - response = await client.get_location( - request={ - "name": "locations", - } - ) - call.assert_called() - - -def test_transport_close(): - transports = { - "rest": "_session", - "grpc": "_grpc_channel", - } - - for transport, close_name in transports.items(): - client = VersionsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport - ) - with mock.patch.object(type(getattr(client.transport, close_name)), "close") as close: - with client: - close.assert_not_called() - close.assert_called_once() - -def test_client_ctx(): - transports = [ - 'rest', - 'grpc', - ] - for transport in transports: - client = VersionsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport - ) - # Test client calls underlying transport. - with mock.patch.object(type(client.transport), "close") as close: - close.assert_not_called() - with client: - pass - close.assert_called() - -@pytest.mark.parametrize("client_class,transport_class", [ - (VersionsClient, transports.VersionsGrpcTransport), - (VersionsAsyncClient, transports.VersionsGrpcAsyncIOTransport), -]) -def test_api_key_credentials(client_class, transport_class): - with mock.patch.object( - google.auth._default, "get_api_key_credentials", create=True - ) as get_api_key_credentials: - mock_cred = mock.Mock() - get_api_key_credentials.return_value = mock_cred - options = client_options.ClientOptions() - options.api_key = "api_key" - 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=mock_cred, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - )